summaryrefslogtreecommitdiff
path: root/src/vm/codepitchingmanager.cpp
blob: 6a937fb2174afe84877990a8cff2334e0a446b70 (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
// 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: CodePitchingManager.cpp
//

// ===========================================================================
// This file contains the implementation for code pitching.
// Its distinctive features and algorithm are:
//
// 1. All its code is under #if defined(FEATURE_JIT_PITCHING) and doesn't mess up with other code
// 2. This feature is working only if the options INTERNAL_JitPitchEnabled != 0 and INTERNAL_JitPitchMemThreshold > 0
// 3. Jitted code can be pitched only for methods that are not Dynamic, FCall or Virtual
// 4. If the size of the generated native code exceeds the value of INTERNAL_JitDPitchMethodSizeThreshold this code is
//    placed in the special heap code list. Each heap block in this list stores the code for only one method and has the
//    sufficient size for the code of a method aligned to 4K. The pointers to such methods are stored in the
//    "PitchingCandidateMethods" hash map.
// 5. If the entrypoint of a method is backpatched this method is excluded from the "PitchingCandidateMethods" hash map
//    and stored in "NotForPitchingMethods" hashmap.
// 6. When the total size of the generated native code exceeds the value of INTERNAL_JitPitchMemThreshold option, the
//    execution of the program is stopped and stack frames for all the threads are inspected and pointers to methods
//    being executed are stored in the "ExecutedMethods" hash map
// 7. The code for all the methods from the "PitchingCandidateMethods" that are not in the "ExecutedMethods" is pitched.
//    (All heap blocks for these methods are set in the initial state and can be reused for newly compiled methods, pointers
//     to the code for non-executed methods are set to nullptr).
// 8. If the code for the given method is pitched once, this method is stored in the "NotForPitchingMethods" hashmap. Thus,
//    if this method is compiled the second time, it is considered as called repeatedly, therefore, pitching for it is inexpedient,
//    and the newly compiled code stored in the usual heap.
// 9. The coreclr code with this feature is built by the option
//     ./build.sh cmakeargs -DFEATURE_JIT_PITCHING=true
// ===========================================================================

#include "common.h"

#ifndef DACCESS_COMPILE

#if defined(FEATURE_JIT_PITCHING)

#include "nibblemapmacros.h"
#include "threadsuspend.h"

static PtrHashMap* s_pPitchingCandidateMethods = nullptr;
static PtrHashMap* s_pPitchingCandidateSizes = nullptr;
static SimpleRWLock* s_pPitchingCandidateMethodsLock = nullptr;

static PtrHashMap* s_pExecutedMethods = nullptr;
static SimpleRWLock* s_pExecutedMethodsLock = nullptr;

static PtrHashMap* s_pNotForPitchingMethods = nullptr;
static SimpleRWLock* s_pNotForPitchingMethodsLock = nullptr;

#ifdef _DEBUG
static PtrHashMap* s_pPitchedMethods = nullptr;
static SimpleRWLock* s_pPitchedMethodsLock = nullptr;
#endif

static ULONG s_totalNCSize = 0;
static SimpleRWLock* s_totalNCSizeLock = nullptr;

static ULONG s_jitPitchedBytes = 0;

static INT64 s_JitPitchLastTick = 0;

static bool s_JitPitchInitialized = false;


static BOOL IsOwnerOfRWLock(LPVOID lock)
{
    // @TODO - SimpleRWLock does not have knowledge of which thread gets the writer
    // lock, so no way to verify
    return TRUE;
}

static void CreateRWLock(SimpleRWLock** lock)
{
    if (*lock == nullptr)
    {
        void *pLockSpace = SystemDomain::GetGlobalLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(SimpleRWLock)));
        SimpleRWLock *pLock = new (pLockSpace) SimpleRWLock(COOPERATIVE_OR_PREEMPTIVE, LOCK_TYPE_DEFAULT);

        if (FastInterlockCompareExchangePointer(lock, pLock, NULL) != NULL)
            SystemDomain::GetGlobalLoaderAllocator()->GetLowFrequencyHeap()->BackoutMem(pLockSpace, sizeof(SimpleRWLock));
    }
}

