summaryrefslogtreecommitdiff
path: root/src/vm/amd64/JitHelpers_InlineGetThread.asm
blob: 700c3b393c61e8a2b9d369b474026c97a139d602 (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
; Licensed to the .NET Foundation under one or more agreements.
; The .NET Foundation licenses this file to you under the MIT license.
; See the LICENSE file in the project root for more information.

; ==++==
;

;
; ==--==
; ***********************************************************************
; File: JitHelpers_InlineGetThread.asm, see history in jithelp.asm
;
; Notes: These routinues will be patched at runtime with the location in 
;        the TLS to find the Thread* and are the fastest implementation 
;        of their specific functionality.
; ***********************************************************************

include AsmMacros.inc
include asmconstants.inc

; Min amount of stack space that a nested function should allocate.
MIN_SIZE equ 28h

; Macro to create a patchable inline GetAppdomain, if we decide to create patchable
; high TLS inline versions then just change this macro to make sure to create enough
; space in the asm to patch the high TLS getter instructions.
PATCHABLE_INLINE_GETTHREAD macro Reg, PatchLabel
PATCH_LABEL PatchLabel
        mov     Reg, gs:[OFFSET__TEB__TlsSlots]
        endm


JIT_NEW                 equ     ?JIT_New@@YAPEAVObject@@PEAUCORINFO_CLASS_STRUCT_@@@Z
Object__DEBUG_SetAppDomain equ ?DEBUG_SetAppDomain@Object@@QEAAXPEAVAppDomain@@@Z
CopyValueClassUnchecked equ     ?CopyValueClassUnchecked@@YAXPEAX0PEAVMethodTable@@@Z
JIT_Box                 equ     ?JIT_Box@@YAPEAVObject@@PEAUCORINFO_CLASS_STRUCT_@@PEAX@Z
g_pStringClass          equ     ?g_pStringClass@@3PEAVMethodTable@@EA
FramedAllocateString    equ     ?FramedAllocateString@@YAPEAVStringObject@@K@Z
JIT_NewArr1             equ     ?JIT_NewArr1@@YAPEAVObject@@PEAUCORINFO_CLASS_STRUCT_@@_J@Z

INVALIDGCVALUE          equ     0CCCCCCCDh

extern JIT_NEW:proc
extern CopyValueClassUnchecked:proc
extern JIT_Box:proc
extern g_pStringClass:QWORD
extern FramedAllocateString:proc
extern JIT_NewArr1:proc

extern JIT_InternalThrow:proc

ifdef _DEBUG
extern DEBUG_TrialAllocSetAppDomain:proc
extern DEBUG_TrialAllocSetAppDomain_NoScratchArea:proc
endif

; IN: rcx: MethodTable*
; OUT: rax: new object
LEAF_ENTRY JIT_TrialAllocSFastMP_InlineGetThread, _TEXT
        mov     edx, [rcx + OFFSET__MethodTable__m_BaseSize]

        ; m_BaseSize is guaranteed to be a multiple of 8.

        PATCHABLE_INLINE_GETTHREAD r11, JIT_TrialAllocSFastMP_InlineGetThread__PatchTLSOffset
        mov     r10, [r11 + OFFSET__Thread__m_alloc_context__alloc_limit]
        mov     rax, [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr]

        add     rdx, rax

        cmp     rdx, r10
        ja      AllocFailed

        mov     [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr], rdx
        mov     [rax], rcx

ifdef _DEBUG
        call    DEBUG_TrialAllocSetAppDomain_NoScratchArea
endif ; _DEBUG

        ret

    AllocFailed:
        jmp     JIT_NEW
LEAF_END JIT_TrialAllocSFastMP_InlineGetThread, _TEXT

; HCIMPL2(Object*, JIT_Box, CORINFO_CLASS_HANDLE type, void* unboxedData)
NESTED_ENTRY JIT_BoxFastMP_InlineGetThread, _TEXT
        mov     rax, [rcx + OFFSETOF__MethodTable__m_pWriteableData]

        ; Check whether the class has not been initialized
        test    dword ptr [rax + OFFSETOF__MethodTableWriteableData__m_dwFlags], MethodTableWriteableData__enum_flag_Unrestored
        jnz     ClassNotInited

        mov     r8d, [rcx + OFFSET__MethodTable__m_BaseSize]

        ; m_BaseSize is guaranteed to be a multiple of 8.

        PATCHABLE_INLINE_GETTHREAD r11, JIT_BoxFastMPIGT__PatchTLSLabel
        mov     r10, [r11 + OFFSET__Thread__m_alloc_context__alloc_limit]
        mov     rax, [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr]

        add     r8, rax

        cmp     r8, r10
        ja      AllocFailed

        mov     [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr], r8
        mov     [rax], rcx

ifdef _DEBUG
        call    DEBUG_TrialAllocSetAppDomain_NoScratchArea
endif ; _DEBUG

        ; Check whether the object contains pointers
        test    dword ptr [rcx + OFFSETOF__MethodTable__m_dwFlags], MethodTable__enum_flag_ContainsPointers
        jnz     ContainsPointers

        ; We have no pointers - emit a simple inline copy loop
        ; Copy the contents from the end
        mov     ecx, [rcx + OFFSET__MethodTable__m_BaseSize]
        sub     ecx, 18h  ; sizeof(ObjHeader) + sizeof(Object) + last slot

align 16
    CopyLoop:
        mov     r8, [rdx+rcx]
        mov     [rax+rcx+8], r8
        sub     ecx, 8
        jge     CopyLoop
        REPRET

    ContainsPointers:
        ; Do call to CopyValueClassUnchecked(object, data, pMT)
        push_vol_reg rax
        alloc_stack 20h
        END_PROLOGUE

        mov     r8, rcx
        lea     rcx, [rax + 8]
        call    CopyValueClassUnchecked

        add     rsp, 20h
        pop     rax
        ret

    ClassNotInited:
    AllocFailed:
        jmp     JIT_Box
NESTED_END JIT_BoxFastMP_InlineGetThread, _TEXT

FIX_INDIRECTION macro Reg
ifdef FEATURE_PREJIT
        test    Reg, 1
        jz      @F
        mov     Reg, [Reg-1]
    @@:
endif
endm

LEAF_ENTRY AllocateStringFastMP_InlineGetThread, _TEXT
        ; We were passed the number of characters in ECX

        ; we need to load the method table for string from the global
        mov     r9, [g_pStringClass]

        ; Instead of doing elaborate overflow checks, we just limit the number of elements
        ; to (LARGE_OBJECT_SIZE - 256)/sizeof(WCHAR) or less.
        ; This will avoid all overflow problems, as well as making sure
        ; big string objects are correctly allocated in the big object heap.

        cmp     ecx, (ASM_LARGE_OBJECT_SIZE - 256)/2
        jae     OversizedString

        mov     edx, [r9 + OFFSET__MethodTable__m_BaseSize]

        ; Calculate the final size to allocate.
        ; We need to calculate baseSize + cnt*2, then round that up by adding 7 and anding ~7.

        lea     edx, [edx + ecx*2 + 7]
        and     edx, -8

        PATCHABLE_INLINE_GETTHREAD r11, AllocateStringFastMP_InlineGetThread__PatchTLSOffset
        mov     r10, [r11 + OFFSET__Thread__m_alloc_context__alloc_limit]
        mov     rax, [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr]

        add     rdx, rax

        cmp     rdx, r10
        ja      AllocFailed

        mov     [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr], rdx
        mov     [rax], r9

        mov     [rax + OFFSETOF__StringObject__m_StringLength], ecx

ifdef _DEBUG
        call    DEBUG_TrialAllocSetAppDomain_NoScratchArea
endif ; _DEBUG

        ret

    OversizedString:
    AllocFailed:
        jmp     FramedAllocateString
LEAF_END AllocateStringFastMP_InlineGetThread, _TEXT

; HCIMPL2(Object*, JIT_NewArr1, CORINFO_CLASS_HANDLE arrayTypeHnd_, INT_PTR size)
LEAF_ENTRY JIT_NewArr1VC_MP_InlineGetThread, _TEXT
        ; We were passed a type descriptor in RCX, which contains the (shared)
        ; array method table and the element type.

        ; The element count is in RDX

        ; NOTE: if this code is ported for CORINFO_HELP_NEWSFAST_ALIGN8, it will need
        ; to emulate the double-specific behavior of JIT_TrialAlloc::GenAllocArray.

        ; Do a conservative check here.  This is to avoid overflow while doing the calculations.  We don't
        ; have to worry about "large" objects, since the allocation quantum is never big enough for
        ; LARGE_OBJECT_SIZE.

        ; For Value Classes, this needs to be 2^16 - slack (2^32 / max component size), 
        ; The slack includes the size for the array header and round-up ; for alignment.  Use 256 for the
        ; slack value out of laziness.

        ; In both cases we do a final overflow check after adding to the alloc_ptr.

        ; we need to load the true method table from the type desc
        mov     r9, [rcx + OFFSETOF__ArrayTypeDesc__m_TemplateMT - 2]
        
        FIX_INDIRECTION r9

        cmp     rdx, (65535 - 256)
        jae     OversizedArray

        movzx   r8d, word ptr [r9 + OFFSETOF__MethodTable__m_dwFlags]  ; component size is low 16 bits
        imul    r8d, edx
        add     r8d, dword ptr [r9 + OFFSET__MethodTable__m_BaseSize] 

        ; round the size to a multiple of 8

        add     r8d, 7
        and     r8d, -8


        PATCHABLE_INLINE_GETTHREAD r11, JIT_NewArr1VC_MP_InlineGetThread__PatchTLSOffset
        mov     r10, [r11 + OFFSET__Thread__m_alloc_context__alloc_limit]
        mov     rax, [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr]

        add     r8, rax
        jc      AllocFailed

        cmp     r8, r10
        ja      AllocFailed

        mov     [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr], r8
        mov     [rax], r9

        mov     dword ptr [rax + OFFSETOF__ArrayBase__m_NumComponents], edx

ifdef _DEBUG
        call    DEBUG_TrialAllocSetAppDomain_NoScratchArea
endif ; _DEBUG

        ret

    OversizedArray:
    AllocFailed:
        jmp     JIT_NewArr1
LEAF_END JIT_NewArr1VC_MP_InlineGetThread, _TEXT


; HCIMPL2(Object*, JIT_NewArr1, CORINFO_CLASS_HANDLE arrayTypeHnd_, INT_PTR size)
LEAF_ENTRY JIT_NewArr1OBJ_MP_InlineGetThread, _TEXT
        ; We were passed a type descriptor in RCX, which contains the (shared)
        ; array method table and the element type.

        ; The element count is in RDX

        ; NOTE: if this code is ported for CORINFO_HELP_NEWSFAST_ALIGN8, it will need
        ; to emulate the double-specific behavior of JIT_TrialAlloc::GenAllocArray.

        ; Verifies that LARGE_OBJECT_SIZE fits in 32-bit.  This allows us to do array size
        ; arithmetic using 32-bit registers.
        .erre ASM_LARGE_OBJECT_SIZE lt 100000000h

        cmp     rdx, (ASM_LARGE_OBJECT_SIZE - 256)/8 ; sizeof(void*)
        jae     OversizedArray

        ; we need to load the true method table from the type desc
        mov     r9, [rcx + OFFSETOF__ArrayTypeDesc__m_TemplateMT - 2]
        
        FIX_INDIRECTION r9

        ; In this case we know the element size is sizeof(void *), or 8 for x64
        ; This helps us in two ways - we can shift instead of multiplying, and
        ; there's no need to align the size either

        mov     r8d, dword ptr [r9 + OFFSET__MethodTable__m_BaseSize]
        lea     r8d, [r8d + edx * 8]

        ; No need for rounding in this case - element size is 8, and m_BaseSize is guaranteed
        ; to be a multiple of 8.

        PATCHABLE_INLINE_GETTHREAD r11, JIT_NewArr1OBJ_MP_InlineGetThread__PatchTLSOffset
        mov     r10, [r11 + OFFSET__Thread__m_alloc_context__alloc_limit]
        mov     rax, [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr]

        add     r8, rax

        cmp     r8, r10
        ja      AllocFailed

        mov     [r11 + OFFSET__Thread__m_alloc_context__alloc_ptr], r8
        mov     [rax], r9

        mov     dword ptr [rax + OFFSETOF__ArrayBase__m_NumComponents], edx

ifdef _DEBUG
        call    DEBUG_TrialAllocSetAppDomain_NoScratchArea
endif ; _DEBUG

        ret

    OversizedArray:
    AllocFailed:
        jmp     JIT_NewArr1
LEAF_END JIT_NewArr1OBJ_MP_InlineGetThread, _TEXT


MON_ENTER_STACK_SIZE                equ     00000020h
MON_EXIT_STACK_SIZE                 equ     00000068h

ifdef MON_DEBUG
ifdef TRACK_SYNC
MON_ENTER_STACK_SIZE_INLINEGETTHREAD equ     00000020h
MON_EXIT_STACK_SIZE_INLINEGETTHREAD  equ     00000068h
endif
endif

BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX    equ     08000000h   ; syncblk.h
BIT_SBLK_IS_HASHCODE                equ     04000000h   ; syncblk.h
BIT_SBLK_SPIN_LOCK                  equ     10000000h   ; syncblk.h

SBLK_MASK_LOCK_THREADID             equ     000003FFh   ; syncblk.h
SBLK_LOCK_RECLEVEL_INC              equ     00000400h   ; syncblk.h
SBLK_MASK_LOCK_RECLEVEL             equ     0000FC00h   ; syncblk.h

MASK_SYNCBLOCKINDEX                 equ     03FFFFFFh   ; syncblk.h
STATE_CHECK                         equ    0FFFFFFFEh

MT_CTX_PROXY_FLAG                   equ     10000000h

g_pSyncTable    equ ?g_pSyncTable@@3PEAVSyncTableEntry@@EA
g_SystemInfo    equ ?g_SystemInfo@@3U_SYSTEM_INFO@@A
g_SpinConstants equ ?g_SpinConstants@@3USpinConstants@@A

extern g_pSyncTable:QWORD
extern g_SystemInfo:QWORD
extern g_SpinConstants:QWORD

; JITutil_MonEnterWorker(Object* obj, BYTE* pbLockTaken)
extern JITutil_MonEnterWorker:proc
; JITutil_MonTryEnter(Object* obj, INT32 timeout, BYTE* pbLockTaken)
extern JITutil_MonTryEnter:proc
; JITutil_MonExitWorker(Object* obj, BYTE* pbLockTaken)
extern JITutil_MonExitWorker:proc
; JITutil_MonSignal(AwareLock* lock, BYTE* pbLockTaken)
extern JITutil_MonSignal:proc
; JITutil_MonContention(AwareLock* lock, BYTE* pbLockTaken)
extern JITutil_MonContention:proc

ifdef _DEBUG
MON_DEBUG   equ  1
endif

ifdef MON_DEBUG
ifdef TRACK_SYNC
extern EnterSyncHelper:proc
extern LeaveSyncHelper:proc
endif
endif


MON_ENTER_EPILOG_ADJUST_STACK macro
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MON_ENTER_STACK_SIZE_INLINEGETTHREAD
endif
endif
        endm


MON_ENTER_RETURN_SUCCESS macro
        ; This is sensitive to the potential that pbLockTaken is NULL
        test    rsi, rsi
        jz      @F
        mov     byte ptr [rsi], 1
    @@:
        MON_ENTER_EPILOG_ADJUST_STACK
        pop     rsi
        ret

        endm

        
; The worker versions of these functions are smart about the potential for pbLockTaken
; to be NULL, and if it is then they treat it as if they don't have a state variable.
; This is because when locking is not inserted by the JIT (instead by explicit calls to
; Monitor.Enter() and Monitor.Exit()) we will call these guys.
;
; This is a frameless helper for entering a monitor on a object.
; The object is in ARGUMENT_REG1.  This tries the normal case (no
; blocking or object allocation) in line and calls a framed helper
; for the other cases.
;
; EXTERN_C void JIT_MonEnterWorker_InlineGetThread(Object* obj, /*OUT*/ BYTE* pbLockTaken)
JIT_HELPER_MONITOR_THUNK JIT_MonEnter, _TEXT
NESTED_ENTRY JIT_MonEnterWorker_InlineGetThread, _TEXT
        push_nonvol_reg     rsi
ifdef MON_DEBUG
ifdef TRACK_SYNC
        alloc_stack         MON_ENTER_STACK_SIZE_INLINEGETTHREAD

        save_reg_postrsp    rcx, MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 10h + 0h
        save_reg_postrsp    rdx, MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 10h + 8h
        save_reg_postrsp    r8,  MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 10h + 10h
        save_reg_postrsp    r9,  MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 10h + 18h
endif
endif
        END_PROLOGUE

        ; Put pbLockTaken in rsi, this can be null
        mov     rsi, rdx

        ; Check if the instance is NULL
        test    rcx, rcx
        jz      FramedLockHelper

        PATCHABLE_INLINE_GETTHREAD r11, JIT_MonEnterWorker_InlineGetThread_GetThread_PatchLabel

        ; Initialize delay value for retry with exponential backoff
        mov     r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwInitialDuration]

        ; Check if we can abort here
        mov     eax, dword ptr [r11 + OFFSETOF__Thread__m_State]
        and     eax, THREAD_CATCHATSAFEPOINT_BITS
        ; Go through the slow code path to initiate ThreadAbort
        jnz     FramedLockHelper

        ; r8 will hold the syncblockindex address
        lea     r8, [rcx - OFFSETOF__ObjHeader__SyncBlkIndex]

    RetryThinLock:
        ; Fetch the syncblock dword
        mov     eax, dword ptr [r8]

        ; Check whether we have the "thin lock" layout, the lock is free and the spin lock bit is not set
        test    eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX + BIT_SBLK_SPIN_LOCK + SBLK_MASK_LOCK_THREADID + SBLK_MASK_LOCK_RECLEVEL
        jnz     NeedMoreTests

        ; Everything is fine - get the thread id to store in the lock
        mov     edx, dword ptr [r11 + OFFSETOF__Thread__m_ThreadId]

        ; If the thread id is too large, we need a syncblock for sure
        cmp     edx, SBLK_MASK_LOCK_THREADID
        ja      FramedLockHelper

        ; We want to store a new value with the current thread id set in the low 10 bits
        or      edx, eax
   lock cmpxchg dword ptr [r8], edx
        jnz     PrepareToWaitThinLock

        ; Everything went fine and we're done
        add     dword ptr [r11 + OFFSETOF__Thread__m_dwLockCount], 1

        ; Done, leave and set pbLockTaken if we have it
        MON_ENTER_RETURN_SUCCESS

    NeedMoreTests:
        ; OK, not the simple case, find out which case it is
        test    eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX
        jnz     HaveHashOrSyncBlockIndex

        ; The header is transitioning or the lock, treat this as if the lock was taken
        test    eax, BIT_SBLK_SPIN_LOCK
        jnz     PrepareToWaitThinLock

        ; Here we know we have the "thin lock" layout, but the lock is not free.
        ; It could still be the recursion case, compare the thread id to check
        mov     edx, eax
        and     edx, SBLK_MASK_LOCK_THREADID
        cmp     edx, dword ptr [r11 + OFFSETOF__Thread__m_ThreadId]
        jne     PrepareToWaitThinLock

        ; Ok, the thread id matches, it's the recursion case.
        ; Bump up the recursion level and check for overflow
        lea     edx, [eax + SBLK_LOCK_RECLEVEL_INC]
        test    edx, SBLK_MASK_LOCK_RECLEVEL
        jz      FramedLockHelper

        ; Try to put the new recursion level back. If the header was changed in the meantime
        ; we need a full retry, because the layout could have changed
   lock cmpxchg dword ptr [r8], edx
        jnz     RetryHelperThinLock

        ; Done, leave and set pbLockTaken if we have it
        MON_ENTER_RETURN_SUCCESS

    PrepareToWaitThinLock:
        ; If we are on an MP system, we try spinning for a certain number of iterations
        cmp     dword ptr [g_SystemInfo + OFFSETOF__g_SystemInfo__dwNumberOfProcessors], 1
        jle     FramedLockHelper

        ; Exponential backoff; delay by approximately 2*r10 clock cycles
        mov     eax, r10d
    delayLoopThinLock:
        pause   ; indicate to the CPU that we are spin waiting
        sub     eax, 1
        jnz     delayLoopThinLock

        ; Next time, wait a factor longer
        imul    r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwBackoffFactor]

        cmp     r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwMaximumDuration]
        jle     RetryHelperThinLock

        jmp     FramedLockHelper

    RetryHelperThinLock:
        jmp     RetryThinLock

    HaveHashOrSyncBlockIndex:
        ; If we have a hash code already, we need to create a sync block
        test    eax, BIT_SBLK_IS_HASHCODE
        jnz     FramedLockHelper

        ; OK, we have a sync block index, just and out the top bits and grab the synblock index
        and     eax, MASK_SYNCBLOCKINDEX

        ; Get the sync block pointer
        mov     rdx, qword ptr [g_pSyncTable]
        shl     eax, 4h
        mov     rdx, [rdx + rax + OFFSETOF__SyncTableEntry__m_SyncBlock]

        ; Check if the sync block has been allocated
        test    rdx, rdx
        jz      FramedLockHelper

        ; Get a pointer to the lock object
        lea     rdx, [rdx + OFFSETOF__SyncBlock__m_Monitor]

        ; Attempt to acquire the lock
    RetrySyncBlock:
        mov     eax, dword ptr [rdx + OFFSETOF__AwareLock__m_MonitorHeld]
        test    eax, eax
        jne     HaveWaiters

        ; Common case, lock isn't held and there are no waiters. Attempt to
        ; gain ownership ourselves
        xor     ecx, ecx
        inc     ecx

   lock cmpxchg dword ptr [rdx + OFFSETOF__AwareLock__m_MonitorHeld], ecx
        jnz     RetryHelperSyncBlock

        ; Success. Save the thread object in the lock and increment the use count
        mov     qword ptr [rdx + OFFSETOF__AwareLock__m_HoldingThread], r11
        add     dword ptr [rdx + OFFSETOF__AwareLock__m_Recursion], 1
        add     dword ptr [r11 + OFFSETOF__Thread__m_dwLockCount], 1

