forked from tanishiking/scala-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHelperFunctions.scala
1898 lines (1627 loc) · 67.8 KB
/
HelperFunctions.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.ir2wasm
import org.scalajs.ir.{Trees => IRTrees}
import org.scalajs.ir.{Types => IRTypes}
import org.scalajs.ir.{Names => IRNames}
import org.scalajs.linker.standard.LinkedClass
import org.scalajs.ir.ClassKind
import wasm.wasm4s._
import wasm.wasm4s.WasmContext._
import wasm.wasm4s.Names._
import wasm.wasm4s.Types._
import wasm.wasm4s.WasmInstr._
import EmbeddedConstants._
import TypeTransformer._
import wasm4s.Defaults
object HelperFunctions {
def genGlobalHelpers()(implicit ctx: WasmContext): Unit = {
genStringLiteral()
genCreateStringFromData()
genTypeDataName()
genCreateClassOf()
genGetClassOf()
genArrayTypeData()
genIsInstance()
genIsAssignableFromExternal()
genIsAssignableFrom()
genCheckCast()
genGetComponentType()
genNewArrayOfThisClass()
genAnyGetClass()
genNewArrayObject()
genIdentityHashCode()
genSearchReflectiveProxy()
}
private def genStringLiteral()(implicit ctx: WasmContext): Unit = {
import WasmTypeName.WasmArrayTypeName
val fctx = WasmFunctionContext(
WasmFunctionName.stringLiteral,
List("offset" -> WasmInt32, "size" -> WasmInt32, "stringIndex" -> WasmInt32),
List(WasmRefType.any)
)
val List(offsetParam, sizeParam, stringIndexParam) = fctx.paramIndices
val str = fctx.addLocal("str", WasmRefType.any)
import fctx.instrs
fctx.block(WasmRefType.any) { cacheHit =>
instrs += GLOBAL_GET(WasmGlobalName.stringLiteralCache)
instrs += LOCAL_GET(stringIndexParam)
instrs += ARRAY_GET(WasmArrayTypeName.anyArray)
instrs += BR_ON_NON_NULL(cacheHit)
// cache miss, create a new string and cache it
instrs += GLOBAL_GET(WasmGlobalName.stringLiteralCache)
instrs += LOCAL_GET(stringIndexParam)
instrs += LOCAL_GET(offsetParam)
instrs += LOCAL_GET(sizeParam)
instrs += ARRAY_NEW_DATA(WasmArrayTypeName.i16Array, WasmDataName.string)
instrs += CALL(WasmFunctionName.createStringFromData)
instrs += LOCAL_TEE(str)
instrs += ARRAY_SET(WasmArrayTypeName.anyArray)
instrs += LOCAL_GET(str)
}
fctx.buildAndAddToContext()
}
/** `createStringFromData: (ref array u16) -> (ref any)` (representing a `string`). */
private def genCreateStringFromData()(implicit ctx: WasmContext): Unit = {
import WasmTypeName.WasmArrayTypeName
val dataType = WasmRefType(WasmArrayTypeName.i16Array)
val fctx = WasmFunctionContext(
WasmFunctionName.createStringFromData,
List("data" -> dataType),
List(WasmRefType.any)
)
val List(dataParam) = fctx.paramIndices
import fctx.instrs
val lenLocal = fctx.addLocal("len", WasmInt32)
val iLocal = fctx.addLocal("i", WasmInt32)
val resultLocal = fctx.addLocal("result", WasmRefType.any)
// len := data.length
instrs += LOCAL_GET(dataParam)
instrs += ARRAY_LEN
instrs += LOCAL_SET(lenLocal)
// i := 0
instrs += I32_CONST(0)
instrs += LOCAL_SET(iLocal)
// result := ""
instrs += CALL(WasmFunctionName.emptyString)
instrs += LOCAL_SET(resultLocal)
fctx.loop() { labelLoop =>
// if i == len
instrs += LOCAL_GET(iLocal)
instrs += LOCAL_GET(lenLocal)
instrs += I32_EQ
fctx.ifThen() {
// then return result
instrs += LOCAL_GET(resultLocal)
instrs += RETURN
}
// result := concat(result, charToString(data(i)))
instrs += LOCAL_GET(resultLocal)
instrs += LOCAL_GET(dataParam)
instrs += LOCAL_GET(iLocal)
instrs += ARRAY_GET_U(WasmArrayTypeName.i16Array)
instrs += CALL(WasmFunctionName.charToString)
instrs += CALL(WasmFunctionName.stringConcat)
instrs += LOCAL_SET(resultLocal)
// i := i - 1
instrs += LOCAL_GET(iLocal)
instrs += I32_CONST(1)
instrs += I32_ADD
instrs += LOCAL_SET(iLocal)
// loop back to the beginning
instrs += BR(labelLoop)
} // end loop $loop
instrs += UNREACHABLE
fctx.buildAndAddToContext()
}
/** `typeDataName: (ref typeData) -> (ref any)` (representing a `string`).
*
* Initializes the `name` field of the given `typeData` if that was not done yet, and returns its
* value.
*
* The computed value is specified by `java.lang.Class.getName()`. See also the documentation on
* [[Names.StructFieldIdx.typeData.name]] for details.
*
* @see
* [[https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Class.html#getName()]]
*/
private def genTypeDataName()(implicit ctx: WasmContext): Unit = {
import WasmTypeName._
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val nameDataType = WasmRefType(WasmArrayTypeName.i16Array)
val fctx = WasmFunctionContext(
WasmFunctionName.typeDataName,
List("typeData" -> typeDataType),
List(WasmRefType.any)
)
val List(typeDataParam) = fctx.paramIndices
import fctx.instrs
val componentTypeDataLocal = fctx.addLocal("componentTypeData", typeDataType)
val componentNameDataLocal = fctx.addLocal("componentNameData", nameDataType)
val firstCharLocal = fctx.addLocal("firstChar", WasmInt32)
val nameLocal = fctx.addLocal("name", WasmRefType.any)
fctx.block(WasmRefType.any) { alreadyInitializedLabel =>
// br_on_non_null $alreadyInitialized typeData.name
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.nameIdx)
instrs += BR_ON_NON_NULL(alreadyInitializedLabel)
// for the STRUCT_SET typeData.name near the end
instrs += LOCAL_GET(typeDataParam)
// if typeData.kind == KindArray
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.kindIdx)
instrs += I32_CONST(KindArray)
instrs += I32_EQ
fctx.ifThenElse(WasmRefType.any) {
// it is an array; compute its name from the component type name
// <top of stack> := "[", for the CALL to stringConcat near the end
instrs += I32_CONST('['.toInt)
instrs += CALL(WasmFunctionName.charToString)
// componentTypeData := ref_as_non_null(typeData.componentType)
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(
WasmStructTypeName.typeData,
WasmFieldIdx.typeData.componentTypeIdx
)
instrs += REF_AS_NOT_NULL
instrs += LOCAL_SET(componentTypeDataLocal)
// switch (componentTypeData.kind)
// the result of this switch is the string that must come after "["
fctx.switch(WasmRefType.any) { () =>
// scrutinee
instrs += LOCAL_GET(componentTypeDataLocal)
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.kindIdx)
}(
List(KindBoolean) -> { () =>
instrs += I32_CONST('Z'.toInt)
instrs += CALL(WasmFunctionName.charToString)
},
List(KindChar) -> { () =>
instrs += I32_CONST('C'.toInt)
instrs += CALL(WasmFunctionName.charToString)
},
List(KindByte) -> { () =>
instrs += I32_CONST('B'.toInt)
instrs += CALL(WasmFunctionName.charToString)
},
List(KindShort) -> { () =>
instrs += I32_CONST('S'.toInt)
instrs += CALL(WasmFunctionName.charToString)
},
List(KindInt) -> { () =>
instrs += I32_CONST('I'.toInt)
instrs += CALL(WasmFunctionName.charToString)
},
List(KindLong) -> { () =>
instrs += I32_CONST('J'.toInt)
instrs += CALL(WasmFunctionName.charToString)
},
List(KindFloat) -> { () =>
instrs += I32_CONST('F'.toInt)
instrs += CALL(WasmFunctionName.charToString)
},
List(KindDouble) -> { () =>
instrs += I32_CONST('D'.toInt)
instrs += CALL(WasmFunctionName.charToString)
},
List(KindArray) -> { () =>
// the component type is an array; get its own name
instrs += LOCAL_GET(componentTypeDataLocal)
instrs += CALL(WasmFunctionName.typeDataName)
}
) { () =>
// default: the component type is neither a primitive nor an array;
// concatenate "L" + <its own name> + ";"
instrs += I32_CONST('L'.toInt)
instrs += CALL(WasmFunctionName.charToString)
instrs += LOCAL_GET(componentTypeDataLocal)
instrs += CALL(WasmFunctionName.typeDataName)
instrs += CALL(WasmFunctionName.stringConcat)
instrs += I32_CONST(';'.toInt)
instrs += CALL(WasmFunctionName.charToString)
instrs += CALL(WasmFunctionName.stringConcat)
}
// At this point, the stack contains "[" and the string that must be concatenated with it
instrs += CALL(WasmFunctionName.stringConcat)
} {
// it is not an array; its name is stored in nameData
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(
WasmStructTypeName.typeData,
WasmFieldIdx.typeData.nameDataIdx
)
instrs += REF_AS_NOT_NULL
instrs += CALL(WasmFunctionName.createStringFromData)
}
// typeData.name := <top of stack> ; leave it on the stack
instrs += LOCAL_TEE(nameLocal)
instrs += STRUCT_SET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.nameIdx)
instrs += LOCAL_GET(nameLocal)
}
fctx.buildAndAddToContext()
}
/** `createClassOf: (ref typeData) -> (ref jlClass)`.
*
* Creates the unique `java.lang.Class` instance associated with the given `typeData`, stores it
* in its `classOfValue` field, and returns it.
*
* Must be called only if the `classOfValue` of the typeData is null. All call sites must deal
* with the non-null case as a fast-path.
*/
private def genCreateClassOf()(implicit ctx: WasmContext): Unit = {
import WasmTypeName.WasmStructTypeName
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val fctx = WasmFunctionContext(
WasmFunctionName.createClassOf,
List("typeData" -> typeDataType),
List(WasmRefType(WasmHeapType.ClassType))
)
val List(typeDataParam) = fctx.paramIndices
import fctx.instrs
val classInstanceLocal = fctx.addLocal("classInstance", WasmRefType(WasmHeapType.ClassType))
// classInstance := newDefault$java.lang.Class()
// leave it on the stack for the constructor call
instrs += CALL(WasmFunctionName.newDefault(IRNames.ClassClass))
instrs += LOCAL_TEE(classInstanceLocal)
/* The JS object containing metadata to pass as argument to the `jl.Class` constructor.
* Specified by https://lampwww.epfl.ch/~doeraene/sjsir-semantics/#sec-sjsir-createclassdataof
* Leave it on the stack.
*/
instrs += CALL(WasmFunctionName.jsNewObject)
// "__typeData": typeData (TODO hide this better? although nobody will notice anyway)
instrs ++= ctx.getConstantStringInstr("__typeData")
instrs += LOCAL_GET(typeDataParam)
instrs += CALL(WasmFunctionName.jsObjectPush)
// "name": typeDataName(typeData)
instrs ++= ctx.getConstantStringInstr("name")
instrs += LOCAL_GET(typeDataParam)
instrs += CALL(WasmFunctionName.typeDataName)
instrs += CALL(WasmFunctionName.jsObjectPush)
// "isPrimitive": (typeData.kind <= KindLastPrimitive)
instrs ++= ctx.getConstantStringInstr("isPrimitive")
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.kindIdx)
instrs += I32_CONST(KindLastPrimitive)
instrs += I32_LE_U
instrs += CALL(WasmFunctionName.box(IRTypes.BooleanRef))
instrs += CALL(WasmFunctionName.jsObjectPush)
// "isArrayClass": (typeData.kind == KindArray)
instrs ++= ctx.getConstantStringInstr("isArrayClass")
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.kindIdx)
instrs += I32_CONST(KindArray)
instrs += I32_EQ
instrs += CALL(WasmFunctionName.box(IRTypes.BooleanRef))
instrs += CALL(WasmFunctionName.jsObjectPush)
// "isInterface": (typeData.kind == KindInterface)
instrs ++= ctx.getConstantStringInstr("isInterface")
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.kindIdx)
instrs += I32_CONST(KindInterface)
instrs += I32_EQ
instrs += CALL(WasmFunctionName.box(IRTypes.BooleanRef))
instrs += CALL(WasmFunctionName.jsObjectPush)
// "isInstance": closure(isInstance, typeData)
instrs ++= ctx.getConstantStringInstr("isInstance")
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.isInstance)
instrs += LOCAL_GET(typeDataParam)
instrs += CALL(WasmFunctionName.closure)
instrs += CALL(WasmFunctionName.jsObjectPush)
// "isAssignableFrom": closure(isAssignableFrom, typeData)
instrs ++= ctx.getConstantStringInstr("isAssignableFrom")
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.isAssignableFromExternal)
instrs += LOCAL_GET(typeDataParam)
instrs += CALL(WasmFunctionName.closure)
instrs += CALL(WasmFunctionName.jsObjectPush)
// "checkCast": closure(checkCast, typeData)
instrs ++= ctx.getConstantStringInstr("checkCast")
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.checkCast)
instrs += LOCAL_GET(typeDataParam)
instrs += CALL(WasmFunctionName.closure)
instrs += CALL(WasmFunctionName.jsObjectPush)
// "isAssignableFrom": closure(isAssignableFrom, typeData)
// "getComponentType": closure(getComponentType, typeData)
instrs ++= ctx.getConstantStringInstr("getComponentType")
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.getComponentType)
instrs += LOCAL_GET(typeDataParam)
instrs += CALL(WasmFunctionName.closure)
instrs += CALL(WasmFunctionName.jsObjectPush)
// "newArrayOfThisClass": closure(newArrayOfThisClass, typeData)
instrs ++= ctx.getConstantStringInstr("newArrayOfThisClass")
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.newArrayOfThisClass)
instrs += LOCAL_GET(typeDataParam)
instrs += CALL(WasmFunctionName.closure)
instrs += CALL(WasmFunctionName.jsObjectPush)
// Call java.lang.Class::<init>(dataObject)
instrs += CALL(
WasmFunctionName(
IRTrees.MemberNamespace.Constructor,
IRNames.ClassClass,
SpecialNames.ClassCtor
)
)
// typeData.classOf := classInstance
instrs += LOCAL_GET(typeDataParam)
instrs += LOCAL_GET(classInstanceLocal)
instrs += STRUCT_SET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.classOfIdx)
// <top-of-stack> := classInstance for the implicit return
instrs += LOCAL_GET(classInstanceLocal)
fctx.buildAndAddToContext()
}
/** `getClassOf: (ref typeData) -> (ref jlClass)`.
*
* Initializes the `java.lang.Class` instance associated with the given `typeData` if not already
* done, and returns it.
*
* This includes the fast-path and the slow-path to `createClassOf`, for call sites that are not
* performance-sensitive.
*/
private def genGetClassOf()(implicit ctx: WasmContext): Unit = {
import WasmTypeName.WasmStructTypeName
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val fctx = WasmFunctionContext(
WasmFunctionName.getClassOf,
List("typeData" -> typeDataType),
List(WasmRefType(WasmHeapType.ClassType))
)
val List(typeDataParam) = fctx.paramIndices
import fctx.instrs
fctx.block(WasmRefType(WasmHeapType.ClassType)) { alreadyInitializedLabel =>
// fast path
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.classOfIdx)
instrs += BR_ON_NON_NULL(alreadyInitializedLabel)
// slow path
instrs += LOCAL_GET(typeDataParam)
instrs += CALL(WasmFunctionName.createClassOf)
} // end bock alreadyInitializedLabel
fctx.buildAndAddToContext()
}
/** `arrayTypeData: (ref typeData), i32 -> (ref $java.lang.Object___vtable)`.
*
* Returns the typeData/vtable of an array with `dims` dimensions over the given typeData. `dims`
* must be be strictly positive.
*/
private def genArrayTypeData()(implicit ctx: WasmContext): Unit = {
import WasmTypeName._
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val objectVTableType = WasmRefType(WasmTypeName.WasmStructTypeName.ObjectVTable)
/* Array classes extend Cloneable, Serializable and Object.
* Filter out the ones that do not have run-time type info at all, as
* we do for other classes.
*/
val strictAncestors =
List(IRNames.CloneableClass, IRNames.SerializableClass, IRNames.ObjectClass)
.filter(name => ctx.getClassInfoOption(name).exists(_.hasRuntimeTypeInfo))
val fctx = WasmFunctionContext(
WasmFunctionName.arrayTypeData,
List("typeData" -> typeDataType, "dims" -> WasmInt32),
List(objectVTableType)
)
val List(typeDataParam, dimsParam) = fctx.paramIndices
import fctx.instrs
val arrayTypeDataLocal = fctx.addLocal("arrayTypeData", objectVTableType)
fctx.loop() { loopLabel =>
fctx.block(objectVTableType) { arrayOfIsNonNullLabel =>
// br_on_non_null $arrayOfIsNonNull typeData.arrayOf
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(
WasmStructTypeName.typeData,
WasmFieldIdx.typeData.arrayOfIdx
)
instrs += BR_ON_NON_NULL(arrayOfIsNonNullLabel)
// <top-of-stack> := typeData ; for the <old typeData>.arrayOf := ... later on
instrs += LOCAL_GET(typeDataParam)
// typeData := new typeData(...)
instrs += REF_NULL(WasmHeapType.None) // nameData
instrs += I32_CONST(KindArray) // kind = KindArray
instrs += I32_CONST(0) // specialInstanceTypes = 0
// strictAncestors
for (strictAncestor <- strictAncestors)
instrs += GLOBAL_GET(WasmGlobalName.forVTable(strictAncestor))
instrs += ARRAY_NEW_FIXED(
WasmArrayTypeName.typeDataArray,
strictAncestors.size
)
instrs += LOCAL_GET(typeDataParam) // componentType
instrs += REF_NULL(WasmHeapType.None) // name
instrs += REF_NULL(WasmHeapType.None) // classOf
instrs += REF_NULL(WasmHeapType.None) // arrayOf
// clone
fctx.switch(WasmRefType(ctx.cloneFunctionTypeName)) { () =>
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, WasmFieldIdx.typeData.kindIdx)
}(
List(KindBoolean) -> { () =>
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.clone(IRTypes.BooleanRef))
},
List(KindChar) -> { () =>
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.clone(IRTypes.CharRef))
},
List(KindByte) -> { () =>
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.clone(IRTypes.ByteRef))
},
List(KindShort) -> { () =>
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.clone(IRTypes.ShortRef))
},
List(KindInt) -> { () =>
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.clone(IRTypes.IntRef))
},
List(KindLong) -> { () =>
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.clone(IRTypes.LongRef))
},
List(KindFloat) -> { () =>
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.clone(IRTypes.FloatRef))
},
List(KindDouble) -> { () =>
instrs += ctx.refFuncWithDeclaration(WasmFunctionName.clone(IRTypes.DoubleRef))
}
) { () =>
instrs += ctx.refFuncWithDeclaration(
WasmFunctionName.clone(IRTypes.ClassRef(IRNames.ObjectClass))
)
}
// isJSClassInstance
instrs += REF_NULL(WasmHeapType.NoFunc)
// reflectiveProxies
instrs += ARRAY_NEW_FIXED(WasmArrayTypeName.reflectiveProxies, 0) // TODO
instrs ++= ctx
.calculateGlobalVTable(IRNames.ObjectClass)
.map(method => WasmInstr.REF_FUNC(method.name))
instrs += STRUCT_NEW(WasmTypeName.WasmStructTypeName.ObjectVTable)
instrs += LOCAL_TEE(arrayTypeDataLocal)
// <old typeData>.arrayOf := typeData
instrs += STRUCT_SET(
WasmStructTypeName.typeData,
WasmFieldIdx.typeData.arrayOfIdx
)
// put arrayTypeData back on the stack
instrs += LOCAL_GET(arrayTypeDataLocal)
} // end block $arrayOfIsNonNullLabel
// dims := dims - 1 -- leave dims on the stack
instrs += LOCAL_GET(dimsParam)
instrs += I32_CONST(1)
instrs += I32_SUB
instrs += LOCAL_TEE(dimsParam)
// if dims == 0 then
// return typeData.arrayOf (which is on the stack)
instrs += I32_EQZ
fctx.ifThen(WasmFunctionSignature(List(objectVTableType), List(objectVTableType))) {
instrs += RETURN
}
// typeData := typeData.arrayOf (which is on the stack), then loop back to the beginning
instrs += LOCAL_SET(typeDataParam)
instrs += BR(loopLabel)
} // end loop $loop
instrs += UNREACHABLE
fctx.buildAndAddToContext()
}
/** `isInstance: (ref typeData), anyref -> i32` (a boolean).
*
* Tests whether the given value is a non-null instance of the given type.
*
* Specified by `"isInstance"` at
* [[https://lampwww.epfl.ch/~doeraene/sjsir-semantics/#sec-sjsir-createclassdataof]].
*/
private def genIsInstance()(implicit ctx: WasmContext): Unit = {
import WasmTypeName.WasmStructTypeName
import WasmFieldIdx.typeData._
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val objectRefType = WasmRefType(WasmTypeName.WasmStructTypeName.forClass(IRNames.ObjectClass))
val fctx = WasmFunctionContext(
WasmFunctionName.isInstance,
List("typeData" -> typeDataType, "value" -> WasmRefType.anyref),
List(WasmInt32)
)
val List(typeDataParam, valueParam) = fctx.paramIndices
import fctx.instrs
val valueNonNullLocal = fctx.addLocal("valueNonNull", WasmRefType.any)
val specialInstanceTypesLocal = fctx.addLocal("specialInstanceTypes", WasmInt32)
// switch (typeData.kind)
fctx.switch(WasmInt32) { () =>
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, kindIdx)
}(
// case anyPrimitiveKind => false
(KindVoid to KindLastPrimitive).toList -> { () =>
instrs += I32_CONST(0)
},
// case KindObject => value ne null
List(KindObject) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += REF_IS_NULL
instrs += I32_EQZ
},
// for each boxed class, the corresponding primitive type test
List(KindBoxedUnit) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += CALL(WasmFunctionName.isUndef)
},
List(KindBoxedBoolean) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += CALL(WasmFunctionName.typeTest(IRTypes.BooleanRef))
},
List(KindBoxedCharacter) -> { () =>
instrs += LOCAL_GET(valueParam)
val structTypeName = WasmStructTypeName.forClass(SpecialNames.CharBoxClass)
instrs += REF_TEST(WasmRefType(structTypeName))
},
List(KindBoxedByte) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += CALL(WasmFunctionName.typeTest(IRTypes.ByteRef))
},
List(KindBoxedShort) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += CALL(WasmFunctionName.typeTest(IRTypes.ShortRef))
},
List(KindBoxedInteger) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += CALL(WasmFunctionName.typeTest(IRTypes.IntRef))
},
List(KindBoxedLong) -> { () =>
instrs += LOCAL_GET(valueParam)
val structTypeName = WasmStructTypeName.forClass(SpecialNames.LongBoxClass)
instrs += REF_TEST(WasmRefType(structTypeName))
},
List(KindBoxedFloat) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += CALL(WasmFunctionName.typeTest(IRTypes.FloatRef))
},
List(KindBoxedDouble) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += CALL(WasmFunctionName.typeTest(IRTypes.DoubleRef))
},
List(KindBoxedString) -> { () =>
instrs += LOCAL_GET(valueParam)
instrs += CALL(WasmFunctionName.isString)
},
// case KindJSType => call typeData.isJSClassInstance(value) or throw if it is null
List(KindJSType) -> { () =>
fctx.block(WasmRefType.anyref) { isJSClassInstanceIsNull =>
// Load value as the argument to the function
instrs += LOCAL_GET(valueParam)
// Load the function reference; break if null
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, isJSClassInstanceIdx)
instrs += BR_ON_NULL(isJSClassInstanceIsNull)
// Call the function
instrs += CALL_REF(ctx.isJSClassInstanceFuncTypeName)
instrs += RETURN
}
instrs += DROP // drop `value` which was left on the stack
// throw new TypeError("...")
instrs ++= ctx.getConstantStringInstr("TypeError")
instrs += CALL(WasmFunctionName.jsGlobalRefGet)
instrs += CALL(WasmFunctionName.jsNewArray)
instrs ++= ctx.getConstantStringInstr(
"Cannot call isInstance() on a Class representing a JS trait/object"
)
instrs += CALL(WasmFunctionName.jsArrayPush)
instrs += CALL(WasmFunctionName.jsNew)
instrs += EXTERN_CONVERT_ANY
instrs += THROW(ctx.exceptionTagName)
}
) { () =>
// case _ =>
// valueNonNull := as_non_null value; return false if null
fctx.block(WasmRefType.any) { nonNullLabel =>
instrs += LOCAL_GET(valueParam)
instrs += BR_ON_NON_NULL(nonNullLabel)
instrs += I32_CONST(0)
instrs += RETURN
}
instrs += LOCAL_SET(valueNonNullLocal)
/* If `typeData` represents an ancestor of a hijacked classes, we have to
* answer `true` if `valueNonNull` is a primitive instance of any of the
* hijacked classes that ancestor class/interface. For example, for
* `Comparable`, we have to answer `true` if `valueNonNull` is a primitive
* boolean, number or string.
*
* To do that, we use `jsValueType` and `typeData.specialInstanceTypes`.
*
* We test whether `jsValueType(valueNonNull)` is in the set represented by
* `specialInstanceTypes`. Since the latter is a bitset where the bit
* indices correspond to the values returned by `jsValueType`, we have to
* test whether
*
* ((1 << jsValueType(valueNonNull)) & specialInstanceTypes) != 0
*
* Since computing `jsValueType` is somewhat expensive, we first test
* whether `specialInstanceTypes != 0` before calling `jsValueType`.
*
* There is a more elaborated concrete example of this algorithm in
* `genInstanceTest`.
*/
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, specialInstanceTypesIdx)
instrs += LOCAL_TEE(specialInstanceTypesLocal)
instrs += I32_CONST(0)
instrs += I32_NE
fctx.ifThen() {
// Load (1 << jsValueType(valueNonNull))
instrs += I32_CONST(1)
instrs += LOCAL_GET(valueNonNullLocal)
instrs += CALL(WasmFunctionName.jsValueType)
instrs += I32_SHL
// if ((... & specialInstanceTypes) != 0)
instrs += LOCAL_GET(specialInstanceTypesLocal)
instrs += I32_AND
instrs += I32_CONST(0)
instrs += I32_NE
fctx.ifThen() {
// then return true
instrs += I32_CONST(1)
instrs += RETURN
}
}
// Get the vtable and delegate to isAssignableFrom
// Load typeData
instrs += LOCAL_GET(typeDataParam)
// Load the vtable; return false if it is not one of our object
fctx.block(objectRefType) { ourObjectLabel =>
// Try cast to jl.Object
instrs += LOCAL_GET(valueNonNullLocal)
instrs += BR_ON_CAST(
ourObjectLabel,
WasmRefType.any,
WasmRefType(objectRefType.heapType)
)
// on cast fail, return false
instrs += I32_CONST(0)
instrs += RETURN
}
instrs += STRUCT_GET(
WasmStructTypeName.forClass(IRNames.ObjectClass),
WasmFieldIdx.vtable
)
// Call isAssignableFrom
instrs += CALL(WasmFunctionName.isAssignableFrom)
}
fctx.buildAndAddToContext()
}
/** `isAssignableFromExternal: (ref typeData), anyref -> i32` (a boolean).
*
* This is the underlying func for the `isAssignableFrom()` closure inside class data objects.
*/
private def genIsAssignableFromExternal()(implicit ctx: WasmContext): Unit = {
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val fctx = WasmFunctionContext(
WasmFunctionName.isAssignableFromExternal,
List("typeData" -> typeDataType, "from" -> WasmRefType.anyref),
List(WasmInt32)
)
val List(typeDataParam, fromParam) = fctx.paramIndices
import fctx.instrs
// load typeData
instrs += LOCAL_GET(typeDataParam)
// load ref.cast<typeData> from["__typeData"] (as a JS selection)
instrs += LOCAL_GET(fromParam)
instrs ++= ctx.getConstantStringInstr("__typeData")
instrs += CALL(WasmFunctionName.jsSelect)
instrs += REF_CAST(WasmRefType(typeDataType.heapType))
// delegate to isAssignableFrom
instrs += CALL(WasmFunctionName.isAssignableFrom)
fctx.buildAndAddToContext()
}
/** `isAssignableFrom: (ref typeData), (ref typeData) -> i32` (a boolean).
*
* Specified by `java.lang.Class.isAssignableFrom(Class)`.
*/
private def genIsAssignableFrom()(implicit ctx: WasmContext): Unit = {
import WasmTypeName._
import WasmFieldIdx.typeData._
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val fctx = WasmFunctionContext(
WasmFunctionName.isAssignableFrom,
List("typeData" -> typeDataType, "fromTypeData" -> typeDataType),
List(WasmInt32)
)
val List(typeDataParam, fromTypeDataParam) = fctx.paramIndices
import fctx.instrs
val fromAncestorsLocal = fctx.addLocal(
"fromAncestorsLocal",
WasmRefType(WasmArrayTypeName.typeDataArray)
)
val lenLocal = fctx.addLocal("len", WasmInt32)
val iLocal = fctx.addLocal("i", WasmInt32)
// if (fromTypeData eq typeData)
instrs += LOCAL_GET(fromTypeDataParam)
instrs += LOCAL_GET(typeDataParam)
instrs += REF_EQ
fctx.ifThen() {
// then return true
instrs += I32_CONST(1)
instrs += RETURN
}
// "Tail call" loop for diving into array component types
fctx.loop(WasmInt32) { loopForArrayLabel =>
// switch (typeData.kind)
fctx.switch(WasmInt32) { () =>
// typeData.kind
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, kindIdx)
}(
// case anyPrimitiveKind => return false
(KindVoid to KindLastPrimitive).toList -> { () =>
instrs += I32_CONST(0)
},
// case KindArray => check that from is an array, recurse into component types
List(KindArray) -> { () =>
fctx.block() { fromComponentTypeIsNullLabel =>
// fromTypeData := fromTypeData.componentType; jump out if null
instrs += LOCAL_GET(fromTypeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, componentTypeIdx)
instrs += BR_ON_NULL(fromComponentTypeIsNullLabel)
instrs += LOCAL_SET(fromTypeDataParam)
// typeData := ref.as_non_null typeData.componentType (OK because KindArray)
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, componentTypeIdx)
instrs += REF_AS_NOT_NULL
instrs += LOCAL_SET(typeDataParam)
// loop back ("tail call")
instrs += BR(loopForArrayLabel)
}
// return false
instrs += I32_CONST(0)
},
// case KindObject => return (fromTypeData.kind > KindLastPrimitive)
List(KindObject) -> { () =>
instrs += LOCAL_GET(fromTypeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, kindIdx)
instrs += I32_CONST(KindLastPrimitive)
instrs += I32_GT_U
}
) { () =>
// All other cases: test whether `fromTypeData.strictAncestors` contains `typeData`
fctx.block() { fromAncestorsIsNullLabel =>
// fromAncestors := fromTypeData.strictAncestors; go to fromAncestorsIsNull if null
instrs += LOCAL_GET(fromTypeDataParam)
instrs += STRUCT_GET(WasmStructTypeName.typeData, strictAncestorsIdx)
instrs += BR_ON_NULL(fromAncestorsIsNullLabel)
instrs += LOCAL_TEE(fromAncestorsLocal)
// if fromAncestors contains typeData, return true
// len := fromAncestors.length
instrs += ARRAY_LEN
instrs += LOCAL_SET(lenLocal)
// i := 0
instrs += I32_CONST(0)
instrs += LOCAL_SET(iLocal)
// while (i != len)
fctx.whileLoop() {
instrs += LOCAL_GET(iLocal)
instrs += LOCAL_GET(lenLocal)
instrs += I32_NE
} {
// if (fromAncestors[i] eq typeData)
instrs += LOCAL_GET(fromAncestorsLocal)
instrs += LOCAL_GET(iLocal)
instrs += ARRAY_GET(WasmArrayTypeName.typeDataArray)
instrs += LOCAL_GET(typeDataParam)
instrs += REF_EQ
fctx.ifThen() {
// then return true
instrs += I32_CONST(1)
instrs += RETURN
}
// i := i + 1
instrs += LOCAL_GET(iLocal)
instrs += I32_CONST(1)
instrs += I32_ADD
instrs += LOCAL_SET(iLocal)
}
}
// from.strictAncestors is null or does not contain typeData
// return false
instrs += I32_CONST(0)
}
}
fctx.buildAndAddToContext()
}
/** `checkCast: (ref typeData), anyref -> anyref`.
*
* Casts the given value to the given type; subject to undefined behaviors.
*/
private def genCheckCast()(implicit ctx: WasmContext): Unit = {
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val fctx = WasmFunctionContext(
WasmFunctionName.checkCast,
List("typeData" -> typeDataType, "value" -> WasmRefType.anyref),
List(WasmRefType.anyref)
)
val List(typeDataParam, valueParam) = fctx.paramIndices
import fctx.instrs
/* Given that we only implement `CheckedBehavior.Unchecked` semantics for
* now, this is always the identity.
*/
instrs += LOCAL_GET(valueParam)
fctx.buildAndAddToContext()
}
/** `getComponentType: (ref typeData) -> (ref null jlClass)`.
*
* This is the underlying func for the `getComponentType()` closure inside class data objects.
*/
private def genGetComponentType()(implicit ctx: WasmContext): Unit = {
import WasmTypeName.WasmStructTypeName
val typeDataType = WasmRefType(WasmStructType.typeData.name)
val fctx = WasmFunctionContext(
WasmFunctionName.getComponentType,
List("typeData" -> typeDataType),
List(WasmRefType.nullable(WasmHeapType.ClassType))
)
val List(typeDataParam) = fctx.paramIndices
import fctx.instrs
val componentTypeDataLocal = fctx.addLocal("componentTypeData", typeDataType)
fctx.block() { nullResultLabel =>
// Try and extract non-null component type data
instrs += LOCAL_GET(typeDataParam)
instrs += STRUCT_GET(
WasmStructTypeName.typeData,