static PtrHashMap* CreateHashMap(SimpleRWLock* rwLock)
{
    PtrHashMap *pMap = new (SystemDomain::GetGlobalLoaderAllocator()->GetLowFrequencyHeap()) PtrHashMap();
    LockOwner lock = {rwLock, IsOwnerOfRWLock};
    pMap->Init(32, nullptr, FALSE, &lock);
    return pMap;
}

static void InitializeJitPitching()
{
    if (!s_JitPitchInitialized)
    {
        CreateRWLock(&s_pNotForPitchingMethodsLock);
        CreateRWLock(&s_pPitchingCandidateMethodsLock);
        CreateRWLock(&s_totalNCSizeLock);

        {
            SimpleReadLockHolder srlh(s_pNotForPitchingMethodsLock);
            if (s_pNotForPitchingMethods == nullptr)
            {
                s_pNotForPitchingMethods = CreateHashMap(s_pNotForPitchingMethodsLock);
            }
        }

        {
            SimpleReadLockHolder srlh(s_pPitchingCandidateMethodsLock);
            if (s_pPitchingCandidateMethods == nullptr)
            {
                s_pPitchingCandidateMethods = CreateHashMap(s_pPitchingCandidateMethodsLock);
                s_pPitchingCandidateSizes = CreateHashMap(s_pPitchingCandidateMethodsLock);
            }
        }

        s_JitPitchInitialized = true;
    }
}

static COUNT_T GetFullHash(MethodDesc* pMD)
{
    const char *moduleName = pMD->GetModule()->GetSimpleName();

    COUNT_T hash = HashStringA(moduleName);         // Start the hash with the Module name

    SString className, methodName, methodSig;

    pMD->GetMethodInfo(className, methodName, methodSig);

    hash = HashCOUNT_T(hash, className.Hash());   // Hash in the name of the Class name
    hash = HashCOUNT_T(hash, methodName.Hash());  // Hash in the name of the Method name
    hash = HashCOUNT_T(hash, 0xffffffff & (ULONGLONG)pMD);

    return hash;
}

bool MethodDesc::IsPitchable()
{
    if ((CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchEnabled) == 0) ||
        (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchMemThreshold) == 0))
        return FALSE;

    InitializeJitPitching();

    if (IsLCGMethod() || IsVtableMethod() || IsInterface() || IsVirtual())
        return FALSE;

    _ASSERTE(s_pNotForPitchingMethodsLock != nullptr && s_pNotForPitchingMethods != nullptr);

    {
        SimpleReadLockHolder srlh(s_pNotForPitchingMethodsLock);
        UPTR key = (UPTR)GetFullHash(this);
        MethodDesc *pFound = (MethodDesc *)s_pNotForPitchingMethods->LookupValue(key, (LPVOID)this);
        if (pFound != (MethodDesc *)INVALIDENTRY)
        {
            return FALSE;
        }
    }
    return TRUE;
}

EXTERN_C bool LookupOrCreateInNotForPitching(MethodDesc* pMD)
{
    CONTRACTL
    {
        MODE_COOPERATIVE;
        GC_TRIGGERS;
        THROWS;
    }
    CONTRACTL_END;

    if (pMD != nullptr && pMD->IsPitchable())
    {
        UPTR key = (UPTR)GetFullHash(pMD);

        _ASSERTE(s_pNotForPitchingMethodsLock != nullptr && s_pNotForPitchingMethods != nullptr);

        {
             SimpleReadLockHolder srlh(s_pNotForPitchingMethodsLock);
             MethodDesc *pFound = (MethodDesc *)s_pNotForPitchingMethods->LookupValue(key, (LPVOID)pMD);
             if (pFound != (MethodDesc *)INVALIDENTRY)
                 return TRUE;
        }

        {
             SimpleWriteLockHolder swlh(s_pNotForPitchingMethodsLock);
             s_pNotForPitchingMethods->InsertValue(key, (LPVOID)pMD);
        }
    }
    return FALSE;
}