ifdef MON_DEBUG
ifdef TRACK_SYNC
        mov     rcx, [rsp + MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 8h]       ; return address
        ; void EnterSyncHelper(UINT_PTR caller, AwareLock* lock)
        call    EnterSyncHelper
endif
endif

        ; Done, leave and set pbLockTaken if we have it
        MON_ENTER_RETURN_SUCCESS

        ; It's possible to get here with waiters by no lock held, but in this
        ; case a signal is about to be fired which will wake up the waiter. So
        ; for fairness sake we should wait too.
        ; Check first for recur11ve lock attempts on the same thread.
    HaveWaiters:
        ; Is mutex already owned by current thread?
        cmp     [rdx + OFFSETOF__AwareLock__m_HoldingThread], r11
        jne     PrepareToWait

        ; Yes, bump our use count.
        add     dword ptr [rdx + OFFSETOF__AwareLock__m_Recursion], 1

ifdef MON_DEBUG
ifdef TRACK_SYNC
        mov     rcx, [rsp + MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 8h]       ; return address
        ; void EnterSyncHelper(UINT_PTR caller, AwareLock* lock)
        call    EnterSyncHelper
endif
endif
        ; Done, leave and set pbLockTaken if we have it
        MON_ENTER_RETURN_SUCCESS

    PrepareToWait:
        ; If we are on a MP system we try spinning for a certain number of iterations
        cmp     dword ptr [g_SystemInfo + OFFSETOF__g_SystemInfo__dwNumberOfProcessors], 1
        jle     HaveWaiters1

        ; Exponential backoff: delay by approximately 2*r10 clock cycles
        mov     eax, r10d
    delayLoop:
        pause   ; indicate to the CPU that we are spin waiting
        sub     eax, 1
        jnz     delayLoop

        ; Next time, wait a factor longer
        imul    r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwBackoffFactor]

        cmp     r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwMaximumDuration]
        jle     RetrySyncBlock

    HaveWaiters1:
        mov     rcx, rdx
        mov     rdx, rsi
        MON_ENTER_EPILOG_ADJUST_STACK
        pop     rsi
        ; void JITutil_MonContention(AwareLock* lock, BYTE* pbLockTaken)
        jmp     JITutil_MonContention

    RetryHelperSyncBlock:
        jmp     RetrySyncBlock

    FramedLockHelper:
        mov     rdx, rsi
        MON_ENTER_EPILOG_ADJUST_STACK
        pop     rsi
        ; void JITutil_MonEnterWorker(Object* obj, BYTE* pbLockTaken)
        jmp     JITutil_MonEnterWorker

