-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathOMRCodeCache.cpp
1673 lines (1449 loc) · 59.9 KB
/
OMRCodeCache.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
/*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "runtime/CodeCache.hpp"
#include <algorithm>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "env/FrontEnd.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "env/CompilerEnv.hpp"
#include "env/IO.hpp"
#include "env/defines.h"
#include "env/jittypes.h"
#include "il/DataTypes.hpp"
#include "infra/Assert.hpp"
#include "infra/CriticalSection.hpp"
#include "infra/Monitor.hpp"
#include "omrformatconsts.h"
#include "runtime/CodeCache.hpp"
#include "runtime/CodeCacheManager.hpp"
#include "runtime/CodeCacheMemorySegment.hpp"
#include "runtime/CodeCacheConfig.hpp"
#include "runtime/Runtime.hpp"
#ifdef LINUX
#include <elf.h>
#include <unistd.h>
#endif
namespace TR { class CodeGenerator; }
/*****************************************************************************
* Multi Code Cache page management
*/
/**
* \page CodeCache Code Cache Layout:
*
* Basic layout of the code cache memory (capitalized names are fixed, others
* move)
*
*
* TRAMPOLINEBASE TEMPTRAMPOLINETOP
* | TEMPTRAMPOLINEBASE |
* | | |
* warmCodeAlloc coldCodeAlloc | | HELPERBASE HELPERTOP
* |--> <--| | | | |
* |_____v_________________v______v_______________v___________v_________v
* warm cold
* \ /
* ----> Method Bodies<--- ^ Trampolines ^ TempTramps^ Helpers
*
* (Low memory) ---------------------------------------> (High memory)
*
*
* * There are a fixed number of helper trampolines. Each helper has an index into
* these trampolines.
* * There are a fixed number of temporary trampoline slots. `_tempTrampolineNext`
* goes from `_tempTrampolineBase`, allocating to `tempTrampolineMax.`
* * There are a fixed number of permanent trampoline slots.
* ** `_trampolineReservationMark` goes from `_tempTrampolineBase` to `_trampolineBase`
* backwards, reserving trampoline slots.
* ** `_trampolineAllocationMark` goes from `_tempTrampolineBase` to
* `_trampolineReservationMark` filling in the trampoline slots.
*
* When there is no more room for trampolines the code cache is full.
*
* 5% of the code cache is allocated to the above trampolines. The rest is used
* for method bodies. Regular parts of method bodies are allocated from the
* heapBase forwards, and cold parts of method bodies are allocated from
* `_trampolineBase` backwards. When the two meet, the code cache is full.
*
*/
OMR::CodeCache::CacheCriticalSection::CacheCriticalSection(TR::CodeCache *codeCache)
: CriticalSection(codeCache->_mutex)
{
}
TR::CodeCache *
OMR::CodeCache::self()
{
return static_cast<TR::CodeCache *>(this);
}
void
OMR::CodeCache::destroy(TR::CodeCacheManager *manager)
{
while (_hashEntrySlab)
{
CodeCacheHashEntrySlab *slab = _hashEntrySlab;
_hashEntrySlab = slab->_next;
slab->free(manager);
}
#if defined(TR_HOST_POWER)
if (_trampolineSyncList)
{
if (_trampolineSyncList->_hashEntryArray)
manager->freeMemory(_trampolineSyncList->_hashEntryArray);
manager->freeMemory(_trampolineSyncList);
}
#endif
if (manager->codeCacheConfig().needsMethodTrampolines())
{
if (_resolvedMethodHT)
{
if (_resolvedMethodHT->_buckets)
manager->freeMemory(_resolvedMethodHT->_buckets);
manager->freeMemory(_resolvedMethodHT);
}
if (_unresolvedMethodHT)
{
if (_unresolvedMethodHT->_buckets)
manager->freeMemory(_unresolvedMethodHT->_buckets);
manager->freeMemory(_unresolvedMethodHT);
}
}
}
uint8_t *
OMR::CodeCache::getCodeAlloc()
{
return _segment->segmentAlloc();
}
uint8_t *
OMR::CodeCache::getCodeBase()
{
return _segment->segmentBase();
}
uint8_t *
OMR::CodeCache::getCodeTop()
{
return _segment->segmentTop();
}
void
OMR::CodeCache::reserve(int32_t reservingCompThreadID)
{
_reserved = true;
_reservingCompThreadID = reservingCompThreadID;
}
void
OMR::CodeCache::unreserve()
{
_reserved = false;
_reservingCompThreadID = -2;
}
void
OMR::CodeCache::writeMethodHeader(void *freeBlock, size_t size, bool isCold)
{
CodeCacheMethodHeader * block = (CodeCacheMethodHeader *)freeBlock;
block->_size = size;
TR::CodeCacheConfig & config = _manager->codeCacheConfig();
if (!isCold)
memcpy(block->_eyeCatcher, config.warmEyeCatcher(), sizeof(block->_eyeCatcher));
else
memcpy(block->_eyeCatcher, config.coldEyeCatcher(), sizeof(block->_eyeCatcher));
block->_metaData = NULL;
}
bool
OMR::CodeCache::trimCodeMemoryAllocation(void *codeMemoryStart, size_t actualSizeInBytes)
{
if (actualSizeInBytes == 0) return false; // nothing to resize, just return
TR::CodeCacheConfig & config = _manager->codeCacheConfig();
size_t round = config.codeCacheAlignment() - 1;
codeMemoryStart = (uint8_t *) codeMemoryStart - sizeof(CodeCacheMethodHeader); // Do we always have a header?
actualSizeInBytes = (actualSizeInBytes + sizeof(CodeCacheMethodHeader) + round) & ~round;
CodeCacheMethodHeader *cacheHeader = (CodeCacheMethodHeader *) codeMemoryStart;
// sanity check, the eyecatcher must be there
TR_ASSERT(cacheHeader->_eyeCatcher[0] == config.warmEyeCatcher()[0], "Missing eyecatcher during trimCodeMemoryAllocation");
size_t oldSize = cacheHeader->_size;
if (actualSizeInBytes >= oldSize)
return false;
size_t shrinkage = oldSize - actualSizeInBytes;
uint8_t *expectedHeapAlloc = (uint8_t *) codeMemoryStart + oldSize;
if (config.verboseReclamation())
{
TR_VerboseLog::writeLineLocked(TR_Vlog_CODECACHE,"--trimCodeMemoryAllocation-- CC=%p cacheHeader=%p oldSize=%u actualSizeInBytes=%d shrinkage=%u", this, cacheHeader, oldSize, actualSizeInBytes, shrinkage);
}
if (expectedHeapAlloc == _warmCodeAlloc)
{
_manager->increaseFreeSpaceInCodeCacheRepository(shrinkage);
_warmCodeAlloc -= shrinkage;
cacheHeader->_size = actualSizeInBytes;
return true;
}
else // the allocation could have been from a free block or from the cold portion
{
if (shrinkage >= MIN_SIZE_BLOCK)
{
// addFreeBlock needs to be done with VM access because the GC may also
// change the list of free blocks
if (self()->addFreeBlock2((uint8_t *) codeMemoryStart+actualSizeInBytes, (uint8_t *)expectedHeapAlloc))
{
//fprintf(stderr, "---ccr--- addFreeBlock due to shrinkage\n");
}
cacheHeader->_size = actualSizeInBytes;
return true;
}
}
//fprintf(stderr, "--ccr-- shrink code by %d\n", shrinkage);
return false;
}
// Initialize a code cache
//
bool
OMR::CodeCache::initialize(TR::CodeCacheManager *manager,
TR::CodeCacheMemorySegment *codeCacheSegment,
size_t allocatedCodeCacheSizeInBytes)
{
_manager = manager;
// heapSize can be calculated as (codeCache->helperTop - codeCacheSegment->heapBase), which is equal to segmentSize
// If codeCachePadKB is set, this will make the system believe that we allocated segmentSize bytes,
// instead of _jitConfig->codeCachePadKB * 1024 bytes
// If codeCachePadKB is not set, heapSize is segmentSize anyway
_segment = codeCacheSegment;
// helperTop is heapTop, usually
// When codeCachePadKB > segmentSize, the helperTop is not at the very end of the segemnt
_helperTop = _segment->segmentBase() + allocatedCodeCacheSizeInBytes;
TR::CodeCacheConfig &config = manager->codeCacheConfig();
// Allocate the CodeCacheHashEntrySlab object and the initial slab
//
_hashEntrySlab = CodeCacheHashEntrySlab::allocate(manager, config.codeCacheHashEntryAllocatorSlabSize());
if (!_hashEntrySlab)
{
return false;
}
// FIXME: try to provide different names to the mutex based on the codecache
if (!(_mutex = TR::Monitor::create("JIT-CodeCacheMonitor-??")))
{
_hashEntrySlab->free(manager);
return false;
}
_hashEntryFreeList = NULL;
_freeBlockList = NULL;
_flags = 0;
_CCPreLoadedCodeInitialized = false;
self()->unreserve();
_almostFull = TR_no;
_sizeOfLargestFreeColdBlock = 0;
_sizeOfLargestFreeWarmBlock = 0;
_lastAllocatedBlock = NULL; // MP
*((TR::CodeCache **)(_segment->segmentBase())) = self(); // Write a pointer to this cache at the beginning of the segment
_warmCodeAlloc = _segment->segmentBase() + sizeof(this);
_warmCodeAlloc = align(_warmCodeAlloc, config.codeCacheAlignment() - 1);
if (!config.trampolineCodeSize())
{
// _helperTop is heapTop
_trampolineBase = _helperTop;
_helperBase = _helperTop;
_trampolineReservationMark = _trampolineAllocationMark = _trampolineBase;
// set the pre loaded per Cache Helper slab
_CCPreLoadedCodeTop = (uint8_t *)(((size_t)_trampolineBase) & (~config.codeCacheHelperAlignmentMask()));
_CCPreLoadedCodeBase = _CCPreLoadedCodeTop - config.ccPreLoadedCodeSize();
TR_ASSERT( (((size_t)_CCPreLoadedCodeBase) & config.codeCacheHelperAlignmentMask()) == 0, "Per-code cache helper sizes do not account for alignment requirements." );
_coldCodeAlloc = _CCPreLoadedCodeBase;
_trampolineSyncList = NULL;
return true;
}
// Helpers are located at the top of the code cache (offset N), growing down towards the base (offset 0)
size_t trampolineSpaceSize = config.trampolineCodeSize() * config.numRuntimeHelpers();
// _helperTop is heapTop
_helperBase = _helperTop - trampolineSpaceSize;
_helperBase = (uint8_t *)(((size_t)_helperBase) & (~config.codeCacheTrampolineAlignmentBytes()));
if (!config.needsMethodTrampolines())
{
// There is no need in method trampolines when there is going to be
// only one code cache segment
//
_trampolineBase = _helperBase;
_tempTrampolinesMax = 0;
}
else
{
// _helperTop is heapTop
// (_helperTop - segment->heapBase) is heapSize
_trampolineBase = _helperBase -
((_helperBase - _segment->segmentBase())*config.trampolineSpacePercentage()/100);
// Grab the configuration details from the JIT platform code
//
// (_helperTop - segment->heapBase) is heapSize
config.mccCallbacks().codeCacheConfig((_helperTop - _segment->segmentBase()), &_tempTrampolinesMax);
}
mcc_printf("mcc_initialize: trampoline base %p\n", _trampolineBase);
// set the temporary trampoline slab right under the helper trampolines, should be already aligned
_tempTrampolineTop = _helperBase;
_tempTrampolineBase = _tempTrampolineTop - (config.trampolineCodeSize() * _tempTrampolinesMax);
_tempTrampolineNext = _tempTrampolineBase;
// Check if we have enough space in the code cache to contain the trampolines
if (_trampolineBase >= _tempTrampolineNext && config.needsMethodTrampolines())
{
_hashEntrySlab->free(manager);
return false;
}
// set the allocation pointer to right after the temporary trampolines
_trampolineAllocationMark = _tempTrampolineBase;
_trampolineReservationMark = _trampolineAllocationMark;
// set the pre loaded per Cache Helper slab
_CCPreLoadedCodeTop = (uint8_t *)(((size_t)_trampolineBase) & (~config.codeCacheHelperAlignmentMask()));
_CCPreLoadedCodeBase = _CCPreLoadedCodeTop - config.ccPreLoadedCodeSize();
TR_ASSERT( (((size_t)_CCPreLoadedCodeBase) & config.codeCacheHelperAlignmentMask()) == 0, "Per-code cache helper sizes do not account for alignment requirements." );
_coldCodeAlloc = _CCPreLoadedCodeBase;
// Set helper trampoline table available
//
config.mccCallbacks().createHelperTrampolines((uint8_t *)_helperBase, config.numRuntimeHelpers());
_trampolineSyncList = NULL;
if (_tempTrampolinesMax)
{
// Initialize temporary trampoline synchronization list
if (!self()->allocateTempTrampolineSyncBlock())
{
_hashEntrySlab->free(manager);
return false;
}
}
if (config.needsMethodTrampolines())
{
// Initialize hashtables to hold trampolines for resolved and unresolved methods
_resolvedMethodHT = CodeCacheHashTable::allocate(manager);
_unresolvedMethodHT = CodeCacheHashTable::allocate(manager);
if (_resolvedMethodHT==NULL || _unresolvedMethodHT==NULL)
{
_hashEntrySlab->free(manager);
return false;
}
}
// Before returning, let's adjust the free space seen by VM.
// Usable space is between _warmCodeAlloc and _trampolineBase. Everything else is overhead
// Only relevant if code cache repository is used
size_t spaceLost = (_warmCodeAlloc - _segment->segmentBase()) + (_segment->segmentTop() - _trampolineBase);
_manager->decreaseFreeSpaceInCodeCacheRepository(spaceLost);
return true;
}
/*****************************************************************************
* Trampoline Reservation
*/
// Allocate a trampoline in given code cache
//
// An allocation MUST be preceeded by at least one reservation. If we get a case
// where we dont have reserved space, abort
//
OMR::CodeCacheTrampolineCode *
OMR::CodeCache::allocateTrampoline()
{
CodeCacheTrampolineCode *trampoline = NULL;
if (_trampolineAllocationMark > _trampolineReservationMark)
{
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
_trampolineAllocationMark -= config.trampolineCodeSize();
trampoline = (CodeCacheTrampolineCode *) _trampolineAllocationMark;
}
else
{
//TR_ASSERT(0);
}
return trampoline;
}
// Allocate a temporary trampoline
//
OMR::CodeCacheTrampolineCode *
OMR::CodeCache::allocateTempTrampoline()
{
CodeCacheTrampolineCode *freeTrampolineSlot;
if (_tempTrampolineNext >= _tempTrampolineTop)
return NULL;
freeTrampolineSlot = _tempTrampolineNext;
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
_tempTrampolineNext += config.trampolineCodeSize();
return freeTrampolineSlot;
}
OMR::CodeCacheErrorCode::ErrorCode
OMR::CodeCache::reserveSpaceForTrampoline_bridge(int32_t numTrampolines)
{
return self()->reserveSpaceForTrampoline(numTrampolines);
}
OMR::CodeCacheErrorCode::ErrorCode
OMR::CodeCache::reserveSpaceForTrampoline(int32_t numTrampolines)
{
CacheCriticalSection ReserveSpaceForTrampoline(self());
CodeCacheErrorCode::ErrorCode status = CodeCacheErrorCode::ERRORCODE_SUCCESS;
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
size_t size = numTrampolines * config.trampolineCodeSize();
if (size)
{
// See if we are hitting against the method body allocation pointer
// indicating that there is no more free space left in this code cache
//
if (_trampolineReservationMark >= _trampolineBase + size)
{
_trampolineReservationMark -= size;
}
else
{
status = CodeCacheErrorCode::ERRORCODE_INSUFFICIENTSPACE;
_almostFull = TR_yes;
if (config.verboseCodeCache())
{
TR_VerboseLog::writeLineLocked(TR_Vlog_CODECACHE, "CodeCache %p marked as full in reserveSpaceForTrampoline", self());
}
}
}
return status;
}
void
OMR::CodeCache::unreserveSpaceForTrampoline()
{
// sanity check, should never have the reservation mark dip past the
// allocation mark
//TR_ASSERT(_trampolineReservationMark < _trampolineAllocationMark);
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
_trampolineReservationMark += config.trampolineCodeSize();
}
//------------------------------ reserveResolvedTrampoline ------------------
// Find or create a reservation for an resolved method trampoline.
// Method must be called with VM access in hand to prevent unloading
// Returns 0 on success or a negative error code on failure
//---------------------------------------------------------------------------
int32_t
OMR::CodeCache::reserveResolvedTrampoline(TR_OpaqueMethodBlock *method,
bool inBinaryEncoding)
{
int32_t retValue = CodeCacheErrorCode::ERRORCODE_SUCCESS; // assume success
TR_ASSERT(_reserved, "CodeCache %p is not reserved when calling reservedResolvedTrampoline\n", this);
// does the platform need trampolines at all?
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
if (!config.needsMethodTrampolines())
return retValue;
// scope for cache critical section
{
CacheCriticalSection reserveTrampoline(self());
// see if a reservation for this method already exists, return corresponding
// code cache if thats the case
CodeCacheHashEntry *entry = _resolvedMethodHT->findResolvedMethod(method);
if (!entry)
{
// Reserve a new trampoline since there is not an active reservation for given method
//
retValue = self()->reserveSpaceForTrampoline();
if (retValue == OMR::CodeCacheErrorCode::ERRORCODE_SUCCESS)
{
// add hashtable entry
if (!self()->addResolvedMethod(method))
retValue = CodeCacheErrorCode::ERRORCODE_FATALERROR; // couldn't allocate memory from VM
}
}
}
return retValue;
}
// Trampoline lookup for resolved methods
//
OMR::CodeCacheTrampolineCode *
OMR::CodeCache::findTrampoline(TR_OpaqueMethodBlock * method)
{
CodeCacheTrampolineCode *trampoline;
// scope for critical section
{
CacheCriticalSection resolveAndCreateTrampoline(self());
CodeCacheHashEntry *entry = _resolvedMethodHT->findResolvedMethod(method);
trampoline = entry->_info._resolved._currentTrampoline;
if (!trampoline)
{
void *newPC = (void *) TR::Compiler->mtd.startPC(method);
trampoline = self()->allocateTrampoline();
self()->createTrampoline(trampoline, newPC, method);
entry->_info._resolved._currentTrampoline = trampoline;
entry->_info._resolved._currentStartPC = newPC;
}
}
return trampoline;
}
// Trampoline lookup for helper methods
//
OMR::CodeCacheTrampolineCode *
OMR::CodeCache::findTrampoline(int32_t helperIndex)
{
CodeCacheTrampolineCode *trampoline;
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
trampoline = (CodeCacheTrampolineCode *) (_helperBase + (config.trampolineCodeSize() * helperIndex));
//TR_ASSERT(trampoline < _helperTop);
return trampoline;
}
// Replace a trampoline
//
OMR::CodeCacheTrampolineCode *
OMR::CodeCache::replaceTrampoline(TR_OpaqueMethodBlock *method,
void *oldTrampoline,
void *oldTargetPC,
void *newTargetPC,
bool needSync)
{
CodeCacheTrampolineCode *trampoline = oldTrampoline;
CodeCacheHashEntry *entry;
entry = _resolvedMethodHT->findResolvedMethod(method);
//suspicious that this assertion is commented out...
//TR_ASSERT(entry);
if (oldTrampoline == NULL)
{
// A trampoline has not been created. Simply allocate a new one.
//
trampoline = self()->allocateTrampoline();
entry->_info._resolved._currentTrampoline = trampoline;
}
else
{
if (needSync)
{
// Trampoline CANNOT be safely modified in place
// We have to allocate a new temporary trampoline
// and rely on the sync later on to update the old one using the
// temporary data
//
// A permanent trampoline already exists, create a temporary one,
// This might fail due to lack of free slots
//
trampoline = self()->allocateTempTrampoline();
// Save the temporary trampoline entry for future temp->parm synchronization
self()->saveTempTrampoline(entry);
if (!trampoline)
{
// Unable to fulfill the replacement request, no temp space left
return NULL;
}
}
}
// update the hash entry for this method
entry->_info._resolved._currentStartPC = newTargetPC;
return trampoline;
}
// Synchronize all temporary trampolines in given code cache
//
void
OMR::CodeCache::syncTempTrampolines()
{
if (_flags & CODECACHE_FULL_SYNC_REQUIRED)
{
for (uint32_t entryIdx = 0; entryIdx < _resolvedMethodHT->_size; entryIdx++)
{
for (CodeCacheHashEntry *entry = _resolvedMethodHT->_buckets[entryIdx]; entry; entry = entry->_next)
{
void *newPC = (void *) TR::Compiler->mtd.startPC(entry->_info._resolved._method);
void *trampoline = entry->_info._resolved._currentTrampoline;
if (trampoline && entry->_info._resolved._currentStartPC != newPC)
{
self()->createTrampoline(trampoline,
newPC,
entry->_info._resolved._method);
entry->_info._resolved._currentStartPC = newPC;
}
}
}
for (CodeCacheTempTrampolineSyncBlock *syncBlock = _trampolineSyncList; syncBlock; syncBlock = syncBlock->_next)
syncBlock->_entryCount = 0;
_flags &= ~CODECACHE_FULL_SYNC_REQUIRED;
}
else
{
CodeCacheTempTrampolineSyncBlock *syncBlock = NULL;
// Traverse the list of trampoline synchronization blocks
for (syncBlock = _trampolineSyncList; syncBlock; syncBlock = syncBlock->_next)
{
//TR_ASSERT(syncBlock->_entryCount <= syncBlock->_entryListSize);
// Synchronize all stored sync requests
for (uint32_t entryIdx = 0; entryIdx < syncBlock->_entryCount; entryIdx++)
{
CodeCacheHashEntry *entry = syncBlock->_hashEntryArray[entryIdx];
void *newPC = (void *) TR::Compiler->mtd.startPC(entry->_info._resolved._method);
// call the codegen to perform the trampoline code modification
self()->createTrampoline(entry->_info._resolved._currentTrampoline,
newPC,
entry->_info._resolved._method);
entry->_info._resolved._currentStartPC = newPC;
}
syncBlock->_entryCount = 0;
}
}
_tempTrampolineNext = _tempTrampolineBase;
}
// Patch the address of a method in this code cache's trampolines
//
void
OMR::CodeCache::patchCallPoint(TR_OpaqueMethodBlock *method,
void *callSite,
void *newStartPC,
void *extraArg)
{
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
// the name is still the same. The logic of callPointPatching is as follow:
// look up the right codeCache,
// search for the hashEntry for the method,
// grab its current trampoline plus its current pointed-at address (if no trampoline, both are NULL).
// Then, call code_patching with these things as argument.
// scope to patch trampoline
{
CacheCriticalSection patching(self());
CodeCacheTrampolineCode *resolvedTramp = NULL;
void *methodRunAddress = NULL;
if (config.needsMethodTrampolines())
{
CodeCacheHashEntry *entry = _resolvedMethodHT->findResolvedMethod(method);
if (entry)
{
resolvedTramp = entry->_info._resolved._currentTrampoline;
if (resolvedTramp)
methodRunAddress = entry->_info._resolved._currentStartPC;
}
}
else if (TR::Options::getCmdLineOptions()->getOption(TR_UseGlueIfMethodTrampolinesAreNotNeeded))
{
// Safety measure, return to the old behaviour of always going through the glue
return;
}
if (TR::Options::getCmdLineOptions()->getVerboseOption(TR_VerbosePatching))
{
TR_VerboseLog::writeLineLocked(TR_Vlog_PATCH, "Patching callsite=0x%p using j9method=0x%p,resolvedTramp=0x%p,methodRunAddress=0x%p,newStartPC=0x%p,extraArg=0x%p",
callSite,
method,
resolvedTramp,
methodRunAddress,
newStartPC,
extraArg);
}
// Patch the code for a method trampoline
int32_t rc = _manager->codeCacheConfig().mccCallbacks().patchTrampoline(method, callSite, methodRunAddress, resolvedTramp, newStartPC, extraArg);
}
}
// Create code for a method trampoline at indicated address
//
// Calls platform dependent code to create a trampoline code snippet at the
// specified address and initialize it to jump to targetStartPC.
//
void
OMR::CodeCache::createTrampoline(CodeCacheTrampolineCode *trampoline,
void *targetStartPC,
TR_OpaqueMethodBlock *method)
{
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
config.mccCallbacks().createMethodTrampoline(trampoline, targetStartPC, method);
}
bool
OMR::CodeCache::saveTempTrampoline(CodeCacheHashEntry *entry)
{
CodeCacheTempTrampolineSyncBlock *freeSyncBlock = NULL;
CodeCacheTempTrampolineSyncBlock *syncBlock;
for (syncBlock = _trampolineSyncList; syncBlock; syncBlock = syncBlock->_next)
{
// See if the entry already exists in the block.
// If so, don't add another copy.
//
for (int32_t i = 0; i < syncBlock->_entryCount; i++)
{
if (syncBlock->_hashEntryArray[i] == entry)
return true;
}
// Remember the first sync block that has some free slots
//
if (syncBlock->_entryCount < syncBlock->_entryListSize && !freeSyncBlock)
freeSyncBlock = syncBlock;
}
if (!freeSyncBlock)
{
// Allocate a new temp trampoline sync block
//
if (!self()->allocateTempTrampolineSyncBlock())
{
// Can't allocate another block, mark the code cache as needing a
// full/slow sync during a safe point
//
_flags |= CODECACHE_FULL_SYNC_REQUIRED;
return false;
}
// New block is now at the at head of list
//
freeSyncBlock = _trampolineSyncList;
}
freeSyncBlock->_hashEntryArray[freeSyncBlock->_entryCount] = entry;
freeSyncBlock->_entryCount++;
return true;
}
// Allocate a new temp trampoline sync block and add it to the head of the list
// of such blocks.
//
bool
OMR::CodeCache::allocateTempTrampolineSyncBlock()
{
CodeCacheTempTrampolineSyncBlock *block = static_cast<CodeCacheTempTrampolineSyncBlock*>(_manager->getMemory(sizeof(CodeCacheTempTrampolineSyncBlock)));
if (!block)
return false;
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
block->_hashEntryArray = static_cast<CodeCacheHashEntry**>(_manager->getMemory(sizeof(CodeCacheHashEntry *) * config.codeCacheTempTrampolineSyncArraySize()));
if (!block->_hashEntryArray)
{
_manager->freeMemory(block);
return false;
}
mcc_printf("mcc_temptrampolinesyncblock: trampolineSyncList = %p\n", _trampolineSyncList);
mcc_printf("mcc_temptrampolinesyncblock: block = %p\n", block);
block->_entryCount = 0;
block->_entryListSize = config.codeCacheTempTrampolineSyncArraySize();
block->_next = _trampolineSyncList;
_trampolineSyncList = block;
return true;
}
// Allocate a trampoline hash entry
//
OMR::CodeCacheHashEntry *
OMR::CodeCache::allocateHashEntry()
{
CodeCacheHashEntry *entry;
CodeCacheHashEntrySlab *slab = _hashEntrySlab;
// Do we have any free entries that were previously allocated from (perhaps)
// a slab or this list and were released onto it?
if (_hashEntryFreeList)
{
entry = _hashEntryFreeList;
_hashEntryFreeList = entry->_next;
return entry;
}
// Look for a slab with free hash entries
if ((slab->_heapAlloc + sizeof(CodeCacheHashEntry)) > slab->_heapTop)
{
TR::CodeCacheConfig & config = _manager->codeCacheConfig();
slab = CodeCacheHashEntrySlab::allocate(_manager, config.codeCacheHashEntryAllocatorSlabSize());
if (slab == NULL)
return NULL;
slab->_next = _hashEntrySlab;
_hashEntrySlab = slab;
}
entry = (CodeCacheHashEntry *) slab->_heapAlloc;
slab->_heapAlloc += sizeof(CodeCacheHashEntry);
return entry;
}
// Release an unused trampoline hash entry back onto the free list
//
void
OMR::CodeCache::freeHashEntry(CodeCacheHashEntry *entry)
{
// put it back onto the first slabs free list, see comment above
entry->_next = _hashEntryFreeList;
_hashEntryFreeList = entry;
}
// Add a resolved method to the trampoline hash table
//
bool
OMR::CodeCache::addResolvedMethod(TR_OpaqueMethodBlock *method)
{
CodeCacheHashEntry *entry = self()->allocateHashEntry();
if (!entry)
return false;
entry->_key = _resolvedMethodHT->hashResolvedMethod(method);
entry->_info._resolved._method = method;
entry->_info._resolved._currentStartPC = NULL;
entry->_info._resolved._currentTrampoline = NULL;
_resolvedMethodHT->add(entry);
return true;
}
// empty by default
OMR::CodeCacheMethodHeader *
OMR::CodeCache::addFreeBlock(void * metaData)
{
return NULL;
}
// May add the block between start and end to freeBlockList.
// returns false if block is not added
// No lock is needed because this operation is performed at GC points
// when GC has exclusive access; This is why the allocation (by the compilation
// thread needs to be done with VM access
// It can also be done by a compilation thread that performs a resize, but we
// also take VM access around resize.
bool
OMR::CodeCache::addFreeBlock2WithCallSite(uint8_t *start,
uint8_t *end,
char *file,
uint32_t lineNumber)
{
TR::CodeCacheConfig &config = _manager->codeCacheConfig();
// align start on a code cache alignment boundary
uint8_t *start_o = start;
uint32_t round = config.codeCacheAlignment() - 1;
start = align(start, round);
// make sure aligning start didn't push it past end
if (end <= (start+sizeof(CodeCacheFreeCacheBlock)))
{
if (config.verboseReclamation())
{
TR_VerboseLog::writeLineLocked(TR_Vlog_FAILURE,"addFreeBlock2[%s.%d]: failed to add free block. start = 0x%016x end = 0x%016x alignment = 0x%04x sizeof(CodeCacheFreeCacheBlock) = 0x%08x",
file, lineNumber, start_o, end, config.codeCacheAlignment(), sizeof(CodeCacheFreeCacheBlock));
}
return false;
}
uint64_t size = end - start; // Size of space to be freed
// Destroy the eyeCatcher; note that there might not be an eyecatcher at all
//
if (size >= sizeof(CodeCacheMethodHeader))
((CodeCacheMethodHeader*)start)->_eyeCatcher[0] = 0;
//fprintf(stderr, "--ccr-- newFreeBlock size %d at %p\n", size, start);
CodeCacheFreeCacheBlock *mergedBlock = NULL;
CodeCacheFreeCacheBlock *link = NULL;
if (_freeBlockList)
{
CodeCacheFreeCacheBlock *curr;
// find the insertion point
for (curr = _freeBlockList; curr->_next && (uint8_t *)(curr->_next) < start; curr = curr->_next)
{}
if (start < (uint8_t *)curr && (uint8_t *)curr - end < sizeof(CodeCacheFreeCacheBlock))
{
// merge with the curr block ahead, which is also the first block
TR_ASSERT(end <= (uint8_t *)curr, "assertion failure"); // check for no overlap of blocks
// we should not merge warm block with cold blocks
if (!(start < _warmCodeAlloc && (uint8_t *)curr >= _coldCodeAlloc))
{
// which is also the first block
link = (CodeCacheFreeCacheBlock *) start;
mergedBlock = curr;
//fprintf(stderr, "--ccr-- merging new free block of the size %d with a block of the size %d at %p\n", size, curr->size, link);
link->_size = (uint8_t *)curr + curr->_size - start;
link->_next = curr->_next;
_freeBlockList = link;
//fprintf(stderr, "--ccr-- new merged free block's size is %d\n", link->size);
}
}
else if (curr->_next && ((uint8_t *)curr->_next - end < sizeof(CodeCacheFreeCacheBlock)) &&
!(start < _warmCodeAlloc && (uint8_t *)curr->_next >= _coldCodeAlloc))
{