static void LookupOrCreateInPitchingCandidate(MethodDesc* pMD, ULONG sizeOfCode)
{
    CONTRACTL
    {
        MODE_COOPERATIVE;
        GC_TRIGGERS;
        THROWS;
    }
    CONTRACTL_END;

    if (pMD == nullptr || !pMD->IsPitchable())
        return;

    PCODE prCode = pMD->GetPreImplementedCode();
    if (prCode)
        return;

    if (!pMD->HasPrecode())
        return;

    UPTR key = (UPTR)GetFullHash(pMD);

    _ASSERTE(s_pPitchingCandidateMethodsLock != nullptr && s_pPitchingCandidateMethods != nullptr);
    _ASSERTE(s_pPitchingCandidateSizes);

    {
        // Try getting an existing value first.
        SimpleReadLockHolder srlh(s_pPitchingCandidateMethodsLock);
        MethodDesc *pFound = (MethodDesc *)s_pPitchingCandidateMethods->LookupValue(key, (LPVOID)pMD);
        if (pFound != (MethodDesc *)INVALIDENTRY)
            return;
    }

    {
        SimpleWriteLockHolder swlh(s_pPitchingCandidateMethodsLock);
        s_pPitchingCandidateMethods->InsertValue(key, (LPVOID)pMD);
        s_pPitchingCandidateSizes->InsertValue(key, (LPVOID)((ULONGLONG)(sizeOfCode << 1)));
#ifdef _DEBUG
        if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchPrintStat) != 0)
        {
            SString className, methodName, methodSig;
            pMD->GetMethodInfo(className, methodName, methodSig);

            StackScratchBuffer scratch;
            const char* szClassName = className.GetUTF8(scratch);
            const char* szMethodSig = methodSig.GetUTF8(scratch);

            printf("Candidate %lu %s :: %s %s\n",
                   sizeOfCode, szClassName, pMD->GetName(), szMethodSig);
        }
#endif
    }
}

EXTERN_C void DeleteFromPitchingCandidate(MethodDesc* pMD)
{
    CONTRACTL
    {
        MODE_COOPERATIVE;
        GC_TRIGGERS;
        THROWS;
    }
    CONTRACTL_END;

    if (pMD != nullptr && pMD->IsPitchable())
    {
        PCODE pCode = pMD->GetPreImplementedCode();

        if (pCode)
           return;

        _ASSERTE(s_pPitchingCandidateMethodsLock != nullptr && s_pPitchingCandidateMethods != nullptr);
        _ASSERTE(s_pPitchingCandidateSizes != nullptr);

        UPTR key = (UPTR)GetFullHash(pMD);
        {
            SimpleReadLockHolder srlh(s_pPitchingCandidateMethodsLock);
            MethodDesc *pFound = (MethodDesc *)s_pPitchingCandidateMethods->LookupValue(key, (LPVOID)pMD);
            if (pFound == (MethodDesc *)INVALIDENTRY)
                return;
        }

        {
            SimpleWriteLockHolder swlh(s_pPitchingCandidateMethodsLock);
            s_pPitchingCandidateMethods->DeleteValue(key, (LPVOID)pMD);
        }

        LPVOID pitchedBytes;
        {
            SimpleReadLockHolder srlh(s_pPitchingCandidateMethodsLock);
            pitchedBytes = s_pPitchingCandidateSizes->LookupValue(key, nullptr);
            _ASSERTE(pitchedBytes != (LPVOID)INVALIDENTRY);
        }
        {
            SimpleWriteLockHolder swlh(s_pPitchingCandidateMethodsLock);
            s_pPitchingCandidateSizes->DeleteValue(key, pitchedBytes);
        }
    }
}

