forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprestub.cpp
4191 lines (3541 loc) · 146 KB
/
prestub.cpp
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ===========================================================================
// File: Prestub.cpp
//
// ===========================================================================
// This file contains the implementation for creating and using prestubs
// ===========================================================================
//
#include "common.h"
#include "vars.hpp"
#include "eeconfig.h"
#include "dllimport.h"
#include "comdelegate.h"
#include "dbginterface.h"
#include "stubgen.h"
#include "eventtrace.h"
#include "array.h"
#include "ecall.h"
#include "virtualcallstub.h"
#include "../debug/ee/debugger.h"
#ifdef FEATURE_COMINTEROP
#include "clrtocomcall.h"
#endif
#ifdef FEATURE_PERFMAP
#include "perfmap.h"
#endif
#include "methoddescbackpatchinfo.h"
#if defined(FEATURE_GDBJIT)
#include "gdbjit.h"
#endif // FEATURE_GDBJIT
#ifndef DACCESS_COMPILE
#include "customattribute.h"
#if defined(FEATURE_JIT_PITCHING)
EXTERN_C void CheckStacksAndPitch();
EXTERN_C void SavePitchingCandidate(MethodDesc* pMD, ULONG sizeOfCode);
EXTERN_C void DeleteFromPitchingCandidate(MethodDesc* pMD);
EXTERN_C void MarkMethodNotPitchingCandidate(MethodDesc* pMD);
#endif
EXTERN_C void STDCALL ThePreStubPatch();
#if defined(HAVE_GCCOVER)
CrstStatic MethodDesc::m_GCCoverCrst;
void MethodDesc::Init()
{
m_GCCoverCrst.Init(CrstGCCover);
}
#endif
#define LOG_USING_R2R_CODE(method) LOG((LF_ZAP, LL_INFO10000, \
"ZAP: Using R2R precompiled code" FMT_ADDR " for %s.%s sig=\"%s\" (token %x).\n", \
DBG_ADDR(pCode), \
m_pszDebugClassName, \
m_pszDebugMethodName, \
m_pszDebugMethodSignature, \
GetMemberDef()));
//==========================================================================
PCODE MethodDesc::DoBackpatch(MethodTable * pMT, MethodTable *pDispatchingMT, BOOL fFullBackPatch)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(!ContainsGenericVariables());
PRECONDITION(pMT == GetMethodTable());
}
CONTRACTL_END;
bool isVersionableWithVtableSlotBackpatch = IsVersionableWithVtableSlotBackpatch();
LoaderAllocator *mdLoaderAllocator = isVersionableWithVtableSlotBackpatch ? GetLoaderAllocator() : nullptr;
// Only take the lock if the method is versionable with vtable slot backpatch, for recording slots and synchronizing with
// backpatching slots
MethodDescBackpatchInfoTracker::ConditionalLockHolder slotBackpatchLockHolder(isVersionableWithVtableSlotBackpatch);
// Get the method entry point inside the lock above to synchronize with backpatching in
// MethodDesc::BackpatchEntryPointSlots()
PCODE pTarget = GetMethodEntryPoint();
PCODE pExpected;
if (isVersionableWithVtableSlotBackpatch)
{
_ASSERTE(pTarget == GetEntryPointToBackpatch_Locked());
pExpected = GetTemporaryEntryPoint();
if (pExpected == pTarget)
return pTarget;
// True interface methods are never backpatched and are not versionable with vtable slot backpatch
_ASSERTE(!(pMT->IsInterface() && !IsStatic()));
// Backpatching the funcptr stub:
// For methods versionable with vtable slot backpatch, a funcptr stub is guaranteed to point to the at-the-time
// current entry point shortly after creation, and backpatching it further is taken care of by
// MethodDesc::BackpatchEntryPointSlots()
// Backpatching the temporary entry point:
// The temporary entry point is never backpatched for methods versionable with vtable slot backpatch. New vtable
// slots inheriting the method will initially point to the temporary entry point and it must point to the prestub
// and come here for backpatching such that the new vtable slot can be discovered and recorded for future
// backpatching.
_ASSERTE(!HasNonVtableSlot());
}
else
{
_ASSERTE(pTarget == GetStableEntryPoint());
pExpected = GetTemporaryEntryPoint();
if (pExpected == pTarget)
return pTarget;
// True interface methods are never backpatched
if (pMT->IsInterface() && !IsStatic())
return pTarget;
if (fFullBackPatch)
{
FuncPtrStubs * pFuncPtrStubs = GetLoaderAllocator()->GetFuncPtrStubsNoCreate();
if (pFuncPtrStubs != NULL)
{
Precode* pFuncPtrPrecode = pFuncPtrStubs->Lookup(this);
if (pFuncPtrPrecode != NULL)
{
// If there is a funcptr precode to patch, we are done for this round.
if (pFuncPtrPrecode->SetTargetInterlocked(pTarget))
return pTarget;
}
}
// Patch the fake entrypoint if necessary
Precode::GetPrecodeFromEntryPoint(pExpected)->SetTargetInterlocked(pTarget);
}
if (HasNonVtableSlot())
return pTarget;
}
auto RecordAndBackpatchSlot = [&](MethodTable *patchedMT, DWORD slotIndex)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(isVersionableWithVtableSlotBackpatch);
RecordAndBackpatchEntryPointSlot_Locked(
mdLoaderAllocator,
patchedMT->GetLoaderAllocator(),
dac_cast<TADDR>(patchedMT->GetSlotPtr(slotIndex)),
EntryPointSlots::SlotType_Vtable,
pTarget);
};
BOOL fBackpatched = FALSE;
#define BACKPATCH(pPatchedMT) \
do \
{ \
if (pPatchedMT->GetSlot(dwSlot) == pExpected) \
{ \
if (isVersionableWithVtableSlotBackpatch) \
{ \
RecordAndBackpatchSlot(pPatchedMT, dwSlot); \
} \
else \
{ \
pPatchedMT->SetSlot(dwSlot, pTarget); \
} \
fBackpatched = TRUE; \
} \
} \
while(0)
// The owning slot has been updated already, so there is no need to backpatch it
_ASSERTE(pMT->GetSlot(GetSlot()) == pTarget);
if (pDispatchingMT != NULL && pDispatchingMT != pMT)
{
DWORD dwSlot = GetSlot();
BACKPATCH(pDispatchingMT);
if (fFullBackPatch)
{
//
// Backpatch the MethodTable that code:MethodTable::GetRestoredSlot() reads the value from.
// VSD reads the slot value using code:MethodTable::GetRestoredSlot(), and so we need to make sure
// that it returns the stable entrypoint eventually to avoid going through the slow path all the time.
//
MethodTable * pRestoredSlotMT = pDispatchingMT->GetRestoredSlotMT(dwSlot);
if (pRestoredSlotMT != pDispatchingMT)
{
BACKPATCH(pRestoredSlotMT);
}
}
}
if (IsMethodImpl())
{
MethodImpl::Iterator it(this);
while (it.IsValid())
{
DWORD dwSlot = it.GetSlot();
BACKPATCH(pMT);
if (pDispatchingMT != NULL && pDispatchingMT != pMT)
{
BACKPATCH(pDispatchingMT);
}
it.Next();
}
}
if (fFullBackPatch && !fBackpatched && IsDuplicate())
{
// If this is a duplicate, let's scan the rest of the VTable hunting for other hits.
unsigned numSlots = pMT->GetNumVirtuals();
for (DWORD dwSlot=0; dwSlot<numSlots; dwSlot++)
{
BACKPATCH(pMT);
if (pDispatchingMT != NULL && pDispatchingMT != pMT)
{
BACKPATCH(pDispatchingMT);
}
}
}
#undef BACKPATCH
return pTarget;
}
// <TODO> FIX IN BETA 2
//
// g_pNotificationTable is only modified by the DAC and therefore the
// optimizer can assume that it will always be its default value and has
// been seen to (on IA64 free builds) eliminate the code in DACNotifyCompilationFinished
// such that DAC notifications are no longer sent.
//
// TODO: fix this in Beta 2
// the RIGHT fix is to make g_pNotificationTable volatile, but currently
// we don't have DAC macros to do that. Additionally, there are a number
// of other places we should look at DAC definitions to determine if they
// should be also declared volatile.
//
// for now we just turn off optimization for these guys
#ifdef _MSC_VER
#pragma optimize("", off)
#endif
void DACNotifyCompilationFinished(MethodDesc *methodDesc, PCODE pCode)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
// Is the list active?
JITNotifications jn(g_pNotificationTable);
if (jn.IsActive())
{
// Get Module and mdToken
mdToken t = methodDesc->GetMemberDef();
Module *modulePtr = methodDesc->GetModule();
_ASSERTE(modulePtr);
// Are we listed?
USHORT jnt = jn.Requested((TADDR) modulePtr, t);
if (jnt & CLRDATA_METHNOTIFY_GENERATED)
{
// If so, throw an exception!
DACNotify::DoJITNotification(methodDesc, (TADDR)pCode);
}
}
}
#ifdef _MSC_VER
#pragma optimize("", on)
#endif
// </TODO>
PCODE MethodDesc::PrepareInitialCode(CallerGCMode callerGCMode)
{
STANDARD_VM_CONTRACT;
PrepareCodeConfig config(NativeCodeVersion(this), TRUE, TRUE);
config.SetCallerGCMode(callerGCMode);
return PrepareCode(&config);
}
PCODE MethodDesc::PrepareCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
// If other kinds of code need multi-versioning we could add more cases here,
// but for now generation of all other code/stubs occurs in other code paths
_ASSERTE(IsIL() || IsNoMetadata());
PCODE pCode = PrepareILBasedCode(pConfig);
#if defined(FEATURE_GDBJIT) && defined(TARGET_UNIX)
NotifyGdb::MethodPrepared(this);
#endif
return pCode;
}
bool MayUsePrecompiledILStub()
{
if (g_pConfig->InteropValidatePinnedObjects())
return false;
if (CORProfilerTrackTransitions())
return false;
if (g_pConfig->InteropLogArguments())
return false;
return true;
}
PCODE MethodDesc::PrepareILBasedCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
PCODE pCode = (PCODE)NULL;
bool shouldTier = false;
#if defined(FEATURE_TIERED_COMPILATION)
shouldTier = pConfig->GetMethodDesc()->IsEligibleForTieredCompilation();
// If the method is eligible for tiering but is being
// called from a Preemptive GC Mode thread or the method
// has the UnmanagedCallersOnlyAttribute then the Tiered Compilation
// should be disabled.
if (shouldTier
&& (pConfig->GetCallerGCMode() == CallerGCMode::Preemptive
|| (pConfig->GetCallerGCMode() == CallerGCMode::Unknown
&& HasUnmanagedCallersOnlyAttribute())))
{
NativeCodeVersion codeVersion = pConfig->GetCodeVersion();
if (codeVersion.IsDefaultVersion())
{
pConfig->GetMethodDesc()->GetLoaderAllocator()->GetCallCountingManager()->DisableCallCounting(codeVersion);
_ASSERTE(codeVersion.IsFinalTier());
}
else if (!codeVersion.IsFinalTier())
{
codeVersion.SetOptimizationTier(NativeCodeVersion::OptimizationTierOptimized);
}
pConfig->SetWasTieringDisabledBeforeJitting();
shouldTier = false;
}
#endif // FEATURE_TIERED_COMPILATION
NativeCodeVersion nativeCodeVersion = pConfig->GetCodeVersion();
if (shouldTier && !nativeCodeVersion.IsDefaultVersion())
{
CodeVersionManager::LockHolder codeVersioningLockHolder;
if (pConfig->GetCodeVersion().GetILCodeVersion().IsDeoptimized())
{
shouldTier = false;
}
}
if (pConfig->MayUsePrecompiledCode())
{
#ifdef FEATURE_READYTORUN
if (IsDynamicMethod() && GetLoaderModule()->IsSystem() && MayUsePrecompiledILStub())
{
// Images produced using crossgen2 have non-shareable pinvoke stubs which can't be used with the IL
// stubs that the runtime generates (they take no secret parameter, and each pinvoke has a separate code)
if (GetModule()->IsReadyToRun() && !GetModule()->GetReadyToRunInfo()->HasNonShareablePInvokeStubs())
{
DynamicMethodDesc* stubMethodDesc = this->AsDynamicMethodDesc();
if (stubMethodDesc->IsILStub() && stubMethodDesc->IsPInvokeStub())
{
MethodDesc* pTargetMD = stubMethodDesc->GetILStubResolver()->GetStubTargetMethodDesc();
if (pTargetMD != NULL)
{
pCode = pTargetMD->GetPrecompiledR2RCode(pConfig);
if (pCode != (PCODE)NULL)
{
LOG_USING_R2R_CODE(this);
pConfig->SetNativeCode(pCode, &pCode);
}
}
}
}
}
#endif // FEATURE_READYTORUN
if (pCode == (PCODE)NULL)
{
pCode = GetPrecompiledCode(pConfig, shouldTier);
}
#ifdef FEATURE_PERFMAP
if (pCode != (PCODE)NULL)
PerfMap::LogPreCompiledMethod(this, pCode);
#endif
}
if (pConfig->IsForMulticoreJit() && pCode == (PCODE)NULL && pConfig->ReadyToRunRejectedPrecompiledCode())
{
// Was unable to load code from r2r image in mcj thread, don't try to jit it, this method will be loaded later
return (PCODE)NULL;
}
if (pCode == (PCODE)NULL)
{
LOG((LF_CLASSLOADER, LL_INFO1000000,
" In PrepareILBasedCode, calling JitCompileCode\n"));
pCode = JitCompileCode(pConfig);
#ifdef FEATURE_INTERPRETER
if (pConfig->IsInterpreterCode())
{
AllocMemTracker amt;
InterpreterPrecode* pPrecode = Precode::AllocateInterpreterPrecode(pCode, GetLoaderAllocator(), &amt);
amt.SuppressRelease();
pCode = PINSTRToPCODE(pPrecode->GetEntryPoint());
SetNativeCodeInterlocked(pCode);
}
#endif // FEATURE_INTERPRETER
}
else
{
DACNotifyCompilationFinished(this, pCode);
}
return pCode;
}
PCODE MethodDesc::GetPrecompiledCode(PrepareCodeConfig* pConfig, bool shouldTier)
{
STANDARD_VM_CONTRACT;
PCODE pCode = (PCODE)NULL;
#ifdef FEATURE_READYTORUN
pCode = GetPrecompiledR2RCode(pConfig);
if (pCode != (PCODE)NULL)
{
LOG_USING_R2R_CODE(this);
#ifdef FEATURE_TIERED_COMPILATION
// Finalize the optimization tier before SetNativeCode() is called
bool shouldCountCalls = shouldTier && pConfig->FinalizeOptimizationTierForTier0Load();
#endif
if (pConfig->SetNativeCode(pCode, &pCode))
{
#ifdef FEATURE_CODE_VERSIONING
pConfig->SetGeneratedOrLoadedNewCode();
#endif
#ifdef FEATURE_TIERED_COMPILATION
if (shouldCountCalls)
{
_ASSERTE(!pConfig->GetCodeVersion().IsFinalTier());
pConfig->SetShouldCountCalls();
}
#endif
#ifdef FEATURE_MULTICOREJIT
// Multi-core JIT is only applicable to the default code version. A method is recorded in the profile only when
// SetNativeCode() above succeeds to avoid recording duplicates in the multi-core JIT profile. Successful loads
// of R2R code are also recorded.
if (pConfig->NeedsMulticoreJitNotification())
{
_ASSERTE(pConfig->GetCodeVersion().IsDefaultVersion());
_ASSERTE(!pConfig->IsForMulticoreJit());
MulticoreJitManager & mcJitManager = GetAppDomain()->GetMulticoreJitManager();
if (mcJitManager.IsRecorderActive())
{
if (MulticoreJitManager::IsMethodSupported(this))
{
mcJitManager.RecordMethodJitOrLoad(this);
}
}
}
#endif
}
}
#endif // FEATURE_READYTORUN
return pCode;
}
PCODE MethodDesc::GetPrecompiledR2RCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
PCODE pCode = (PCODE)NULL;
#ifdef FEATURE_READYTORUN
ReadyToRunInfo* pAlreadyExaminedInfos[2] = {NULL, NULL};
Module * pModule = GetModule();
if (pModule->IsReadyToRun())
{
pAlreadyExaminedInfos[0] = pModule->GetReadyToRunInfo();
pCode = pAlreadyExaminedInfos[0]->GetEntryPoint(this, pConfig, TRUE /* fFixups */);
}
// Generics may be located in several places
if (pCode == (PCODE)NULL && HasClassOrMethodInstantiation())
{
// Generics have an alternative location that is looked up which is based on the first generic
// argument that the crossgen2 compiler will consider as requiring the cross module compilation logic to kick in.
pAlreadyExaminedInfos[1] = ReadyToRunInfo::ComputeAlternateGenericLocationForR2RCode(this);
if (pAlreadyExaminedInfos[1] != NULL && pAlreadyExaminedInfos[1] != pAlreadyExaminedInfos[0])
{
pCode = pAlreadyExaminedInfos[1]->GetEntryPoint(this, pConfig, TRUE /* fFixups */);
}
if (pCode == (PCODE)NULL)
{
// R2R also supports a concept of R2R code that has code for "Unrelated" generics embedded within it
// A linked list of these are formed as those modules are loaded, and this restricted set of modules
// is examined for all generic method lookups
ReadyToRunInfo* pUnrelatedInfo = ReadyToRunInfo::GetUnrelatedR2RModules();
for (;pUnrelatedInfo != NULL && pCode == (PCODE)NULL; pUnrelatedInfo = pUnrelatedInfo->GetNextUnrelatedR2RModule())
{
if (pUnrelatedInfo == pAlreadyExaminedInfos[0]) continue;
if (pUnrelatedInfo == pAlreadyExaminedInfos[1]) continue;
pCode = pUnrelatedInfo->GetEntryPoint(this, pConfig, TRUE /* fFixups */);
}
}
}
#endif
return pCode;
}
PCODE MethodDesc::GetMulticoreJitCode(PrepareCodeConfig* pConfig, bool* pWasTier0)
{
STANDARD_VM_CONTRACT;
_ASSERTE(pConfig != NULL);
_ASSERTE(pConfig->GetMethodDesc() == this);
_ASSERTE(pWasTier0 != NULL);
_ASSERTE(!*pWasTier0);
MulticoreJitCodeInfo codeInfo;
#ifdef FEATURE_MULTICOREJIT
// Quick check before calling expensive out of line function on this method's domain has code JITted by background thread
MulticoreJitManager & mcJitManager = GetAppDomain()->GetMulticoreJitManager();
if (mcJitManager.GetMulticoreJitCodeStorage().GetRemainingMethodCount() > 0)
{
if (MulticoreJitManager::IsMethodSupported(this))
{
codeInfo = mcJitManager.RequestMethodCode(this); // Query multi-core JIT manager for compiled code
#ifdef FEATURE_TIERED_COMPILATION
if (!codeInfo.IsNull())
{
if (codeInfo.WasTier0())
{
*pWasTier0 = true;
}
if (codeInfo.JitSwitchedToOptimized())
{
pConfig->SetJitSwitchedToOptimized();
}
}
#endif
}
}
#endif // FEATURE_MULTICOREJIT
return codeInfo.GetEntryPoint();
}
// ********************************************************************
// README!!
// ********************************************************************
// JitCompileCode is the thread safe way to invoke the JIT compiler
// If multiple threads get in here for the same config, ALL of them
// MUST return the SAME value for pcode.
//
// This function creates a DeadlockAware list of methods being jitted
// which prevents us from trying to JIT the same method more that once.
PCODE MethodDesc::JitCompileCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
LOG((LF_JIT, LL_INFO1000000,
"JitCompileCode(%p, ILStub: %s) for %s::%s\n",
this,
IsILStub() ? "true" : "false",
GetMethodTable()->GetDebugClassName(),
m_pszDebugMethodName));
#if defined(FEATURE_JIT_PITCHING)
CheckStacksAndPitch();
#endif
PCODE pCode = (PCODE)NULL;
{
// Enter the global lock which protects the list of all functions being JITd
JitListLock::LockHolder pJitLock(AppDomain::GetCurrentDomain()->GetJitLock());
// It is possible that another thread stepped in before we entered the global lock for the first time.
if ((pCode = pConfig->IsJitCancellationRequested()))
{
return pCode;
}
NativeCodeVersion version = pConfig->GetCodeVersion();
const char *description = "jit lock";
INDEBUG(description = m_pszDebugMethodName;)
ReleaseHolder<JitListLockEntry> pEntry(JitListLockEntry::Find(
pJitLock, version, description));
// We have an entry now, we can release the global lock
pJitLock.Release();
// Take the entry lock
{
JitListLockEntry::LockHolder pEntryLock(pEntry, FALSE);
if (pEntryLock.DeadlockAwareAcquire())
{
if (pEntry->m_hrResultCode == S_FALSE)
{
// Nobody has jitted the method yet
}
else
{
// We came in to jit but someone beat us so return the
// jitted method!
// We can just fall through because we will notice below that
// the method has code.
// @todo: Note that we may have a failed HRESULT here -
// we might want to return an early error rather than
// repeatedly failing the jit.
}
}
else
{
// Taking this lock would cause a deadlock (presumably because we
// are involved in a class constructor circular dependency.) For
// instance, another thread may be waiting to run the class constructor
// that we are jitting, but is currently jitting this function.
//
// To remedy this, we want to go ahead and do the jitting anyway.
// The other threads contending for the lock will then notice that
// the jit finished while they were running class constructors, and abort their
// current jit effort.
//
// We don't have to do anything special right here since we
// can check HasNativeCode() to detect this case later.
//
// Note that at this point we don't have the lock, but that's OK because the
// thread which does have the lock is blocked waiting for us.
}
// It is possible that another thread stepped in before we entered the lock.
if ((pCode = pConfig->IsJitCancellationRequested()))
{
return pCode;
}
// Multi-core-jitted code is generated for the default code version at the initial optimization tier, and so is only
// applicable to the default code version
NativeCodeVersion codeVersion = pConfig->GetCodeVersion();
if (codeVersion.IsDefaultVersion())
{
bool wasTier0 = false;
pCode = GetMulticoreJitCode(pConfig, &wasTier0);
if (pCode != (PCODE)NULL)
{
#ifdef FEATURE_TIERED_COMPILATION
// Finalize the optimization tier before SetNativeCode() is called
bool shouldCountCalls = wasTier0 && pConfig->FinalizeOptimizationTierForTier0LoadOrJit();
#endif
if (pConfig->SetNativeCode(pCode, &pCode))
{
#ifdef FEATURE_CODE_VERSIONING
pConfig->SetGeneratedOrLoadedNewCode();
#endif
#ifdef FEATURE_TIERED_COMPILATION
if (shouldCountCalls)
{
pConfig->SetShouldCountCalls();
}
#endif
}
pEntry->m_hrResultCode = S_OK;
return pCode;
}
}
return JitCompileCodeLockedEventWrapper(pConfig, pEntryLock);
}
}
}
namespace
{
COR_ILMETHOD_DECODER* GetAndVerifyMetadataILHeader(MethodDesc* pMD, PrepareCodeConfig* pConfig, COR_ILMETHOD_DECODER* pDecoderMemory)
{
STANDARD_VM_CONTRACT;
_ASSERTE(pMD != NULL);
_ASSERTE(!pMD->IsNoMetadata());
_ASSERTE(pConfig != NULL);
_ASSERTE(pDecoderMemory != NULL);
COR_ILMETHOD_DECODER* pHeader = NULL;
COR_ILMETHOD* ilHeader = pConfig->GetILHeader();
if (ilHeader == NULL)
return NULL;
COR_ILMETHOD_DECODER::DecoderStatus status = COR_ILMETHOD_DECODER::FORMAT_ERROR;
{
// Decoder ctor can AV on a malformed method header
AVInRuntimeImplOkayHolder AVOkay;
pHeader = new (pDecoderMemory) COR_ILMETHOD_DECODER(ilHeader, pMD->GetMDImport(), &status);
}
if (status == COR_ILMETHOD_DECODER::FORMAT_ERROR)
COMPlusThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_IL);
return pHeader;
}
COR_ILMETHOD_DECODER* GetAndVerifyILHeader(MethodDesc* pMD, PrepareCodeConfig* pConfig, COR_ILMETHOD_DECODER* pIlDecoderMemory)
{
STANDARD_VM_CONTRACT;
_ASSERTE(pMD != NULL);
if (pMD->IsIL())
{
return GetAndVerifyMetadataILHeader(pMD, pConfig, pIlDecoderMemory);
}
else if (pMD->IsILStub())
{
ILStubResolver* pResolver = pMD->AsDynamicMethodDesc()->GetILStubResolver();
return pResolver->GetILHeader();
}
_ASSERTE(pMD->IsNoMetadata());
return NULL;
}
}
PCODE MethodDesc::JitCompileCodeLockedEventWrapper(PrepareCodeConfig* pConfig, JitListLockEntry* pEntry)
{
STANDARD_VM_CONTRACT;
PCODE pCode = (PCODE)NULL;
ULONG sizeOfCode = 0;
#ifdef PROFILING_SUPPORTED
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackJITInfo());
// For methods with non-zero rejit id we send ReJITCompilationStarted, otherwise
// JITCompilationStarted. It isn't clear if this is the ideal policy for these
// notifications yet.
NativeCodeVersion nativeCodeVersion = pConfig->GetCodeVersion();
ReJITID rejitId = nativeCodeVersion.GetILCodeVersionId();
if (rejitId != 0)
{
_ASSERTE(!nativeCodeVersion.IsDefaultVersion());
(&g_profControlBlock)->ReJITCompilationStarted((FunctionID)this,
rejitId,
TRUE);
}
else
// If profiling, need to give a chance for a tool to examine and modify
// the IL before it gets to the JIT. This allows one to add probe calls for
// things like code coverage, performance, or whatever.
{
if (!IsNoMetadata())
{
(&g_profControlBlock)->JITCompilationStarted((FunctionID)this, TRUE);
}
else
{
unsigned int ilSize, unused;
CorInfoOptions corOptions;
LPCBYTE ilHeaderPointer = this->AsDynamicMethodDesc()->GetResolver()->GetCodeInfo(&ilSize, &unused, &corOptions, &unused);
(&g_profControlBlock)->DynamicMethodJITCompilationStarted((FunctionID)this, TRUE, ilHeaderPointer, ilSize);
}
if (nativeCodeVersion.IsDefaultVersion())
{
pConfig->SetProfilerMayHaveActivatedNonDefaultCodeVersion();
}
}
END_PROFILER_CALLBACK();
}
#endif // PROFILING_SUPPORTED
// The profiler may have changed the code on the callback. Need to
// pick up the new code.
//
// (don't want this for OSR, need to see how it works)
COR_ILMETHOD_DECODER ilDecoderTemp;
COR_ILMETHOD_DECODER* pilHeader = GetAndVerifyILHeader(this, pConfig, &ilDecoderTemp);
if (!ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context,
TRACE_LEVEL_VERBOSE,
CLR_JIT_KEYWORD))
{
pCode = JitCompileCodeLocked(pConfig, pilHeader, pEntry, &sizeOfCode);
}
else
{
SString namespaceOrClassName, methodName, methodSignature;
#ifdef FEATURE_EVENT_TRACE
ETW::MethodLog::MethodJitting(this,
pilHeader,
&namespaceOrClassName,
&methodName,
&methodSignature);
#endif //FEATURE_EVENT_TRACE
pCode = JitCompileCodeLocked(pConfig, pilHeader, pEntry, &sizeOfCode);
#ifdef FEATURE_EVENT_TRACE
ETW::MethodLog::MethodJitted(this,
&namespaceOrClassName,
&methodName,
&methodSignature,
pCode,
pConfig);
#endif //FEATURE_EVENT_TRACE
}
#ifdef PROFILING_SUPPORTED
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackJITInfo());
// For methods with non-zero rejit id we send ReJITCompilationFinished, otherwise
// JITCompilationFinished. It isn't clear if this is the ideal policy for these
// notifications yet.
NativeCodeVersion nativeCodeVersion = pConfig->GetCodeVersion();
ReJITID rejitId = nativeCodeVersion.GetILCodeVersionId();
if (rejitId != 0)
{
_ASSERTE(!nativeCodeVersion.IsDefaultVersion());
(&g_profControlBlock)->ReJITCompilationFinished((FunctionID)this,
rejitId,
S_OK,
TRUE);
}
else
// Notify the profiler that JIT completed.
// Must do this after the address has been set.
// @ToDo: Why must we set the address before notifying the profiler ??
{
if (!IsNoMetadata())
{
(&g_profControlBlock)->
JITCompilationFinished((FunctionID)this,
pEntry->m_hrResultCode,
TRUE);
}
else
{
(&g_profControlBlock)->DynamicMethodJITCompilationFinished((FunctionID)this, pEntry->m_hrResultCode, TRUE);
}
if (nativeCodeVersion.IsDefaultVersion())
{
pConfig->SetProfilerMayHaveActivatedNonDefaultCodeVersion();
}
}
END_PROFILER_CALLBACK();
}
#endif // PROFILING_SUPPORTED
#ifdef FEATURE_PERFMAP
// Save the JIT'd method information so that perf can resolve JIT'd call frames.
PerfMap::LogJITCompiledMethod(this, pCode, sizeOfCode, pConfig);
#endif
// The notification will only occur if someone has registered for this method.
DACNotifyCompilationFinished(this, pCode);
return pCode;
}
PCODE MethodDesc::JitCompileCodeLocked(PrepareCodeConfig* pConfig, COR_ILMETHOD_DECODER* pilHeader, JitListLockEntry* pEntry, ULONG* pSizeOfCode)
{
STANDARD_VM_CONTRACT;
PCODE pCode = (PCODE)NULL;
CORJIT_FLAGS jitFlags;
PCODE pOtherCode = (PCODE)NULL;
EX_TRY
{
Thread::CurrentPrepareCodeConfigHolder threadPrepareCodeConfigHolder(GetThread(), pConfig);
pCode = UnsafeJitFunction(pConfig, pilHeader, &jitFlags, pSizeOfCode);
}
EX_CATCH
{
// If the current thread threw an exception, but a competing thread
// somehow succeeded at JITting the same function (e.g., out of memory
// encountered on current thread but not competing thread), then go ahead
// and swallow this current thread's exception, since we somehow managed
// to successfully JIT the code on the other thread.
//
// Note that if a deadlock cycle is broken, that does not result in an
// exception--the thread would just pass through the lock and JIT the
// function in competition with the other thread (with the winner of the
// race decided later on when we do SetNativeCodeInterlocked). This
// try/catch is purely to deal with the (unusual) case where a competing
// thread succeeded where we aborted.
if (!(pOtherCode = pConfig->IsJitCancellationRequested()))
{
pEntry->m_hrResultCode = E_FAIL;
EX_RETHROW;
}
}
EX_END_CATCH(RethrowTerminalExceptions)
if (pOtherCode != (PCODE)NULL)
{
// Somebody finished jitting recursively while we were jitting the method.
// Just use their method & leak the one we finished. (Normally we hope
// not to finish our JIT in this case, as we will abort early if we notice
// a reentrant jit has occurred. But we may not catch every place so we
// do a definitive final check here.
return pOtherCode;
}
_ASSERTE(pCode != (PCODE)NULL);
#ifdef HAVE_GCCOVER
// Instrument for coverage before trying to publish this version
// of the code as the native code, to avoid other threads seeing
// partially instrumented methods.
if (GCStress<cfg_instr_jit>::IsEnabled())
{
// Do the instrumentation and publish atomically, so that the
// instrumentation data always matches the published code.
CrstHolder gcCoverLock(&m_GCCoverCrst);
// Make sure no other thread has stepped in before us.
if ((pOtherCode = pConfig->IsJitCancellationRequested()))
{
return pOtherCode;
}
SetupGcCoverage(pConfig->GetCodeVersion(), (BYTE*)pCode);
}
#endif // HAVE_GCCOVER
#ifdef FEATURE_TIERED_COMPILATION
// Finalize the optimization tier before SetNativeCode() is called
bool shouldCountCalls = jitFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_TIER0) && pConfig->FinalizeOptimizationTierForTier0LoadOrJit();
#endif
// Aside from rejit, performing a SetNativeCodeInterlocked at this point
// generally ensures that there is only one winning version of the native
// code. This also avoid races with profiler overriding ngened code (see
// matching SetNativeCodeInterlocked done after
// JITCachedFunctionSearchStarted)
if (!pConfig->SetNativeCode(pCode, &pOtherCode))
{
#ifdef HAVE_GCCOVER
// When GCStress is enabled, this thread should always win the publishing race
// since we're under a lock.
_ASSERTE(!GCStress<cfg_instr_jit>::IsEnabled() || !"GC Cover native code publish failed");
#endif
// Another thread beat us to publishing its copy of the JITted code.
return pOtherCode;
}
#ifdef FEATURE_CODE_VERSIONING
pConfig->SetGeneratedOrLoadedNewCode();
#endif
#ifdef FEATURE_TIERED_COMPILATION
if (shouldCountCalls)
{
pConfig->SetShouldCountCalls();
}