NESTED_END JIT_MonEnterWorker_InlineGetThread, _TEXT


MON_EXIT_EPILOG_ADJUST_STACK macro
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MON_EXIT_STACK_SIZE_INLINEGETTHREAD
endif
endif
        endm

MON_EXIT_RETURN_SUCCESS macro
        ; This is sensitive to the potential that pbLockTaken is null
        test    r10, r10
        jz      @F
        mov     byte ptr [r10], 0
    @@:
        MON_EXIT_EPILOG_ADJUST_STACK
        ret

        endm

               
; The worker versions of these functions are smart about the potential for pbLockTaken
; to be NULL, and if it is then they treat it as if they don't have a state variable.
; This is because when locking is not inserted by the JIT (instead by explicit calls to
; Monitor.Enter() and Monitor.Exit()) we will call these guys.
;
; This is a frameless helper for exiting a monitor on a object.
; The object is in ARGUMENT_REG1.  This tries the normal case (no
; blocking or object allocation) in line and calls a framed helper
; for the other cases.
;
; void JIT_MonExitWorker_InlineGetThread(Object* obj, BYTE* pbLockTaken)
JIT_HELPER_MONITOR_THUNK JIT_MonExit, _TEXT
NESTED_ENTRY JIT_MonExitWorker_InlineGetThread, _TEXT
        .savereg    rcx, 0