EXTERN_C void MarkMethodNotPitchingCandidate(MethodDesc* pMD)
{

    DeleteFromPitchingCandidate(pMD);
    (void)LookupOrCreateInNotForPitching(pMD);
}

StackWalkAction CrawlFrameVisitor(CrawlFrame* pCf, Thread* pMdThread)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;

    MethodDesc* pMD = pCf->GetFunction();

    // Filter out methods we don't care about
    if (pMD == nullptr || !pMD->IsPitchable())
    {
        return SWA_CONTINUE;
    }

    if (s_pExecutedMethods == nullptr)
    {
        PtrHashMap *pMap = new (SystemDomain::GetGlobalLoaderAllocator()->GetLowFrequencyHeap()) PtrHashMap();
        pMap->Init(TRUE, nullptr);
        s_pExecutedMethods = pMap;
    }

    UPTR key = (UPTR)GetFullHash(pMD);
    MethodDesc *pFound = (MethodDesc *)s_pExecutedMethods->LookupValue(key, (LPVOID)pMD);
    if (pFound == (MethodDesc *)INVALIDENTRY)
    {
        s_pExecutedMethods->InsertValue(key, (LPVOID)pMD);
    }

    return SWA_CONTINUE;
}

// Visitor for stack walk callback.
StackWalkAction StackWalkCallback(CrawlFrame* pCf, VOID* data)
{
    WRAPPER_NO_CONTRACT;

    // WalkInfo* info = (WalkInfo*) data;
    return CrawlFrameVisitor(pCf, (Thread *)data);
}

static ULONG s_PitchedMethodCounter = 0;
void MethodDesc::PitchNativeCode()
{
    WRAPPER_NO_CONTRACT;
    SUPPORTS_DAC;

    g_IBCLogger.LogMethodDescAccess(this);

    if (!IsPitchable())
        return;

    PCODE pCode = GetNativeCode();

    if (!pCode)
        return;

    _ASSERTE(HasPrecode());

    _ASSERTE(HasNativeCode());

    ++s_PitchedMethodCounter;

    if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchMinVal) > s_PitchedMethodCounter)
    {
        return;
    }
    if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchMaxVal) < s_PitchedMethodCounter)
    {
        return;
    }

    if (LookupOrCreateInNotForPitching(this))
        return;

    MethodTable * pMT = GetMethodTable();
    _ASSERTE(pMT != nullptr);

    CodeHeader* pCH = dac_cast<PTR_CodeHeader>(PCODEToPINSTR(pCode)) - 1;
    _ASSERTE(pCH->GetMethodDesc() == this);

    HostCodeHeap* pHeap = HostCodeHeap::GetCodeHeap((TADDR)pCode);
    pHeap->GetJitManager()->FreeCodeMemory(pHeap, (void*)pCode);

    ClearFlagsOnUpdate();

    _ASSERTE(HasPrecode());
    GetPrecode()->Reset();

    if (HasNativeCodeSlot())
    {
        RelativePointer<TADDR> *pRelPtr = (RelativePointer<TADDR> *)GetAddrOfNativeCodeSlot();
        pRelPtr->SetValueMaybeNull(NULL);
    }
    else
    {
#ifdef FEATURE_INTERPRETER
        SetNativeCodeInterlocked(NULL, NULL, FALSE);
#else
        SetNativeCodeInterlocked(NULL, NULL);
#endif
    }

    _ASSERTE(!HasNativeCode());

    UPTR key = (UPTR)GetFullHash(this);
    ULONGLONG pitchedBytes;
    {
        SimpleReadLockHolder srlh(s_pPitchingCandidateMethodsLock);
        pitchedBytes = (ULONGLONG)s_pPitchingCandidateSizes->LookupValue(key, nullptr);
        _ASSERTE(pitchedBytes != (ULONGLONG)INVALIDENTRY);
        if (pitchedBytes == (ULONGLONG)INVALIDENTRY)
            pitchedBytes = 0;
        s_jitPitchedBytes += (pitchedBytes >> 1);
    }
    {
        SimpleWriteLockHolder swlh(s_pPitchingCandidateMethodsLock);
        s_pPitchingCandidateMethods->DeleteValue(key, (LPVOID)this);
        if (pitchedBytes != 0)
            s_pPitchingCandidateSizes->DeleteValue(key, (LPVOID)pitchedBytes);
    }

    if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchPrintStat) != 0)
    {
        SString className, methodName, methodSig;
        GetMethodInfo(className, methodName, methodSig);

        StackScratchBuffer scratch;
        const char* szClassName = className.GetUTF8(scratch);
        const char* szMethodSig = methodSig.GetUTF8(scratch);

        printf("Pitched %lu %lu %s :: %s %s\n",
               s_PitchedMethodCounter, pitchedBytes, szClassName, GetName(), szMethodSig);
    }

    DACNotify::DoJITPitchingNotification(this);
}

