forked from tanishiking/scala-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWasmExpressionBuilder.scala
2518 lines (2169 loc) · 92.1 KB
/
WasmExpressionBuilder.scala
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
package wasm
package ir2wasm
import scala.annotation.switch
import scala.collection.mutable
import org.scalajs.ir.{Trees => IRTrees}
import org.scalajs.ir.{Types => IRTypes}
import org.scalajs.ir.{Names => IRNames}
import wasm4s._
import wasm4s.Names._
import wasm4s.Names.WasmTypeName._
import wasm4s.WasmInstr._
import org.scalajs.ir.Types.ClassType
import org.scalajs.ir.ClassKind
import org.scalajs.ir.Position
import _root_.wasm4s.Defaults
import EmbeddedConstants._
object WasmExpressionBuilder {
/** Whether to use the legacy `try` instruction to implement `TryCatch`.
*
* Support for catching JS exceptions was only added to `try_table` in V8 12.5 from April 2024.
* While waiting for Node.js to catch up with V8, we use `try` to implement our `TryCatch`.
*
* We use this "fixed configuration option" to keep the code that implements `TryCatch` using
* `try_table` in the codebase, as code that is actually compiled, so that refactorings apply to
* it as well. It also makes it easier to manually experiment with the new `try_table` encoding,
* which will become available in Chrome v125.
*
* Note that we use `try_table` regardless to implement `TryFinally`. Its `catch_all_ref` handler
* is perfectly happy to catch and rethrow JavaScript exception in Node.js 22. Duplicating that
* implementation for `try` would be a nightmare, given how complex it is already.
*/
private final val UseLegacyExceptionsForTryCatch = true
def generateIRBody(tree: IRTrees.Tree, resultType: IRTypes.Type)(implicit
ctx: TypeDefinableWasmContext,
fctx: WasmFunctionContext
): Unit = {
val builder = new WasmExpressionBuilder(ctx, fctx)
builder.genBody(tree, resultType)
}
def generateBlockStats[A](stats: List[IRTrees.Tree])(inner: => A)(implicit
ctx: TypeDefinableWasmContext,
fctx: WasmFunctionContext
): A = {
val builder = new WasmExpressionBuilder(ctx, fctx)
builder.genBlockStats(stats)(inner)
}
def genLoadJSNativeLoadSpec(fctx: WasmFunctionContext, loadSpec: IRTrees.JSNativeLoadSpec)(
implicit ctx: TypeDefinableWasmContext
): IRTypes.Type = {
import IRTrees.JSNativeLoadSpec._
import fctx.instrs
def genFollowPath(path: List[String]): Unit = {
for (prop <- path) {
instrs ++= ctx.getConstantStringInstr(prop)
instrs += CALL(WasmFunctionName.jsSelect)
}
}
loadSpec match {
case Global(globalRef, path) =>
instrs ++= ctx.getConstantStringInstr(globalRef)
instrs += CALL(WasmFunctionName.jsGlobalRefGet)
genFollowPath(path)
IRTypes.AnyType
case Import(module, path) =>
instrs += GLOBAL_GET(ctx.getImportedModuleGlobal(module))
genFollowPath(path)
IRTypes.AnyType
case ImportWithGlobalFallback(importSpec, globalSpec) =>
genLoadJSNativeLoadSpec(fctx, importSpec)
}
}
private val ObjectRef = IRTypes.ClassRef(IRNames.ObjectClass)
private val BoxedStringRef = IRTypes.ClassRef(IRNames.BoxedStringClass)
private val toStringMethodName = IRNames.MethodName("toString", Nil, BoxedStringRef)
private val equalsMethodName = IRNames.MethodName("equals", List(ObjectRef), IRTypes.BooleanRef)
private val compareToMethodName = IRNames.MethodName("compareTo", List(ObjectRef), IRTypes.IntRef)
private val CharSequenceClass = IRNames.ClassName("java.lang.CharSequence")
private val ComparableClass = IRNames.ClassName("java.lang.Comparable")
private val JLNumberClass = IRNames.ClassName("java.lang.Number")
}
private class WasmExpressionBuilder private (
ctx: TypeDefinableWasmContext,
fctx: WasmFunctionContext
) {
import WasmExpressionBuilder._
private val instrs = fctx.instrs
def genBody(tree: IRTrees.Tree, expectedType: IRTypes.Type): Unit =
genTree(tree, expectedType)
def genTrees(trees: List[IRTrees.Tree], expectedTypes: List[IRTypes.Type]): Unit = {
for ((tree, expectedType) <- trees.zip(expectedTypes))
genTree(tree, expectedType)
}
def genTreeAuto(tree: IRTrees.Tree): Unit =
genTree(tree, tree.tpe)
def genTree(tree: IRTrees.Tree, expectedType: IRTypes.Type): Unit = {
val generatedType: IRTypes.Type = tree match {
case t: IRTrees.Literal => genLiteral(t)
case t: IRTrees.UnaryOp => genUnaryOp(t)
case t: IRTrees.BinaryOp => genBinaryOp(t)
case t: IRTrees.VarRef => genVarRef(t)
case t: IRTrees.LoadModule => genLoadModule(t)
case t: IRTrees.StoreModule => genStoreModule(t)
case t: IRTrees.This => genThis(t)
case t: IRTrees.ApplyStatically => genApplyStatically(t)
case t: IRTrees.Apply => genApply(t)
case t: IRTrees.ApplyStatic => genApplyStatic(t)
case t: IRTrees.ApplyDynamicImport => genApplyDynamicImport(t)
case t: IRTrees.IsInstanceOf => genIsInstanceOf(t)
case t: IRTrees.AsInstanceOf => genAsInstanceOf(t)
case t: IRTrees.GetClass => genGetClass(t)
case t: IRTrees.Block => genBlock(t, expectedType)
case t: IRTrees.Labeled => genLabeled(t, expectedType)
case t: IRTrees.Return => genReturn(t)
case t: IRTrees.Select => genSelect(t)
case t: IRTrees.SelectStatic => genSelectStatic(t)
case t: IRTrees.Assign => genAssign(t)
case t: IRTrees.VarDef => genVarDef(t)
case t: IRTrees.New => genNew(t)
case t: IRTrees.If => genIf(t, expectedType)
case t: IRTrees.While => genWhile(t)
case t: IRTrees.ForIn => genForIn(t)
case t: IRTrees.TryCatch => genTryCatch(t)
case t: IRTrees.TryFinally => genTryFinally(t)
case t: IRTrees.Throw => genThrow(t)
case t: IRTrees.Match => genMatch(t)
case t: IRTrees.Debugger => IRTypes.NoType // ignore
case t: IRTrees.Skip => IRTypes.NoType
case t: IRTrees.Clone => genClone(t)
case t: IRTrees.IdentityHashCode => genIdentityHashCode(t)
case t: IRTrees.WrapAsThrowable => genWrapAsThrowable(t)
case t: IRTrees.UnwrapFromThrowable => genUnwrapFromThrowable(t)
// JavaScript expressions
case t: IRTrees.JSNew => genJSNew(t)
case t: IRTrees.JSSelect => genJSSelect(t)
case t: IRTrees.JSFunctionApply => genJSFunctionApply(t)
case t: IRTrees.JSMethodApply => genJSMethodApply(t)
case t: IRTrees.JSImportCall => genJSImportCall(t)
case t: IRTrees.JSImportMeta => genJSImportMeta(t)
case t: IRTrees.LoadJSConstructor => genLoadJSConstructor(t)
case t: IRTrees.LoadJSModule => genLoadJSModule(t)
case t: IRTrees.SelectJSNativeMember => genSelectJSNativeMember(t)
case t: IRTrees.JSDelete => genJSDelete(t)
case t: IRTrees.JSUnaryOp => genJSUnaryOp(t)
case t: IRTrees.JSBinaryOp => genJSBinaryOp(t)
case t: IRTrees.JSArrayConstr => genJSArrayConstr(t)
case t: IRTrees.JSObjectConstr => genJSObjectConstr(t)
case t: IRTrees.JSGlobalRef => genJSGlobalRef(t)
case t: IRTrees.JSTypeOfGlobalRef => genJSTypeOfGlobalRef(t)
case t: IRTrees.JSLinkingInfo => genJSLinkingInfo(t)
case t: IRTrees.Closure => genClosure(t)
// array
case t: IRTrees.ArrayLength => genArrayLength(t)
case t: IRTrees.NewArray => genNewArray(t)
case t: IRTrees.ArraySelect => genArraySelect(t)
case t: IRTrees.ArrayValue => genArrayValue(t)
// Non-native JS classes
case t: IRTrees.CreateJSClass => genCreateJSClass(t)
case t: IRTrees.JSPrivateSelect => genJSPrivateSelect(t)
case t: IRTrees.JSSuperSelect => genJSSuperSelect(t)
case t: IRTrees.JSSuperMethodCall => genJSSuperMethodCall(t)
case t: IRTrees.JSNewTarget => genJSNewTarget(t)
case _: IRTrees.RecordSelect | _: IRTrees.RecordValue | _: IRTrees.Transient |
_: IRTrees.JSSuperConstructorCall =>
throw new AssertionError(s"Invalid tree: $tree")
}
genAdapt(generatedType, expectedType)
}
private def genAdapt(generatedType: IRTypes.Type, expectedType: IRTypes.Type): Unit = {
(generatedType, expectedType) match {
case _ if generatedType == expectedType =>
()
case (IRTypes.NothingType, _) =>
()
case (_, IRTypes.NoType) =>
instrs += DROP
case (primType: IRTypes.PrimTypeWithRef, _) =>
// box
primType match {
case IRTypes.NullType =>
()
case IRTypes.CharType =>
/* `char` and `long` are opaque to JS in the Scala.js semantics.
* We implement them with real Wasm classes following the correct
* vtable. Upcasting wraps a primitive into the corresponding class.
*/
genBox(IRTypes.CharType, SpecialNames.CharBoxClass)
case IRTypes.LongType =>
genBox(IRTypes.LongType, SpecialNames.LongBoxClass)
case IRTypes.NoType | IRTypes.NothingType =>
throw new AssertionError(s"Unexpected adaptation from $primType to $expectedType")
case _ =>
/* Calls a `bX` helper. Most of them are of the form
* bX: (x) => x
* at the JavaScript level, but with a primType->anyref Wasm type.
* For example, for `IntType`, `bI` has type `i32 -> anyref`. This
* asks the JS host to turn a primitive `i32` into its generic
* representation, which we can store in an `anyref`.
*/
instrs += CALL(WasmFunctionName.box(primType.primRef))
}
case _ =>
()
}
}
private def genAssign(t: IRTrees.Assign): IRTypes.Type = {
t.lhs match {
case sel: IRTrees.Select =>
val className = sel.field.name.className
val classInfo = ctx.getClassInfo(className)
// For Select, the receiver can never be a hijacked class, so we can use genTreeAuto
genTreeAuto(sel.qualifier)
if (!classInfo.hasInstances) {
/* The field may not exist in that case, and we cannot look it up.
* However we necessarily have a `null` receiver if we reach this
* point, so we can trap as NPE.
*/
instrs += UNREACHABLE
} else {
val fieldName = WasmFieldName.forClassInstanceField(sel.field.name)
val idx = ctx.getClassInfo(className).getFieldIdx(sel.field.name)
genTree(t.rhs, t.lhs.tpe)
instrs += STRUCT_SET(WasmStructTypeName.forClass(className), idx)
}
case sel: IRTrees.SelectStatic =>
genTree(t.rhs, sel.tpe)
instrs += GLOBAL_SET(Names.WasmGlobalName.forStaticField(sel.field.name))
case sel: IRTrees.ArraySelect =>
genTreeAuto(sel.array)
sel.array.tpe match {
case IRTypes.ArrayType(arrayTypeRef) =>
// Get the underlying array; implicit trap on null
instrs += STRUCT_GET(
WasmStructTypeName.forArrayClass(arrayTypeRef),
WasmFieldIdx.uniqueRegularField
)
genTree(sel.index, IRTypes.IntType)
genTree(t.rhs, sel.tpe)
instrs += ARRAY_SET(WasmArrayTypeName.underlyingOf(arrayTypeRef))
case IRTypes.NothingType =>
// unreachable
()
case IRTypes.NullType =>
instrs += UNREACHABLE
case _ =>
throw new IllegalArgumentException(
s"ArraySelect.array must be an array type, but has type ${sel.array.tpe}"
)
}
case sel: IRTrees.JSPrivateSelect =>
genTree(sel.qualifier, IRTypes.AnyType)
instrs += GLOBAL_GET(WasmGlobalName.forJSPrivateField(sel.field.name))
genTree(t.rhs, IRTypes.AnyType)
instrs += CALL(WasmFunctionName.jsSelectSet)
case assign: IRTrees.JSSelect =>
genTree(assign.qualifier, IRTypes.AnyType)
genTree(assign.item, IRTypes.AnyType)
genTree(t.rhs, IRTypes.AnyType)
instrs += CALL(WasmFunctionName.jsSelectSet)
case assign: IRTrees.JSSuperSelect =>
genTree(assign.superClass, IRTypes.AnyType)
genTree(assign.receiver, IRTypes.AnyType)
genTree(assign.item, IRTypes.AnyType)
genTree(t.rhs, IRTypes.AnyType)
instrs += CALL(WasmFunctionName.jsSuperSet)
case assign: IRTrees.JSGlobalRef =>
genLiteral(IRTrees.StringLiteral(assign.name)(assign.pos))
genTree(t.rhs, IRTypes.AnyType)
instrs += CALL(WasmFunctionName.jsGlobalRefSet)
case ref: IRTrees.VarRef =>
import WasmFunctionContext.VarStorage
fctx.lookupLocal(ref.ident.name) match {
case VarStorage.Local(local) =>
genTree(t.rhs, t.lhs.tpe)
instrs += LOCAL_SET(local)
case VarStorage.StructField(structLocal, structTypeName, fieldIdx) =>
instrs += LOCAL_GET(structLocal)
genTree(t.rhs, t.lhs.tpe)
instrs += STRUCT_SET(structTypeName, fieldIdx)
}
case assign: IRTrees.RecordSelect =>
throw new AssertionError(s"Invalid tree: $t")
}
IRTypes.NoType
}
private def genApply(t: IRTrees.Apply): IRTypes.Type = {
t.receiver.tpe match {
case IRTypes.NothingType =>
genTree(t.receiver, IRTypes.NothingType)
// nothing else to do; this is unreachable
IRTypes.NothingType
case IRTypes.NullType =>
genTree(t.receiver, IRTypes.NullType)
instrs += UNREACHABLE // trap
IRTypes.NothingType
case prim: IRTypes.PrimType =>
// statically resolved call with non-null argument
val receiverClassName = IRTypes.PrimTypeToBoxedClass(prim)
genApplyStatically(
IRTrees.ApplyStatically(t.flags, t.receiver, receiverClassName, t.method, t.args)(t.tpe)(
t.pos
)
)
case IRTypes.ClassType(className) if IRNames.HijackedClasses.contains(className) =>
// statically resolved call with maybe-null argument
genApplyStatically(
IRTrees.ApplyStatically(t.flags, t.receiver, className, t.method, t.args)(t.tpe)(t.pos)
)
case _ if t.method.name.isReflectiveProxy =>
genReflectiveCall(t)
case _ =>
genApplyNonPrim(t)
}
}
private def genReflectiveCall(t: IRTrees.Apply): IRTypes.Type = {
assert(t.method.name.isReflectiveProxy)
val receiverLocalForDispatch =
fctx.addSyntheticLocal(Types.WasmRefType.any)
val proxyId = ctx.getReflectiveProxyId(t.method.name.nameString)
val receiverType = TypeTransformer.makeReceiverType
val paramTys = t.method.name.paramTypeRefs.map(TypeTransformer.transformTypeRef(_)(ctx))
val sig = WasmFunctionSignature(
receiverType +: paramTys,
TypeTransformer.transformResultType(IRTypes.AnyType)(ctx)
)
val funcTy = WasmFunctionType(ctx.addFunctionType(sig), sig)
fctx.block(sig.results) { done =>
fctx.block(Types.WasmRefType.any) { labelNotOurObject =>
// arguments
genTree(t.receiver, IRTypes.AnyType)
instrs += REF_AS_NOT_NULL
instrs += LOCAL_TEE(receiverLocalForDispatch)
genArgs(t.args, t.method.name)
// Looks up the method to be (reflectively) called
instrs += LOCAL_GET(receiverLocalForDispatch)
instrs += BR_ON_CAST_FAIL(
labelNotOurObject,
Types.WasmRefType.any,
Types.WasmRefType(Types.WasmHeapType.ObjectType)
)
instrs += STRUCT_GET(
WasmStructTypeName.forClass(IRNames.ObjectClass),
WasmFieldIdx.vtable
)
instrs += I32_CONST(proxyId)
// `searchReflectiveProxy`: [typeData, i32] -> [(ref func)]
instrs += CALL(WasmFunctionName.searchReflectiveProxy)
instrs += REF_CAST(Types.WasmRefType(Types.WasmHeapType(funcTy.name)))
instrs += CALL_REF(funcTy.name)
instrs += BR(done)
} // labelNotFound
instrs += UNREACHABLE
// TODO? reflective call on primitive types
t.tpe
}
// done
}
/** Generates the code an `Apply` call where the receiver's type is not statically known to be a
* primitive or hijacked class.
*
* In that case, there is always at least a vtable/itable-based dispatch. It may also contain
* primitive-based dispatch if the receiver's type is an ancestor of a hijacked class.
*/
private def genApplyNonPrim(t: IRTrees.Apply): IRTypes.Type = {
implicit val pos: Position = t.pos
val receiverClassName = t.receiver.tpe match {
case ClassType(className) => className
case IRTypes.AnyType => IRNames.ObjectClass
case IRTypes.ArrayType(_) => IRNames.ObjectClass
case _ => throw new Error(s"Invalid receiver type ${t.receiver.tpe}")
}
val receiverClassInfo = ctx.getClassInfo(receiverClassName)
/* Similar to transformType(t.receiver.tpe), but:
* - it is non-null,
* - ancestors of hijacked classes are not treated specially,
* - array types are treated as j.l.Object.
*
* This is used in the code paths where we have already ruled out `null`
* values and primitive values (that implement hijacked classes).
*/
val heapTypeForDispatch: Types.WasmHeapType = {
if (receiverClassInfo.isInterface)
Types.WasmHeapType.ObjectType
else
Types.WasmHeapType(Names.WasmTypeName.WasmStructTypeName.forClass(receiverClassName))
}
// A local for a copy of the receiver that we will use to resolve dispatch
val receiverLocalForDispatch =
fctx.addSyntheticLocal(Types.WasmRefType(heapTypeForDispatch))
/* Gen loading of the receiver and check that it is non-null.
* After this codegen, the non-null receiver is on the stack.
*/
def genReceiverNotNull(): Unit = {
genTreeAuto(t.receiver)
instrs += REF_AS_NOT_NULL
}
/* Generates a resolved call to a method of a hijacked class.
* Before this code gen, the stack must contain the receiver and the args.
* After this code gen, the stack contains the result.
*/
def genHijackedClassCall(hijackedClass: IRNames.ClassName): Unit = {
val funcName = Names.WasmFunctionName(
IRTrees.MemberNamespace.Public,
hijackedClass,
t.method.name
)
instrs += CALL(funcName)
}
if (!receiverClassInfo.hasInstances) {
/* If the target class info does not have any instance, the only possible
* for the receiver is `null`. We can therefore immediately trap for an
* NPE. It is important to short-cut this path because the reachability
* analysis may have dead-code eliminated the target method method
* entirely, which means we do not know its signature and therefore
* cannot emit the corresponding vtable/itable calls.
*/
genTreeAuto(t.receiver)
instrs += UNREACHABLE // NPE
} else if (!receiverClassInfo.isAncestorOfHijackedClass) {
// Standard dispatch codegen
genReceiverNotNull()
instrs += LOCAL_TEE(receiverLocalForDispatch)
genArgs(t.args, t.method.name)
genTableDispatch(receiverClassInfo, t.method.name, receiverLocalForDispatch)
} else {
/* Here the receiver's type is an ancestor of a hijacked class (or `any`,
* which is treated as `jl.Object`).
*
* We must emit additional dispatch for the possible primitive values.
*
* The overall structure of the generated code is as follows:
*
* block resultType $done
* block (ref any) $notOurObject
* load non-null receiver and args and store into locals
* reload copy of receiver
* br_on_cast_fail (ref any) (ref $targetRealClass) $notOurObject
* reload args
* generate standard table-based dispatch
* br $done
* end $notOurObject
* choose an implementation of a single hijacked class, or a JS helper
* reload args
* call the chosen implementation
* end $done
*/
assert(receiverClassInfo.kind != ClassKind.HijackedClass, receiverClassName)
val resultTyp = TypeTransformer.transformResultType(t.tpe)(ctx)
fctx.block(resultTyp) { labelDone =>
def pushArgs(argsLocals: List[WasmLocalName]): Unit =
argsLocals.foreach(argLocal => instrs += LOCAL_GET(argLocal))
// First try the case where the value is one of our objects
val argsLocals = fctx.block(Types.WasmRefType.any) { labelNotOurObject =>
// Load receiver and arguments and store them in temporary variables
genReceiverNotNull()
val argsLocals = if (t.args.isEmpty) {
/* When there are no arguments, we can leave the receiver directly on
* the stack instead of going through a local. We will still need a
* local for the table-based dispatch, though.
*/
Nil
} else {
val receiverLocal = fctx.addSyntheticLocal(Types.WasmRefType.any)
instrs += LOCAL_SET(receiverLocal)
val argsLocals: List[WasmLocalName] =
for ((arg, typeRef) <- t.args.zip(t.method.name.paramTypeRefs)) yield {
val typ = ctx.inferTypeFromTypeRef(typeRef)
genTree(arg, typ)
val localName = fctx.addSyntheticLocal(TypeTransformer.transformType(typ)(ctx))
instrs += LOCAL_SET(localName)
localName
}
instrs += LOCAL_GET(receiverLocal)
argsLocals
}
instrs += BR_ON_CAST_FAIL(
labelNotOurObject,
Types.WasmRefType.any,
Types.WasmRefType(heapTypeForDispatch)
)
instrs += LOCAL_TEE(receiverLocalForDispatch)
pushArgs(argsLocals)
genTableDispatch(receiverClassInfo, t.method.name, receiverLocalForDispatch)
instrs += BR(labelDone)
argsLocals
} // end block labelNotOurObject
/* Now we have a value that is not one of our objects, so it must be
* a JavaScript value whose representative class extends/implements the
* receiver class. It may be a primitive instance of a hijacked class, or
* any other value (whose representative class is therefore `jl.Object`).
*
* It is also *not* `char` or `long`, since those would reach
* `genApplyNonPrim` in their boxed form, and therefore they are
* "ourObject".
*
* The (ref any) is still on the stack.
*/
if (t.method.name == toStringMethodName) {
// By spec, toString() is special
assert(argsLocals.isEmpty)
instrs += CALL(WasmFunctionName.jsValueToString)
} else if (receiverClassName == JLNumberClass) {
// the value must be a `number`, hence we can unbox to `double`
genUnbox(IRTypes.DoubleType)
pushArgs(argsLocals)
genHijackedClassCall(IRNames.BoxedDoubleClass)
} else if (receiverClassName == CharSequenceClass) {
// the value must be a `string`; it already has the right type
pushArgs(argsLocals)
genHijackedClassCall(IRNames.BoxedStringClass)
} else if (t.method.name == compareToMethodName) {
/* The only method of jl.Comparable. Here the value can be a boolean,
* a number or a string. We use `jsValueType` to dispatch to Wasm-side
* implementations because they have to perform casts on their arguments.
*/
assert(argsLocals.size == 1)
val receiverLocal = fctx.addSyntheticLocal(Types.WasmRefType.any)
instrs += LOCAL_TEE(receiverLocal)
val jsValueTypeLocal = fctx.addSyntheticLocal(Types.WasmInt32)
instrs += CALL(WasmFunctionName.jsValueType)
instrs += LOCAL_TEE(jsValueTypeLocal)
import wasm.wasm4s.{WasmFunctionSignature => Sig}
fctx.switch(Sig(List(Types.WasmInt32), Nil), Sig(Nil, List(Types.WasmInt32))) { () =>
// scrutinee is already on the stack
}(
// case JSValueTypeFalse | JSValueTypeTrue =>
List(JSValueTypeFalse, JSValueTypeTrue) -> { () =>
// the jsValueTypeLocal is the boolean value, thanks to the chosen encoding
instrs += LOCAL_GET(jsValueTypeLocal)
pushArgs(argsLocals)
genHijackedClassCall(IRNames.BoxedBooleanClass)
},
// case JSValueTypeString =>
List(JSValueTypeString) -> { () =>
instrs += LOCAL_GET(receiverLocal)
// no need to unbox for string
pushArgs(argsLocals)
genHijackedClassCall(IRNames.BoxedStringClass)
}
) { () =>
// case _ (JSValueTypeNumber) =>
instrs += LOCAL_GET(receiverLocal)
genUnbox(IRTypes.DoubleType)
pushArgs(argsLocals)
genHijackedClassCall(IRNames.BoxedDoubleClass)
}
} else {
/* It must be a method of j.l.Object and it can be any value.
* hashCode() and equals() are overridden in all hijacked classes.
* We use `identityHashCode` for `hashCode` and `Object.is` for `equals`,
* as they coincide with the respective specifications (on purpose).
* The other methods are never overridden and can be statically
* resolved to j.l.Object.
*/
pushArgs(argsLocals)
t.method.name match {
case SpecialNames.hashCodeMethodName =>
instrs += CALL(WasmFunctionName.identityHashCode)
case `equalsMethodName` =>
instrs += CALL(WasmFunctionName.is)
case _ =>
genHijackedClassCall(IRNames.ObjectClass)
}
}
} // end block labelDone
}
if (t.tpe == IRTypes.NothingType)
instrs += UNREACHABLE
t.tpe
}
/** Generates a vtable- or itable-based dispatch.
*
* Before this code gen, the stack must contain the receiver and the args of the target method.
* In addition, the receiver must be available in the local `receiverLocalForDispatch`. The two
* occurrences of the receiver must have the type for dispatch.
*
* After this code gen, the stack contains the result. If the result type is `NothingType`,
* `genTableDispatch` leaves the stack in an arbitrary state. It is up to the caller to insert an
* `unreachable` instruction when appropriate.
*/
def genTableDispatch(
receiverClassInfo: WasmContext.WasmClassInfo,
methodName: IRNames.MethodName,
receiverLocalForDispatch: WasmLocalName
): Unit = {
// Generates an itable-based dispatch.
def genITableDispatch(): Unit = {
val itableIdx = ctx.getItableIdx(receiverClassInfo.name)
val methodIdx =
receiverClassInfo.methods.indexWhere(meth => meth.name.simpleName == methodName.nameString)
if (methodIdx < 0)
throw new Error(
s"Method ${methodName.nameString} not found in class ${receiverClassInfo.name}"
)
val methodInfo = receiverClassInfo.methods(methodIdx)
instrs += LOCAL_GET(receiverLocalForDispatch)
instrs += STRUCT_GET(
// receiver type should be upcasted into `Object` if it's interface
// by TypeTransformer#transformType
WasmStructTypeName.forClass(IRNames.ObjectClass),
WasmFieldIdx.itables
)
instrs += I32_CONST(itableIdx)
instrs += ARRAY_GET(WasmArrayType.itables.name)
instrs += REF_CAST(Types.WasmRefType(WasmStructTypeName.forITable(receiverClassInfo.name)))
instrs += STRUCT_GET(
WasmStructTypeName.forITable(receiverClassInfo.name),
WasmFieldIdx(methodIdx)
)
instrs += CALL_REF(methodInfo.toWasmFunctionType()(ctx).name)
}
// Generates a vtable-based dispatch.
def genVTableDispatch(): Unit = {
val receiverClassName = receiverClassInfo.name
val (methodIdx, info) = ctx
.calculateVtableType(receiverClassName)
.resolveWithIdx(
WasmFunctionName(
IRTrees.MemberNamespace.Public,
receiverClassName,
methodName
)
)
// // push args to the stacks
// local.get $this ;; for accessing funcref
// local.get $this ;; for accessing vtable
// struct.get $classType 0 ;; get vtable
// struct.get $vtableType $methodIdx ;; get funcref
// call.ref (type $funcType) ;; call funcref
instrs += LOCAL_GET(receiverLocalForDispatch)
instrs += REF_CAST(Types.WasmRefType(WasmStructTypeName.forClass(receiverClassName)))
instrs += STRUCT_GET(
WasmStructTypeName.forClass(receiverClassName),
WasmFieldIdx.vtable
)
instrs += STRUCT_GET(
WasmStructTypeName.forVTable(receiverClassName),
WasmFieldIdx(WasmStructType.typeDataFieldCount(ctx) + methodIdx)
)
instrs += CALL_REF(info.toWasmFunctionType()(ctx).name)
}
if (receiverClassInfo.isInterface)
genITableDispatch()
else
genVTableDispatch()
}
private def genApplyStatically(t: IRTrees.ApplyStatically): IRTypes.Type = {
t.receiver.tpe match {
case IRTypes.NothingType =>
genTree(t.receiver, IRTypes.NothingType)
// nothing else to do; this is unreachable
IRTypes.NothingType
case IRTypes.NullType =>
genTree(t.receiver, IRTypes.NullType)
instrs += UNREACHABLE // trap
IRTypes.NothingType
case _ =>
val namespace = IRTrees.MemberNamespace.forNonStaticCall(t.flags)
val targetClassName =
ctx.getClassInfo(t.className).resolvePublicMethod(namespace, t.method.name)(ctx)
IRTypes.BoxedClassToPrimType.get(targetClassName) match {
case None =>
genTree(t.receiver, IRTypes.ClassType(targetClassName))
instrs += REF_AS_NOT_NULL
case Some(primReceiverType) =>
if (t.receiver.tpe == primReceiverType) {
genTreeAuto(t.receiver)
} else if (t.receiver.isInstanceOf[IRTrees.This]) {
// TODO: investigate what's going on
// Don't know why, but it seems that `this` isn't boxed even if
// t.receiver.tpe = ClassType(ClassName<java.lang.Boolean>), and
// primReceiverType = BooleanType
// This wired patch is required for `(func $f#java.lang.Boolean#compareTo_Ljava.lang.Boolean_R`
genTreeAuto(t.receiver)
} else {
genTree(t.receiver, IRTypes.AnyType)
instrs += REF_AS_NOT_NULL
genUnbox(primReceiverType)(t.pos)
}
}
genArgs(t.args, t.method.name)
val funcName = Names.WasmFunctionName(namespace, targetClassName, t.method.name)
instrs += CALL(funcName)
if (t.tpe == IRTypes.NothingType)
instrs += UNREACHABLE
t.tpe
}
}
private def genApplyStatic(tree: IRTrees.ApplyStatic): IRTypes.Type = {
genArgs(tree.args, tree.method.name)
val namespace = IRTrees.MemberNamespace.forStaticCall(tree.flags)
val funcName = Names.WasmFunctionName(namespace, tree.className, tree.method.name)
instrs += CALL(funcName)
if (tree.tpe == IRTypes.NothingType)
instrs += UNREACHABLE
tree.tpe
}
private def genApplyDynamicImport(tree: IRTrees.ApplyDynamicImport): IRTypes.Type = {
// As long as we do not support multiple modules, this cannot happen
throw new AssertionError(
s"Unexpected $tree at ${tree.pos}; multiple modules are not supported yet"
)
}
private def genArgs(args: List[IRTrees.Tree], methodName: IRNames.MethodName): Unit = {
for ((arg, paramTypeRef) <- args.zip(methodName.paramTypeRefs)) {
val paramType = ctx.inferTypeFromTypeRef(paramTypeRef)
genTree(arg, paramType)
}
}
private def genLiteral(l: IRTrees.Literal): IRTypes.Type = {
l match {
case IRTrees.BooleanLiteral(v) => instrs += WasmInstr.I32_CONST(if (v) 1 else 0)
case IRTrees.ByteLiteral(v) => instrs += WasmInstr.I32_CONST(v)
case IRTrees.ShortLiteral(v) => instrs += WasmInstr.I32_CONST(v)
case IRTrees.IntLiteral(v) => instrs += WasmInstr.I32_CONST(v)
case IRTrees.CharLiteral(v) => instrs += WasmInstr.I32_CONST(v)
case IRTrees.LongLiteral(v) => instrs += WasmInstr.I64_CONST(v)
case IRTrees.FloatLiteral(v) => instrs += WasmInstr.F32_CONST(v)
case IRTrees.DoubleLiteral(v) => instrs += WasmInstr.F64_CONST(v)
case v: IRTrees.Undefined =>
instrs += CALL(WasmFunctionName.undef)
case v: IRTrees.Null =>
instrs += WasmInstr.REF_NULL(Types.WasmHeapType.None)
case v: IRTrees.StringLiteral =>
instrs ++= ctx.getConstantStringInstr(v.value)
case v: IRTrees.ClassOf =>
v.typeRef match {
case typeRef: IRTypes.NonArrayTypeRef =>
genClassOfFromTypeData(getNonArrayTypeDataInstr(typeRef))
case typeRef: IRTypes.ArrayTypeRef =>
val typeDataType = Types.WasmRefType(WasmStructTypeName.typeData)
val typeDataLocal = fctx.addSyntheticLocal(typeDataType)
genLoadArrayTypeData(typeRef)
instrs += LOCAL_SET(typeDataLocal)
genClassOfFromTypeData(LOCAL_GET(typeDataLocal))
}
}
l.tpe
}
private def getNonArrayTypeDataInstr(typeRef: IRTypes.NonArrayTypeRef): WasmInstr =
GLOBAL_GET(WasmGlobalName.forVTable(typeRef))
private def genLoadArrayTypeData(arrayTypeRef: IRTypes.ArrayTypeRef): Unit = {
instrs += getNonArrayTypeDataInstr(arrayTypeRef.base)
instrs += I32_CONST(arrayTypeRef.dimensions)
instrs += CALL(WasmFunctionName.arrayTypeData)
}
private def genClassOfFromTypeData(loadTypeDataInstr: WasmInstr): Unit = {
fctx.block(Types.WasmRefType(Types.WasmHeapType.ClassType)) { nonNullLabel =>
// fast path first
instrs += loadTypeDataInstr
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.classOfIdx)
instrs += BR_ON_NON_NULL(nonNullLabel)
// slow path
instrs += loadTypeDataInstr
instrs += CALL(WasmFunctionName.createClassOf)
}
}
private def genSelect(sel: IRTrees.Select): IRTypes.Type = {
val className = sel.field.name.className
val classInfo = ctx.getClassInfo(className)
// For Select, the receiver can never be a hijacked class, so we can use genTreeAuto
genTreeAuto(sel.qualifier)
if (!classInfo.hasInstances) {
/* The field may not exist in that case, and we cannot look it up.
* However we necessarily have a `null` receiver if we reach this point,
* so we can trap as NPE.
*/
instrs += UNREACHABLE
} else {
val fieldName = WasmFieldName.forClassInstanceField(sel.field.name)
val idx = classInfo.getFieldIdx(sel.field.name)
instrs += STRUCT_GET(WasmStructTypeName.forClass(className), idx)
}
sel.tpe
}
private def genSelectStatic(tree: IRTrees.SelectStatic): IRTypes.Type = {
instrs += GLOBAL_GET(Names.WasmGlobalName.forStaticField(tree.field.name))
tree.tpe
}
private def genStoreModule(t: IRTrees.StoreModule): IRTypes.Type = {
val className = fctx.enclosingClassName.getOrElse {
throw new AssertionError(s"Cannot emit $t at ${t.pos} without enclosing class name")
}
genTreeAuto(IRTrees.This()(IRTypes.ClassType(className))(t.pos))
instrs += GLOBAL_SET(WasmGlobalName.forModuleInstance(className))
IRTypes.NoType
}
/** Push module class instance to the stack.
*
* see: WasmBuilder.genLoadModuleFunc
*/
private def genLoadModule(t: IRTrees.LoadModule): IRTypes.Type = {
instrs += CALL(Names.WasmFunctionName.loadModule(t.className))
t.tpe
}
private def genUnaryOp(unary: IRTrees.UnaryOp): IRTypes.Type = {
import IRTrees.UnaryOp._
genTreeAuto(unary.lhs)
(unary.op: @switch) match {
case Boolean_! =>
instrs += I32_CONST(1)
instrs += I32_XOR
// Widening conversions
case CharToInt | ByteToInt | ShortToInt =>
() // these are no-ops because they are all represented as i32's with the right mathematical value
case IntToLong =>
instrs += I64_EXTEND_I32_S
case IntToDouble =>
instrs += F64_CONVERT_I32_S
case FloatToDouble =>
instrs += F64_PROMOTE_F32
// Narrowing conversions
case IntToChar =>
instrs += I32_CONST(0xFFFF)
instrs += I32_AND
case IntToByte =>
instrs += I32_EXTEND8_S
case IntToShort =>
instrs += I32_EXTEND16_S
case LongToInt =>
instrs += I32_WRAP_I64
case DoubleToInt =>
instrs += I32_TRUNC_SAT_F64_S
case DoubleToFloat =>
instrs += F32_DEMOTE_F64
// Long <-> Double (neither widening nor narrowing)
case LongToDouble =>
instrs += F64_CONVERT_I64_S
case DoubleToLong =>
instrs += I64_TRUNC_SAT_F64_S
// Long -> Float (neither widening nor narrowing), introduced in 1.6
case LongToFloat =>
instrs += F32_CONVERT_I64_S
// String.length, introduced in 1.11
case String_length =>
instrs += CALL(WasmFunctionName.stringLength)
}
unary.tpe
}
private def genBinaryOp(binary: IRTrees.BinaryOp): IRTypes.Type = {
import IRTrees.BinaryOp
def genLongShiftOp(shiftInstr: WasmInstr): IRTypes.Type = {
genTree(binary.lhs, IRTypes.LongType)
genTree(binary.rhs, IRTypes.IntType)
instrs += I64_EXTEND_I32_S
instrs += shiftInstr
IRTypes.LongType
}
binary.op match {
case BinaryOp.=== | BinaryOp.!== => genEq(binary)
case BinaryOp.String_+ => genStringConcat(binary.lhs, binary.rhs)
case BinaryOp.Long_<< => genLongShiftOp(I64_SHL)
case BinaryOp.Long_>>> => genLongShiftOp(I64_SHR_U)
case BinaryOp.Long_>> => genLongShiftOp(I64_SHR_S)
/* Floating point remainders are specified by
* https://262.ecma-international.org/#sec-numeric-types-number-remainder
* which says that it is equivalent to the C library function `fmod`.
* For `Float`s, we promote and demote to `Double`s.
* `fmod` seems quite hard to correctly implement, so we delegate to a
* JavaScript Helper.
* (The naive function `x - trunc(x / y) * y` that we can find on the
* Web does not work.)
*/
case BinaryOp.Float_% =>
genTree(binary.lhs, IRTypes.FloatType)
instrs += F64_PROMOTE_F32
genTree(binary.rhs, IRTypes.FloatType)
instrs += F64_PROMOTE_F32
instrs += CALL(WasmFunctionName.fmod)
instrs += F32_DEMOTE_F64
IRTypes.FloatType
case BinaryOp.Double_% =>
genTree(binary.lhs, IRTypes.DoubleType)
genTree(binary.rhs, IRTypes.DoubleType)
instrs += CALL(WasmFunctionName.fmod)
IRTypes.DoubleType
// New in 1.11
case BinaryOp.String_charAt =>