ifdef MON_DEBUG
ifdef TRACK_SYNC
        alloc_stack         MON_EXIT_STACK_SIZE_INLINEGETTHREAD

        save_reg_postrsp    rcx, MON_EXIT_STACK_SIZE_INLINEGETTHREAD + 8h + 0h
        save_reg_postrsp    rdx, MON_EXIT_STACK_SIZE_INLINEGETTHREAD + 8h + 8h
        save_reg_postrsp    r8,  MON_EXIT_STACK_SIZE_INLINEGETTHREAD + 8h + 10h
        save_reg_postrsp    r9,  MON_EXIT_STACK_SIZE_INLINEGETTHREAD + 8h + 18h
endif
endif 
        END_PROLOGUE

        ; pbLockTaken is stored in r10, this can be null
        mov     r10, rdx

        ; if pbLockTaken is NULL then we got here without a state variable, avoid the
        ; next comparison in that case as it will AV
        test    rdx, rdx
        jz      Null_pbLockTaken

        ; If the lock wasn't taken then we bail quickly without doing anything
        cmp     byte ptr [rdx], 0
        je      LockNotTaken

    Null_pbLockTaken:
        ; Check is the instance is null
        test    rcx, rcx
        jz      FramedLockHelper

        PATCHABLE_INLINE_GETTHREAD r11, JIT_MonExitWorker_InlineGetThread_GetThread_PatchLabel

        ; r8 will hold the syncblockindex address
        lea     r8, [rcx - OFFSETOF__ObjHeader__SyncBlkIndex]

    RetryThinLock:
        ; Fetch the syncblock dword
        mov     eax, dword ptr [r8]
        test    eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX + BIT_SBLK_SPIN_LOCK
        jnz     NeedMoreTests

        ; Ok, we have a "thin lock" layout - check whether the thread id matches
        mov     edx, eax
        and     edx, SBLK_MASK_LOCK_THREADID
        cmp     edx, dword ptr [r11 + OFFSETOF__Thread__m_ThreadId]
        jne     FramedLockHelper

        ; check the recursion level
        test    eax, SBLK_MASK_LOCK_RECLEVEL
        jne     DecRecursionLevel

        ; It's zero -- we're leaving the lock.
        ; So try to put back a zero thread id.
        ; edx and eax match in the thread id bits, and edx is zero else where, so the xor is sufficient
        xor     edx, eax
   lock cmpxchg dword ptr [r8], edx
        jnz     RetryThinLockHelper1  ; forward jump to avoid mispredict on success

        ; Dec the dwLockCount on the thread
        sub     dword ptr [r11 + OFFSETOF__Thread__m_dwLockCount], 1

        ; Done, leave and set pbLockTaken if we have it
        MON_EXIT_RETURN_SUCCESS

    RetryThinLockHelper1:
        jmp     RetryThinLock

    DecRecursionLevel:
        lea     edx, [eax - SBLK_LOCK_RECLEVEL_INC]
   lock cmpxchg dword ptr [r8], edx
        jnz     RetryThinLockHelper2  ; forward jump to avoid mispredict on success

        ; We're done, leave and set pbLockTaken if we have it
        MON_EXIT_RETURN_SUCCESS
        
    RetryThinLockHelper2:
        jmp     RetryThinLock

    NeedMoreTests:
        ; Forward all special cases to the slow helper
        test    eax, BIT_SBLK_IS_HASHCODE + BIT_SBLK_SPIN_LOCK
        jnz     FramedLockHelper

        ; Get the sync block index and use it to compute the sync block pointer
        mov     rdx, qword ptr [g_pSyncTable]
        and     eax, MASK_SYNCBLOCKINDEX
        shl     eax, 4
        mov     rdx, [rdx + rax + OFFSETOF__SyncTableEntry__m_SyncBlock]

        ; Was there a sync block?
        test    rdx, rdx
        jz      FramedLockHelper

        ; Get a pointer to the lock object.
        lea     rdx, [rdx + OFFSETOF__SyncBlock__m_Monitor]

        ; Check if the lock is held.
        cmp     qword ptr [rdx + OFFSETOF__AwareLock__m_HoldingThread], r11
        jne     FramedLockHelper