EXTERN_C void CheckStacksAndPitch()
{
    if ((CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchEnabled) != 0) &&
        (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchMemThreshold) != 0) &&
        (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchTimeInterval) == 0 ||
         ((::GetTickCount64() - s_JitPitchLastTick) > CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchTimeInterval))))
    {
        SimpleReadLockHolder srlh(s_totalNCSizeLock);

        if ((s_totalNCSize - s_jitPitchedBytes) > CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchMemThreshold) &&
            s_pPitchingCandidateMethods != nullptr)
        {
            EX_TRY
            {
                // Suspend the runtime.
                ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_OTHER);

                // Walk all other threads.
                Thread* pThread = nullptr;
                while ((pThread = ThreadStore::GetThreadList(pThread)) != nullptr)
                {
                    pThread->StackWalkFrames(StackWalkCallback, (VOID *)pThread, ALLOW_ASYNC_STACK_WALK);
                }

                if (s_pExecutedMethods)
                {
                    PtrHashMap::PtrIterator i = s_pPitchingCandidateMethods->begin();
                    while (!i.end())
                    {
                        MethodDesc *pMD = (MethodDesc *) i.GetValue();
                        UPTR key = (UPTR)GetFullHash(pMD);
                        MethodDesc *pFound = (MethodDesc *)s_pExecutedMethods->LookupValue(key, (LPVOID)pMD);
                        ++i;
                        if (pFound == (MethodDesc *)INVALIDENTRY)
                        {
                            pMD->PitchNativeCode();
                        }
                    }
                    s_pExecutedMethods->Clear();
                    delete s_pExecutedMethods;
                    s_pExecutedMethods = nullptr;
                    s_pPitchingCandidateMethods->Compact();
                    s_pPitchingCandidateSizes->Compact();
                }

                s_JitPitchLastTick = ::GetTickCount64();

                ThreadSuspend::RestartEE(FALSE, TRUE);
            }
            EX_CATCH
            {
            }
            EX_END_CATCH(SwallowAllExceptions);
        }
    }
}

EXTERN_C void SavePitchingCandidate(MethodDesc* pMD, ULONG sizeOfCode)
{
    if (pMD && pMD->IsPitchable() && CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchMethodSizeThreshold) < sizeOfCode)
    {
        LookupOrCreateInPitchingCandidate(pMD, sizeOfCode);
    }
    if (sizeOfCode > 0)
    {
        SimpleWriteLockHolder swlh(s_totalNCSizeLock);
        s_totalNCSize += sizeOfCode;
        if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchPrintStat) != 0)
            printf("jitted %lu (bytes) pitched %lu (bytes)\n", s_totalNCSize, s_jitPitchedBytes);
    }
}
#endif

#endif