-
Notifications
You must be signed in to change notification settings - Fork 541
Expand file tree
/
Copy pathCompiler.cpp
More file actions
4762 lines (3825 loc) · 167 KB
/
Compiler.cpp
File metadata and controls
4762 lines (3825 loc) · 167 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
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
#include "Luau/Compiler.h"
#include "Luau/Parser.h"
#include "Luau/BytecodeBuilder.h"
#include "Luau/Common.h"
#include "Luau/TimeTrace.h"
#include "Builtins.h"
#include "ConstantFolding.h"
#include "CostModel.h"
#include "TableShape.h"
#include "Types.h"
#include "Utils.h"
#include "ValueTracking.h"
#include <algorithm>
#include <bitset>
#include <memory>
#include <math.h>
LUAU_FASTINTVARIABLE(LuauCompileLoopUnrollThreshold, 25)
LUAU_FASTINTVARIABLE(LuauCompileLoopUnrollThresholdMaxBoost, 300)
LUAU_FASTINTVARIABLE(LuauCompileInlineThreshold, 25)
LUAU_FASTINTVARIABLE(LuauCompileInlineThresholdMaxBoost, 300)
LUAU_FASTINTVARIABLE(LuauCompileInlineDepth, 5)
LUAU_FASTFLAG(LuauExplicitTypeInstantiationSyntax)
LUAU_FASTFLAGVARIABLE(LuauCompileCallCostModel)
LUAU_FASTFLAGVARIABLE(LuauCompileNoInterpStorage)
LUAU_FASTFLAGVARIABLE(LuauCompileInlineInitializers)
LUAU_FASTFLAGVARIABLE(LuauCompileExtraTableHints)
LUAU_FASTFLAGVARIABLE(LuauCompileInlinedBuiltins)
namespace Luau
{
using namespace Luau::Compile;
static const uint32_t kMaxRegisterCount = 255;
static const uint32_t kMaxUpvalueCount = 200;
static const uint32_t kMaxLocalCount = 200;
static const uint32_t kMaxInstructionCount = 1'000'000'000;
static const uint8_t kInvalidReg = 255;
static const uint32_t kDefaultAllocPc = ~0u;
void escapeAndAppend(std::string& buffer, const char* str, size_t len)
{
if (memchr(str, '%', len))
{
for (size_t characterIndex = 0; characterIndex < len; ++characterIndex)
{
char character = str[characterIndex];
buffer.push_back(character);
if (character == '%')
buffer.push_back('%');
}
}
else
buffer.append(str, len);
}
CompileError::CompileError(const Location& location, std::string message)
: location(location)
, message(std::move(message))
{
}
CompileError::~CompileError() throw() {}
const char* CompileError::what() const throw()
{
return message.c_str();
}
const Location& CompileError::getLocation() const
{
return location;
}
// NOINLINE is used to limit the stack cost of this function due to std::string object / exception plumbing
LUAU_NOINLINE void CompileError::raise(const Location& location, const char* format, ...)
{
va_list args;
va_start(args, format);
std::string message = vformat(format, args);
va_end(args);
throw CompileError(location, message);
}
static BytecodeBuilder::StringRef sref(AstName name)
{
LUAU_ASSERT(name.value);
return {name.value, strlen(name.value)};
}
static BytecodeBuilder::StringRef sref(AstArray<char> data)
{
LUAU_ASSERT(data.data);
return {data.data, data.size};
}
static BytecodeBuilder::StringRef sref(AstArray<const char> data)
{
LUAU_ASSERT(data.data);
return {data.data, data.size};
}
struct Compiler
{
struct RegScope;
Compiler(BytecodeBuilder& bytecode, const CompileOptions& options, AstNameTable& names)
: bytecode(bytecode)
, options(options)
, functions(nullptr)
, locals(nullptr)
, globals(AstName())
, variables(nullptr)
, constants(nullptr)
, locstants(nullptr)
, tableShapes(nullptr)
, builtins(nullptr)
, userdataTypes(AstName())
, functionTypes(nullptr)
, localTypes(nullptr)
, exprTypes(nullptr)
, builtinTypes(options.vectorType)
, names(names)
{
// preallocate some buffers that are very likely to grow anyway; this works around std::vector's inefficient growth policy for small arrays
localStack.reserve(16);
upvals.reserve(16);
}
int getLocalReg(AstLocal* local)
{
Local* l = locals.find(local);
return l && l->allocated ? l->reg : -1;
}
uint8_t getUpval(AstLocal* local)
{
for (size_t uid = 0; uid < upvals.size(); ++uid)
if (upvals[uid] == local)
return uint8_t(uid);
if (upvals.size() >= kMaxUpvalueCount)
CompileError::raise(
local->location, "Out of upvalue registers when trying to allocate %s: exceeded limit %d", local->name.value, kMaxUpvalueCount
);
// mark local as captured so that closeLocals emits LOP_CLOSEUPVALS accordingly
Variable* v = variables.find(local);
if (v && v->written)
locals[local].captured = true;
upvals.push_back(local);
return uint8_t(upvals.size() - 1);
}
bool alwaysTerminates(AstStat* node)
{
if (FFlag::LuauCompileCallCostModel)
{
return Compile::alwaysTerminates(constants, node);
}
else
{
if (AstStatBlock* stat = node->as<AstStatBlock>())
return stat->body.size > 0 && alwaysTerminates(stat->body.data[stat->body.size - 1]);
else if (node->is<AstStatReturn>())
return true;
else if (node->is<AstStatBreak>() || node->is<AstStatContinue>())
return true;
else if (AstStatIf* stat = node->as<AstStatIf>())
return stat->elsebody && alwaysTerminates(stat->thenbody) && alwaysTerminates(stat->elsebody);
else
return false;
}
}
void emitLoadK(uint8_t target, int32_t cid)
{
LUAU_ASSERT(cid >= 0);
if (cid < 32768)
{
bytecode.emitAD(LOP_LOADK, target, int16_t(cid));
}
else
{
bytecode.emitAD(LOP_LOADKX, target, 0);
bytecode.emitAux(cid);
}
}
AstExprFunction* getFunctionExpr(AstExpr* node)
{
if (AstExprLocal* expr = node->as<AstExprLocal>())
{
Variable* lv = variables.find(expr->local);
if (!lv || lv->written || !lv->init)
return nullptr;
return getFunctionExpr(lv->init);
}
else if (AstExprGroup* expr = node->as<AstExprGroup>())
return getFunctionExpr(expr->expr);
else if (AstExprTypeAssertion* expr = node->as<AstExprTypeAssertion>())
return getFunctionExpr(expr->expr);
else
return node->as<AstExprFunction>();
}
uint32_t compileFunction(AstExprFunction* func, uint8_t& protoflags)
{
LUAU_TIMETRACE_SCOPE("Compiler::compileFunction", "Compiler");
if (func->debugname.value)
LUAU_TIMETRACE_ARGUMENT("name", func->debugname.value);
LUAU_ASSERT(!functions.contains(func));
LUAU_ASSERT(regTop == 0 && stackSize == 0 && localStack.empty() && upvals.empty());
RegScope rs(this);
bool self = func->self != 0;
uint32_t fid = bytecode.beginFunction(uint8_t(self + func->args.size), func->vararg);
setDebugLine(func);
if (func->vararg)
bytecode.emitABC(LOP_PREPVARARGS, uint8_t(self + func->args.size), 0, 0);
uint8_t args = allocReg(func, self + unsigned(func->args.size));
if (func->self)
pushLocal(func->self, args, kDefaultAllocPc);
for (size_t i = 0; i < func->args.size; ++i)
pushLocal(func->args.data[i], uint8_t(args + self + i), kDefaultAllocPc);
argCount = localStack.size();
AstStatBlock* stat = func->body;
if (FFlag::LuauCompileCallCostModel)
{
bool terminatesEarly = false;
for (size_t i = 0; i < stat->body.size; ++i)
{
AstStat* bodyStat = stat->body.data[i];
compileStat(bodyStat);
if (alwaysTerminates(bodyStat))
{
terminatesEarly = true;
break;
}
}
// valid function bytecode must always end with RETURN
// we elide this if we're guaranteed to hit a RETURN statement regardless of the control flow
if (!terminatesEarly)
{
setDebugLineEnd(stat);
closeLocals(0);
bytecode.emitABC(LOP_RETURN, 0, 1, 0);
}
}
else
{
for (size_t i = 0; i < stat->body.size; ++i)
compileStat(stat->body.data[i]);
// valid function bytecode must always end with RETURN
// we elide this if we're guaranteed to hit a RETURN statement regardless of the control flow
if (!alwaysTerminates(stat))
{
setDebugLineEnd(stat);
closeLocals(0);
bytecode.emitABC(LOP_RETURN, 0, 1, 0);
}
}
// constant folding may remove some upvalue refs from bytecode, so this puts them back
if (options.optimizationLevel >= 1 && options.debugLevel >= 2)
gatherConstUpvals(func);
bytecode.setDebugFunctionLineDefined(func->location.begin.line + 1);
if (options.debugLevel >= 1 && func->debugname.value)
bytecode.setDebugFunctionName(sref(func->debugname));
if (options.debugLevel >= 2 && !upvals.empty())
{
for (AstLocal* l : upvals)
bytecode.pushDebugUpval(sref(l->name));
}
if (options.typeInfoLevel >= 1)
{
for (AstLocal* l : upvals)
{
LuauBytecodeType ty = LBC_TYPE_ANY;
if (LuauBytecodeType* recordedTy = localTypes.find(l))
ty = *recordedTy;
bytecode.pushUpvalTypeInfo(ty);
}
}
if (options.optimizationLevel >= 1)
bytecode.foldJumps();
bytecode.expandJumps();
popLocals(0);
if (bytecode.getInstructionCount() > kMaxInstructionCount)
CompileError::raise(func->location, "Exceeded function instruction limit; split the function into parts to compile");
// note: we move types out of typeMap which is safe because compileFunction is only called once per function
if (std::string* funcType = functionTypes.find(func))
bytecode.setFunctionTypeInfo(std::move(*funcType));
// top-level code only executes once so it can be marked as cold if it has no loops; code with loops might be profitable to compile natively
if (func->functionDepth == 0 && !hasLoops)
protoflags |= LPF_NATIVE_COLD;
if (func->hasNativeAttribute())
protoflags |= LPF_NATIVE_FUNCTION;
bytecode.endFunction(uint8_t(stackSize), uint8_t(upvals.size()), protoflags);
Function& f = functions[func];
f.id = fid;
f.upvals = upvals;
// record information for inlining
if (options.optimizationLevel >= 2 && !func->vararg && !func->self && !getfenvUsed && !setfenvUsed)
{
f.canInline = true;
f.stackSize = stackSize;
f.costModel = modelCost(func->body, func->args.data, func->args.size, builtins, constants);
// track functions that only ever return a single value so that we can convert multret calls to fixedret calls
if (alwaysTerminates(func->body))
{
ReturnVisitor returnVisitor(this);
stat->visit(&returnVisitor);
f.returnsOne = returnVisitor.returnsOne;
}
}
upvals.clear(); // note: instead of std::move above, we copy & clear to preserve capacity for future pushes
stackSize = 0;
argCount = 0;
hasLoops = false;
return fid;
}
// returns true if node can return multiple values; may conservatively return true even if expr is known to return just a single value
bool isExprMultRet(AstExpr* node)
{
AstExprCall* expr = node->as<AstExprCall>();
if (!expr)
return node->is<AstExprVarargs>();
// conservative version, optimized for compilation throughput
if (options.optimizationLevel <= 1)
return true;
// handles builtin calls that can be constant-folded
// without this we may omit some optimizations eg compiling fast calls without use of FASTCALL2K
if (isConstant(expr))
return false;
// handles builtin calls that can't be constant-folded but are known to return one value
// note: optimizationLevel check is technically redundant but it's important that we never optimize based on builtins in O1
if (options.optimizationLevel >= 2)
{
if (FFlag::LuauCompileInlinedBuiltins)
{
if (int* bfid = builtins.find(expr); bfid && *bfid != LBF_NONE)
return getBuiltinInfo(*bfid).results != 1;
}
else
{
if (int* bfid = builtins.find(expr))
return getBuiltinInfo(*bfid).results != 1;
}
}
// handles local function calls where we know only one argument is returned
AstExprFunction* func = getFunctionExpr(expr->func);
Function* fi = func ? functions.find(func) : nullptr;
if (fi && fi->returnsOne)
return false;
// unrecognized call, so we conservatively assume multret
return true;
}
// note: this doesn't just clobber target (assuming it's temp), but also clobbers *all* allocated registers >= target!
// this is important to be able to support "multret" semantics due to Lua call frame structure
bool compileExprTempMultRet(AstExpr* node, uint8_t target)
{
if (AstExprCall* expr = node->as<AstExprCall>())
{
// Optimization: convert multret calls that always return one value to fixedret calls; this facilitates inlining/constant folding
if (options.optimizationLevel >= 2 && !isExprMultRet(node))
{
compileExprTemp(node, target);
return false;
}
// We temporarily swap out regTop to have targetTop work correctly...
// This is a crude hack but it's necessary for correctness :(
RegScope rs(this, target);
compileExprCall(expr, target, /* targetCount= */ 0, /* targetTop= */ true, /* multRet= */ true);
return true;
}
else if (AstExprVarargs* expr = node->as<AstExprVarargs>())
{
// We temporarily swap out regTop to have targetTop work correctly...
// This is a crude hack but it's necessary for correctness :(
RegScope rs(this, target);
compileExprVarargs(expr, target, /* targetCount= */ 0, /* multRet= */ true);
return true;
}
else
{
compileExprTemp(node, target);
return false;
}
}
// note: this doesn't just clobber target (assuming it's temp), but also clobbers *all* allocated registers >= target!
// this is important to be able to emit code that takes fewer registers and runs faster
void compileExprTempTop(AstExpr* node, uint8_t target)
{
// We temporarily swap out regTop to have targetTop work correctly...
// This is a crude hack but it's necessary for performance :(
// It makes sure that nested call expressions can use targetTop optimization and don't need to have too many registers
RegScope rs(this, target + 1);
compileExprTemp(node, target);
}
void compileExprVarargs(AstExprVarargs* expr, uint8_t target, uint8_t targetCount, bool multRet = false)
{
LUAU_ASSERT(!multRet || unsigned(target + targetCount) == regTop);
setDebugLine(expr); // normally compileExpr sets up line info, but compileExprVarargs can be called directly
bytecode.emitABC(LOP_GETVARARGS, target, multRet ? 0 : uint8_t(targetCount + 1), 0);
}
void compileExprSelectVararg(AstExprCall* expr, uint8_t target, uint8_t targetCount, bool targetTop, bool multRet, uint8_t regs)
{
LUAU_ASSERT(targetCount == 1);
LUAU_ASSERT(!expr->self);
LUAU_ASSERT(expr->args.size == 2 && expr->args.data[1]->is<AstExprVarargs>());
AstExpr* arg = expr->args.data[0];
uint8_t argreg;
if (int reg = getExprLocalReg(arg); reg >= 0)
argreg = uint8_t(reg);
else
{
argreg = uint8_t(regs + 1);
compileExprTempTop(arg, argreg);
}
size_t fastcallLabel = bytecode.emitLabel();
bytecode.emitABC(LOP_FASTCALL1, LBF_SELECT_VARARG, argreg, 0);
// note, these instructions are normally not executed and are used as a fallback for FASTCALL
// we can't use TempTop variant here because we need to make sure the arguments we already computed aren't overwritten
compileExprTemp(expr->func, regs);
if (argreg != regs + 1)
bytecode.emitABC(LOP_MOVE, uint8_t(regs + 1), argreg, 0);
bytecode.emitABC(LOP_GETVARARGS, uint8_t(regs + 2), 0, 0);
size_t callLabel = bytecode.emitLabel();
if (!bytecode.patchSkipC(fastcallLabel, callLabel))
CompileError::raise(expr->func->location, "Exceeded jump distance limit; simplify the code to compile");
// note, this is always multCall (last argument is variadic)
bytecode.emitABC(LOP_CALL, regs, 0, multRet ? 0 : uint8_t(targetCount + 1));
// if we didn't output results directly to target, we need to move them
if (!targetTop)
{
for (size_t i = 0; i < targetCount; ++i)
bytecode.emitABC(LOP_MOVE, uint8_t(target + i), uint8_t(regs + i), 0);
}
}
void compileExprFastcallN(
AstExprCall* expr,
uint8_t target,
uint8_t targetCount,
bool targetTop,
bool multRet,
uint8_t regs,
int bfid,
int bfK = -1
)
{
LUAU_ASSERT(!expr->self);
LUAU_ASSERT(expr->args.size >= 1);
LUAU_ASSERT(expr->args.size <= 3);
LUAU_ASSERT(bfid == LBF_BIT32_EXTRACTK ? bfK >= 0 : bfK < 0);
LuauOpcode opc = LOP_NOP;
if (expr->args.size == 1)
opc = LOP_FASTCALL1;
else if (bfK >= 0 || (expr->args.size == 2 && isConstant(expr->args.data[1])))
opc = LOP_FASTCALL2K;
else if (expr->args.size == 2)
opc = LOP_FASTCALL2;
else
opc = LOP_FASTCALL3;
uint32_t args[3] = {};
for (size_t i = 0; i < expr->args.size; ++i)
{
if (i > 0 && opc == LOP_FASTCALL2K)
{
int32_t cid = getConstantIndex(expr->args.data[i]);
if (cid < 0)
CompileError::raise(expr->location, "Exceeded constant limit; simplify the code to compile");
args[i] = cid;
}
else if (int reg = getExprLocalReg(expr->args.data[i]); reg >= 0)
{
args[i] = uint8_t(reg);
}
else
{
args[i] = uint8_t(regs + 1 + i);
compileExprTempTop(expr->args.data[i], uint8_t(args[i]));
}
}
size_t fastcallLabel = bytecode.emitLabel();
bytecode.emitABC(opc, uint8_t(bfid), uint8_t(args[0]), 0);
if (opc == LOP_FASTCALL3)
{
LUAU_ASSERT(bfK < 0);
bytecode.emitAux(args[1] | (args[2] << 8));
}
else if (opc != LOP_FASTCALL1)
{
bytecode.emitAux(bfK >= 0 ? bfK : args[1]);
}
// Set up a traditional Lua stack for the subsequent LOP_CALL.
// Note, as with other instructions that immediately follow FASTCALL, these are normally not executed and are used as a fallback for
// these FASTCALL variants.
for (size_t i = 0; i < expr->args.size; ++i)
{
if (i > 0 && opc == LOP_FASTCALL2K)
emitLoadK(uint8_t(regs + 1 + i), args[i]);
else if (args[i] != regs + 1 + i)
bytecode.emitABC(LOP_MOVE, uint8_t(regs + 1 + i), uint8_t(args[i]), 0);
}
// note, these instructions are normally not executed and are used as a fallback for FASTCALL
// we can't use TempTop variant here because we need to make sure the arguments we already computed aren't overwritten
compileExprTemp(expr->func, regs);
size_t callLabel = bytecode.emitLabel();
// FASTCALL will skip over the instructions needed to compute function and jump over CALL which must immediately follow the instruction
// sequence after FASTCALL
if (!bytecode.patchSkipC(fastcallLabel, callLabel))
CompileError::raise(expr->func->location, "Exceeded jump distance limit; simplify the code to compile");
bytecode.emitABC(LOP_CALL, regs, uint8_t(expr->args.size + 1), multRet ? 0 : uint8_t(targetCount + 1));
// if we didn't output results directly to target, we need to move them
if (!targetTop)
{
for (size_t i = 0; i < targetCount; ++i)
bytecode.emitABC(LOP_MOVE, uint8_t(target + i), uint8_t(regs + i), 0);
}
}
bool tryCompileInlinedCall(
AstExprCall* expr,
AstExprFunction* func,
uint8_t target,
uint8_t targetCount,
bool multRet,
int thresholdBase,
int thresholdMaxBoost,
int depthLimit
)
{
Function* fi = functions.find(func);
LUAU_ASSERT(fi);
// make sure we have enough register space
if (regTop > 128 || fi->stackSize > 32)
{
bytecode.addDebugRemark("inlining failed: high register pressure");
return false;
}
// we should ideally aggregate the costs during recursive inlining, but for now simply limit the depth
if (int(inlineFrames.size()) >= depthLimit)
{
bytecode.addDebugRemark("inlining failed: too many inlined frames");
return false;
}
// compiling recursive inlining is difficult because we share constant/variable state but need to bind variables to different registers
for (InlineFrame& frame : inlineFrames)
if (frame.func == func)
{
bytecode.addDebugRemark("inlining failed: can't inline recursive calls");
return false;
}
// we can't inline multret functions because the caller expects L->top to be adjusted:
// - inlined return compiles to a JUMP, and we don't have an instruction that adjusts L->top arbitrarily
// - even if we did, right now all L->top adjustments are immediately consumed by the next instruction, and for now we want to preserve that
// - additionally, we can't easily compile multret expressions into designated target as computed call arguments will get clobbered
if (multRet)
{
bytecode.addDebugRemark("inlining failed: can't convert fixed returns to multret");
return false;
}
// compute constant bitvector for all arguments to feed the cost model
bool varc[8] = {};
bool hasConstant = false;
for (size_t i = 0; i < func->args.size && i < expr->args.size && i < 8; ++i)
{
if (isConstant(expr->args.data[i]))
{
varc[i] = true;
hasConstant = true;
}
}
// if the last argument only returns a single value, all following arguments are nil
if (expr->args.size != 0 && !isExprMultRet(expr->args.data[expr->args.size - 1]))
{
for (size_t i = expr->args.size; i < func->args.size && i < 8; ++i)
{
varc[i] = true;
hasConstant = true;
}
}
// If we had constant arguments that can affect the cost model of this specific call in non-trivial ways
uint64_t callCostModel = fi->costModel;
if (FFlag::LuauCompileCallCostModel && hasConstant)
callCostModel = costModelInlinedCall(expr, func);
// we use a dynamic cost threshold that's based on the fixed limit boosted by the cost advantage we gain due to inlining
int inlinedCost = computeCost(FFlag::LuauCompileCallCostModel ? callCostModel : fi->costModel, varc, std::min(int(func->args.size), 8));
int baselineCost = computeCost(fi->costModel, nullptr, 0) + 3;
int inlineProfit = (inlinedCost == 0) ? thresholdMaxBoost : std::min(thresholdMaxBoost, 100 * baselineCost / inlinedCost);
int threshold = thresholdBase * inlineProfit / 100;
if (inlinedCost > threshold)
{
bytecode.addDebugRemark("inlining failed: too expensive (cost %d, profit %.2fx)", inlinedCost, double(inlineProfit) / 100);
return false;
}
bytecode.addDebugRemark(
"inlining succeeded (cost %d, profit %.2fx, depth %d)", inlinedCost, double(inlineProfit) / 100, int(inlineFrames.size())
);
compileInlinedCall(expr, func, target, targetCount);
return true;
}
uint64_t costModelInlinedCall(AstExprCall* expr, AstExprFunction* func)
{
LUAU_ASSERT(FFlag::LuauCompileCallCostModel);
for (size_t i = 0; i < func->args.size; ++i)
{
AstLocal* var = func->args.data[i];
AstExpr* arg = i < expr->args.size ? expr->args.data[i] : nullptr;
// last expression is a multret, there are no constant for it and it will fill all values
if (i + 1 == expr->args.size && func->args.size > expr->args.size && isExprMultRet(arg))
break;
// variable gets mutated at some point, so we do not have a constant for it
if (Variable* vv = variables.find(var); vv && vv->written)
continue;
if (arg == nullptr)
locstants[var] = {Constant::Type_Nil};
else if (const Constant* cv = constants.find(arg); cv && cv->type != Constant::Type_Unknown)
locstants[var] = *cv;
}
// fold constant values updated above into expressions in the function body
foldConstants(constants, variables, locstants, builtinsFold, builtinsFoldLibraryK, options.libraryMemberConstantCb, func->body, names);
// model the cost of the function evaluated with current constants
uint64_t cost = modelCost(func->body, func->args.data, func->args.size, builtins, constants);
// clean up constant state for future inlining attempts
for (size_t i = 0; i < func->args.size; ++i)
{
if (Constant* var = locstants.find(func->args.data[i]))
var->type = Constant::Type_Unknown;
}
foldConstants(constants, variables, locstants, builtinsFold, builtinsFoldLibraryK, options.libraryMemberConstantCb, func->body, names);
return cost;
}
void compileInlinedCall(AstExprCall* expr, AstExprFunction* func, uint8_t target, uint8_t targetCount)
{
RegScope rs(this);
size_t oldLocals = localStack.size();
std::vector<InlineArg> args;
args.reserve(func->args.size);
// evaluate all arguments; note that we don't emit code for constant arguments (relying on constant folding)
// note that compiler state (variable registers/values) does not change here - we defer that to a separate loop below to handle nested calls
for (size_t i = 0; i < func->args.size; ++i)
{
AstLocal* var = func->args.data[i];
AstExpr* arg = i < expr->args.size ? expr->args.data[i] : nullptr;
if (i + 1 == expr->args.size && func->args.size > expr->args.size && isExprMultRet(arg))
{
// if the last argument can return multiple values, we need to compute all of them into the remaining arguments
unsigned int tail = unsigned(func->args.size - expr->args.size) + 1;
uint8_t reg = allocReg(arg, tail);
uint32_t allocpc = bytecode.getDebugPC();
if (AstExprCall* expr = arg->as<AstExprCall>())
compileExprCall(expr, reg, tail, /* targetTop= */ true);
else if (AstExprVarargs* expr = arg->as<AstExprVarargs>())
compileExprVarargs(expr, reg, tail);
else
LUAU_ASSERT(!"Unexpected expression type");
for (size_t j = i; j < func->args.size; ++j)
args.push_back({func->args.data[j], uint8_t(reg + (j - i)), {Constant::Type_Unknown}, allocpc});
// all remaining function arguments have been allocated and assigned to
break;
}
else if (Variable* vv = variables.find(var); vv && vv->written)
{
// if the argument is mutated, we need to allocate a fresh register even if it's a constant
uint8_t reg = allocReg(arg, 1);
uint32_t allocpc = bytecode.getDebugPC();
if (arg)
compileExprTemp(arg, reg);
else
bytecode.emitABC(LOP_LOADNIL, reg, 0, 0);
args.push_back({var, reg, {Constant::Type_Unknown}, allocpc});
}
else if (arg == nullptr)
{
// since the argument is not mutated, we can simply fold the value into the expressions that need it
args.push_back({var, kInvalidReg, {Constant::Type_Nil}});
}
else if (const Constant* cv = constants.find(arg); cv && cv->type != Constant::Type_Unknown)
{
// since the argument is not mutated, we can simply fold the value into the expressions that need it
args.push_back({var, kInvalidReg, *cv});
}
else
{
AstExprLocal* le = getExprLocal(arg);
Variable* lv = le ? variables.find(le->local) : nullptr;
// if the argument is a local that isn't mutated, we will simply reuse the existing register
if (int reg = le ? getExprLocalReg(le) : -1; reg >= 0 && (!lv || !lv->written))
{
args.push_back({var, uint8_t(reg), {Constant::Type_Unknown}, kDefaultAllocPc, lv ? lv->init : nullptr});
}
else
{
uint8_t temp = allocReg(arg, 1);
uint32_t allocpc = bytecode.getDebugPC();
compileExprTemp(arg, temp);
if (FFlag::LuauCompileInlineInitializers)
args.push_back({var, temp, {Constant::Type_Unknown}, allocpc, arg});
else
args.push_back({var, temp, {Constant::Type_Unknown}, allocpc});
}
}
}
// evaluate extra expressions for side effects
for (size_t i = func->args.size; i < expr->args.size; ++i)
compileExprSide(expr->args.data[i]);
// apply all evaluated arguments to the compiler state
// note: locals use current startpc for debug info, although some of them have been computed earlier; this is similar to compileStatLocal
for (InlineArg& arg : args)
{
if (arg.value.type == Constant::Type_Unknown)
{
pushLocal(arg.local, arg.reg, arg.allocpc);
if (arg.init)
{
if (Variable* lv = variables.find(arg.local))
lv->init = arg.init;
}
}
else
{
locstants[arg.local] = arg.value;
}
}
// the inline frame will be used to compile return statements as well as to reject recursive inlining attempts
inlineFrames.push_back({func, oldLocals, target, targetCount});
if (FFlag::LuauCompileInlinedBuiltins)
{
// this pass tracks which calls are builtins and can be compiled more efficiently
analyzeBuiltins(inlineBuiltins, globals, variables, options, func->body, names);
// If we found new builtins, apply them, but record which expressions we changed so we can undo later
if (!inlineBuiltins.empty())
{
for (auto [callExpr, bfid] : inlineBuiltins)
{
int& builtin = builtins[callExpr]; // If there was no builtin previously, we will get LBF_NONE
if (bfid != builtin)
{
inlineBuiltinsBackup[callExpr] = builtin;
builtin = bfid;
}
}
inlineBuiltins.clear();
}
}
// fold constant values updated above into expressions in the function body
foldConstants(constants, variables, locstants, builtinsFold, builtinsFoldLibraryK, options.libraryMemberConstantCb, func->body, names);
if (FFlag::LuauCompileCallCostModel)
{
bool terminatesEarly = false;
for (size_t i = 0; i < func->body->body.size; ++i)
{
AstStat* stat = func->body->body.data[i];
compileStat(stat);
if (alwaysTerminates(stat))
{
terminatesEarly = true;
// Remove the last jump which jumps directly to the next instruction
InlineFrame& currFrame = inlineFrames.back();
if (!currFrame.returnJumps.empty() && currFrame.returnJumps.back() == bytecode.emitLabel() - 1)
{
bytecode.undoEmit(LOP_JUMP);
currFrame.returnJumps.pop_back();
}
break;
}
}
// for the fallthrough path we need to ensure we clear out target registers
if (!terminatesEarly)
{
for (size_t i = 0; i < targetCount; ++i)
bytecode.emitABC(LOP_LOADNIL, uint8_t(target + i), 0, 0);
closeLocals(oldLocals);
}
}
else
{
bool usedFallthrough = false;
for (size_t i = 0; i < func->body->body.size; ++i)
{
AstStat* stat = func->body->body.data[i];
if (AstStatReturn* ret = stat->as<AstStatReturn>())
{
// Optimization: use fallthrough when compiling return at the end of the function to avoid an extra JUMP
compileInlineReturn(ret, /* fallthrough= */ true);
// TODO: This doesn't work when return is part of control flow; ideally we would track the state somehow and generalize this
usedFallthrough = true;
break;
}
else
compileStat(stat);
}
// for the fallthrough path we need to ensure we clear out target registers
if (!usedFallthrough && !alwaysTerminates(func->body))
{
for (size_t i = 0; i < targetCount; ++i)
bytecode.emitABC(LOP_LOADNIL, uint8_t(target + i), 0, 0);
closeLocals(oldLocals);
}
}
popLocals(oldLocals);
size_t returnLabel = bytecode.emitLabel();
patchJumps(expr, inlineFrames.back().returnJumps, returnLabel);
inlineFrames.pop_back();
// clean up constant state for future inlining attempts
for (size_t i = 0; i < func->args.size; ++i)
{
AstLocal* local = func->args.data[i];
if (Constant* var = locstants.find(local))
var->type = Constant::Type_Unknown;
if (Variable* lv = variables.find(local))
lv->init = nullptr;
}
if (FFlag::LuauCompileInlinedBuiltins)
{
if (!inlineBuiltinsBackup.empty())
{
for (auto [callExpr, bfid] : inlineBuiltinsBackup)
builtins[callExpr] = bfid;
inlineBuiltinsBackup.clear();
}
}
foldConstants(constants, variables, locstants, builtinsFold, builtinsFoldLibraryK, options.libraryMemberConstantCb, func->body, names);
}
void compileExprCall(AstExprCall* expr, uint8_t target, uint8_t targetCount, bool targetTop = false, bool multRet = false)
{
LUAU_ASSERT(!targetTop || unsigned(target + targetCount) == regTop);
setDebugLine(expr); // normally compileExpr sets up line info, but compileExprCall can be called directly
// try inlining the function
if (options.optimizationLevel >= 2 && !expr->self)
{
AstExprFunction* func = getFunctionExpr(expr->func);
Function* fi = func ? functions.find(func) : nullptr;