ifdef MON_DEBUG
ifdef TRACK_SYNC
        mov     [rsp + 28h], rcx
        mov     [rsp + 30h], rdx
        mov     [rsp + 38h], r10
        mov     [rsp + 40h], r11

        mov     rcx, [rsp + MON_EXIT_STACK_SIZE_INLINEGETTHREAD ]       ; return address
        ; void LeaveSyncHelper(UINT_PTR caller, AwareLock* lock)
        call    LeaveSyncHelper

        mov     rcx, [rsp + 28h]
        mov     rdx, [rsp + 30h]
        mov     r10, [rsp + 38h]
        mov     r11, [rsp + 40h]
endif
endif

        ; Reduce our recursion count
        sub     dword ptr [rdx + OFFSETOF__AwareLock__m_Recursion], 1
        jz      LastRecursion

        ; Done, leave and set pbLockTaken if we have it
        MON_EXIT_RETURN_SUCCESS

    RetryHelperThinLock:
        jmp     RetryThinLock

    FramedLockHelper:
        mov     rdx, r10
        MON_EXIT_EPILOG_ADJUST_STACK
        ; void JITutil_MonExitWorker(Object* obj, BYTE* pbLockTaken)
        jmp     JITutil_MonExitWorker

    LastRecursion:
ifdef MON_DEBUG
ifdef TRACK_SYNC
        mov     rax, [rdx + OFFSETOF__AwareLock__m_HoldingThread]
