1 /*
  2  * Copyright (c) 1997, 2025, 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 #ifndef SHARE_OOPS_MARKWORD_HPP
 26 #define SHARE_OOPS_MARKWORD_HPP
 27 
 28 #include "metaprogramming/primitiveConversions.hpp"
 29 #include "layoutKind.hpp"
 30 #include "oops/oopsHierarchy.hpp"
 31 #include "runtime/globals.hpp"
 32 #include "utilities/vmEnums.hpp"
 33 
 34 #include <type_traits>
 35 
 36 // The markWord describes the header of an object.
 37 //
 38 // Bit-format of an object header (most significant first, big endian layout below):
 39 //
 40 //  32 bits:
 41 //  --------
 42 //             hash:25 ------------>| age:4  unused_gap:1  lock:2 (normal object)
 43 //
 44 //  64 bits:
 45 //  --------
 46 //  unused:25 hash:31 -->| unused_gap:1  age:4  unused_gap:1  lock:2 (normal object)
 47 //
 48 //  - hash contains the identity hash value: largest value is
 49 //    31 bits, see os::random().  Also, 64-bit vm's require
 50 //    a hash value no bigger than 32 bits because they will not
 51 //    properly generate a mask larger than that: see library_call.cpp
 52 //
 53 //  - the two lock bits are used to describe three states: locked/unlocked and monitor.
 54 //
 55 //    [ptr             | 00]  locked             ptr points to real header on stack (stack-locking in use)
 56 //    [header          | 00]  locked             locked regular object header (fast-locking in use)
 57 //    [header          | 01]  unlocked           regular object header
 58 //    [ptr             | 10]  monitor            inflated lock (header is swapped out, UseObjectMonitorTable == false)
 59 //    [header          | 10]  monitor            inflated lock (UseObjectMonitorTable == true)
 60 //    [ptr             | 11]  marked             used to mark an object
 61 //    [0 ............ 0| 00]  inflating          inflation in progress (stack-locking in use)
 62 //
 63 //    We assume that stack/thread pointers have the lowest two bits cleared.
 64 //
 65 //
 66 //  - INFLATING() is a distinguished markword value of all zeros that is
 67 //    used when inflating an existing stack-lock into an ObjectMonitor.
 68 //    See below for is_being_inflated() and INFLATING().
 69 //
 70 //
 71 //
 72 //  Valhalla
 73 //
 74 //  <CMH: merge this doc into the text above>
 75 //
 76 //  Project Valhalla has mark word encoding requirements for the following oops:
 77 //
 78 //  * inline types: have alternative bytecode behavior, e.g. can not be locked
 79 //    - "larval state": mutable state, but only during object init, observable
 80 //      by only by a single thread (generally do not mutate markWord)
 81 //
 82 //  * flat arrays: load/decode of klass layout helper is expensive for aaload
 83 //
 84 //  * "null free" arrays: load/decode of klass layout helper again for aaload
 85 //
 86 //  EnableValhalla
 87 //
 88 //  Formerly known as "biased lock bit", "unused_gap" is free to use: using this
 89 //  bit to indicate inline type, combined with "unlocked" lock bits, means we
 90 //  will not interfere with lock encodings (displaced, inflating, and monitor),
 91 //  since inline types can't be locked.
 92 //
 93 //  Further state encoding
 94 //
 95 //  32 bit plaforms currently have no further room for encoding. No room for
 96 //  "denormalized layout helper bits", these fast mark word tests can only be made on
 97 //  64 bit platforms. 32-bit platforms need to load the klass->_layout_helper. This
 98 //  said, the larval state bit is still required for operation, stealing from the hash
 99 //  code is simplest mechanism.
100 //
101 //  Valhalla specific encodings
102 //
103 //  Revised Bit-format of an object header (most significant first, big endian layout below):
104 //
105 //  32 bits:
106 //  --------
107 //  hash:24 ------------>| larval:1 age:4 inline_type:1 lock:2
108 //
109 //  64 bits:
110 //  --------
111 //  unused:1 | <-- hash:31 -->| unused:22 larval:1 age:4 flat_array:1 null_free_array:1 inline_type:1 lock:2
112 //
113 //  The "fast" static type bits (flat_array, null_free_array, and inline_type)
114 //  are placed lowest next to lock bits to more easily decode forwarding pointers.
115 //  G1 for example, implicitly clears age bits ("G1FullGCCompactionPoint::forward()")
116 //  using "oopDesc->forwardee()", so it necessary for "markWord::decode_pointer()"
117 //  to return a non-nullptr for this case, but not confuse the static type bits for
118 //  a pointer.
119 //
120 //  Static types bits are recorded in the "klass->prototype_header()", displaced
121 //  mark should simply use the prototype header as "slow path", rather chasing
122 //  monitor or stack lock races.
123 //
124 //  Lock patterns (note inline types can't be locked/monitor/inflating)...
125 //
126 //  [ptr            | 000]  locked             ptr points to real header on stack
127 //  [header         | ?01]  unlocked           regular object header
128 //  [ptr            | 010]  monitor            inflated lock (header is wapped out)
129 //  [ptr            | ?11]  marked             used to mark an object
130 //  [0 ............ | 000]  inflating          inflation in progress
131 //
132 //
133 
134 class BasicLock;
135 class ObjectMonitor;
136 class JavaThread;
137 class outputStream;
138 
139 class markWord {
140  private:
141   uintptr_t _value;
142 
143  public:
144   explicit markWord(uintptr_t value) : _value(value) {}
145 
146   markWord() = default;         // Doesn't initialize _value.
147 
148   // It is critical for performance that this class be trivially
149   // destructable, copyable, and assignable.
150   ~markWord() = default;
151   markWord(const markWord&) = default;
152   markWord& operator=(const markWord&) = default;
153 
154   static markWord from_pointer(void* ptr) {
155     return markWord((uintptr_t)ptr);
156   }
157   void* to_pointer() const {
158     return (void*)_value;
159   }
160 
161   bool operator==(const markWord& other) const {
162     return _value == other._value;
163   }
164   bool operator!=(const markWord& other) const {
165     return !operator==(other);
166   }
167 
168   // Conversion
169   uintptr_t value() const { return _value; }
170 
171   // Constants, in least significant bit order
172   static const int lock_bits                      = 2;
173   static const int first_unused_gap_bits          = 1; // When !EnableValhalla
174   // EnableValhalla: static prototype header bits (fast path instead of klass layout_helper)
175   static const int inline_type_bits               = 1;
176   static const int null_free_array_bits           = LP64_ONLY(1) NOT_LP64(0);
177   static const int flat_array_bits                = LP64_ONLY(1) NOT_LP64(0);
178   // instance state
179   static const int age_bits                       = 4;
180   static const int larval_bits                    = 1;
181   static const int max_hash_bits                  = BitsPerWord - age_bits - lock_bits - inline_type_bits - larval_bits - flat_array_bits - null_free_array_bits;
182   static const int hash_bits                      = max_hash_bits > 31 ? 31 : max_hash_bits;
183   static const int second_unused_gap_bits         = LP64_ONLY(1) NOT_LP64(0); // !EnableValhalla: unused
184 
185   static const int lock_shift                     = 0;
186   static const int inline_type_shift              = lock_bits;
187   static const int null_free_array_shift          = inline_type_shift + inline_type_bits;
188   static const int flat_array_shift               = null_free_array_shift + null_free_array_bits;
189   static const int age_shift                      = flat_array_shift + flat_array_bits;
190   static const int unused_gap_shift               = age_shift + age_bits; // !EnableValhalla: unused
191   static const int larval_shift                   = age_shift + age_bits;
192   static const int hash_shift                     = LP64_ONLY(32) NOT_LP64(larval_shift + larval_bits);
193 
194   static const uintptr_t lock_mask                = right_n_bits(lock_bits);
195   static const uintptr_t lock_mask_in_place       = lock_mask << lock_shift;
196   static const uintptr_t inline_type_mask         = right_n_bits(lock_bits + inline_type_bits);
197   static const uintptr_t inline_type_mask_in_place = inline_type_mask << lock_shift;
198   static const uintptr_t inline_type_bit_in_place = 1 << inline_type_shift;
199   static const uintptr_t null_free_array_mask     = right_n_bits(null_free_array_bits);
200   static const uintptr_t null_free_array_mask_in_place = (null_free_array_mask << null_free_array_shift) | lock_mask_in_place;
201   static const uintptr_t null_free_array_bit_in_place  = (1 << null_free_array_shift);
202   static const uintptr_t flat_array_mask          = right_n_bits(flat_array_bits);
203   static const uintptr_t flat_array_mask_in_place = (flat_array_mask << flat_array_shift) | null_free_array_mask_in_place | lock_mask_in_place;
204   static const uintptr_t flat_array_bit_in_place  = (1 << flat_array_shift);
205 
206   static const uintptr_t age_mask                 = right_n_bits(age_bits);
207   static const uintptr_t age_mask_in_place        = age_mask << age_shift;
208 
209   static const uintptr_t larval_mask              = right_n_bits(larval_bits);
210   static const uintptr_t larval_mask_in_place     = (larval_mask << larval_shift) | inline_type_mask_in_place;
211   static const uintptr_t larval_bit_in_place      = (1 << larval_shift);
212 
213   static const uintptr_t hash_mask                = right_n_bits(hash_bits);
214   static const uintptr_t hash_mask_in_place       = hash_mask << hash_shift;
215 
216   static const uintptr_t locked_value             = 0;
217   static const uintptr_t unlocked_value           = 1;
218   static const uintptr_t monitor_value            = 2;
219   static const uintptr_t marked_value             = 3;
220 
221   static const uintptr_t inline_type_pattern      = inline_type_bit_in_place | unlocked_value;
222   static const uintptr_t null_free_array_pattern  = null_free_array_bit_in_place | unlocked_value;
223   static const uintptr_t null_free_flat_array_pattern = flat_array_bit_in_place | null_free_array_pattern;
224   static const uintptr_t nullable_flat_array_pattern = flat_array_bit_in_place | unlocked_value;
225 
226   // Has static klass prototype, used for decode/encode pointer
227   static const uintptr_t static_prototype_mask    = LP64_ONLY(right_n_bits(inline_type_bits + flat_array_bits + null_free_array_bits)) NOT_LP64(right_n_bits(inline_type_bits));
228   static const uintptr_t static_prototype_mask_in_place = static_prototype_mask << lock_bits;
229   static const uintptr_t static_prototype_value_max = (1 << age_shift) - 1;
230 
231   static const uintptr_t larval_pattern           = larval_bit_in_place | inline_type_pattern;
232 
233   static const uintptr_t no_hash                  = 0 ;  // no hash value assigned
234   static const uintptr_t no_hash_in_place         = (uintptr_t)no_hash << hash_shift;
235   static const uintptr_t no_lock_in_place         = unlocked_value;
236 
237   static const uint max_age                       = age_mask;
238 
239   // Creates a markWord with all bits set to zero.
240   static markWord zero() { return markWord(uintptr_t(0)); }
241 
242   bool is_inline_type() const {
243     return (mask_bits(value(), inline_type_mask_in_place) == inline_type_pattern);
244   }
245 
246   // lock accessors (note that these assume lock_shift == 0)
247   bool is_locked()   const {
248     return (mask_bits(value(), lock_mask_in_place) != unlocked_value);
249   }
250   bool is_unlocked() const {
251     return (mask_bits(value(), lock_mask_in_place) == unlocked_value);
252   }
253   bool is_marked()   const {
254     return (mask_bits(value(), lock_mask_in_place) == marked_value);
255   }
256 
257   // is unlocked and not an inline type (which cannot be involved in locking, displacement or inflation)
258   // i.e. test both lock bits and the inline type bit together
259   bool is_neutral()  const {  // Not locked, or marked - a "clean" neutral state
260     return (mask_bits(value(), inline_type_mask_in_place) == unlocked_value);
261   }
262 
263   bool is_forwarded()   const {
264     return (mask_bits(value(), lock_mask_in_place) == marked_value);
265   }
266 
267   // Special temporary state of the markWord while being inflated.
268   // Code that looks at mark outside a lock need to take this into account.
269   bool is_being_inflated() const { return (value() == 0); }
270 
271   // Distinguished markword value - used when inflating over
272   // an existing stack-lock.  0 indicates the markword is "BUSY".
273   // Lockword mutators that use a LD...CAS idiom should always
274   // check for and avoid overwriting a 0 value installed by some
275   // other thread.  (They should spin or block instead.  The 0 value
276   // is transient and *should* be short-lived).
277   // Fast-locking does not use INFLATING.
278   static markWord INFLATING() { return zero(); }    // inflate-in-progress
279 
280   // Should this header be preserved during GC?
281   bool must_be_preserved(const oopDesc* obj) const {
282     return (!is_unlocked() || !has_no_hash() || (EnableValhalla && is_larval_state()));
283   }
284 
285   // WARNING: The following routines are used EXCLUSIVELY by
286   // synchronization functions. They are not really gc safe.
287   // They must get updated if markWord layout get changed.
288   markWord set_unlocked() const {
289     return markWord(value() | unlocked_value);
290   }
291   bool has_locker() const {
292     assert(LockingMode == LM_LEGACY, "should only be called with legacy stack locking");
293     return (value() & lock_mask_in_place) == locked_value;
294   }
295   BasicLock* locker() const {
296     assert(has_locker(), "check");
297     return (BasicLock*) value();
298   }
299 
300   bool is_fast_locked() const {
301     assert(LockingMode == LM_LIGHTWEIGHT, "should only be called with new lightweight locking");
302     return (value() & lock_mask_in_place) == locked_value;
303   }
304   markWord set_fast_locked() const {
305     // Clear the lock_mask_in_place bits to set locked_value:
306     return markWord(value() & ~lock_mask_in_place);
307   }
308 
309   bool has_monitor() const {
310     return ((value() & lock_mask_in_place) == monitor_value);
311   }
312   ObjectMonitor* monitor() const {
313     assert(has_monitor(), "check");
314     assert(!UseObjectMonitorTable, "Lightweight locking with OM table does not use markWord for monitors");
315     // Use xor instead of &~ to provide one extra tag-bit check.
316     return (ObjectMonitor*) (value() ^ monitor_value);
317   }
318   bool has_displaced_mark_helper() const {
319     intptr_t lockbits = value() & lock_mask_in_place;
320     if (LockingMode == LM_LIGHTWEIGHT) {
321       return !UseObjectMonitorTable && lockbits == monitor_value;
322     }
323     // monitor (0b10) | stack-locked (0b00)?
324     return (lockbits & unlocked_value) == 0;
325   }
326   markWord displaced_mark_helper() const;
327   void set_displaced_mark_helper(markWord m) const;
328   markWord copy_set_hash(intptr_t hash) const {
329     uintptr_t tmp = value() & (~hash_mask_in_place);
330     tmp |= ((hash & hash_mask) << hash_shift);
331     return markWord(tmp);
332   }
333   // it is only used to be stored into BasicLock as the
334   // indicator that the lock is using heavyweight monitor
335   static markWord unused_mark() {
336     return markWord(marked_value);
337   }
338   // the following two functions create the markWord to be
339   // stored into object header, it encodes monitor info
340   static markWord encode(BasicLock* lock) {
341     return from_pointer(lock);
342   }
343   static markWord encode(ObjectMonitor* monitor) {
344     assert(!UseObjectMonitorTable, "Lightweight locking with OM table does not use markWord for monitors");
345     uintptr_t tmp = (uintptr_t) monitor;
346     return markWord(tmp | monitor_value);
347   }
348 
349   markWord set_has_monitor() const {
350     return markWord((value() & ~lock_mask_in_place) | monitor_value);
351   }
352 
353   // used to encode pointers during GC
354   markWord clear_lock_bits() const { return markWord(value() & ~lock_mask_in_place); }
355 
356   // age operations
357   markWord set_marked()   { return markWord((value() & ~lock_mask_in_place) | marked_value); }
358   markWord set_unmarked() { return markWord((value() & ~lock_mask_in_place) | unlocked_value); }
359 
360   uint     age()           const { return (uint) mask_bits(value() >> age_shift, age_mask); }
361   markWord set_age(uint v) const {
362     assert((v & ~age_mask) == 0, "shouldn't overflow age field");
363     return markWord((value() & ~age_mask_in_place) | ((v & age_mask) << age_shift));
364   }
365   markWord incr_age()      const { return age() == max_age ? markWord(_value) : set_age(age() + 1); }
366 
367   // hash operations
368   intptr_t hash() const {
369     return mask_bits(value() >> hash_shift, hash_mask);
370   }
371 
372   bool has_no_hash() const {
373     return hash() == no_hash;
374   }
375 
376   // private buffered value operations
377   markWord enter_larval_state() const {
378     return markWord(value() | larval_bit_in_place);
379   }
380   markWord exit_larval_state() const {
381     return markWord(value() & ~larval_bit_in_place);
382   }
383   bool is_larval_state() const {
384     return (mask_bits(value(), larval_mask_in_place) == larval_pattern);
385   }
386 
387 #ifdef _LP64 // 64 bit encodings only
388   bool is_flat_array() const {
389     return (mask_bits(value(), flat_array_mask_in_place) == null_free_flat_array_pattern)
390            || (mask_bits(value(), flat_array_mask_in_place) == nullable_flat_array_pattern);
391   }
392 
393   bool is_null_free_array() const {
394     return (mask_bits(value(), null_free_array_mask_in_place) == null_free_array_pattern);
395   }
396 #else
397   bool is_flat_array() const {
398     fatal("Should not ask this for mark word, ask oopDesc");
399     return false;
400   }
401 
402   bool is_null_free_array() const {
403     fatal("Should not ask this for mark word, ask oopDesc");
404     return false;
405   }
406 #endif
407   // Prototype mark for initialization
408   static markWord prototype() {
409     return markWord( no_hash_in_place | no_lock_in_place );
410   }
411 
412   static markWord inline_type_prototype() {
413     return markWord(inline_type_pattern);
414   }
415 
416 #ifdef _LP64 // 64 bit encodings only
417   static markWord flat_array_prototype(LayoutKind lk);
418 
419   static markWord null_free_array_prototype() {
420     return markWord(null_free_array_pattern);
421   }
422 #endif
423 
424   // Debugging
425   void print_on(outputStream* st, bool print_monitor_info = true) const;
426 
427   // Prepare address of oop for placement into mark
428   inline static markWord encode_pointer_as_mark(void* p) { return from_pointer(p).set_marked(); }
429 
430   // Recover address of oop from encoded form used in mark
431   inline void* decode_pointer() const {
432     return (EnableValhalla && _value < static_prototype_value_max) ? nullptr :
433       (void*) (clear_lock_bits().value());
434   }
435 
436   inline oop forwardee() const {
437     return cast_to_oop(decode_pointer());
438   }
439 };
440 
441 // Support atomic operations.
442 template<>
443 struct PrimitiveConversions::Translate<markWord> : public std::true_type {
444   typedef markWord Value;
445   typedef uintptr_t Decayed;
446 
447   static Decayed decay(const Value& x) { return x.value(); }
448   static Value recover(Decayed x) { return Value(x); }
449 };
450 
451 #endif // SHARE_OOPS_MARKWORD_HPP