aboutsummaryrefslogtreecommitdiff
path: root/atomicfu-transformer/src/main/kotlin/kotlinx/atomicfu/transformer/AtomicFUTransformer.kt
blob: c7c262c4801c389687fa6a80323a1205a5970e39 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
/*
 * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

@file:Suppress("EXPERIMENTAL_FEATURE_WARNING")

package kotlinx.atomicfu.transformer

import org.objectweb.asm.*
import org.objectweb.asm.ClassReader.*
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.*
import org.objectweb.asm.commons.*
import org.objectweb.asm.commons.InstructionAdapter.*
import org.objectweb.asm.tree.*
import java.io.*
import java.net.*
import java.util.*

class TypeInfo(val fuType: Type, val originalType: Type, val transformedType: Type)

private const val AFU_PKG = "kotlinx/atomicfu"
private const val JUCA_PKG = "java/util/concurrent/atomic"
private const val JLI_PKG = "java/lang/invoke"
private const val ATOMIC = "atomic"

private const val TRACE = "Trace"
private const val TRACE_BASE = "TraceBase"
private const val TRACE_FORMAT = "TraceFormat"

private val INT_ARRAY_TYPE = getType("[I")
private val LONG_ARRAY_TYPE = getType("[J")
private val BOOLEAN_ARRAY_TYPE = getType("[Z")
private val REF_ARRAY_TYPE = getType("[Ljava/lang/Object;")
private val REF_TYPE = getType("L$AFU_PKG/AtomicRef;")
private val ATOMIC_ARRAY_TYPE = getType("L$AFU_PKG/AtomicArray;")

private val AFU_CLASSES: Map<String, TypeInfo> = mapOf(
    "$AFU_PKG/AtomicInt" to TypeInfo(getObjectType("$JUCA_PKG/AtomicIntegerFieldUpdater"), INT_TYPE, INT_TYPE),
    "$AFU_PKG/AtomicLong" to TypeInfo(getObjectType("$JUCA_PKG/AtomicLongFieldUpdater"), LONG_TYPE, LONG_TYPE),
    "$AFU_PKG/AtomicRef" to TypeInfo(getObjectType("$JUCA_PKG/AtomicReferenceFieldUpdater"), OBJECT_TYPE, OBJECT_TYPE),
    "$AFU_PKG/AtomicBoolean" to TypeInfo(getObjectType("$JUCA_PKG/AtomicIntegerFieldUpdater"), BOOLEAN_TYPE, INT_TYPE),

    "$AFU_PKG/AtomicIntArray" to TypeInfo(getObjectType("$JUCA_PKG/AtomicIntegerArray"), INT_ARRAY_TYPE, INT_ARRAY_TYPE),
    "$AFU_PKG/AtomicLongArray" to TypeInfo(getObjectType("$JUCA_PKG/AtomicLongArray"), LONG_ARRAY_TYPE, LONG_ARRAY_TYPE),
    "$AFU_PKG/AtomicBooleanArray" to TypeInfo(getObjectType("$JUCA_PKG/AtomicIntegerArray"), BOOLEAN_ARRAY_TYPE, INT_ARRAY_TYPE),
    "$AFU_PKG/AtomicArray" to TypeInfo(getObjectType("$JUCA_PKG/AtomicReferenceArray"), REF_ARRAY_TYPE, REF_ARRAY_TYPE),
    "$AFU_PKG/AtomicFU_commonKt" to TypeInfo(getObjectType("$JUCA_PKG/AtomicReferenceArray"), REF_ARRAY_TYPE, REF_ARRAY_TYPE)
)

private val WRAPPER: Map<Type, String> = mapOf(
    INT_TYPE to "java/lang/Integer",
    LONG_TYPE to "java/lang/Long",
    BOOLEAN_TYPE to "java/lang/Boolean"
)

private val ARRAY_ELEMENT_TYPE: Map<Type, Int> = mapOf(
    INT_ARRAY_TYPE to T_INT,
    LONG_ARRAY_TYPE to T_LONG,
    BOOLEAN_ARRAY_TYPE to T_BOOLEAN
)

private val AFU_TYPES: Map<Type, TypeInfo> = AFU_CLASSES.mapKeys { getObjectType(it.key) }

private val METHOD_HANDLES = "$JLI_PKG/MethodHandles"
private val LOOKUP = "$METHOD_HANDLES\$Lookup"
private val VH_TYPE = getObjectType("$JLI_PKG/VarHandle")

private val STRING_TYPE = getObjectType("java/lang/String")
private val CLASS_TYPE = getObjectType("java/lang/Class")

private fun String.prettyStr() = replace('/', '.')

data class MethodId(val owner: String, val name: String, val desc: String, val invokeOpcode: Int) {
    override fun toString(): String = "${owner.prettyStr()}::$name"
}

private const val GET_VALUE = "getValue"
private const val SET_VALUE = "setValue"
private const val GET_SIZE = "getSize"

private const val AFU_CLS = "$AFU_PKG/AtomicFU"
private const val TRACE_KT = "$AFU_PKG/TraceKt"
private const val TRACE_BASE_CLS = "$AFU_PKG/$TRACE_BASE"

private val TRACE_BASE_TYPE = getObjectType(TRACE_BASE_CLS)

private val TRACE_APPEND = MethodId(TRACE_BASE_CLS, "append", getMethodDescriptor(VOID_TYPE, OBJECT_TYPE), INVOKEVIRTUAL)
private val TRACE_APPEND_2 = MethodId(TRACE_BASE_CLS, "append", getMethodDescriptor(VOID_TYPE, OBJECT_TYPE, OBJECT_TYPE), INVOKEVIRTUAL)
private val TRACE_APPEND_3 = MethodId(TRACE_BASE_CLS, "append", getMethodDescriptor(VOID_TYPE, OBJECT_TYPE, OBJECT_TYPE, OBJECT_TYPE), INVOKEVIRTUAL)
private val TRACE_APPEND_4 = MethodId(TRACE_BASE_CLS, "append", getMethodDescriptor(VOID_TYPE, OBJECT_TYPE, OBJECT_TYPE, OBJECT_TYPE, OBJECT_TYPE), INVOKEVIRTUAL)
private val TRACE_DEFAULT_ARGS = "I${OBJECT_TYPE.descriptor}"
private const val DEFAULT = "\$default"
private const val DELEGATE = "\$delegate"

private val TRACE_FACTORY = MethodId(TRACE_KT, TRACE, "(IL$AFU_PKG/$TRACE_FORMAT;)L$AFU_PKG/$TRACE_BASE;", INVOKESTATIC)
private val TRACE_PARTIAL_ARGS_FACTORY = MethodId(TRACE_KT, "$TRACE$DEFAULT", "(IL$AFU_PKG/$TRACE_FORMAT;$TRACE_DEFAULT_ARGS)L$AFU_PKG/$TRACE_BASE;", INVOKESTATIC)

private val FACTORIES: Set<MethodId> = setOf(
    MethodId(AFU_CLS, ATOMIC, "(Ljava/lang/Object;)L$AFU_PKG/AtomicRef;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC, "(I)L$AFU_PKG/AtomicInt;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC, "(J)L$AFU_PKG/AtomicLong;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC, "(Z)L$AFU_PKG/AtomicBoolean;", INVOKESTATIC),

    MethodId("$AFU_PKG/AtomicIntArray", "<init>", "(I)V", INVOKESPECIAL),
    MethodId("$AFU_PKG/AtomicLongArray", "<init>", "(I)V", INVOKESPECIAL),
    MethodId("$AFU_PKG/AtomicBooleanArray", "<init>", "(I)V", INVOKESPECIAL),
    MethodId("$AFU_PKG/AtomicArray", "<init>", "(I)V", INVOKESPECIAL),
    MethodId("$AFU_PKG/AtomicFU_commonKt", "atomicArrayOfNulls", "(I)L$AFU_PKG/AtomicArray;", INVOKESTATIC),

    MethodId(AFU_CLS, ATOMIC, "(Ljava/lang/Object;L$TRACE_BASE_CLS;)L$AFU_PKG/AtomicRef;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC, "(IL$TRACE_BASE_CLS;)L$AFU_PKG/AtomicInt;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC, "(JL$TRACE_BASE_CLS;)L$AFU_PKG/AtomicLong;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC, "(ZL$TRACE_BASE_CLS;)L$AFU_PKG/AtomicBoolean;", INVOKESTATIC),

    MethodId(AFU_CLS, ATOMIC + DEFAULT, "(Ljava/lang/Object;L$TRACE_BASE_CLS;$TRACE_DEFAULT_ARGS)L$AFU_PKG/AtomicRef;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC + DEFAULT, "(IL$TRACE_BASE_CLS;$TRACE_DEFAULT_ARGS)L$AFU_PKG/AtomicInt;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC + DEFAULT, "(JL$TRACE_BASE_CLS;$TRACE_DEFAULT_ARGS)L$AFU_PKG/AtomicLong;", INVOKESTATIC),
    MethodId(AFU_CLS, ATOMIC + DEFAULT, "(ZL$TRACE_BASE_CLS;$TRACE_DEFAULT_ARGS)L$AFU_PKG/AtomicBoolean;", INVOKESTATIC)
)

private operator fun Int.contains(bit: Int) = this and bit != 0

private inline fun code(mv: MethodVisitor, block: InstructionAdapter.() -> Unit) {
    block(InstructionAdapter(mv))
}

private inline fun insns(block: InstructionAdapter.() -> Unit): InsnList {
    val node = MethodNode(ASM5)
    block(InstructionAdapter(node))
    return node.instructions
}

data class FieldId(val owner: String, val name: String, val desc: String) {
    override fun toString(): String = "${owner.prettyStr()}::$name"
}

class FieldInfo(
    val fieldId: FieldId,
    val fieldType: Type,
    val isStatic: Boolean = false
) {
    val owner = fieldId.owner
    val ownerType: Type = getObjectType(owner)
    val typeInfo = AFU_CLASSES.getValue(fieldType.internalName)
    val fuType = typeInfo.fuType
    val isArray = typeInfo.originalType.sort == ARRAY

    // state: updated during analysis
    val accessors = mutableSetOf<MethodId>() // set of accessor method that read the corresponding atomic
    var hasExternalAccess = false // accessed from different package
    var hasAtomicOps = false // has atomic operations operations other than getValue/setValue

    val name: String
        get() = if (hasExternalAccess) mangleInternal(fieldId.name) else fieldId.name
    val fuName: String
        get() {
            val fuName = fieldId.name + '$' + "FU"
            return if (hasExternalAccess) mangleInternal(fuName) else fuName
        }

    val refVolatileClassName = "${owner.replace('.', '/')}$${name.capitalize()}RefVolatile"
    val staticRefVolatileField = refVolatileClassName.substringAfterLast("/").decapitalize()

    fun getPrimitiveType(vh: Boolean): Type = if (vh) typeInfo.originalType else typeInfo.transformedType

    private fun mangleInternal(fieldName: String): String = "$fieldName\$internal"

    override fun toString(): String = "${owner.prettyStr()}::$name"
}

enum class Variant { FU, VH, BOTH }

class AtomicFUTransformer(
    classpath: List<String>,
    inputDir: File,
    outputDir: File = inputDir,
    var variant: Variant = Variant.FU
) : AtomicFUTransformerBase(inputDir, outputDir) {

    private val classPathLoader = URLClassLoader(
        (listOf(inputDir) + (classpath.map { File(it) } - outputDir))
            .map { it.toURI().toURL() }.toTypedArray()
    )

    private val fields = mutableMapOf<FieldId, FieldInfo>()
    private val accessors = mutableMapOf<MethodId, FieldInfo>()
    private val traceFields = mutableSetOf<FieldId>()
    private val traceAccessors = mutableSetOf<MethodId>()
    private val fieldDelegates = mutableMapOf<FieldId, FieldInfo>()
    private val removeMethods = mutableSetOf<MethodId>()

    override fun transform() {
        info("Analyzing in $inputDir")
        val files = inputDir.walk().filter { it.isFile }.toList()
        val needTransform = analyzeFilesForFields(files)
        if (needTransform || outputDir == inputDir) {
            val vh = variant == Variant.VH
            // visit method bodies for external references to fields, runs all logic, fails if anything is wrong
            val needsTransform = analyzeFilesForRefs(files, vh)
            // perform transformation
            info("Transforming to $outputDir")
            files.forEach { file ->
                val bytes = file.readBytes()
                val outBytes = if (file.isClassFile() && file in needsTransform) transformFile(file, bytes, vh) else bytes
                val outFile = file.toOutputFile()
                outFile.mkdirsAndWrite(outBytes)
                if (variant == Variant.BOTH && outBytes !== bytes) {
                    val vhBytes = transformFile(file, bytes, true)
                    val vhFile = outputDir / "META-INF" / "versions" / "9" / file.relativeTo(inputDir).toString()
                    vhFile.mkdirsAndWrite(vhBytes)
                }
            }
        } else {
            info("Nothing to transform -- all classes are up to date")
        }
    }

    // Phase 1: visit methods and fields, register all accessors, collect times
    // Returns 'true' if any files are out of date
    private fun analyzeFilesForFields(files: List<File>): Boolean {
        var needTransform = false
        files.forEach { file ->
            val inpTime = file.lastModified()
            val outTime = file.toOutputFile().lastModified()
            if (inpTime > outTime) needTransform = true
            if (file.isClassFile()) analyzeFileForFields(file)
        }
        if (lastError != null) throw TransformerException("Encountered errors while analyzing fields", lastError)
        return needTransform
    }

    private fun analyzeFileForFields(file: File) {
        file.inputStream().use { ClassReader(it).accept(FieldsCollectorCV(), SKIP_FRAMES) }
    }

    // Phase2: visit method bodies for external references to fields and
    //          run method analysis in "analysisMode" to see which fields need AU/VH generated for them
    // Returns a set of files that need transformation
    private fun analyzeFilesForRefs(files: List<File>, vh: Boolean): Set<File> {
        val result = HashSet<File>()
        files.forEach { file ->
            if (file.isClassFile() && analyzeFileForRefs(file, vh)) result += file
        }
        // Batch analyze all files, report all errors, bail out only at the end
        if (lastError != null) throw TransformerException("Encountered errors while analyzing references", lastError)
        return result
    }

    private fun analyzeFileForRefs(file: File, vh: Boolean): Boolean =
        file.inputStream().use { input ->
            transformed = false // clear global "transformed" flag
            val cv = TransformerCV(null, vh, analyzePhase2 = true)
            try {
                ClassReader(input).accept(cv, SKIP_FRAMES)
            } catch (e: Exception) {
                error("Failed to analyze: $e", cv.sourceInfo)
                e.printStackTrace(System.out)
                if (lastError == null) lastError = e
            }
            transformed // true for classes that need transformation
        }

    // Phase 3: Transform file (only called for files that need to be transformed)
    // Returns updated byte array for class data
    private fun transformFile(file: File, bytes: ByteArray, vh: Boolean): ByteArray {
        transformed = false // clear global "transformed" flag
        val cw = CW()
        val cv = TransformerCV(cw, vh, analyzePhase2 = false)
        try {
            ClassReader(ByteArrayInputStream(bytes)).accept(cv, SKIP_FRAMES)
        } catch (e: Throwable) {
            error("Failed to transform: $e", cv.sourceInfo)
            e.printStackTrace(System.out)
            if (lastError == null) lastError = e
        }
        if (!transformed) error("Invoked transformFile on a file that does not need transformation: $file")
        if (lastError != null) throw TransformerException("Encountered errors while transforming: $file", lastError)
        info("Transformed $file")
        return cw.toByteArray() // write transformed bytes
    }

    private abstract inner class CV(cv: ClassVisitor?) : ClassVisitor(ASM5, cv) {
        lateinit var className: String

        override fun visit(
            version: Int,
            access: Int,
            name: String,
            signature: String?,
            superName: String?,
            interfaces: Array<out String>?
        ) {
            className = name
            super.visit(version, access, name, signature, superName, interfaces)
        }
    }

    private fun registerField(field: FieldId, fieldType: Type, isStatic: Boolean): FieldInfo {
        val result = fields.getOrPut(field) { FieldInfo(field, fieldType, isStatic) }
        if (result.fieldType != fieldType) abort("$field type mismatch between $fieldType and ${result.fieldType}")
        return result
    }

    private inner class FieldsCollectorCV : CV(null) {
        override fun visitField(
            access: Int,
            name: String,
            desc: String,
            signature: String?,
            value: Any?
        ): FieldVisitor? {
            val fieldType = getType(desc)
            if (fieldType.sort == OBJECT && fieldType.internalName in AFU_CLASSES) {
                val field = FieldId(className, name, desc)
                info("$field field found")
                if (ACC_PUBLIC in access) error("$field field cannot be public")
                if (ACC_FINAL !in access) error("$field field must be final")
                registerField(field, fieldType, (ACC_STATIC in access))
            }
            return null
        }

        override fun visitMethod(
            access: Int,
            name: String,
            desc: String,
            signature: String?,
            exceptions: Array<out String>?
        ): MethodVisitor? {
            val methodType = getMethodType(desc)
            if (methodType.argumentTypes.any { it in AFU_TYPES }) {
                val methodId = MethodId(className, name, desc, accessToInvokeOpcode(access))
                info("$methodId method to be removed")
                removeMethods += methodId
            }
            getPotentialAccessorType(access, className, methodType)?.let { onType ->
                return AccessorCollectorMV(onType.internalName, access, name, desc, signature, exceptions)
            }
            if (name == "<init>" || name == "<clinit>") {
                // check for copying atomic values into delegate fields and register potential delegate fields
                return DelegateFieldsCollectorMV(access, name, desc, signature, exceptions)
            }
            return null
        }
    }

    private inner class AccessorCollectorMV(
        private val className: String,
        access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?
    ) : MethodNode(ASM5, access, name, desc, signature, exceptions) {
        override fun visitEnd() {
            val insns = instructions.listUseful(4)
            if (insns.size == 3 &&
                insns[0].isAload(0) &&
                insns[1].isGetField(className) &&
                insns[2].isAreturn() ||
                insns.size == 2 &&
                insns[0].isGetStatic(className) &&
                insns[1].isAreturn()
            ) {
                val isStatic = insns.size == 2
                val fi = (if (isStatic) insns[0] else insns[1]) as FieldInsnNode
                val fieldName = fi.name
                val field = FieldId(className, fieldName, fi.desc)
                val fieldType = getType(fi.desc)
                val accessorMethod = MethodId(className, name, desc, accessToInvokeOpcode(access))
                info("$field accessor $name found")
                if (fieldType == TRACE_BASE_TYPE) {
                    traceAccessors.add(accessorMethod)
                } else {
                    val fieldInfo = registerField(field, fieldType, isStatic)
                    fieldInfo.accessors += accessorMethod
                    accessors[accessorMethod] = fieldInfo
                }
            }
        }
    }

    // returns a type on which this is a potential accessor
    private fun getPotentialAccessorType(access: Int, className: String, methodType: Type): Type? {
        if (methodType.returnType !in AFU_TYPES && methodType.returnType != TRACE_BASE_TYPE) return null
        return if (access and ACC_STATIC != 0) {
            if (access and ACC_FINAL != 0 && methodType.argumentTypes.isEmpty()) {
                // accessor for top-level atomic
                getObjectType(className)
            } else {
                // accessor for top-level atomic
                if (methodType.argumentTypes.size == 1 && methodType.argumentTypes[0].sort == OBJECT)
                    methodType.argumentTypes[0] else null
            }
        } else {
            // if it not static, then it must be final
            if (access and ACC_FINAL != 0 && methodType.argumentTypes.isEmpty())
                getObjectType(className) else null
        }
    }

    private inner class DelegateFieldsCollectorMV(
            access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?
    ) : MethodNode(ASM5, access, name, desc, signature, exceptions) {
        override fun visitEnd() {
            // register delegate field and the corresponding original atomic field
            // getfield a: *Atomic
            // putfield a$delegate: *Atomic
            instructions.forEach { insn ->
                if (insn is FieldInsnNode) {
                    insn.checkGetFieldOrGetStatic()?.let { getfieldId ->
                        val next = insn.next
                        (next as? FieldInsnNode)?.checkPutFieldOrPutStatic()?.let { delegateFieldId ->
                            if (delegateFieldId.name.endsWith(DELEGATE)) {
                                // original atomic value is copied to the synthetic delegate atomic field <delegated field name>$delegate
                                val originalField = fields[getfieldId]!!
                                fieldDelegates[delegateFieldId] = originalField
                            }
                        }
                    }
                }
                if (insn is MethodInsnNode) {
                    val methodId = MethodId(insn.owner, insn.name, insn.desc, insn.opcode)
                    if (methodId in FACTORIES) {
                        (insn.nextUseful as? FieldInsnNode)?.checkPutFieldOrPutStatic()?.let { delegateFieldId ->
                            if (delegateFieldId.name.endsWith(DELEGATE)) {
                                // delegate field is initialized by a factory invocation
                                val fieldType = getType(insn.desc).returnType
                                // for volatile delegated properties store FieldInfo of the delegate field itself
                                fieldDelegates[delegateFieldId] = FieldInfo(delegateFieldId, fieldType)
                            }
                        }
                    }
                }
            }
        }
    }

    private fun descToName(desc: String): String = desc.drop(1).dropLast(1)

    private fun FieldInsnNode.checkPutFieldOrPutStatic(): FieldId? {
        if (opcode != PUTFIELD && opcode != PUTSTATIC) return null
        val fieldId = FieldId(owner, name, desc)
        return if (fieldId in fields) fieldId else null
    }

    private fun FieldInsnNode.checkGetFieldOrGetStatic(): FieldId? {
        if (opcode != GETFIELD && opcode != GETSTATIC) return null
        val fieldId = FieldId(owner, name, desc)
        return if (fieldId in fields) fieldId else null
    }

    private inner class TransformerCV(
        cv: ClassVisitor?,
        private val vh: Boolean,
        private val analyzePhase2: Boolean // true in Phase 2 when we are analyzing file for refs (not transforming yet)
    ) : CV(cv) {
        private var source: String? = null
        var sourceInfo: SourceInfo? = null

        private var metadata: AnnotationNode? = null

        private var originalClinit: MethodNode? = null
        private var newClinit: MethodNode? = null

        private fun newClinit() = MethodNode(ASM5, ACC_STATIC, "<clinit>", "()V", null, null)
        fun getOrCreateNewClinit(): MethodNode = newClinit ?: newClinit().also { newClinit = it }

        override fun visitSource(source: String?, debug: String?) {
            this.source = source
            super.visitSource(source, debug)
        }

        override fun visitField(
            access: Int,
            name: String,
            desc: String,
            signature: String?,
            value: Any?
        ): FieldVisitor? {
            val fieldType = getType(desc)
            if (fieldType.sort == OBJECT && fieldType.internalName in AFU_CLASSES) {
                val fieldId = FieldId(className, name, desc)
                // skip delegate field
                if (fieldId in fieldDelegates && (fieldId != fieldDelegates[fieldId]!!.fieldId)) {
                    transformed = true
                    return null
                }
                val f = fields[fieldId]!!
                val visibility = when {
                    f.hasExternalAccess -> ACC_PUBLIC
                    f.accessors.isEmpty() -> ACC_PRIVATE
                    else -> 0
                }
                val protection = ACC_SYNTHETIC or visibility or when {
                    // reference to wrapper class (primitive atomics) or reference to to j.u.c.a.Atomic*Array (atomic array)
                    f.isStatic && !vh -> ACC_STATIC or ACC_FINAL
                    // primitive type field
                    f.isStatic && vh -> ACC_STATIC
                    else -> 0
                }
                val primitiveType = f.getPrimitiveType(vh)
                val fv = when {
                    // replace (top-level) Atomic*Array with (static) j.u.c.a/Atomic*Array field
                    f.isArray && !vh -> super.visitField(protection, f.name, f.fuType.descriptor, null, null)
                    // replace top-level primitive atomics with static instance of the corresponding wrapping *RefVolatile class
                    f.isStatic && !vh -> super.visitField(
                        protection,
                        f.staticRefVolatileField,
                        getObjectType(f.refVolatileClassName).descriptor,
                        null,
                        null
                    )
                    // volatile primitive type field
                    else -> super.visitField(protection or ACC_VOLATILE, f.name, primitiveType.descriptor, null, null)
                }
                if (vh) {
                    // VarHandle is needed for all array element accesses and for regular fields with atomic ops
                    if (f.hasAtomicOps || f.isArray) vhField(protection, f)
                } else {
                    // FieldUpdater is not needed for arrays (they use AtomicArrays)
                    if (f.hasAtomicOps && !f.isArray) fuField(protection, f)
                }
                transformed = true
                return fv
            }
            // skip trace field
            if (fieldType == TRACE_BASE_TYPE) {
                traceFields += FieldId(className, name, desc)
                transformed = true
                return null
            }
            return super.visitField(access, name, desc, signature, value)
        }

        // Generates static VarHandle field
        private fun vhField(protection: Int, f: FieldInfo) {
            super.visitField(protection or ACC_FINAL or ACC_STATIC, f.fuName, VH_TYPE.descriptor, null, null)
            code(getOrCreateNewClinit()) {
                if (!f.isArray) {
                    invokestatic(METHOD_HANDLES, "lookup", "()L$LOOKUP;", false)
                    aconst(getObjectType(className))
                    aconst(f.name)
                    val primitiveType = f.getPrimitiveType(vh)
                    if (primitiveType.sort == OBJECT) {
                        aconst(primitiveType)
                    } else {
                        val wrapper = WRAPPER.getValue(primitiveType)
                        getstatic(wrapper, "TYPE", CLASS_TYPE.descriptor)
                    }
                    val findVHName = if (f.isStatic) "findStaticVarHandle" else "findVarHandle"
                    invokevirtual(
                        LOOKUP, findVHName,
                        getMethodDescriptor(VH_TYPE, CLASS_TYPE, STRING_TYPE, CLASS_TYPE), false
                    )
                    putstatic(className, f.fuName, VH_TYPE.descriptor)
                } else {
                    // create VarHandle for array
                    aconst(f.getPrimitiveType(vh))
                    invokestatic(
                        METHOD_HANDLES,
                        "arrayElementVarHandle",
                        getMethodDescriptor(VH_TYPE, CLASS_TYPE),
                        false
                    )
                    putstatic(className, f.fuName, VH_TYPE.descriptor)
                }
            }
        }

        // Generates static AtomicXXXFieldUpdater field
        private fun fuField(protection: Int, f: FieldInfo) {
            super.visitField(protection or ACC_FINAL or ACC_STATIC, f.fuName, f.fuType.descriptor, null, null)
            code(getOrCreateNewClinit()) {
                val params = mutableListOf<Type>()
                params += CLASS_TYPE
                if (!f.isStatic) aconst(getObjectType(className)) else aconst(getObjectType(f.refVolatileClassName))
                val primitiveType = f.getPrimitiveType(vh)
                if (primitiveType.sort == OBJECT) {
                    params += CLASS_TYPE
                    aconst(primitiveType)
                }
                params += STRING_TYPE
                aconst(f.name)
                invokestatic(
                    f.fuType.internalName,
                    "newUpdater",
                    getMethodDescriptor(f.fuType, *params.toTypedArray()),
                    false
                )
                putstatic(className, f.fuName, f.fuType.descriptor)
            }
        }

        override fun visitMethod(
            access: Int,
            name: String,
            desc: String,
            signature: String?,
            exceptions: Array<out String>?
        ): MethodVisitor? {
            val methodId = MethodId(className, name, desc, accessToInvokeOpcode(access))
            if (methodId in accessors || methodId in traceAccessors || methodId in removeMethods) {
                // drop and skip the methods that were found in Phase 1
                // todo: should remove those methods from kotlin metadata, too
                transformed = true
                return null // drop accessor
            }
            val sourceInfo = SourceInfo(methodId, source)
            val superMV = if (name == "<clinit>" && desc == "()V") {
                if (access and ACC_STATIC == 0) abort("<clinit> method not marked as static")
                // defer writing class initialization method
                val node = MethodNode(ASM5, access, name, desc, signature, exceptions)
                if (originalClinit != null) abort("Multiple <clinit> methods found")
                originalClinit = node
                node
            } else {
                // write transformed method to class right away
                super.visitMethod(access, name, desc, signature, exceptions)
            }
            val mv = TransformerMV(
                sourceInfo, access, name, desc, signature, exceptions, superMV,
                className.ownerPackageName, vh, analyzePhase2
            )
            this.sourceInfo = mv.sourceInfo
            return mv
        }

        override fun visitAnnotation(desc: String?, visible: Boolean): AnnotationVisitor? {
            if (desc == KOTLIN_METADATA_DESC) {
                check(visible) { "Expected run-time visible $KOTLIN_METADATA_DESC annotation" }
                check(metadata == null) { "Only one $KOTLIN_METADATA_DESC annotation is expected" }
                return AnnotationNode(desc).also { metadata = it }
            }
            return super.visitAnnotation(desc, visible)
        }

        override fun visitEnd() {
            // remove unused methods from metadata
            metadata?.let {
                val mt = MetadataTransformer(
                    removeFields = fields.keys + traceFields,
                    removeMethods = accessors.keys + traceAccessors + removeMethods
                )
                if (mt.transformMetadata(it)) transformed = true
                if (cv != null) it.accept(cv.visitAnnotation(KOTLIN_METADATA_DESC, true))
            }
            if (analyzePhase2) return // nop in analyze phase
            // collect class initialization
            if (originalClinit != null || newClinit != null) {
                val newClinit = newClinit
                if (newClinit == null) {
                    // dump just original clinit
                    originalClinit!!.accept(cv)
                } else {
                    // create dummy base code if needed
                    val originalClinit = originalClinit ?: newClinit().also {
                        code(it) { visitInsn(RETURN) }
                    }
                    // makes sure return is last useful instruction
                    val last = originalClinit.instructions.last
                    val ret = last.thisOrPrevUseful
                    if (ret == null || !ret.isReturn()) abort("Last instruction in <clinit> shall be RETURN", ret)
                    originalClinit.instructions.insertBefore(ret, newClinit.instructions)
                    originalClinit.accept(cv)
                }
            }
            super.visitEnd()
        }
    }

    private inner class TransformerMV(
        sourceInfo: SourceInfo,
        access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?,
        mv: MethodVisitor?,
        private val packageName: String,
        private val vh: Boolean,
        private val analyzePhase2: Boolean // true in Phase 2 when we are analyzing file for refs (not transforming yet)
    ) : MethodNode(ASM5, access, name, desc, signature, exceptions) {
        init {
            this.mv = mv
        }

        val sourceInfo = sourceInfo.copy(insnList = instructions)

        private var tempLocal = 0
        private var bumpedLocals = 0

        private fun bumpLocals(n: Int) {
            if (bumpedLocals == 0) tempLocal = maxLocals
            while (n > bumpedLocals) bumpedLocals = n
            maxLocals = tempLocal + bumpedLocals
        }

        override fun visitMethodInsn(opcode: Int, owner: String, name: String, desc: String, itf: Boolean) {
            val methodId = MethodId(owner, name, desc, opcode)
            val fieldInfo = accessors[methodId]
            // compare owner packages
            if (fieldInfo != null && methodId.owner.ownerPackageName != packageName) {
                if (analyzePhase2) {
                    fieldInfo.hasExternalAccess = true
                } else {
                    check(fieldInfo.hasExternalAccess) // should have been set on previous phase
                }
            }
            super.visitMethodInsn(opcode, owner, name, desc, itf)
        }

        override fun visitEnd() {
            // transform instructions list
            var hasErrors = false
            var i = instructions.first
            while (i != null)
                try {
                    i = transform(i)
                } catch (e: AbortTransform) {
                    error(e.message!!, sourceInfo.copy(i = e.i))
                    i = i.next
                    hasErrors = true
                }
            // save transformed method if not in analysis phase
            if (!hasErrors && !analyzePhase2)
                accept(mv)
        }

        private fun FieldInsnNode.checkCopyToDelegate(): AbstractInsnNode? {
            val fieldId = FieldId(owner, name, desc)
            if (fieldId in fieldDelegates) {
                // original atomic value is copied to the synthetic delegate atomic field <delegated field name>$delegate
                val originalField = fieldDelegates[fieldId]!!
                val getField = previous as FieldInsnNode
                val next = this.next
                if (!originalField.isStatic) instructions.remove(getField.previous) // no aload for static field
                instructions.remove(getField)
                instructions.remove(this)
                return next
            }
            return null
        }

        // ld: instruction that loads atomic field (already changed to getstatic)
        // iv: invoke virtual on the loaded atomic field (to be fixed)
        private fun fixupInvokeVirtual(
            ld: FieldInsnNode,
            onArrayElement: Boolean, // true when fixing invokeVirtual on loaded array element
            iv: MethodInsnNode,
            f: FieldInfo
        ): AbstractInsnNode? {
            check(f.isArray || !onArrayElement) { "Cannot fix array element access on non array fields" }
            val typeInfo = if (onArrayElement) f.typeInfo else AFU_CLASSES.getValue(iv.owner)
            if (iv.name == GET_VALUE || iv.name == SET_VALUE) {
                check(!f.isArray || onArrayElement) { "getValue/setValue can only be called on elements of arrays" }
                val setInsn = iv.name == SET_VALUE
                if (!onArrayElement) {
                    val primitiveType = f.getPrimitiveType(vh)
                    val owner = if (!vh && f.isStatic) f.refVolatileClassName else f.owner
                    if (!vh && f.isStatic) {
                        val getOwnerClass = FieldInsnNode(
                            GETSTATIC,
                            f.owner,
                            f.staticRefVolatileField,
                            getObjectType(owner).descriptor
                        )
                        instructions.insert(ld, getOwnerClass)
                    }
                    instructions.remove(ld) // drop getstatic (we don't need field updater)
                    val j = FieldInsnNode(
                        when {
                            iv.name == GET_VALUE -> if (f.isStatic && vh) GETSTATIC else GETFIELD
                            else -> if (f.isStatic && vh) PUTSTATIC else PUTFIELD
                        }, owner, f.name, primitiveType.descriptor
                    )
                    instructions.set(iv, j) // replace invokevirtual with get/setfield
                    return j.next
                } else {
                    var methodType = getMethodType(iv.desc)
                    if (f.typeInfo.originalType != f.typeInfo.transformedType && !vh) {
                        val ret = f.typeInfo.transformedType.elementType
                        iv.desc = if (setInsn) getMethodDescriptor(methodType.returnType, ret) else getMethodDescriptor(ret, *methodType.argumentTypes)
                        methodType = getMethodType(iv.desc)
                    }
                    iv.name = iv.name.substring(0, 3)
                    if (!vh) {
                        // map to j.u.c.a.Atomic*Array get or set
                        iv.owner = descToName(f.fuType.descriptor)
                        iv.desc = getMethodDescriptor(methodType.returnType, INT_TYPE, *methodType.argumentTypes)
                    } else {
                        // map to VarHandle get or set
                        iv.owner = descToName(VH_TYPE.descriptor)
                        iv.desc = getMethodDescriptor(
                            methodType.returnType,
                            f.getPrimitiveType(vh),
                            INT_TYPE,
                            *methodType.argumentTypes
                        )
                    }
                    return iv
                }
            }
            if (f.isArray && iv.name == GET_SIZE) {
                if (!vh) {
                    // map to j.u.c.a.Atomic*Array length()
                    iv.owner = descToName(f.fuType.descriptor)
                    iv.name = "length"
                } else {
                    // replace with arraylength of the primitive type array
                    val arrayLength = InsnNode(ARRAYLENGTH)
                    instructions.insert(ld, arrayLength)
                    // do not need varhandle
                    if (!f.isStatic) {
                        instructions.remove(ld.previous.previous)
                        instructions.remove(ld.previous)
                    } else {
                        instructions.remove(ld.previous)
                    }
                    instructions.remove(iv)
                    return arrayLength
                }
                return iv
            }
            // An operation other than getValue/setValue is used
            if (f.isArray && iv.name == "get") { // "operator get" that retrieves array element, further ops apply to it
                // fixup atomic operation on this array element
                return fixupLoadedArrayElement(f, ld, iv)
            }
            // non-trivial atomic operation
            check(f.isArray == onArrayElement) { "Atomic operations can be performed on atomic elements only" }
            if (analyzePhase2) {
                f.hasAtomicOps = true // mark the fact that non-trivial atomic op is used here
            } else {
                check(f.hasAtomicOps) // should have been set on previous phase
            }
            // update method invocation
            if (vh) {
                vhOperation(iv, typeInfo, f)
            } else {
                fuOperation(iv, typeInfo, f)
            }
            if (f.isStatic && !onArrayElement) {
                if (!vh) {
                    // getstatic *RefVolatile class
                    val aload = FieldInsnNode(
                        GETSTATIC,
                        f.owner,
                        f.staticRefVolatileField,
                        getObjectType(f.refVolatileClassName).descriptor
                    )
                    instructions.insert(ld, aload)
                }
                return iv.next
            }
            if (!onArrayElement) {
                // insert swap after field load
                val swap = InsnNode(SWAP)
                instructions.insert(ld, swap)
                return swap.next
            }
            return iv.next
        }

        private fun vhOperation(iv: MethodInsnNode, typeInfo: TypeInfo, f: FieldInfo) {
            val methodType = getMethodType(iv.desc)
            val args = methodType.argumentTypes
            iv.owner = VH_TYPE.internalName
            val params = if (!f.isArray && !f.isStatic) mutableListOf<Type>(
                OBJECT_TYPE,
                *args
            ) else if (!f.isArray && f.isStatic) mutableListOf<Type>(*args) else mutableListOf(
                typeInfo.originalType,
                INT_TYPE,
                *args
            )
            val elementType = if (f.isArray) typeInfo.originalType.elementType else typeInfo.originalType
            val long = elementType == LONG_TYPE
            when (iv.name) {
                "lazySet" -> iv.name = "setRelease"
                "getAndIncrement" -> {
                    instructions.insertBefore(iv, insns { if (long) lconst(1) else iconst(1) })
                    params += elementType
                    iv.name = "getAndAdd"
                }
                "getAndDecrement" -> {
                    instructions.insertBefore(iv, insns { if (long) lconst(-1) else iconst(-1) })
                    params += elementType
                    iv.name = "getAndAdd"
                }
                "addAndGet" -> {
                    bumpLocals(if (long) 2 else 1)
                    instructions.insertBefore(iv, insns {
                        if (long) dup2() else dup()
                        store(tempLocal, elementType)
                    })
                    iv.name = "getAndAdd"
                    instructions.insert(iv, insns {
                        load(tempLocal, elementType)
                        add(elementType)
                    })
                }
                "incrementAndGet" -> {
                    instructions.insertBefore(iv, insns { if (long) lconst(1) else iconst(1) })
                    params += elementType
                    iv.name = "getAndAdd"
                    instructions.insert(iv, insns {
                        if (long) lconst(1) else iconst(1)
                        add(elementType)
                    })
                }
                "decrementAndGet" -> {
                    instructions.insertBefore(iv, insns { if (long) lconst(-1) else iconst(-1) })
                    params += elementType
                    iv.name = "getAndAdd"
                    instructions.insert(iv, insns {
                        if (long) lconst(-1) else iconst(-1)
                        add(elementType)
                    })
                }
            }
            iv.desc = getMethodDescriptor(methodType.returnType, *params.toTypedArray())
        }

        private fun fuOperation(iv: MethodInsnNode, typeInfo: TypeInfo, f: FieldInfo) {
            val methodType = getMethodType(iv.desc)
            val originalElementType = if (f.isArray) typeInfo.originalType.elementType else typeInfo.originalType
            val transformedElementType =
                if (f.isArray) typeInfo.transformedType.elementType else typeInfo.transformedType
            val trans = originalElementType != transformedElementType
            val args = methodType.argumentTypes
            var ret = methodType.returnType
            if (trans) {
                args.forEachIndexed { i, type -> if (type == originalElementType) args[i] = transformedElementType }
                if (iv.name == "getAndSet") ret = transformedElementType
            }
            if (f.isArray) {
                // map to j.u.c.a.AtomicIntegerArray method
                iv.owner = typeInfo.fuType.internalName
                // add int argument as element index
                iv.desc = getMethodDescriptor(ret, INT_TYPE, *args)
                return // array operation in this mode does not use FU field
            }
            iv.owner = typeInfo.fuType.internalName
            iv.desc = getMethodDescriptor(ret, OBJECT_TYPE, *args)
        }

        private fun tryEraseUncheckedCast(getter: AbstractInsnNode) {
            if (getter.next.opcode == DUP && getter.next.next.opcode == IFNONNULL) {
                // unchecked cast upon AtomicRef var is performed
                // erase compiler check for this var being not null:
                // (remove all insns from ld till the non null branch label)
                val ifnonnull = (getter.next.next as JumpInsnNode)
                var i: AbstractInsnNode = getter.next
                while (!(i is LabelNode && i.label == ifnonnull.label.label)) {
                    val next = i.next
                    instructions.remove(i)
                    i = next
                }
            }
        }

        private fun fixupLoadedAtomicVar(f: FieldInfo, ld: FieldInsnNode): AbstractInsnNode? {
            if (f.fieldType == REF_TYPE) tryEraseUncheckedCast(ld)
            val j = FlowAnalyzer(ld.next).execute()
            return fixupOperationOnAtomicVar(j, f, ld, null)
        }

        private fun fixupLoadedArrayElement(f: FieldInfo, ld: FieldInsnNode, getter: MethodInsnNode): AbstractInsnNode? {
            if (f.fieldType == ATOMIC_ARRAY_TYPE) tryEraseUncheckedCast(getter)
            // contains array field load (in vh case: + swap and pure type array load) and array element index
            // this array element information is only used in case the reference to this element is stored (copied and inserted at the point of loading)
            val arrayElementInfo = mutableListOf<AbstractInsnNode>()
            if (vh) {
                if (!f.isStatic) {
                    arrayElementInfo.add(ld.previous.previous) // getstatic VarHandle field
                    arrayElementInfo.add(ld.previous) // swap
                } else {
                    arrayElementInfo.add(ld.previous) // getstatic VarHandle field
                }
            }
            var i: AbstractInsnNode = ld
            while (i != getter) {
                arrayElementInfo.add(i)
                i = i.next
            }
            // start of array element operation arguments
            val args = getter.next
            // remove array element getter
            instructions.remove(getter)
            val arrayElementOperation = FlowAnalyzer(args).execute()
            return fixupOperationOnAtomicVar(arrayElementOperation, f, ld, arrayElementInfo)
        }

        private fun fixupOperationOnAtomicVar(operation: AbstractInsnNode, f: FieldInfo, ld: FieldInsnNode, arrayElementInfo: List<AbstractInsnNode>?): AbstractInsnNode? {
            when (operation) {
                is MethodInsnNode -> {
                    // invoked virtual method on atomic var -- fixup & done with it
                    debug("invoke $f.${operation.name}", sourceInfo.copy(i = operation))
                    return fixupInvokeVirtual(ld, arrayElementInfo != null, operation, f)
                }
                is VarInsnNode -> {
                    val onArrayElement = arrayElementInfo != null
                    check(f.isArray == onArrayElement)
                    // was stored to local -- needs more processing:
                    // for class fields store owner ref into the variable instead
                    // for static fields store nothing, remove the local var
                    val v = operation.`var`
                    val next = operation.next
                    if (onArrayElement) {
                        // leave just owner class load insn on stack
                        arrayElementInfo!!.forEach { instructions.remove(it) }
                    } else {
                        instructions.remove(ld)
                    }
                    val lv = localVar(v, operation)
                    if (f.isStatic) instructions.remove(operation) // remove astore operation
                    if (lv != null) {
                        // Stored to a local variable with an entry in LVT (typically because of inline function)
                        if (lv.desc != f.fieldType.descriptor && !onArrayElement)
                            abort("field $f was stored to a local variable #$v \"${lv.name}\" with unexpected type: ${lv.desc}")
                        // correct local variable descriptor
                        lv.desc = f.ownerType.descriptor
                        lv.signature = null
                        // process all loads of this variable in the corresponding local variable range
                        forVarLoads(v, lv.start, lv.end) { otherLd ->
                            fixupLoad(f, ld, otherLd, arrayElementInfo)
                        }
                    } else {
                        // Spilled temporarily to a local variable w/o an entry in LVT -> fixup only one load
                        fixupLoad(f, ld, nextVarLoad(v, next), arrayElementInfo)
                    }
                    return next
                }
                else -> abort("cannot happen")
            }
        }

        private fun fixupLoad(f: FieldInfo, ld: FieldInsnNode, otherLd: VarInsnNode, arrayElementInfo: List<AbstractInsnNode>?): AbstractInsnNode? {
            val next = if (arrayElementInfo != null) {
                fixupArrayElementLoad(f, ld, otherLd, arrayElementInfo)
            } else {
                fixupVarLoad(f, ld, otherLd)
            }
            if (f.isStatic) instructions.remove(otherLd) // remove aload instruction for static fields, nothing is stored there
            return next
        }

        private fun fixupVarLoad(f: FieldInfo, ld: FieldInsnNode, otherLd: VarInsnNode): AbstractInsnNode? {
            val ldCopy = ld.clone(null) as FieldInsnNode
            instructions.insert(otherLd, ldCopy)
            return fixupLoadedAtomicVar(f, ldCopy)
        }

        private fun fixupArrayElementLoad(f: FieldInfo, ld: FieldInsnNode, otherLd: VarInsnNode, arrayElementInfo: List<AbstractInsnNode>): AbstractInsnNode? {
            if (f.fieldType == ATOMIC_ARRAY_TYPE) tryEraseUncheckedCast(otherLd)
            // index instructions from array element info: drop owner class load instruction (in vh case together with preceding getting VH + swap)
            val index = arrayElementInfo.drop(if (vh) 3 else 1)
            // previously stored array element reference is loaded -> arrayElementInfo should be cloned and inserted at the point of this load
            // before cloning make sure that index instructions contain just loads and simple arithmetic, without any invocations and complex data flow
            for (indexInsn in index) {
                checkDataFlowComplexity(indexInsn)
            }
            // start of atomic operation arguments
            val args = otherLd.next
            val operationOnArrayElement = FlowAnalyzer(args).execute()
            val arrayElementInfoCopy = mutableListOf<AbstractInsnNode>()
            arrayElementInfo.forEach { arrayElementInfoCopy.add(it.clone(null)) }
            arrayElementInfoCopy.forEach { instructions.insertBefore(args, it) }
            return fixupOperationOnAtomicVar(operationOnArrayElement, f, ld, arrayElementInfo)
        }

        fun checkDataFlowComplexity(i: AbstractInsnNode) {
            when (i) {
                is MethodInsnNode -> {
                    abort("No method invocations are allowed for calculation of an array element index " +
                        "at the point of loading the reference to this element.\n" +
                        "Extract index calculation to the local variable.", i)
                }
                is LdcInsnNode -> { /* ok loading const */ }
                else -> {
                    when(i.opcode) {
                        IADD, ISUB, IMUL, IDIV, IREM, IAND, IOR, IXOR, ISHL, ISHR, IUSHR -> { /* simple arithmetics */ }
                        ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5, ILOAD, IALOAD -> { /* int loads */ }
                        GETFIELD, GETSTATIC -> { /* getting fields */ }
                        else -> {
                            abort("Complex data flow is not allowed for calculation of an array element index " +
                                "at the point of loading the reference to this element.\n" +
                                "Extract index calculation to the local variable.", i)
                        }
                    }
                }
            }
        }

        private fun putPrimitiveTypeWrapper(
            factoryInsn: MethodInsnNode,
            initStart: AbstractInsnNode,
            f: FieldInfo,
            next: FieldInsnNode
        ): AbstractInsnNode? {
            // generate wrapper class for static fields of primitive type
            val factoryArg = getMethodType(factoryInsn.desc).argumentTypes[0]
            generateRefVolatileClass(f, factoryArg)
            // remove calling atomic factory for static field and following putstatic
            val afterPutStatic = next.next
            instructions.remove(factoryInsn)
            instructions.remove(next)
            initRefVolatile(f, factoryArg, initStart, afterPutStatic)
            return afterPutStatic
        }

        private fun putJucaAtomicArray(
            arrayfactoryInsn: MethodInsnNode,
            initStart: AbstractInsnNode,
            f: FieldInfo,
            next: FieldInsnNode
        ): AbstractInsnNode? {
            // replace with invoking j.u.c.a.Atomic*Array constructor
            val jucaAtomicArrayDesc = f.typeInfo.fuType.descriptor
            if (initStart.opcode == NEW) {
                // change descriptor of NEW instruction
                (initStart as TypeInsnNode).desc = descToName(jucaAtomicArrayDesc)
                arrayfactoryInsn.owner = descToName(jucaAtomicArrayDesc)
            } else {
                // array initialisation starts from bipush size, then static array factory was called (atomicArrayOfNulls)
                // add NEW j.u.c.a.Atomic*Array instruction
                val newInsn = TypeInsnNode(NEW, descToName(jucaAtomicArrayDesc))
                instructions.insert(initStart.previous, newInsn)
                instructions.insert(newInsn, InsnNode(DUP))
                val jucaArrayFactory =
                    MethodInsnNode(INVOKESPECIAL, descToName(jucaAtomicArrayDesc), "<init>", "(I)V", false)
                instructions.set(arrayfactoryInsn, jucaArrayFactory)
            }
            //fix the following putfield
            next.desc = jucaAtomicArrayDesc
            next.name = f.name
            transformed = true
            return next.next
        }

        private fun putPureVhArray(
            arrayFactoryInsn: MethodInsnNode,
            initStart: AbstractInsnNode,
            f: FieldInfo,
            next: FieldInsnNode
        ): AbstractInsnNode? {
            if (initStart.opcode == NEW) {
                // remove dup
                instructions.remove(initStart.next)
                // remove NEW AFU_PKG/Atomic*Array instruction
                instructions.remove(initStart)
            }
            // create pure array of given size and put it
            val primitiveType = f.getPrimitiveType(vh)
            val primitiveElementType = ARRAY_ELEMENT_TYPE[f.typeInfo.originalType]
            val newArray =
                if (primitiveElementType != null) IntInsnNode(NEWARRAY, primitiveElementType)
                else TypeInsnNode(ANEWARRAY, descToName(primitiveType.elementType.descriptor))
            instructions.set(arrayFactoryInsn, newArray)
            next.desc = primitiveType.descriptor
            next.name = f.name
            transformed = true
            return next.next
        }

        // removes pushing atomic factory trace arguments
        // returns the first value argument push
        private fun removeTraceInit(atomicFactory: MethodInsnNode, isArrayFactory: Boolean): AbstractInsnNode {
            val initStart = FlowAnalyzer(atomicFactory).getInitStart(1)
            if (isArrayFactory) return initStart
            var lastArg = atomicFactory.previous
            val valueArgInitLast = FlowAnalyzer(atomicFactory).getValueArgInitLast()
            while (lastArg != valueArgInitLast) {
                val prev = lastArg.previous
                instructions.remove(lastArg)
                lastArg = prev
            }
            return initStart
        }

        private fun removeTraceAppend(append: AbstractInsnNode): AbstractInsnNode {
            // remove append trace instructions: from append invocation up to getfield Trace or accessor to Trace field
            val afterAppend = append.next
            var start = append
            val isGetFieldTrace = { insn: AbstractInsnNode ->
                insn.opcode == GETFIELD && (start as FieldInsnNode).desc == getObjectType(TRACE_BASE_CLS).descriptor }
            val isTraceAccessor = { insn: AbstractInsnNode ->
                if (insn is MethodInsnNode) {
                    val methodId = MethodId(insn.owner, insn.name, insn.desc, insn.opcode)
                    methodId in traceAccessors
                } else false
            }
            while (!(isGetFieldTrace(start) || isTraceAccessor(start))) {
                start = start.previous
            }
            // now start contains Trace getfield insn or Trace accessor
            if (isTraceAccessor(start)) {
                instructions.remove(start.previous.previous)
                instructions.remove(start.previous)
            } else {
                instructions.remove(start.previous)
            }
            while (start != afterAppend) {
                if (start is VarInsnNode) {
                    // remove all local store instructions
                    localVariables.removeIf { it.index == (start as VarInsnNode).`var` }
                }
                val next = start.next
                instructions.remove(start)
                start = next
            }
            return afterAppend
        }

        private fun transform(i: AbstractInsnNode): AbstractInsnNode? {
            when (i) {
                is MethodInsnNode -> {
                    val methodId = MethodId(i.owner, i.name, i.desc, i.opcode)
                    when {
                        methodId in FACTORIES -> {
                            if (name != "<init>" && name != "<clinit>") abort("factory $methodId is used outside of constructor or class initialisation")
                            val next = i.nextUseful
                            val fieldId = (next as? FieldInsnNode)?.checkPutFieldOrPutStatic()
                                ?: abort("factory $methodId invocation must be followed by putfield")
                            val f = fields[fieldId]!!
                            val isArray = AFU_CLASSES[i.owner]?.let { it.originalType.sort == ARRAY } ?: false
                            // erase pushing arguments for trace initialisation
                            val newInitStart = removeTraceInit(i, isArray)
                            // in FU mode wrap values of top-level primitive atomics into corresponding *RefVolatile class
                            if (!vh && f.isStatic && !f.isArray) {
                                return putPrimitiveTypeWrapper(i, newInitStart, f, next)
                            }
                            if (f.isArray) {
                                return if (vh) {
                                    putPureVhArray(i, newInitStart, f, next)
                                } else {
                                    putJucaAtomicArray(i, newInitStart, f, next)
                                }
                            }
                            instructions.remove(i)
                            transformed = true
                            val primitiveType = f.getPrimitiveType(vh)
                            next.desc = primitiveType.descriptor
                            next.name = f.name
                            return next.next
                        }
                        methodId in accessors -> {
                            // replace INVOKESTATIC/VIRTUAL to accessor with GETSTATIC on var handle / field updater
                            val f = accessors[methodId]!!
                            val j = FieldInsnNode(
                                GETSTATIC, f.owner, f.fuName,
                                if (vh) VH_TYPE.descriptor else f.fuType.descriptor
                            )
                            // set original name for an array in FU mode
                            if (!vh && f.isArray) {
                                j.opcode = if (!f.isStatic) GETFIELD else GETSTATIC
                                j.name = f.name
                            }
                            instructions.set(i, j)
                            if (vh && f.isArray) {
                                return insertPureVhArray(j, f)
                            }
                            transformed = true
                            return fixupLoadedAtomicVar(f, j)
                        }
                        methodId == TRACE_FACTORY || methodId == TRACE_PARTIAL_ARGS_FACTORY -> {
                            if (methodId == TRACE_FACTORY) {
                                // remove trace format initialization
                                var checkcastTraceFormat = i
                                while (checkcastTraceFormat.opcode != CHECKCAST) checkcastTraceFormat = checkcastTraceFormat.previous
                                val astoreTraceFormat = checkcastTraceFormat.next
                                val tranceFormatInitStart = FlowAnalyzer(checkcastTraceFormat.previous).getInitStart(1).previous
                                var initInsn = checkcastTraceFormat
                                while (initInsn != tranceFormatInitStart) {
                                    val prev = initInsn.previous
                                    instructions.remove(initInsn)
                                    initInsn = prev
                                }
                                instructions.insertBefore(astoreTraceFormat, InsnNode(ACONST_NULL))
                            }
                            // remove trace factory and following putfield
                            val argsSize = getMethodType(methodId.desc).argumentTypes.size
                            val putfield = i.next
                            val next = putfield.next
                            val depth = if (i.opcode == INVOKESPECIAL) 2 else argsSize
                            val initStart = FlowAnalyzer(i.previous).getInitStart(depth).previous
                            var lastArg = i
                            while (lastArg != initStart) {
                                val prev = lastArg.previous
                                instructions.remove(lastArg)
                                lastArg = prev
                            }
                            instructions.remove(initStart) // aload of the parent class
                            instructions.remove(putfield)
                            return next
                        }
                        methodId == TRACE_APPEND || methodId == TRACE_APPEND_2 || methodId == TRACE_APPEND_3 || methodId == TRACE_APPEND_4 -> {
                            return removeTraceAppend(i)
                        }
                        methodId in removeMethods -> {
                            abort(
                                "invocation of method $methodId on atomic types. " +
                                    "Make the latter method 'inline' to use it", i
                            )
                        }
                        i.opcode == INVOKEVIRTUAL && i.owner in AFU_CLASSES -> {
                            abort("standalone invocation of $methodId that was not traced to previous field load", i)
                        }
                    }
                }
                is FieldInsnNode -> {
                    val fieldId = FieldId(i.owner, i.name, i.desc)
                    if ((i.opcode == GETFIELD || i.opcode == GETSTATIC) && fieldId in fields) {
                        if (fieldId in fieldDelegates && i.next.opcode == ASTORE) {
                            return transformDelegatedFieldAccessor(i, fieldId)
                        }
                        (i.next as? FieldInsnNode)?.checkCopyToDelegate()?.let { return it } // atomic field is copied to delegate field
                        // Convert GETFIELD to GETSTATIC on var handle / field updater
                        val f = fields[fieldId]!!
                        val isArray = f.getPrimitiveType(vh).sort == ARRAY
                        // GETSTATIC for all fields except FU arrays
                        if (!isArray || vh) {
                            if (i.desc != f.fieldType.descriptor) return i.next // already converted get/setfield
                            i.opcode = GETSTATIC
                            i.name = f.fuName
                        }
                        // for FU arrays with external access change name to mangled one
                        if (!vh && isArray && f.hasExternalAccess) {
                            i.name = f.name
                        }
                        i.desc = if (vh) VH_TYPE.descriptor else f.fuType.descriptor
                        val prev = i.previous
                        if (vh && f.getPrimitiveType(vh).sort == ARRAY) {
                            return getInsnOrNull(from = prev, to = insertPureVhArray(i, f)) { it.isAtomicGetFieldOrGetStatic() }
                        }
                        transformed = true
                        // in order not to skip the transformation of atomic field loads
                        // check if there are any nested between the current atomic field load instruction i and it's transformed operation
                        // and return the first one
                        return getInsnOrNull(from = prev, to = fixupLoadedAtomicVar(f, i)) { it.isAtomicGetFieldOrGetStatic() }
                    }
                }
            }
            return i.next
        }

        private fun transformDelegatedFieldAccessor(i: FieldInsnNode, fieldId: FieldId): AbstractInsnNode {
            val f = fieldDelegates[fieldId]!!
            val astore = (i.next as? VarInsnNode) ?: abort("Method $name does not match the pattern of a delegated field accessor")
            val v = astore.`var`
            var cur: AbstractInsnNode = i
            while (!(cur is VarInsnNode && cur.opcode == ALOAD && cur.`var` == v)) {
                val next = cur.next
                instructions.remove(cur)
                cur = next
            }
            val invokeVirtual = FlowAnalyzer(cur.next).execute()
            instructions.remove(cur)
            check(invokeVirtual.isAtomicGetValueOrSetValue()) { "Aload of the field delegate $f should be followed with Atomic*.getValue()/setValue() invocation" }
            val accessorName = (invokeVirtual as MethodInsnNode).name.substring(0, 3)
            val isGetter = accessorName == "get"
            val primitiveType = f.getPrimitiveType(vh)
            val j = FieldInsnNode(if (isGetter) GETFIELD else PUTFIELD, f.owner, f.name, primitiveType.descriptor)
            instructions.set(invokeVirtual, j)
            localVariables.removeIf {
                !(getType(it.desc).internalName == f.owner ||
                        (!isGetter && getType(it.desc) == getType(desc).argumentTypes.first() && it.name == "<set-?>"))
            }
            return j.next
        }

        private fun AbstractInsnNode.isAtomicGetFieldOrGetStatic() =
                this is FieldInsnNode && (opcode == GETFIELD || opcode == GETSTATIC) &&
                        FieldId(owner, name, desc) in fields

        private fun AbstractInsnNode.isAtomicGetValueOrSetValue() =
                isInvokeVirtual() && (getObjectType((this as MethodInsnNode).owner) in AFU_TYPES) &&
                        (name == GET_VALUE || name == SET_VALUE)

        private fun insertPureVhArray(getVarHandleInsn: FieldInsnNode, f: FieldInfo): AbstractInsnNode? {
            val getPureArray = FieldInsnNode(GETFIELD, f.owner, f.name, f.getPrimitiveType(vh).descriptor)
            if (!f.isStatic) {
                // swap className reference and VarHandle
                val swap = InsnNode(SWAP)
                instructions.insert(getVarHandleInsn, swap)
                instructions.insert(swap, getPureArray)
            } else {
                getPureArray.opcode = GETSTATIC
                instructions.insert(getVarHandleInsn, getPureArray)
            }
            transformed = true
            return fixupLoadedAtomicVar(f, getPureArray)
        }

        // generates a ref class with volatile field of primitive type inside
        private fun generateRefVolatileClass(f: FieldInfo, arg: Type) {
            if (analyzePhase2) return // nop
            val cw = ClassWriter(0)
            val visibility = if (f.hasExternalAccess) ACC_PUBLIC else 0
            cw.visit(V1_6, visibility or ACC_SYNTHETIC, f.refVolatileClassName, null, "java/lang/Object", null)
            //creating class constructor
            val cons = cw.visitMethod(ACC_PUBLIC, "<init>", "(${arg.descriptor})V", null, null)
            code(cons) {
                visitVarInsn(ALOAD, 0)
                invokespecial("java/lang/Object", "<init>", "()V", false)
                visitVarInsn(ALOAD, 0)
                load(1, arg)
                putfield(f.refVolatileClassName, f.name, f.getPrimitiveType(vh).descriptor)
                visitInsn(RETURN)
                // stack size to fit long type
                visitMaxs(3, 3)
            }
            //declaring volatile field of primitive type
            cw.visitField(visibility or ACC_VOLATILE, f.name, f.getPrimitiveType(vh).descriptor, null, null)
            val genFile = outputDir / "${f.refVolatileClassName}.class"
            genFile.mkdirsAndWrite(cw.toByteArray())
        }

        // Initializes static instance of generated *RefVolatile class
        private fun initRefVolatile(
            f: FieldInfo,
            argType: Type,
            firstInitInsn: AbstractInsnNode,
            lastInitInsn: AbstractInsnNode
        ) {
            val new = TypeInsnNode(NEW, f.refVolatileClassName)
            val dup = InsnNode(DUP)
            instructions.insertBefore(firstInitInsn, new)
            instructions.insertBefore(firstInitInsn, dup)
            val invokespecial =
                MethodInsnNode(INVOKESPECIAL, f.refVolatileClassName, "<init>", "(${argType.descriptor})V", false)
            val putstatic = FieldInsnNode(
                PUTSTATIC,
                f.owner,
                f.staticRefVolatileField,
                getObjectType(f.refVolatileClassName).descriptor
            )
            instructions.insertBefore(lastInitInsn, invokespecial)
            instructions.insert(invokespecial, putstatic)
        }
    }

    private inner class CW : ClassWriter(COMPUTE_MAXS or COMPUTE_FRAMES) {
        override fun getCommonSuperClass(type1: String, type2: String): String {
            var c: Class<*> = loadClass(type1)
            val d: Class<*> = loadClass(type2)
            if (c.isAssignableFrom(d)) return type1
            if (d.isAssignableFrom(c)) return type2
            return if (c.isInterface || d.isInterface) {
                "java/lang/Object"
            } else {
                do {
                    c = c.superclass
                } while (!c.isAssignableFrom(d))
                c.name.replace('.', '/')
            }
        }
    }

    private fun loadClass(type: String): Class<*> =
        try {
            Class.forName(type.replace('/', '.'), false, classPathLoader)
        } catch (e: Exception) {
            throw TransformerException("Failed to load class for '$type'", e)
        }
}

fun main(args: Array<String>) {
    if (args.size !in 1..3) {
        println("Usage: AtomicFUTransformerKt <dir> [<output>] [<variant>]")
        return
    }
    val t = AtomicFUTransformer(emptyList(), File(args[0]))
    if (args.size > 1) t.outputDir = File(args[1])
    if (args.size > 2) t.variant = enumValueOf(args[2].toUpperCase(Locale.US))
    t.verbose = true
    t.transform()
}