endif
endif

        sub     dword ptr [r11 + OFFSETOF__Thread__m_dwLockCount], 1
        mov     qword ptr [rdx + OFFSETOF__AwareLock__m_HoldingThread], 0

    Retry:
        mov     eax, dword ptr [rdx + OFFSETOF__AwareLock__m_MonitorHeld]
        lea     r9d, [eax - 1]
   lock cmpxchg dword ptr [rdx + OFFSETOF__AwareLock__m_MonitorHeld], r9d
        jne     RetryHelper

        test    eax, STATE_CHECK
        jne     MustSignal

        ; Done, leave and set pbLockTaken if we have it
        MON_EXIT_RETURN_SUCCESS

    MustSignal:
        mov     rcx, rdx
        mov     rdx, r10
        MON_EXIT_EPILOG_ADJUST_STACK
        ; void JITutil_MonSignal(AwareLock* lock, BYTE* pbLockTaken)
        jmp     JITutil_MonSignal

    RetryHelper:
        jmp     Retry

    LockNotTaken:
        MON_EXIT_EPILOG_ADJUST_STACK
        REPRET
NESTED_END JIT_MonExitWorker_InlineGetThread, _TEXT


; This is a frameless helper for trying to enter a monitor on a object.
; The object is in ARGUMENT_REG1 and a timeout in ARGUMENT_REG2. This tries the
; normal case (no object allocation) in line and calls a framed helper for the
; other cases.
;
; void JIT_MonTryEnter_InlineGetThread(Object* obj, INT32 timeOut, BYTE* pbLockTaken)
NESTED_ENTRY JIT_MonTryEnter_InlineGetThread, _TEXT
        ; save rcx, rdx (timeout) in the shadow space
        .savereg            rcx, 8h
        mov                 [rsp + 8h], rcx
        .savereg            rdx, 10h
        mov                 [rsp + 10h], rdx
ifdef MON_DEBUG
ifdef TRACK_SYNC        
        alloc_stack         MON_ENTER_STACK_SIZE_INLINEGETTHREAD

; rcx has already been saved
;        save_reg_postrsp    rcx, MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 8h + 0h
; rdx has already been saved
;        save_reg_postrsp    rdx, MON_ENTER_STACK_SIZE + 8h + 8h
        save_reg_postrsp    r8,  MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 8h + 10h
        save_reg_postrsp    r9,  MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 8h + 18h
endif
endif
        END_PROLOGUE

        ; Check if the instance is NULL
        test    rcx, rcx
        jz      FramedLockHelper

        ; Check if the timeout looks valid
        cmp     edx, -1
        jl      FramedLockHelper

        PATCHABLE_INLINE_GETTHREAD r11, JIT_MonTryEnter_GetThread_PatchLabel

        ; Initialize delay value for retry with exponential backoff
        mov     r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwInitialDuration]

        ; Check if we can abort here
        mov     eax, dword ptr [r11 + OFFSETOF__Thread__m_State]
        and     eax, THREAD_CATCHATSAFEPOINT_BITS
        ; Go through the slow code path to initiate THreadAbort
        jnz     FramedLockHelper

        ; r9 will hold the syncblockindex address
        lea     r9, [rcx - OFFSETOF__ObjHeader__SyncBlkIndex]

    RetryThinLock:
        ; Fetch the syncblock dword
        mov     eax, dword ptr [r9]

        ; Check whether we have the "thin lock" layout, the lock is free and the spin lock bit is not set
        test    eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX + BIT_SBLK_SPIN_LOCK + SBLK_MASK_LOCK_THREADID + SBLK_MASK_LOCK_RECLEVEL
        jne     NeedMoreTests

        ; Everything is fine - get the thread id to store in the lock
        mov     edx, dword ptr [r11 + OFFSETOF__Thread__m_ThreadId]

        ; If the thread id is too large, we need a syncblock for sure
        cmp     edx, SBLK_MASK_LOCK_THREADID
        ja      FramedLockHelper

        ; We want to store a new value with the current thread id set in the low 10 bits
        or      edx, eax
   lock cmpxchg dword ptr [r9], edx
        jnz     RetryHelperThinLock

        ; Got the lock, everything is fine
        add     dword ptr [r11 + OFFSETOF__Thread__m_dwLockCount], 1
        ; Return TRUE
        mov     byte ptr [r8], 1
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MON_ENTER_STACK_SIZE_INLINEGETTHREAD
endif
endif
        ret

    NeedMoreTests:
        ; OK, not the simple case, find out which case it is
        test    eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX
        jnz     HaveHashOrSyncBlockIndex

        ; The header is transitioning or the lock
        test    eax, BIT_SBLK_SPIN_LOCK
        jnz     RetryHelperThinLock

        ; Here we know we have the "thin lock" layout, but the lock is not free.
        ; It could still be the recursion case, compare the thread id to check
        mov     edx, eax
        and     edx, SBLK_MASK_LOCK_THREADID
        cmp     edx, dword ptr [r11 + OFFSETOF__Thread__m_ThreadId]
        jne     PrepareToWaitThinLock

        ; Ok, the thread id matches, it's the recursion case.
        ; Dump up the recursion level and check for overflow
        lea     edx, [eax + SBLK_LOCK_RECLEVEL_INC]
        test    edx, SBLK_MASK_LOCK_RECLEVEL
        jz      FramedLockHelper

        ; Try to put the new recursion level back. If the header was changed in the meantime
        ; we need a full retry, because the layout could have changed
   lock cmpxchg dword ptr [r9], edx
        jnz     RetryHelperThinLock

        ; Everything went fine and we're done, return TRUE
        mov     byte ptr [r8], 1
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MON_ENTER_STACK_SIZE_INLINEGETTHREAD
endif
endif
        ret

    PrepareToWaitThinLock:
        ; Return failure if timeout is zero
        cmp     dword ptr [rsp + 10h], 0
        je      TimeoutZero
 
        ; If we are on an MP system, we try spinning for a certain number of iterations
        cmp     dword ptr [g_SystemInfo + OFFSETOF__g_SystemInfo__dwNumberOfProcessors], 1
        jle     FramedLockHelper

        ; Exponential backoff; delay by approximately 2*r10d clock cycles
        mov     eax, r10d
    DelayLoopThinLock:
        pause   ; indicate to the CPU that we are spin waiting
        sub     eax, 1
        jnz     DelayLoopThinLock

        ; Next time, wait a factor longer
        imul    r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwBackoffFactor]

        cmp     r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwMaximumDuration]
        jle     RetryHelperThinLock

        jmp     FramedLockHelper

    RetryHelperThinLock:
        jmp     RetryThinLock

	TimeoutZero:
        ; Did not acquire, return FALSE
        mov     byte ptr [r8], 0
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MON_ENTER_STACK_SIZE_INLINEGETTHREAD
endif
endif
        ret

    HaveHashOrSyncBlockIndex:
        ; If we have a hash code already, we need to create a sync block
        test    eax, BIT_SBLK_IS_HASHCODE
        jnz     FramedLockHelper

        ; OK, we have a sync block index, just and out the top bits and grab the synblock index
        and     eax, MASK_SYNCBLOCKINDEX

        ; Get the sync block pointer
        mov     rdx, qword ptr [g_pSyncTable]
        shl     eax, 4
        mov     rdx, [rdx + rax + OFFSETOF__SyncTableEntry__m_SyncBlock]

        ; Check if the sync block has been allocated
        test    rdx, rdx
        jz      FramedLockHelper

        ; Get a pointer to the lock object
        lea     rdx, [rdx + OFFSETOF__SyncBlock__m_Monitor]

    RetrySyncBlock:
        ; Attempt to acuire the lock
        mov     eax, dword ptr [rdx + OFFSETOF__AwareLock__m_MonitorHeld]
        test    eax, eax
        jne     HaveWaiters

        ; Common case, lock isn't held and there are no waiters. Attempt to
        ; gain ownership ourselves
        xor     ecx, ecx
        inc     ecx
   lock cmpxchg dword ptr [rdx + OFFSETOF__AwareLock__m_MonitorHeld], ecx
        jnz     RetryHelperSyncBlock

        ; Success. Save the thread object in the lock and increment the use count
        mov     qword ptr [rdx + OFFSETOF__AwareLock__m_HoldingThread], r11
        add     dword ptr [rdx + OFFSETOF__AwareLock__m_Recursion], 1
        add     dword ptr [r11 + OFFSETOF__Thread__m_dwLockCount], 1

