1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "interpreter/bytecodeStream.hpp"
26 #include "interpreter/oopMapCache.hpp"
27 #include "logging/log.hpp"
28 #include "logging/logStream.hpp"
29 #include "memory/allocation.inline.hpp"
30 #include "memory/resourceArea.hpp"
31 #include "oops/generateOopMap.hpp"
32 #include "oops/oop.inline.hpp"
33 #include "runtime/atomicAccess.hpp"
34 #include "runtime/handles.inline.hpp"
35 #include "runtime/safepoint.hpp"
36 #include "runtime/signature.hpp"
37 #include "utilities/globalCounter.inline.hpp"
38
39 class OopMapCacheEntry: private InterpreterOopMap {
40 friend class InterpreterOopMap;
41 friend class OopMapForCacheEntry;
42 friend class OopMapCache;
43 friend class VerifyClosure;
44
45 private:
46 OopMapCacheEntry* _next;
47
48 protected:
49 // Initialization
50 void fill(const methodHandle& method, int bci);
51 // fills the bit mask for native calls
52 void fill_for_native(const methodHandle& method);
53 void set_mask(CellTypeState* vars, CellTypeState* stack, int stack_top);
54
55 // Deallocate bit masks and initialize fields
56 void flush();
57
58 static void deallocate(OopMapCacheEntry* const entry);
59
60 private:
61 void allocate_bit_mask(); // allocates the bit mask on C heap f necessary
62 void deallocate_bit_mask(); // allocates the bit mask on C heap f necessary
63 bool verify_mask(CellTypeState *vars, CellTypeState *stack, int max_locals, int stack_top);
64
65 public:
66 OopMapCacheEntry() : InterpreterOopMap() {
67 _next = nullptr;
68 }
69 };
70
71
72 // Implementation of OopMapForCacheEntry
73 // (subclass of GenerateOopMap, initializes an OopMapCacheEntry for a given method and bci)
74
75 class OopMapForCacheEntry: public GenerateOopMap {
76 OopMapCacheEntry *_entry;
77 int _bci;
78 int _stack_top;
79
80 virtual bool report_results() const { return false; }
81 virtual void fill_stackmap_for_opcodes (BytecodeStream *bcs,
82 CellTypeState* vars,
83 CellTypeState* stack,
84 int stack_top);
85
86 public:
87 OopMapForCacheEntry(const methodHandle& method, int bci, OopMapCacheEntry *entry);
88
89 // Computes stack map for (method,bci) and initialize entry
90 bool compute_map(Thread* current);
91 int size();
92 };
93
94
95 OopMapForCacheEntry::OopMapForCacheEntry(const methodHandle& method, int bci, OopMapCacheEntry* entry) : GenerateOopMap(method) {
96 _bci = bci;
97 _entry = entry;
98 _stack_top = -1;
99 }
100
101
102 bool OopMapForCacheEntry::compute_map(Thread* current) {
103 assert(!method()->is_native(), "cannot compute oop map for native methods");
104 // First check if it is a method where the stackmap is always empty
105 if (method()->code_size() == 0 || method()->max_locals() + method()->max_stack() == 0) {
106 _entry->set_mask_size(0);
107 } else {
108 ResourceMark rm;
109 if (!GenerateOopMap::compute_map(current)) {
110 fatal("Unrecoverable verification or out-of-memory error");
111 return false;
112 }
113 result_for_basicblock(_bci);
114 }
115 return true;
116 }
117
118
119 void OopMapForCacheEntry::fill_stackmap_for_opcodes(BytecodeStream *bcs,
120 CellTypeState* vars,
121 CellTypeState* stack,
122 int stack_top) {
123 // Only interested in one specific bci
124 if (bcs->bci() == _bci) {
125 _entry->set_mask(vars, stack, stack_top);
126 _stack_top = stack_top;
127 }
128 }
129
130
131 int OopMapForCacheEntry::size() {
132 assert(_stack_top != -1, "compute_map must be called first");
133 return ((method()->is_static()) ? 0 : 1) + method()->max_locals() + _stack_top;
134 }
135
136
137 // Implementation of InterpreterOopMap and OopMapCacheEntry
138
139 class VerifyClosure : public OffsetClosure {
140 private:
141 OopMapCacheEntry* _entry;
142 bool _failed;
143
144 public:
145 VerifyClosure(OopMapCacheEntry* entry) { _entry = entry; _failed = false; }
146 void offset_do(int offset) { if (!_entry->is_oop(offset)) _failed = true; }
147 bool failed() const { return _failed; }
148 };
149
150 InterpreterOopMap::InterpreterOopMap() {
151 initialize();
152 }
153
154 InterpreterOopMap::~InterpreterOopMap() {
155 if (has_valid_mask() && mask_size() > small_mask_limit) {
156 assert(_bit_mask[0] != 0, "should have pointer to C heap");
157 FREE_C_HEAP_ARRAY(uintptr_t, _bit_mask[0]);
158 }
159 }
160
161 bool InterpreterOopMap::is_empty() const {
162 bool result = _method == nullptr;
163 assert(_method != nullptr || (_bci == 0 &&
164 (_mask_size == 0 || _mask_size == USHRT_MAX) &&
165 _bit_mask[0] == 0), "Should be completely empty");
166 return result;
167 }
168
169 void InterpreterOopMap::initialize() {
170 _method = nullptr;
171 _mask_size = USHRT_MAX; // This value should cause a failure quickly
172 _bci = 0;
173 _expression_stack_size = 0;
174 _num_oops = 0;
175 for (int i = 0; i < N; i++) _bit_mask[i] = 0;
176 }
177
178 void InterpreterOopMap::iterate_oop(OffsetClosure* oop_closure) const {
179 int n = number_of_entries();
180 int word_index = 0;
181 uintptr_t value = 0;
182 uintptr_t mask = 0;
183 // iterate over entries
184 for (int i = 0; i < n; i++, mask <<= bits_per_entry) {
185 // get current word
186 if (mask == 0) {
187 value = bit_mask()[word_index++];
188 mask = 1;
189 }
190 // test for oop
191 if ((value & (mask << oop_bit_number)) != 0) oop_closure->offset_do(i);
192 }
193 }
194
195 void InterpreterOopMap::print() const {
196 int n = number_of_entries();
197 tty->print("oop map for ");
198 method()->print_value();
199 tty->print(" @ %d = [%d] { ", bci(), n);
200 for (int i = 0; i < n; i++) {
201 if (is_dead(i)) tty->print("%d+ ", i);
202 else
203 if (is_oop(i)) tty->print("%d ", i);
204 }
205 tty->print_cr("}");
206 }
207
208 class MaskFillerForNative: public NativeSignatureIterator {
209 private:
210 uintptr_t * _mask; // the bit mask to be filled
211 int _size; // the mask size in bits
212 int _num_oops;
213
214 void set_one(int i) {
215 _num_oops++;
216 i *= InterpreterOopMap::bits_per_entry;
217 assert(0 <= i && i < _size, "offset out of bounds");
218 _mask[i / BitsPerWord] |= (((uintptr_t) 1 << InterpreterOopMap::oop_bit_number) << (i % BitsPerWord));
219 }
220
221 public:
222 void pass_byte() { /* ignore */ }
223 void pass_short() { /* ignore */ }
224 void pass_int() { /* ignore */ }
225 void pass_long() { /* ignore */ }
226 void pass_float() { /* ignore */ }
227 void pass_double() { /* ignore */ }
228 void pass_object() { set_one(offset()); }
229
230 MaskFillerForNative(const methodHandle& method, uintptr_t* mask, int size) : NativeSignatureIterator(method) {
231 _mask = mask;
232 _size = size;
233 _num_oops = 0;
234 // initialize with 0
235 int i = (size + BitsPerWord - 1) / BitsPerWord;
236 while (i-- > 0) _mask[i] = 0;
237 }
238
239 void generate() {
240 iterate();
241 }
242
243 int num_oops() { return _num_oops; }
244 };
245
246 bool OopMapCacheEntry::verify_mask(CellTypeState* vars, CellTypeState* stack, int max_locals, int stack_top) {
247 // Check mask includes map
248 VerifyClosure blk(this);
249 iterate_oop(&blk);
250 if (blk.failed()) return false;
251
252 // Check if map is generated correctly
253 // (Use ?: operator to make sure all 'true' & 'false' are represented exactly the same so we can use == afterwards)
254 const bool log = log_is_enabled(Trace, interpreter, oopmap);
255 LogStream st(Log(interpreter, oopmap)::trace());
256
257 if (log) st.print("Locals (%d): ", max_locals);
258 for(int i = 0; i < max_locals; i++) {
259 bool v1 = is_oop(i) ? true : false;
260 bool v2 = vars[i].is_reference() ? true : false;
261 assert(v1 == v2, "locals oop mask generation error");
262 if (log) st.print("%d", v1 ? 1 : 0);
263 }
264 if (log) st.cr();
265
266 if (log) st.print("Stack (%d): ", stack_top);
267 for(int j = 0; j < stack_top; j++) {
268 bool v1 = is_oop(max_locals + j) ? true : false;
269 bool v2 = stack[j].is_reference() ? true : false;
270 assert(v1 == v2, "stack oop mask generation error");
271 if (log) st.print("%d", v1 ? 1 : 0);
272 }
273 if (log) st.cr();
274 return true;
275 }
276
277 void OopMapCacheEntry::allocate_bit_mask() {
278 if (mask_size() > small_mask_limit) {
279 assert(_bit_mask[0] == 0, "bit mask should be new or just flushed");
280 _bit_mask[0] = (intptr_t)
281 NEW_C_HEAP_ARRAY(uintptr_t, mask_word_size(), mtClass);
282 }
283 }
284
285 void OopMapCacheEntry::deallocate_bit_mask() {
286 if (mask_size() > small_mask_limit && _bit_mask[0] != 0) {
287 assert(!Thread::current()->resource_area()->contains((void*)_bit_mask[0]),
288 "This bit mask should not be in the resource area");
289 FREE_C_HEAP_ARRAY(uintptr_t, _bit_mask[0]);
290 DEBUG_ONLY(_bit_mask[0] = 0;)
291 }
292 }
293
294
295 void OopMapCacheEntry::fill_for_native(const methodHandle& mh) {
296 assert(mh->is_native(), "method must be native method");
297 set_mask_size(mh->size_of_parameters() * bits_per_entry);
298 allocate_bit_mask();
299 // fill mask for parameters
300 MaskFillerForNative mf(mh, bit_mask(), mask_size());
301 mf.generate();
302 _num_oops = mf.num_oops();
303 }
304
305
306 void OopMapCacheEntry::fill(const methodHandle& method, int bci) {
307 // Flush entry to deallocate an existing entry
308 flush();
309 set_method(method());
310 set_bci(checked_cast<unsigned short>(bci)); // bci is always u2
311 if (method->is_native()) {
312 // Native method activations have oops only among the parameters and one
313 // extra oop following the parameters (the mirror for static native methods).
314 fill_for_native(method);
315 } else {
316 OopMapForCacheEntry gen(method, bci, this);
317 if (!gen.compute_map(Thread::current())) {
318 fatal("Unrecoverable verification or out-of-memory error");
319 }
320 }
321 }
322
323
324 void OopMapCacheEntry::set_mask(CellTypeState *vars, CellTypeState *stack, int stack_top) {
325 // compute bit mask size
326 int max_locals = method()->max_locals();
327 int n_entries = max_locals + stack_top;
328 set_mask_size(n_entries * bits_per_entry);
329 allocate_bit_mask();
330 set_expression_stack_size(stack_top);
331
332 // compute bits
333 int word_index = 0;
334 uintptr_t value = 0;
335 uintptr_t mask = 1;
336
337 _num_oops = 0;
338 CellTypeState* cell = vars;
339 for (int entry_index = 0; entry_index < n_entries; entry_index++, mask <<= bits_per_entry, cell++) {
340 // store last word
341 if (mask == 0) {
342 bit_mask()[word_index++] = value;
343 value = 0;
344 mask = 1;
345 }
346
347 // switch to stack when done with locals
348 if (entry_index == max_locals) {
349 cell = stack;
350 }
351
352 // set oop bit
353 if ( cell->is_reference()) {
354 value |= (mask << oop_bit_number );
355 _num_oops++;
356 }
357
358 // set dead bit
359 if (!cell->is_live()) {
360 value |= (mask << dead_bit_number);
361 assert(!cell->is_reference(), "dead value marked as oop");
362 }
363 }
364
365 // make sure last word is stored
366 bit_mask()[word_index] = value;
367
368 // verify bit mask
369 assert(verify_mask(vars, stack, max_locals, stack_top), "mask could not be verified");
370 }
371
372 void OopMapCacheEntry::flush() {
373 deallocate_bit_mask();
374 initialize();
375 }
376
377 void OopMapCacheEntry::deallocate(OopMapCacheEntry* const entry) {
378 entry->flush();
379 FREE_C_HEAP_OBJ(entry);
380 }
381
382 // Implementation of OopMapCache
383
384 void InterpreterOopMap::copy_from(const OopMapCacheEntry* src) {
385 // The expectation is that this InterpreterOopMap is recently created
386 // and empty. It is used to get a copy of a cached entry.
387 assert(!has_valid_mask(), "InterpreterOopMap object can only be filled once");
388 assert(src->has_valid_mask(), "Cannot copy entry with an invalid mask");
389
390 set_method(src->method());
391 set_bci(src->bci());
392 set_mask_size(src->mask_size());
393 set_expression_stack_size(src->expression_stack_size());
394 _num_oops = src->num_oops();
395
396 // Is the bit mask contained in the entry?
397 if (src->mask_size() <= small_mask_limit) {
398 memcpy(_bit_mask, src->_bit_mask, mask_word_size() * BytesPerWord);
399 } else {
400 _bit_mask[0] = (uintptr_t) NEW_C_HEAP_ARRAY(uintptr_t, mask_word_size(), mtClass);
401 memcpy((void*) _bit_mask[0], (void*) src->_bit_mask[0], mask_word_size() * BytesPerWord);
402 }
403 }
404
405 inline unsigned int OopMapCache::hash_value_for(const methodHandle& method, int bci) const {
406 // We use method->code_size() rather than method->identity_hash() below since
407 // the mark may not be present if a pointer to the method is already reversed.
408 return ((unsigned int) bci)
409 ^ ((unsigned int) method->max_locals() << 2)
410 ^ ((unsigned int) method->code_size() << 4)
411 ^ ((unsigned int) method->size_of_parameters() << 6);
412 }
413
414 OopMapCacheEntry* volatile OopMapCache::_old_entries = nullptr;
415
416 OopMapCache::OopMapCache() {
417 for(int i = 0; i < size; i++) _array[i] = nullptr;
418 }
419
420
421 OopMapCache::~OopMapCache() {
422 // Deallocate oop maps that are allocated out-of-line
423 flush();
424 }
425
426 OopMapCacheEntry* OopMapCache::entry_at(int i) const {
427 return AtomicAccess::load_acquire(&(_array[i % size]));
428 }
429
430 bool OopMapCache::put_at(int i, OopMapCacheEntry* entry, OopMapCacheEntry* old) {
431 return AtomicAccess::cmpxchg(&_array[i % size], old, entry) == old;
432 }
433
434 void OopMapCache::flush() {
435 for (int i = 0; i < size; i++) {
436 OopMapCacheEntry* entry = _array[i];
437 if (entry != nullptr) {
438 _array[i] = nullptr; // no barrier, only called in OopMapCache destructor
439 OopMapCacheEntry::deallocate(entry);
440 }
441 }
442 }
443
444 void OopMapCache::flush_obsolete_entries() {
445 assert(SafepointSynchronize::is_at_safepoint(), "called by RedefineClasses in a safepoint");
446 for (int i = 0; i < size; i++) {
447 OopMapCacheEntry* entry = _array[i];
448 if (entry != nullptr && !entry->is_empty() && entry->method()->is_old()) {
449 // Cache entry is occupied by an old redefined method and we don't want
450 // to pin it down so flush the entry.
451 if (log_is_enabled(Debug, redefine, class, oopmap)) {
452 ResourceMark rm;
453 log_debug(redefine, class, interpreter, oopmap)
454 ("flush: %s(%s): cached entry @%d",
455 entry->method()->name()->as_C_string(), entry->method()->signature()->as_C_string(), i);
456 }
457 _array[i] = nullptr;
458 OopMapCacheEntry::deallocate(entry);
459 }
460 }
461 }
462
463 // Lookup or compute/cache the entry.
464 void OopMapCache::lookup(const methodHandle& method,
465 int bci,
466 InterpreterOopMap* entry_for) {
467 int probe = hash_value_for(method, bci);
468
469 if (log_is_enabled(Debug, interpreter, oopmap)) {
470 static int count = 0;
471 ResourceMark rm;
472 log_debug(interpreter, oopmap)
473 ("%d - Computing oopmap at bci %d for %s at hash %d", ++count, bci,
474 method()->name_and_sig_as_C_string(), probe);
475 }
476
477 // Search hashtable for match.
478 // Need a critical section to avoid race against concurrent reclamation.
479 {
480 GlobalCounter::CriticalSection cs(Thread::current());
481 for (int i = 0; i < probe_depth; i++) {
482 OopMapCacheEntry *entry = entry_at(probe + i);
483 if (entry != nullptr && !entry->is_empty() && entry->match(method, bci)) {
484 entry_for->copy_from(entry);
485 assert(!entry_for->is_empty(), "A non-empty oop map should be returned");
486 log_debug(interpreter, oopmap)("- found at hash %d", probe + i);
487 return;
488 }
489 }
490 }
491
492 // Entry is not in hashtable.
493 // Compute entry
494
495 OopMapCacheEntry* tmp = NEW_C_HEAP_OBJ(OopMapCacheEntry, mtClass);
496 tmp->initialize();
497 tmp->fill(method, bci);
498 entry_for->copy_from(tmp);
499
500 if (method->should_not_be_cached()) {
501 // It is either not safe or not a good idea to cache this Method*
502 // at this time. We give the caller of lookup() a copy of the
503 // interesting info via parameter entry_for, but we don't add it to
504 // the cache. See the gory details in Method*.cpp.
505 OopMapCacheEntry::deallocate(tmp);
506 return;
507 }
508
509 // First search for an empty slot
510 for (int i = 0; i < probe_depth; i++) {
511 OopMapCacheEntry* entry = entry_at(probe + i);
512 if (entry == nullptr) {
513 if (put_at(probe + i, tmp, nullptr)) {
514 assert(!entry_for->is_empty(), "A non-empty oop map should be returned");
515 return;
516 }
517 }
518 }
519
520 log_debug(interpreter, oopmap)("*** collision in oopmap cache - flushing item ***");
521
522 // No empty slot (uncommon case). Use (some approximation of a) LRU algorithm
523 // where the first entry in the collision array is replaced with the new one.
524 OopMapCacheEntry* old = entry_at(probe + 0);
525 if (put_at(probe + 0, tmp, old)) {
526 // Cannot deallocate old entry on the spot: it can still be used by readers
527 // that got a reference to it before we were able to replace it in the map.
528 // Instead of synchronizing on GlobalCounter here and incurring heavy thread
529 // walk, we do this clean up out of band.
530 enqueue_for_cleanup(old);
531 } else {
532 OopMapCacheEntry::deallocate(tmp);
533 }
534
535 assert(!entry_for->is_empty(), "A non-empty oop map should be returned");
536 return;
537 }
538
539 void OopMapCache::enqueue_for_cleanup(OopMapCacheEntry* entry) {
540 while (true) {
541 OopMapCacheEntry* head = AtomicAccess::load(&_old_entries);
542 entry->_next = head;
543 if (AtomicAccess::cmpxchg(&_old_entries, head, entry) == head) {
544 // Enqueued successfully.
545 break;
546 }
547 }
548
549 if (log_is_enabled(Debug, interpreter, oopmap)) {
550 ResourceMark rm;
551 log_debug(interpreter, oopmap)("enqueue %s at bci %d for cleanup",
552 entry->method()->name_and_sig_as_C_string(), entry->bci());
553 }
554 }
555
556 bool OopMapCache::has_cleanup_work() {
557 return AtomicAccess::load(&_old_entries) != nullptr;
558 }
559
560 void OopMapCache::try_trigger_cleanup() {
561 // See we can take the lock for the notification without blocking.
562 // This allows triggering the cleanup from GC paths, that can hold
563 // the service lock for e.g. oop iteration in service thread.
564 if (has_cleanup_work() && Service_lock->try_lock_without_rank_check()) {
565 Service_lock->notify_all();
566 Service_lock->unlock();
567 }
568 }
569
570 void OopMapCache::cleanup() {
571 OopMapCacheEntry* entry = AtomicAccess::xchg(&_old_entries, (OopMapCacheEntry*)nullptr);
572 if (entry == nullptr) {
573 // No work.
574 return;
575 }
576
577 // About to delete the entries than might still be accessed by other threads
578 // on lookup path. Need to sync up with them before proceeding.
579 GlobalCounter::write_synchronize();
580
581 while (entry != nullptr) {
582 if (log_is_enabled(Debug, interpreter, oopmap)) {
583 ResourceMark rm;
584 log_debug(interpreter, oopmap)("cleanup entry %s at bci %d",
585 entry->method()->name_and_sig_as_C_string(), entry->bci());
586 }
587 OopMapCacheEntry* next = entry->_next;
588 OopMapCacheEntry::deallocate(entry);
589 entry = next;
590 }
591 }
592
593 void OopMapCache::compute_one_oop_map(const methodHandle& method, int bci, InterpreterOopMap* entry) {
594 // Due to the invariants above it's tricky to allocate a temporary OopMapCacheEntry on the stack
595 OopMapCacheEntry* tmp = NEW_C_HEAP_OBJ(OopMapCacheEntry, mtClass);
596 tmp->initialize();
597 tmp->fill(method, bci);
598 if (tmp->has_valid_mask()) {
599 entry->copy_from(tmp);
600 }
601 OopMapCacheEntry::deallocate(tmp);
602 }
--- EOF ---