ifdef MON_DEBUG
ifdef TRACK_SYNC
        mov     rcx, [rsp + MON_ENTER_STACK_SIZE_INLINEGETTHREAD]       ; return address
        ; void EnterSyncHelper(UINT_PTR caller, AwareLock* lock)
        call    EnterSyncHelper
endif
endif

        ; Return TRUE
        mov     byte ptr [r8], 1
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MON_ENTER_STACK_SIZE_INLINEGETTHREAD
endif
endif
        ret

        ; It's possible to get here with waiters by no lock held, but in this
        ; case a signal is about to be fired which will wake up the waiter. So
        ; for fairness sake we should wait too.
        ; Check first for recur11ve lock attempts on the same thread.
    HaveWaiters:
        ; Is mutex already owned by current thread?
        cmp     [rdx + OFFSETOF__AwareLock__m_HoldingThread], r11
        jne     PrepareToWait

        ; Yes, bump our use count.
        add     dword ptr [rdx + OFFSETOF__AwareLock__m_Recursion], 1

ifdef MON_DEBUG
ifdef TRACK_SYNC
        mov     rcx, [rsp + MON_ENTER_STACK_SIZE_INLINEGETTHREAD]       ; return address
        ; void EnterSyncHelper(UINT_PTR caller, AwareLock* lock)
        call    EnterSyncHelper
endif
endif

        ; Return TRUE
        mov     byte ptr [r8], 1
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MON_ENTER_STACK_SIZE_INLINEGETTHREAD
endif
endif
        ret

    PrepareToWait:
        ; Return failure if timeout is zero
        cmp     dword ptr [rsp + 10h], 0
ifdef MON_DEBUG
ifdef TRACK_SYNC
        ; if we are using the _DEBUG stuff then rsp has been adjusted
        ; so compare the value at the adjusted position
        ; there's really little harm in the extra stack read
        cmp     dword ptr [rsp + MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 10h]
endif
endif
        je      TimeoutZero

        ; If we are on an MP system, we try spinning for a certain number of iterations
        cmp     dword ptr [g_SystemInfo + OFFSETOF__g_SystemInfo__dwNumberOfProcessors], 1
        jle     Block
    
        ; Exponential backoff; delay by approximately 2*r10d clock cycles
        mov     eax, r10d
    DelayLoop:
        pause   ; indicate to the CPU that we are spin waiting
        sub     eax, 1
        jnz     DelayLoop
    
        ; Next time, wait a factor longer
        imul    r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwBackoffFactor]
    
        cmp     r10d, dword ptr [g_SpinConstants + OFFSETOF__g_SpinConstants__dwMaximumDuration]
        jle     RetrySyncBlock

        jmp     Block

    RetryHelperSyncBlock:
        jmp     RetrySyncBlock

    Block:
        ; In the Block case we've trashed RCX, restore it
        mov     rcx, [rsp + 8h]
ifdef MON_DEBUG
ifdef TRACK_SYNC
        ; if we're tracking this stuff then rcx is at a different offset to RSP, we just
        ; overwrite the wrong value which we just got... this is for debug purposes only
        ; so there's really no performance issue here
        mov     rcx, [rsp + MON_ENTER_STACK_SIZE_INLINEGETTHREAD + 8h]
endif
endif
    FramedLockHelper:
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MON_ENTER_STACK_SIZE_INLINEGETTHREAD
endif
endif
        mov     rdx, [rsp + 10h]
        ; void JITutil_MonTryEnter(Object* obj, INT32 timeout)
        jmp     JITutil_MonTryEnter

NESTED_END JIT_MonTryEnter_InlineGetThread, _TEXT


MON_ENTER_STATIC_RETURN_SUCCESS macro
        ; pbLockTaken is never null for static helpers
        test    rdx, rdx
        mov     byte ptr [rdx], 1
        REPRET
        
        endm

MON_EXIT_STATIC_RETURN_SUCCESS macro
        ; pbLockTaken is never null for static helpers
        mov     byte ptr [rdx], 0
        REPRET
        
        endm


; This is a frameless helper for entering a static monitor on a class.
; The methoddesc is in ARGUMENT_REG1.  This tries the normal case (no
; blocking or object allocation) in line and calls a framed helper
; for the other cases.
;
; void JIT_MonEnterStatic_InlineGetThread(AwareLock *lock, BYTE *pbLockTaken)
NESTED_ENTRY JIT_MonEnterStatic_InlineGetThread, _TEXT
        .savereg            rcx, 0
ifdef MON_DEBUG
ifdef TRACK_SYNC
        alloc_stack         MIN_SIZE
        save_reg_postrsp    rcx, MIN_SIZE + 8h + 0h
endif
endif
    END_PROLOGUE

        ; Attempt to acquire the lock
    Retry:
        mov     eax, dword ptr [rcx + OFFSETOF__AwareLock__m_MonitorHeld]
        test    eax, eax
        jne     HaveWaiters

        ; Common case; lock isn't held and there are no waiters. Attempt to
        ; gain ownership by ourselves.
        mov     r10d, 1

   lock cmpxchg dword ptr [rcx + OFFSETOF__AwareLock__m_MonitorHeld], r10d
        jnz     RetryHelper

        PATCHABLE_INLINE_GETTHREAD rax, JIT_MonEnterStaticWorker_InlineGetThread_GetThread_PatchLabel_1
        
        mov     qword ptr [rcx + OFFSETOF__AwareLock__m_HoldingThread], rax
        add     dword ptr [rcx + OFFSETOF__AwareLock__m_Recursion], 1
        add     dword ptr [rax + OFFSETOF__Thread__m_dwLockCount], 1

ifdef MON_DEBUG
ifdef TRACK_SYNC
        mov     rdx, rcx
        mov     rcx, [rsp]
        add     rsp, MIN_SIZE
        ; void EnterSyncHelper(UINT_PTR caller, AwareLock* lock)
        jmp     EnterSyncHelper
endif
endif
        MON_ENTER_STATIC_RETURN_SUCCESS

        ; It's possible to get here with waiters by with no lock held, in this
        ; case a signal is about to be fired which will wake up a waiter. So
        ; for fairness sake we should wait too.
        ; Check first for recursive lock attempts on the same thread.
    HaveWaiters:
        PATCHABLE_INLINE_GETTHREAD rax, JIT_MonEnterStaticWorker_InlineGetThread_GetThread_PatchLabel_2

        ; Is mutex alread owned by current thread?
        cmp     [rcx + OFFSETOF__AwareLock__m_HoldingThread], rax
        jne     PrepareToWait

        ; Yes, bump our use count.
        add     dword ptr [rcx + OFFSETOF__AwareLock__m_Recursion], 1
ifdef MON_DEBUG
ifdef TRACK_SYNC
        mov     rdx, rcx
        mov     rcx, [rsp + MIN_SIZE]
        add     rsp, MIN_SIZE
        ; void EnterSyncHelper(UINT_PTR caller, AwareLock* lock)
        jmp     EnterSyncHelper
endif
endif
        ret

    PrepareToWait:
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MIN_SIZE
endif
endif
        ; void JITutil_MonContention(AwareLock* obj, BYTE* pbLockTaken)
        jmp     JITutil_MonContention

    RetryHelper:
        jmp     Retry
NESTED_END JIT_MonEnterStatic_InlineGetThread, _TEXT

; A frameless helper for exiting a static monitor on a class.
; The methoddesc is in ARGUMENT_REG1.  This tries the normal case (no
; blocking or object allocation) in line and calls a framed helper
; for the other cases.
;
; void JIT_MonExitStatic_InlineGetThread(AwareLock *lock, BYTE *pbLockTaken)
NESTED_ENTRY JIT_MonExitStatic_InlineGetThread, _TEXT
        .savereg        rcx, 0
ifdef MON_DEBUG
ifdef TRACK_SYNC
        alloc_stack     MIN_SIZE
        save_reg_postrsp    rcx, MIN_SIZE + 8h + 0h
endif
endif
    END_PROLOGUE

ifdef MON_DEBUG
ifdef TRACK_SYNC
        push    rsi
        push    rdi
        mov     rsi, rcx
        mov     rdi, rdx
        mov     rdx, [rsp + 8]
        call    LeaveSyncHelper
        mov     rcx, rsi
        mov     rdx, rdi
        pop     rdi
        pop     rsi
endif
endif
        PATCHABLE_INLINE_GETTHREAD rax, JIT_MonExitStaticWorker_InlineGetThread_GetThread_PatchLabel

        ; Check if lock is held        
        cmp     [rcx + OFFSETOF__AwareLock__m_HoldingThread], rax
        jne     LockError

        ; Reduce our recursion count
        sub     dword ptr [rcx + OFFSETOF__AwareLock__m_Recursion], 1
        jz      LastRecursion

ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MIN_SIZE
        ret
endif
endif
        REPRET

        ; This is the last count we held on this lock, so release the lock
    LastRecursion:
        ; Thead* is in rax
        sub     dword ptr [rax + OFFSETOF__Thread__m_dwLockCount], 1
        mov     qword ptr [rcx + OFFSETOF__AwareLock__m_HoldingThread], 0

    Retry:
        mov     eax, dword ptr [rcx + OFFSETOF__AwareLock__m_MonitorHeld]
        lea     r10d, [eax - 1]
   lock cmpxchg dword ptr [rcx + OFFSETOF__AwareLock__m_MonitorHeld], r10d
        jne     RetryHelper
        test    eax, STATE_CHECK
        jne     MustSignal

ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MIN_SIZE
        ret
endif
endif
        MON_EXIT_STATIC_RETURN_SUCCESS

    MustSignal:
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MIN_SIZE
endif
endif
        ; void JITutil_MonSignal(AwareLock* lock, BYTE* pbLockTaken)
        jmp     JITutil_MonSignal

    RetryHelper:
        jmp     Retry

    LockError:
        mov     rcx, CORINFO_SynchronizationLockException_ASM
ifdef MON_DEBUG
ifdef TRACK_SYNC
        add     rsp, MIN_SIZE
endif
endif
        ; void JIT_InternalThrow(unsigned exceptNum)
        jmp     JIT_InternalThrow
NESTED_END JIT_MonExitStatic_InlineGetThread, _TEXT

        end