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_UTILITIES_GLOBALDEFINITIONS_HPP
  26 #define SHARE_UTILITIES_GLOBALDEFINITIONS_HPP
  27 
  28 #include "utilities/compilerWarnings.hpp"
  29 #include "utilities/debug.hpp"
  30 #include "utilities/forbiddenFunctions.hpp"
  31 #include "utilities/macros.hpp"
  32 
  33 // Get constants like JVM_T_CHAR and JVM_SIGNATURE_INT, before pulling in <jvm.h>.
  34 #include "classfile_constants.h"
  35 
  36 #include COMPILER_HEADER(utilities/globalDefinitions)
  37 
  38 #include <cstddef>
  39 #include <cstdint>
  40 #include <limits>
  41 #include <type_traits>
  42 
  43 class oopDesc;
  44 
  45 // Defaults for macros that might be defined per compiler.
  46 #ifndef NOINLINE
  47 #define NOINLINE
  48 #endif
  49 #ifndef ALWAYSINLINE
  50 #define ALWAYSINLINE inline
  51 #endif
  52 
  53 #ifndef ATTRIBUTE_ALIGNED
  54 #define ATTRIBUTE_ALIGNED(x) alignas(x)
  55 #endif
  56 
  57 #ifndef ATTRIBUTE_FLATTEN
  58 #define ATTRIBUTE_FLATTEN
  59 #endif
  60 
  61 // These are #defines to selectively turn on/off the Print(Opto)Assembly
  62 // capabilities. Choices should be led by a tradeoff between
  63 // code size and improved supportability.
  64 // if PRINT_ASSEMBLY then PRINT_ABSTRACT_ASSEMBLY must be true as well
  65 // to have a fallback in case hsdis is not available.
  66 #if defined(PRODUCT)
  67   #define SUPPORT_ABSTRACT_ASSEMBLY
  68   #define SUPPORT_ASSEMBLY
  69   #undef  SUPPORT_OPTO_ASSEMBLY      // Can't activate. In PRODUCT, many dump methods are missing.
  70   #undef  SUPPORT_DATA_STRUCTS       // Of limited use. In PRODUCT, many print methods are empty.
  71 #else
  72   #define SUPPORT_ABSTRACT_ASSEMBLY
  73   #define SUPPORT_ASSEMBLY
  74   #define SUPPORT_OPTO_ASSEMBLY
  75   #define SUPPORT_DATA_STRUCTS
  76 #endif
  77 #if defined(SUPPORT_ASSEMBLY) && !defined(SUPPORT_ABSTRACT_ASSEMBLY)
  78   #define SUPPORT_ABSTRACT_ASSEMBLY
  79 #endif
  80 
  81 // This file holds all globally used constants & types, class (forward)
  82 // declarations and a few frequently used utility functions.
  83 
  84 // Declare the named class to be noncopyable.  This macro must be followed by
  85 // a semi-colon.  The macro provides deleted declarations for the class's copy
  86 // constructor and assignment operator.  Because these operations are deleted,
  87 // they cannot be defined and potential callers will fail to compile.
  88 #define NONCOPYABLE(C) C(C const&) = delete; C& operator=(C const&) = delete /* next token must be ; */
  89 
  90 
  91 //----------------------------------------------------------------------------------------------------
  92 // Printf-style formatters for fixed- and variable-width types as pointers and
  93 // integers.  These are derived from the definitions in inttypes.h.  If the platform
  94 // doesn't provide appropriate definitions, they should be provided in
  95 // the compiler-specific definitions file (e.g., globalDefinitions_gcc.hpp)
  96 
  97 // Guide to the suffixes used in the format specifiers for integers:
  98 //        - print the decimal value:                   745565
  99 //  _X    - print as hexadecimal, without leading 0s: 0x12345
 100 //  _X_0  - print as hexadecimal, with leading 0s: 0x00012345
 101 //  _W(w) - prints w sized string with the given value right
 102 //          adjusted. Use -w to print left adjusted.
 103 //  _0    - print as hexadecimal, with leading 0s, without 0x prefix: 0012345
 104 //
 105 // Note that the PTR format specifiers print using 0x with leading zeros,
 106 // just like the _X_0 version for integers.
 107 
 108 // Format 8-bit quantities.
 109 #define INT8_FORMAT_X_0          "0x%02"      PRIx8
 110 #define UINT8_FORMAT_X_0         "0x%02"      PRIx8
 111 
 112 // Format 16-bit quantities.
 113 #define INT16_FORMAT_X_0         "0x%04"      PRIx16
 114 #define UINT16_FORMAT_X_0        "0x%04"      PRIx16
 115 
 116 // Format 32-bit quantities.
 117 #define INT32_FORMAT             "%"          PRId32
 118 #define INT32_FORMAT_X           "0x%"        PRIx32
 119 #define INT32_FORMAT_X_0         "0x%08"      PRIx32
 120 #define INT32_FORMAT_W(width)    "%"   #width PRId32
 121 #define UINT32_FORMAT            "%"          PRIu32
 122 #define UINT32_FORMAT_X          "0x%"        PRIx32
 123 #define UINT32_FORMAT_X_0        "0x%08"      PRIx32
 124 #define UINT32_FORMAT_W(width)   "%"   #width PRIu32
 125 
 126 // Format 64-bit quantities.
 127 #define INT64_FORMAT             "%"          PRId64
 128 #define INT64_PLUS_FORMAT        "%+"         PRId64
 129 #define INT64_FORMAT_X           "0x%"        PRIx64
 130 #define INT64_FORMAT_X_0         "0x%016"     PRIx64
 131 #define INT64_FORMAT_W(width)    "%"   #width PRId64
 132 #define UINT64_FORMAT            "%"          PRIu64
 133 #define UINT64_FORMAT_X          "0x%"        PRIx64
 134 #define UINT64_FORMAT_X_0        "0x%016"     PRIx64
 135 #define UINT64_FORMAT_W(width)   "%"   #width PRIu64
 136 #define UINT64_FORMAT_0          "%016"       PRIx64
 137 
 138 // Format jlong, if necessary
 139 #ifndef JLONG_FORMAT
 140 #define JLONG_FORMAT             INT64_FORMAT
 141 #endif
 142 #ifndef JLONG_FORMAT_W
 143 #define JLONG_FORMAT_W(width)    INT64_FORMAT_W(width)
 144 #endif
 145 #ifndef JULONG_FORMAT
 146 #define JULONG_FORMAT            UINT64_FORMAT
 147 #endif
 148 #ifndef JULONG_FORMAT_X
 149 #define JULONG_FORMAT_X          UINT64_FORMAT_X
 150 #endif
 151 
 152 // Format pointers and padded integral values which change size between 32- and 64-bit.
 153 #ifdef  _LP64
 154 #define INTPTR_FORMAT            "0x%016"     PRIxPTR
 155 #define PTR_FORMAT               "0x%016"     PRIxPTR
 156 #define UINTX_FORMAT_X_0         "0x%016"     PRIxPTR
 157 #define SIZE_FORMAT_X_0          "0x%016"     PRIxPTR
 158 #else   // !_LP64
 159 #define INTPTR_FORMAT            "0x%08"      PRIxPTR
 160 #define PTR_FORMAT               "0x%08"      PRIxPTR
 161 #define UINTX_FORMAT_X_0         "0x%08"      PRIxPTR
 162 #define SIZE_FORMAT_X_0          "0x%08"      PRIxPTR
 163 #endif  // _LP64
 164 
 165 // Convert pointer to intptr_t, for use in printing pointers.
 166 inline intptr_t p2i(const volatile void* p) {
 167   return (intptr_t) p;
 168 }
 169 
 170 // Convert pointer to uintptr_t
 171 inline uintptr_t p2u(const volatile void* p) {
 172   return (uintptr_t) p;
 173 }
 174 
 175 #define BOOL_TO_STR(_b_) ((_b_) ? "true" : "false")
 176 
 177 //----------------------------------------------------------------------------------------------------
 178 // Constants
 179 
 180 const int LogBytesPerShort   = 1;
 181 const int LogBytesPerInt     = 2;
 182 #ifdef _LP64
 183 constexpr int LogBytesPerWord    = 3;
 184 #else
 185 constexpr int LogBytesPerWord    = 2;
 186 #endif
 187 const int LogBytesPerLong    = 3;
 188 
 189 const int BytesPerShort      = 1 << LogBytesPerShort;
 190 const int BytesPerInt        = 1 << LogBytesPerInt;
 191 const int BytesPerWord       = 1 << LogBytesPerWord;
 192 const int BytesPerLong       = 1 << LogBytesPerLong;
 193 
 194 constexpr int LogBitsPerByte     = 3;
 195 const int LogBitsPerShort    = LogBitsPerByte + LogBytesPerShort;
 196 const int LogBitsPerInt      = LogBitsPerByte + LogBytesPerInt;
 197 constexpr int LogBitsPerWord     = LogBitsPerByte + LogBytesPerWord;
 198 const int LogBitsPerLong     = LogBitsPerByte + LogBytesPerLong;
 199 
 200 const int BitsPerByte        = 1 << LogBitsPerByte;
 201 const int BitsPerShort       = 1 << LogBitsPerShort;
 202 const int BitsPerInt         = 1 << LogBitsPerInt;
 203 constexpr int BitsPerWord        = 1 << LogBitsPerWord;
 204 const int BitsPerLong        = 1 << LogBitsPerLong;
 205 
 206 const int WordAlignmentMask  = (1 << LogBytesPerWord) - 1;
 207 const int LongAlignmentMask  = (1 << LogBytesPerLong) - 1;
 208 
 209 const int oopSize            = sizeof(char*); // Full-width oop
 210 extern int heapOopSize;                       // Oop within a java object
 211 const int wordSize           = sizeof(char*);
 212 const int longSize           = sizeof(jlong);
 213 const int jintSize           = sizeof(jint);
 214 const int size_tSize         = sizeof(size_t);
 215 
 216 const int BytesPerOop        = BytesPerWord;  // Full-width oop
 217 
 218 extern int LogBytesPerHeapOop;                // Oop within a java object
 219 extern int LogBitsPerHeapOop;
 220 extern int BytesPerHeapOop;
 221 extern int BitsPerHeapOop;
 222 
 223 const int BitsPerJavaInteger = 32;
 224 const int BitsPerJavaLong    = 64;
 225 const int BitsPerSize_t      = size_tSize * BitsPerByte;
 226 
 227 // Size of a char[] needed to represent a jint as a string in decimal.
 228 const int jintAsStringSize = 12;
 229 
 230 // An opaque type, so that HeapWord* can be a generic pointer into the heap.
 231 // We require that object sizes be measured in units of heap words (e.g.
 232 // pointer-sized values), so that given HeapWord* hw,
 233 //   hw += oop(hw)->foo();
 234 // works, where foo is a method (like size or scavenge) that returns the
 235 // object size.
 236 class HeapWordImpl;             // Opaque, never defined.
 237 typedef HeapWordImpl* HeapWord;
 238 
 239 // Analogous opaque struct for metadata allocated from metaspaces.
 240 class MetaWordImpl;             // Opaque, never defined.
 241 typedef MetaWordImpl* MetaWord;
 242 
 243 // HeapWordSize must be 2^LogHeapWordSize.
 244 const int HeapWordSize        = sizeof(HeapWord);
 245 #ifdef _LP64
 246 const int LogHeapWordSize     = 3;
 247 #else
 248 const int LogHeapWordSize     = 2;
 249 #endif
 250 const int HeapWordsPerLong    = BytesPerLong / HeapWordSize;
 251 const int LogHeapWordsPerLong = LogBytesPerLong - LogHeapWordSize;
 252 
 253 // The minimum number of native machine words necessary to contain "byte_size"
 254 // bytes.
 255 inline size_t heap_word_size(size_t byte_size) {
 256   return (byte_size + (HeapWordSize-1)) >> LogHeapWordSize;
 257 }
 258 
 259 inline jfloat jfloat_cast(jint x);
 260 inline jdouble jdouble_cast(jlong x);
 261 
 262 //-------------------------------------------
 263 // Constant for jlong (standardized by C++11)
 264 
 265 // Build a 64bit integer constant
 266 #define CONST64(x)  (x ## LL)
 267 #define UCONST64(x) (x ## ULL)
 268 
 269 const jlong min_jlong = CONST64(0x8000000000000000);
 270 const jlong max_jlong = CONST64(0x7fffffffffffffff);
 271 
 272 // for timer info max values which include all bits, 0xffffffffffffffff
 273 const jlong all_bits_jlong = ~jlong(0);
 274 
 275 //-------------------------------------------
 276 // Constant for jdouble
 277 const jlong min_jlongDouble = CONST64(0x0000000000000001);
 278 const jdouble min_jdouble = jdouble_cast(min_jlongDouble);
 279 const jlong max_jlongDouble = CONST64(0x7fefffffffffffff);
 280 const jdouble max_jdouble = jdouble_cast(max_jlongDouble);
 281 
 282 const size_t K                  = 1024;
 283 const size_t M                  = K*K;
 284 const size_t G                  = M*K;
 285 
 286 // Constants for converting from a base unit to milli-base units.  For
 287 // example from seconds to milliseconds and microseconds
 288 
 289 const int MILLIUNITS    = 1000;         // milli units per base unit
 290 const int MICROUNITS    = 1000000;      // micro units per base unit
 291 const int NANOUNITS     = 1000000000;   // nano units per base unit
 292 const int NANOUNITS_PER_MILLIUNIT = NANOUNITS / MILLIUNITS;
 293 
 294 const jlong NANOSECS_PER_SEC      = CONST64(1000000000);
 295 const jint  NANOSECS_PER_MILLISEC = 1000000;
 296 
 297 
 298 // Unit conversion functions
 299 // The caller is responsible for considering overflow.
 300 
 301 inline int64_t nanos_to_millis(int64_t nanos) {
 302   return nanos / NANOUNITS_PER_MILLIUNIT;
 303 }
 304 inline int64_t millis_to_nanos(int64_t millis) {
 305   return millis * NANOUNITS_PER_MILLIUNIT;
 306 }
 307 
 308 // Proper units routines try to maintain at least three significant digits.
 309 // In worst case, it would print five significant digits with lower prefix.
 310 // G is close to MAX_SIZE on 32-bit platforms, so its product can easily overflow,
 311 // and therefore we need to be careful.
 312 
 313 inline const char* proper_unit_for_byte_size(size_t s) {
 314 #ifdef _LP64
 315   if (s >= 100*G) {
 316     return "G";
 317   }
 318 #endif
 319   if (s >= 100*M) {
 320     return "M";
 321   } else if (s >= 100*K) {
 322     return "K";
 323   } else {
 324     return "B";
 325   }
 326 }
 327 
 328 template <class T>
 329 inline T byte_size_in_proper_unit(T s) {
 330 #ifdef _LP64
 331   if (s >= 100*G) {
 332     return (T)(s/G);
 333   }
 334 #endif
 335   if (s >= 100*M) {
 336     return (T)(s/M);
 337   } else if (s >= 100*K) {
 338     return (T)(s/K);
 339   } else {
 340     return s;
 341   }
 342 }
 343 
 344 #define PROPERFMT             "%zu%s"
 345 #define PROPERFMTARGS(s)      byte_size_in_proper_unit(s), proper_unit_for_byte_size(s)
 346 
 347 // Printing a range, with start and bytes given
 348 #define RANGEFMT              "[" PTR_FORMAT " - " PTR_FORMAT "), (%zu bytes)"
 349 #define RANGEFMTARGS(p1, size) p2i(p1), p2i(p1 + size), size
 350 
 351 // Printing a range, with start and end given
 352 #define RANGE2FMT             "[" PTR_FORMAT " - " PTR_FORMAT "), (%zu bytes)"
 353 #define RANGE2FMTARGS(p1, p2) p2i(p1), p2i(p2), ((uintptr_t)p2 - (uintptr_t)p1)
 354 
 355 inline const char* exact_unit_for_byte_size(size_t s) {
 356 #ifdef _LP64
 357   if (s >= G && (s % G) == 0) {
 358     return "G";
 359   }
 360 #endif
 361   if (s >= M && (s % M) == 0) {
 362     return "M";
 363   }
 364   if (s >= K && (s % K) == 0) {
 365     return "K";
 366   }
 367   return "B";
 368 }
 369 
 370 inline size_t byte_size_in_exact_unit(size_t s) {
 371 #ifdef _LP64
 372   if (s >= G && (s % G) == 0) {
 373     return s / G;
 374   }
 375 #endif
 376   if (s >= M && (s % M) == 0) {
 377     return s / M;
 378   }
 379   if (s >= K && (s % K) == 0) {
 380     return s / K;
 381   }
 382   return s;
 383 }
 384 
 385 #define EXACTFMT            "%zu%s"
 386 #define EXACTFMTARGS(s)     byte_size_in_exact_unit(s), exact_unit_for_byte_size(s)
 387 
 388 // Memory size transition formatting.
 389 
 390 #define HEAP_CHANGE_FORMAT "%s: %zuK(%zuK)->%zuK(%zuK)"
 391 
 392 #define HEAP_CHANGE_FORMAT_ARGS(_name_, _prev_used_, _prev_capacity_, _used_, _capacity_) \
 393   (_name_), (_prev_used_) / K, (_prev_capacity_) / K, (_used_) / K, (_capacity_) / K
 394 
 395 //----------------------------------------------------------------------------------------------------
 396 // VM type definitions
 397 
 398 // intx and uintx are the 'extended' int and 'extended' unsigned int types;
 399 // they are 32bit wide on a 32-bit platform, and 64bit wide on a 64bit platform.
 400 
 401 typedef intptr_t  intx;
 402 typedef uintptr_t uintx;
 403 
 404 const intx  min_intx  = (intx)1 << (sizeof(intx)*BitsPerByte-1);
 405 const intx  max_intx  = (uintx)min_intx - 1;
 406 const uintx max_uintx = (uintx)-1;
 407 
 408 // Table of values:
 409 //      sizeof intx         4               8
 410 // min_intx             0x80000000      0x8000000000000000
 411 // max_intx             0x7FFFFFFF      0x7FFFFFFFFFFFFFFF
 412 // max_uintx            0xFFFFFFFF      0xFFFFFFFFFFFFFFFF
 413 
 414 typedef unsigned int uint;   NEEDS_CLEANUP
 415 
 416 //----------------------------------------------------------------------------------------------------
 417 // Java type definitions
 418 
 419 // All kinds of 'plain' byte addresses
 420 typedef   signed char s_char;
 421 typedef unsigned char u_char;
 422 typedef u_char*       address;
 423 typedef const u_char* const_address;
 424 
 425 // Pointer subtraction.
 426 // The idea here is to avoid ptrdiff_t, which is signed and so doesn't have
 427 // the range we might need to find differences from one end of the heap
 428 // to the other.
 429 // A typical use might be:
 430 //     if (pointer_delta(end(), top()) >= size) {
 431 //       // enough room for an object of size
 432 //       ...
 433 // and then additions like
 434 //       ... top() + size ...
 435 // are safe because we know that top() is at least size below end().
 436 inline size_t pointer_delta(const volatile void* left,
 437                             const volatile void* right,
 438                             size_t element_size) {
 439   assert(left >= right, "avoid underflow - left: " PTR_FORMAT " right: " PTR_FORMAT, p2i(left), p2i(right));
 440   return (((uintptr_t) left) - ((uintptr_t) right)) / element_size;
 441 }
 442 
 443 // A version specialized for HeapWord*'s.
 444 inline size_t pointer_delta(const HeapWord* left, const HeapWord* right) {
 445   return pointer_delta(left, right, sizeof(HeapWord));
 446 }
 447 // A version specialized for MetaWord*'s.
 448 inline size_t pointer_delta(const MetaWord* left, const MetaWord* right) {
 449   return pointer_delta(left, right, sizeof(MetaWord));
 450 }
 451 
 452 // pointer_delta_as_int is called to do pointer subtraction for nearby pointers that
 453 // returns a non-negative int, usually used as a size of a code buffer range.
 454 // This scales to sizeof(T).
 455 template <typename T>
 456 inline int pointer_delta_as_int(const volatile T* left, const volatile T* right) {
 457   size_t delta = pointer_delta(left, right, sizeof(T));
 458   assert(delta <= size_t(INT_MAX), "pointer delta out of range: %zu", delta);
 459   return static_cast<int>(delta);
 460 }
 461 
 462 //
 463 // ANSI C++ does not allow casting from one pointer type to a function pointer
 464 // directly without at best a warning. This macro accomplishes it silently
 465 // In every case that is present at this point the value be cast is a pointer
 466 // to a C linkage function. In some case the type used for the cast reflects
 467 // that linkage and a picky compiler would not complain. In other cases because
 468 // there is no convenient place to place a typedef with extern C linkage (i.e
 469 // a platform dependent header file) it doesn't. At this point no compiler seems
 470 // picky enough to catch these instances (which are few). It is possible that
 471 // using templates could fix these for all cases. This use of templates is likely
 472 // so far from the middle of the road that it is likely to be problematic in
 473 // many C++ compilers.
 474 //
 475 #define CAST_TO_FN_PTR(func_type, value) (reinterpret_cast<func_type>(value))
 476 #define CAST_FROM_FN_PTR(new_type, func_ptr) ((new_type)((uintptr_t)(func_ptr)))
 477 
 478 // Need the correct linkage to call qsort without warnings
 479 extern "C" {
 480   typedef int (*_sort_Fn)(const void *, const void *);
 481 }
 482 
 483 // Additional Java basic types
 484 
 485 typedef uint8_t  jubyte;
 486 typedef uint16_t jushort;
 487 typedef uint32_t juint;
 488 typedef uint64_t julong;
 489 
 490 // Unsigned byte types for os and stream.hpp
 491 
 492 // Unsigned one, two, four and eight byte quantities used for describing
 493 // the .class file format. See JVM book chapter 4.
 494 
 495 typedef jubyte  u1;
 496 typedef jushort u2;
 497 typedef juint   u4;
 498 typedef julong  u8;
 499 
 500 const jubyte  max_jubyte  = (jubyte)-1;  // 0xFF       largest jubyte
 501 const jushort max_jushort = (jushort)-1; // 0xFFFF     largest jushort
 502 const juint   max_juint   = (juint)-1;   // 0xFFFFFFFF largest juint
 503 const julong  max_julong  = (julong)-1;  // 0xFF....FF largest julong
 504 
 505 typedef jbyte  s1;
 506 typedef jshort s2;
 507 typedef jint   s4;
 508 typedef jlong  s8;
 509 
 510 const jbyte min_jbyte = -(1 << 7);       // smallest jbyte
 511 const jbyte max_jbyte = (1 << 7) - 1;    // largest jbyte
 512 const jshort min_jshort = -(1 << 15);    // smallest jshort
 513 const jshort max_jshort = (1 << 15) - 1; // largest jshort
 514 
 515 const jint min_jint = (jint)1 << (sizeof(jint)*BitsPerByte-1); // 0x80000000 == smallest jint
 516 const jint max_jint = (juint)min_jint - 1;                     // 0x7FFFFFFF == largest jint
 517 
 518 const jint min_jintFloat = (jint)(0x00000001);
 519 const jfloat min_jfloat = jfloat_cast(min_jintFloat);
 520 const jint max_jintFloat = (jint)(0x7f7fffff);
 521 const jfloat max_jfloat = jfloat_cast(max_jintFloat);
 522 
 523 const jshort max_jfloat16 = 31743;
 524 const jshort min_jfloat16 = 1;
 525 const jshort one_jfloat16 = 15360;
 526 const jshort pos_inf_jfloat16 = 31744;
 527 const jshort neg_inf_jfloat16 = -1024;
 528 // A named constant for the integral representation of a Java null.
 529 const intptr_t NULL_WORD = 0;
 530 
 531 //----------------------------------------------------------------------------------------------------
 532 // JVM spec restrictions
 533 
 534 const int max_method_code_size = 64*K - 1;  // JVM spec, 2nd ed. section 4.8.1 (p.134)
 535 
 536 //----------------------------------------------------------------------------------------------------
 537 // old CDS options
 538 extern bool RequireSharedSpaces;
 539 extern "C" {
 540 // Make sure UseSharedSpaces is accessible to the serviceability agent.
 541 extern JNIEXPORT jboolean UseSharedSpaces;
 542 }
 543 
 544 //----------------------------------------------------------------------------------------------------
 545 // Object alignment, in units of HeapWords.
 546 //
 547 // Minimum is max(BytesPerLong, BytesPerDouble, BytesPerOop) / HeapWordSize, so jlong, jdouble and
 548 // reference fields can be naturally aligned.
 549 
 550 extern int MinObjAlignment;
 551 extern int MinObjAlignmentInBytes;
 552 extern int MinObjAlignmentInBytesMask;
 553 
 554 extern int LogMinObjAlignment;
 555 extern int LogMinObjAlignmentInBytes;
 556 
 557 // Maximal size of heap where unscaled compression can be used. Also upper bound
 558 // for heap placement: 4GB.
 559 const  uint64_t UnscaledOopHeapMax = (uint64_t(max_juint) + 1);
 560 // Maximal size of heap where compressed oops can be used. Also upper bound for heap
 561 // placement for zero based compression algorithm: UnscaledOopHeapMax << LogMinObjAlignmentInBytes.
 562 extern uint64_t OopEncodingHeapMax;
 563 
 564 // Machine dependent stuff
 565 
 566 #include CPU_HEADER(globalDefinitions)
 567 
 568 // The maximum size of the code cache.  Can be overridden by targets.
 569 #ifndef CODE_CACHE_SIZE_LIMIT
 570 #define CODE_CACHE_SIZE_LIMIT (2*G)
 571 #endif
 572 
 573 // Allow targets to reduce the default size of the code cache.
 574 #define CODE_CACHE_DEFAULT_LIMIT CODE_CACHE_SIZE_LIMIT
 575 
 576 // To assure the IRIW property on processors that are not multiple copy
 577 // atomic, sync instructions must be issued between volatile reads to
 578 // assure their ordering, instead of after volatile stores.
 579 // (See "A Tutorial Introduction to the ARM and POWER Relaxed Memory Models"
 580 // by Luc Maranget, Susmit Sarkar and Peter Sewell, INRIA/Cambridge)
 581 #ifdef CPU_MULTI_COPY_ATOMIC
 582 // Not needed.
 583 const bool support_IRIW_for_not_multiple_copy_atomic_cpu = false;
 584 #else
 585 // From all non-multi-copy-atomic architectures, only PPC64 supports IRIW at the moment.
 586 // Final decision is subject to JEP 188: Java Memory Model Update.
 587 const bool support_IRIW_for_not_multiple_copy_atomic_cpu = PPC64_ONLY(true) NOT_PPC64(false);
 588 #endif
 589 
 590 // The expected size in bytes of a cache line.
 591 #ifndef DEFAULT_CACHE_LINE_SIZE
 592 #error "Platform should define DEFAULT_CACHE_LINE_SIZE"
 593 #endif
 594 
 595 // The default padding size for data structures to avoid false sharing.
 596 #ifndef DEFAULT_PADDING_SIZE
 597 #error "Platform should define DEFAULT_PADDING_SIZE"
 598 #endif
 599 
 600 
 601 //----------------------------------------------------------------------------------------------------
 602 // Prototyping
 603 // "Code Missing Here" macro, un-define when integrating back from prototyping stage and break
 604 // compilation on purpose (i.e. "forget me not")
 605 #define PROTOTYPE
 606 #ifdef PROTOTYPE
 607 #define CMH(m)
 608 #endif
 609 
 610 //----------------------------------------------------------------------------------------------------
 611 // Miscellaneous
 612 
 613 // 6302670 Eliminate Hotspot __fabsf dependency
 614 // All fabs() callers should call this function instead, which will implicitly
 615 // convert the operand to double, avoiding a dependency on __fabsf which
 616 // doesn't exist in early versions of Solaris 8.
 617 inline double fabsd(double value) {
 618   return fabs(value);
 619 }
 620 
 621 // Returns numerator/denominator as percentage value from 0 to 100. If denominator
 622 // is zero, return 0.0.
 623 template<typename T>
 624 inline double percent_of(T numerator, T denominator) {
 625   return denominator != 0 ? (double)numerator / (double)denominator * 100.0 : 0.0;
 626 }
 627 
 628 //----------------------------------------------------------------------------------------------------
 629 // Special casts
 630 // Cast floats into same-size integers and vice-versa w/o changing bit-pattern
 631 typedef union {
 632   jfloat f;
 633   jint i;
 634 } FloatIntConv;
 635 
 636 typedef union {
 637   jdouble d;
 638   jlong l;
 639   julong ul;
 640 } DoubleLongConv;
 641 
 642 inline jint    jint_cast    (jfloat  x)  { return ((FloatIntConv*)&x)->i; }
 643 inline jfloat  jfloat_cast  (jint    x)  { return ((FloatIntConv*)&x)->f; }
 644 
 645 inline jlong   jlong_cast   (jdouble x)  { return ((DoubleLongConv*)&x)->l;  }
 646 inline julong  julong_cast  (jdouble x)  { return ((DoubleLongConv*)&x)->ul; }
 647 inline jdouble jdouble_cast (jlong   x)  { return ((DoubleLongConv*)&x)->d;  }
 648 
 649 inline jint low (jlong value)                    { return jint(value); }
 650 inline jint high(jlong value)                    { return jint(value >> 32); }
 651 
 652 // the fancy casts are a hopefully portable way
 653 // to do unsigned 32 to 64 bit type conversion
 654 inline void set_low (jlong* value, jint low )    { *value &= (jlong)0xffffffff << 32;
 655                                                    *value |= (jlong)(julong)(juint)low; }
 656 
 657 inline void set_high(jlong* value, jint high)    { *value &= (jlong)(julong)(juint)0xffffffff;
 658                                                    *value |= (jlong)high       << 32; }
 659 
 660 inline jlong jlong_from(jint h, jint l) {
 661   jlong result = 0; // initialization to avoid warning
 662   set_high(&result, h);
 663   set_low(&result,  l);
 664   return result;
 665 }
 666 
 667 union jlong_accessor {
 668   jint  words[2];
 669   jlong long_value;
 670 };
 671 
 672 void basic_types_init(); // cannot define here; uses assert
 673 
 674 
 675 // NOTE: replicated in SA in vm/agent/sun/jvm/hotspot/runtime/BasicType.java
 676 enum BasicType : u1 {
 677 // The values T_BOOLEAN..T_LONG (4..11) are derived from the JVMS.
 678   T_BOOLEAN     = JVM_T_BOOLEAN,
 679   T_CHAR        = JVM_T_CHAR,
 680   T_FLOAT       = JVM_T_FLOAT,
 681   T_DOUBLE      = JVM_T_DOUBLE,
 682   T_BYTE        = JVM_T_BYTE,
 683   T_SHORT       = JVM_T_SHORT,
 684   T_INT         = JVM_T_INT,
 685   T_LONG        = JVM_T_LONG,
 686   // The remaining values are not part of any standard.
 687   // T_OBJECT and T_VOID denote two more semantic choices
 688   // for method return values.
 689   // T_OBJECT and T_ARRAY describe signature syntax.
 690   // T_ADDRESS, T_METADATA, T_NARROWOOP, T_NARROWKLASS describe
 691   // internal references within the JVM as if they were Java
 692   // types in their own right.
 693   T_OBJECT      = 12,
 694   T_ARRAY       = 13,
 695   T_FLAT_ELEMENT = 14, // Not a true BasicType, only use in headers of flat arrays
 696   T_VOID        = 15,
 697   T_ADDRESS     = 16,
 698   T_NARROWOOP   = 17,
 699   T_METADATA    = 18,
 700   T_NARROWKLASS = 19,
 701   T_CONFLICT    = 20, // for stack value type with conflicting contents
 702   T_ILLEGAL     = 99
 703 };
 704 
 705 #define SIGNATURE_TYPES_DO(F, N)                \
 706     F(JVM_SIGNATURE_BOOLEAN, T_BOOLEAN, N)      \
 707     F(JVM_SIGNATURE_CHAR,    T_CHAR,    N)      \
 708     F(JVM_SIGNATURE_FLOAT,   T_FLOAT,   N)      \
 709     F(JVM_SIGNATURE_DOUBLE,  T_DOUBLE,  N)      \
 710     F(JVM_SIGNATURE_BYTE,    T_BYTE,    N)      \
 711     F(JVM_SIGNATURE_SHORT,   T_SHORT,   N)      \
 712     F(JVM_SIGNATURE_INT,     T_INT,     N)      \
 713     F(JVM_SIGNATURE_LONG,    T_LONG,    N)      \
 714     F(JVM_SIGNATURE_CLASS,   T_OBJECT,  N)      \
 715     F(JVM_SIGNATURE_ARRAY,   T_ARRAY,   N)      \
 716     F(JVM_SIGNATURE_FLAT_ELEMENT, T_FLAT_ELEMENT, N) \
 717     F(JVM_SIGNATURE_VOID,    T_VOID,    N)      \
 718     /*end*/
 719 
 720 inline bool is_java_type(BasicType t) {
 721   return T_BOOLEAN <= t && t <= T_VOID;
 722 }
 723 
 724 inline bool is_java_primitive(BasicType t) {
 725   return T_BOOLEAN <= t && t <= T_LONG;
 726 }
 727 
 728 inline bool is_subword_type(BasicType t) {
 729   // these guys are processed exactly like T_INT in calling sequences:
 730   return (t == T_BOOLEAN || t == T_CHAR || t == T_BYTE || t == T_SHORT);
 731 }
 732 
 733 inline bool is_signed_subword_type(BasicType t) {
 734   return (t == T_BYTE || t == T_SHORT);
 735 }
 736 
 737 inline bool is_unsigned_subword_type(BasicType t) {
 738   return (t == T_BOOLEAN || t == T_CHAR);
 739 }
 740 
 741 inline bool is_double_word_type(BasicType t) {
 742   return (t == T_DOUBLE || t == T_LONG);
 743 }
 744 
 745 inline bool is_reference_type(BasicType t, bool include_narrow_oop = false) {
 746   return (t == T_OBJECT || t == T_ARRAY || t == T_FLAT_ELEMENT || (include_narrow_oop && t == T_NARROWOOP));
 747 }
 748 
 749 inline bool is_integral_type(BasicType t) {
 750   return is_subword_type(t) || t == T_INT || t == T_LONG;
 751 }
 752 
 753 inline bool is_non_subword_integral_type(BasicType t) {
 754   return t == T_INT || t == T_LONG;
 755 }
 756 
 757 inline bool is_floating_point_type(BasicType t) {
 758   return (t == T_FLOAT || t == T_DOUBLE);
 759 }
 760 
 761 extern char type2char_tab[T_CONFLICT+1];     // Map a BasicType to a jchar
 762 inline char type2char(BasicType t) { return (uint)t < T_CONFLICT+1 ? type2char_tab[t] : 0; }
 763 extern int type2size[T_CONFLICT+1];         // Map BasicType to result stack elements
 764 extern const char* type2name_tab[T_CONFLICT+1];     // Map a BasicType to a char*
 765 extern BasicType name2type(const char* name);
 766 
 767 const char* type2name(BasicType t);
 768 
 769 inline jlong max_signed_integer(BasicType bt) {
 770   if (bt == T_INT) {
 771     return max_jint;
 772   }
 773   assert(bt == T_LONG, "unsupported");
 774   return max_jlong;
 775 }
 776 
 777 inline jlong min_signed_integer(BasicType bt) {
 778   if (bt == T_INT) {
 779     return min_jint;
 780   }
 781   assert(bt == T_LONG, "unsupported");
 782   return min_jlong;
 783 }
 784 
 785 inline uint bits_per_java_integer(BasicType bt) {
 786   if (bt == T_INT) {
 787     return BitsPerJavaInteger;
 788   }
 789   assert(bt == T_LONG, "int or long only");
 790   return BitsPerJavaLong;
 791 }
 792 
 793 // Auxiliary math routines
 794 // least common multiple
 795 extern size_t lcm(size_t a, size_t b);
 796 
 797 
 798 // NOTE: replicated in SA in vm/agent/sun/jvm/hotspot/runtime/BasicType.java
 799 enum BasicTypeSize {
 800   T_BOOLEAN_size     = 1,
 801   T_CHAR_size        = 1,
 802   T_FLOAT_size       = 1,
 803   T_DOUBLE_size      = 2,
 804   T_BYTE_size        = 1,
 805   T_SHORT_size       = 1,
 806   T_INT_size         = 1,
 807   T_LONG_size        = 2,
 808   T_OBJECT_size      = 1,
 809   T_ARRAY_size       = 1,
 810   T_NARROWOOP_size   = 1,
 811   T_NARROWKLASS_size = 1,
 812   T_VOID_size        = 0,
 813   T_FLAT_ELEMENT_size = 1
 814 };
 815 
 816 // this works on valid parameter types but not T_VOID, T_CONFLICT, etc.
 817 inline int parameter_type_word_count(BasicType t) {
 818   if (is_double_word_type(t))  return 2;
 819   assert(is_java_primitive(t) || is_reference_type(t), "no goofy types here please");
 820   assert(type2size[t] == 1, "must be");
 821   return 1;
 822 }
 823 
 824 // maps a BasicType to its instance field storage type:
 825 // all sub-word integral types are widened to T_INT
 826 extern BasicType type2field[T_CONFLICT+1];
 827 extern BasicType type2wfield[T_CONFLICT+1];
 828 
 829 
 830 // size in bytes
 831 enum ArrayElementSize {
 832   T_BOOLEAN_aelem_bytes     = 1,
 833   T_CHAR_aelem_bytes        = 2,
 834   T_FLOAT_aelem_bytes       = 4,
 835   T_DOUBLE_aelem_bytes      = 8,
 836   T_BYTE_aelem_bytes        = 1,
 837   T_SHORT_aelem_bytes       = 2,
 838   T_INT_aelem_bytes         = 4,
 839   T_LONG_aelem_bytes        = 8,
 840 #ifdef _LP64
 841   T_OBJECT_aelem_bytes      = 8,
 842   T_ARRAY_aelem_bytes       = 8,
 843   T_FLAT_ELEMENT_aelem_bytes = 8,
 844 #else
 845   T_OBJECT_aelem_bytes      = 4,
 846   T_ARRAY_aelem_bytes       = 4,
 847   T_FLAT_ELEMENT_aelem_bytes = 4,
 848 #endif
 849   T_NARROWOOP_aelem_bytes   = 4,
 850   T_NARROWKLASS_aelem_bytes = 4,
 851   T_VOID_aelem_bytes        = 0
 852 };
 853 
 854 extern int _type2aelembytes[T_CONFLICT+1]; // maps a BasicType to nof bytes used by its array element
 855 #ifdef ASSERT
 856 extern int type2aelembytes(BasicType t, bool allow_address = false); // asserts
 857 #else
 858 inline int type2aelembytes(BasicType t, bool allow_address = false) { return _type2aelembytes[t]; }
 859 #endif
 860 
 861 inline bool same_type_or_subword_size(BasicType t1, BasicType t2) {
 862   return (t1 == t2) || (is_subword_type(t1) && type2aelembytes(t1) == type2aelembytes(t2));
 863 }
 864 
 865 // JavaValue serves as a container for arbitrary Java values.
 866 
 867 class JavaValue {
 868 
 869  public:
 870   typedef union JavaCallValue {
 871     jfloat   f;
 872     jdouble  d;
 873     jint     i;
 874     jlong    l;
 875     jobject  h;
 876     oopDesc* o;
 877   } JavaCallValue;
 878 
 879  private:
 880   BasicType _type;
 881   JavaCallValue _value;
 882 
 883  public:
 884   JavaValue(BasicType t = T_ILLEGAL) { _type = t; }
 885 
 886   JavaValue(jfloat value) {
 887     _type    = T_FLOAT;
 888     _value.f = value;
 889   }
 890 
 891   JavaValue(jdouble value) {
 892     _type    = T_DOUBLE;
 893     _value.d = value;
 894   }
 895 
 896  jfloat get_jfloat() const { return _value.f; }
 897  jdouble get_jdouble() const { return _value.d; }
 898  jint get_jint() const { return _value.i; }
 899  jlong get_jlong() const { return _value.l; }
 900  jobject get_jobject() const { return _value.h; }
 901  oopDesc* get_oop() const { return _value.o; }
 902  JavaCallValue* get_value_addr() { return &_value; }
 903  BasicType get_type() const { return _type; }
 904 
 905  void set_jfloat(jfloat f) { _value.f = f;}
 906  void set_jdouble(jdouble d) { _value.d = d;}
 907  void set_jint(jint i) { _value.i = i;}
 908  void set_jshort(jshort i) { _value.i = i;}
 909  void set_jlong(jlong l) { _value.l = l;}
 910  void set_jobject(jobject h) { _value.h = h;}
 911  void set_oop(oopDesc* o) { _value.o = o;}
 912  void set_type(BasicType t) { _type = t; }
 913 
 914  jboolean get_jboolean() const { return (jboolean) (_value.i);}
 915  jbyte get_jbyte() const { return (jbyte) (_value.i);}
 916  jchar get_jchar() const { return (jchar) (_value.i);}
 917  jshort get_jshort() const { return (jshort) (_value.i);}
 918 
 919 };
 920 
 921 
 922 // TosState describes the top-of-stack state before and after the execution of
 923 // a bytecode or method. The top-of-stack value may be cached in one or more CPU
 924 // registers. The TosState corresponds to the 'machine representation' of this cached
 925 // value. There's 4 states corresponding to the JAVA types int, long, float & double
 926 // as well as a 5th state in case the top-of-stack value is actually on the top
 927 // of stack (in memory) and thus not cached. The atos state corresponds to the itos
 928 // state when it comes to machine representation but is used separately for (oop)
 929 // type specific operations (e.g. verification code).
 930 
 931 enum TosState {         // describes the tos cache contents
 932   btos = 0,             // byte, bool tos cached
 933   ztos = 1,             // byte, bool tos cached
 934   ctos = 2,             // char tos cached
 935   stos = 3,             // short tos cached
 936   itos = 4,             // int tos cached
 937   ltos = 5,             // long tos cached
 938   ftos = 6,             // float tos cached
 939   dtos = 7,             // double tos cached
 940   atos = 8,             // object cached
 941   vtos = 9,             // tos not cached,
 942   number_of_states,
 943   ilgl                  // illegal state: should not occur
 944 };
 945 
 946 
 947 inline TosState as_TosState(BasicType type) {
 948   switch (type) {
 949     case T_BYTE   : return btos;
 950     case T_BOOLEAN: return ztos;
 951     case T_CHAR   : return ctos;
 952     case T_SHORT  : return stos;
 953     case T_INT    : return itos;
 954     case T_LONG   : return ltos;
 955     case T_FLOAT  : return ftos;
 956     case T_DOUBLE : return dtos;
 957     case T_VOID   : return vtos;
 958     case T_ARRAY  :   // fall through
 959     case T_OBJECT : return atos;
 960     default       : return ilgl;
 961   }
 962 }
 963 
 964 inline BasicType as_BasicType(TosState state) {
 965   switch (state) {
 966     case btos : return T_BYTE;
 967     case ztos : return T_BOOLEAN;
 968     case ctos : return T_CHAR;
 969     case stos : return T_SHORT;
 970     case itos : return T_INT;
 971     case ltos : return T_LONG;
 972     case ftos : return T_FLOAT;
 973     case dtos : return T_DOUBLE;
 974     case atos : return T_OBJECT;
 975     case vtos : return T_VOID;
 976     default   : return T_ILLEGAL;
 977   }
 978 }
 979 
 980 
 981 // Helper function to convert BasicType info into TosState
 982 // Note: Cannot define here as it uses global constant at the time being.
 983 TosState as_TosState(BasicType type);
 984 
 985 
 986 // JavaThreadState keeps track of which part of the code a thread is executing in. This
 987 // information is needed by the safepoint code.
 988 //
 989 // There are 4 essential states:
 990 //
 991 //  _thread_new         : Just started, but not executed init. code yet (most likely still in OS init code)
 992 //  _thread_in_native   : In native code. This is a safepoint region, since all oops will be in jobject handles
 993 //  _thread_in_vm       : Executing in the vm
 994 //  _thread_in_Java     : Executing either interpreted or compiled Java code (or could be in a stub)
 995 //
 996 // Each state has an associated xxxx_trans state, which is an intermediate state used when a thread is in
 997 // a transition from one state to another. These extra states makes it possible for the safepoint code to
 998 // handle certain thread_states without having to suspend the thread - making the safepoint code faster.
 999 //
1000 // Given a state, the xxxx_trans state can always be found by adding 1.
1001 //
1002 enum JavaThreadState {
1003   _thread_uninitialized     =  0, // should never happen (missing initialization)
1004   _thread_new               =  2, // just starting up, i.e., in process of being initialized
1005   _thread_new_trans         =  3, // corresponding transition state (not used, included for completeness)
1006   _thread_in_native         =  4, // running in native code
1007   _thread_in_native_trans   =  5, // corresponding transition state
1008   _thread_in_vm             =  6, // running in VM
1009   _thread_in_vm_trans       =  7, // corresponding transition state
1010   _thread_in_Java           =  8, // running in Java or in stub code
1011   _thread_in_Java_trans     =  9, // corresponding transition state (not used, included for completeness)
1012   _thread_blocked           = 10, // blocked in vm
1013   _thread_blocked_trans     = 11, // corresponding transition state
1014   _thread_max_state         = 12  // maximum thread state+1 - used for statistics allocation
1015 };
1016 
1017 enum LockingMode {
1018   // Use only heavy monitors for locking
1019   LM_MONITOR     = 0,
1020   // Legacy stack-locking, with monitors as 2nd tier
1021   LM_LEGACY      = 1,
1022   // New lightweight locking, with monitors as 2nd tier
1023   LM_LIGHTWEIGHT = 2
1024 };
1025 
1026 //----------------------------------------------------------------------------------------------------
1027 // Special constants for debugging
1028 
1029 const jint     badInt             = -3;                     // generic "bad int" value
1030 const intptr_t badAddressVal      = -2;                     // generic "bad address" value
1031 const intptr_t badOopVal          = -1;                     // generic "bad oop" value
1032 const intptr_t badHeapOopVal      = (intptr_t) CONST64(0x2BAD4B0BBAADBABE); // value used to zap heap after GC
1033 const int      badStackSegVal     = 0xCA;                   // value used to zap stack segments
1034 const int      badHandleValue     = 0xBC;                   // value used to zap vm handle area
1035 const int      badResourceValue   = 0xAB;                   // value used to zap resource area
1036 const int      freeBlockPad       = 0xBA;                   // value used to pad freed blocks.
1037 const int      uninitBlockPad     = 0xF1;                   // value used to zap newly malloc'd blocks.
1038 const juint    uninitMetaWordVal  = 0xf7f7f7f7;             // value used to zap newly allocated metachunk
1039 const jubyte   heapPaddingByteVal = 0xBD;                   // value used to zap object padding in the heap
1040 const juint    badHeapWordVal     = 0xBAADBABE;             // value used to zap heap after GC
1041 const int      badCodeHeapNewVal  = 0xCC;                   // value used to zap Code heap at allocation
1042 const int      badCodeHeapFreeVal = 0xDD;                   // value used to zap Code heap at deallocation
1043 const intptr_t badDispHeaderDeopt = 0xDE0BD000;             // value to fill unused displaced header during deoptimization
1044 const intptr_t badDispHeaderOSR   = 0xDEAD05A0;             // value to fill unused displaced header during OSR
1045 
1046 // (These must be implemented as #defines because C++ compilers are
1047 // not obligated to inline non-integral constants!)
1048 #define       badAddress        ((address)::badAddressVal)
1049 #define       badHeapWord       (::badHeapWordVal)
1050 
1051 // Default TaskQueue size is 16K (32-bit) or 128K (64-bit)
1052 const uint TASKQUEUE_SIZE = (NOT_LP64(1<<14) LP64_ONLY(1<<17));
1053 
1054 //----------------------------------------------------------------------------------------------------
1055 // Utility functions for bitfield manipulations
1056 
1057 const intptr_t AllBits    = ~0; // all bits set in a word
1058 const intptr_t NoBits     =  0; // no bits set in a word
1059 const jlong    NoLongBits =  0; // no bits set in a long
1060 const intptr_t OneBit     =  1; // only right_most bit set in a word
1061 
1062 // get a word with the n.th or the right-most or left-most n bits set
1063 // (note: #define used only so that they can be used in enum constant definitions)
1064 #define nth_bit(n)        (((n) >= BitsPerWord) ? 0 : (OneBit << (n)))
1065 #define right_n_bits(n)   (nth_bit(n) - 1)
1066 
1067 // bit-operations using a mask m
1068 inline void   set_bits    (intptr_t& x, intptr_t m) { x |= m; }
1069 inline void clear_bits    (intptr_t& x, intptr_t m) { x &= ~m; }
1070 inline intptr_t mask_bits      (intptr_t  x, intptr_t m) { return x & m; }
1071 inline jlong    mask_long_bits (jlong     x, jlong    m) { return x & m; }
1072 inline bool mask_bits_are_true (intptr_t flags, intptr_t mask) { return (flags & mask) == mask; }
1073 
1074 // bit-operations using the n.th bit
1075 inline void    set_nth_bit(intptr_t& x, int n) { set_bits  (x, nth_bit(n)); }
1076 inline void  clear_nth_bit(intptr_t& x, int n) { clear_bits(x, nth_bit(n)); }
1077 inline bool is_set_nth_bit(intptr_t  x, int n) { return mask_bits (x, nth_bit(n)) != NoBits; }
1078 
1079 // returns the bitfield of x starting at start_bit_no with length field_length (no sign-extension!)
1080 inline intptr_t bitfield(intptr_t x, int start_bit_no, int field_length) {
1081   return mask_bits(x >> start_bit_no, right_n_bits(field_length));
1082 }
1083 
1084 
1085 //----------------------------------------------------------------------------------------------------
1086 // Utility functions for integers
1087 
1088 // Avoid use of global min/max macros which may cause unwanted double
1089 // evaluation of arguments.
1090 #ifdef max
1091 #undef max
1092 #endif
1093 
1094 #ifdef min
1095 #undef min
1096 #endif
1097 
1098 // It is necessary to use templates here. Having normal overloaded
1099 // functions does not work because it is necessary to provide both 32-
1100 // and 64-bit overloaded functions, which does not work, and having
1101 // explicitly-typed versions of these routines (i.e., MAX2I, MAX2L)
1102 // will be even more error-prone than macros.
1103 template<class T> constexpr T MAX2(T a, T b)           { return (a > b) ? a : b; }
1104 template<class T> constexpr T MIN2(T a, T b)           { return (a < b) ? a : b; }
1105 template<class T> constexpr T MAX3(T a, T b, T c)      { return MAX2(MAX2(a, b), c); }
1106 template<class T> constexpr T MIN3(T a, T b, T c)      { return MIN2(MIN2(a, b), c); }
1107 template<class T> constexpr T MAX4(T a, T b, T c, T d) { return MAX2(MAX3(a, b, c), d); }
1108 template<class T> constexpr T MIN4(T a, T b, T c, T d) { return MIN2(MIN3(a, b, c), d); }
1109 
1110 #define ABS(x) asserted_abs(x, __FILE__, __LINE__)
1111 
1112 template<class T> inline T asserted_abs(T x, const char* file, int line) {
1113   bool valid_arg = !(std::is_integral<T>::value && x == std::numeric_limits<T>::min());
1114 #ifdef ASSERT
1115   if (!valid_arg) {
1116     report_vm_error(file, line, "ABS: argument should not allow overflow");
1117   }
1118 #endif
1119   // Prevent exposure to UB by checking valid_arg here as well.
1120   return (x < 0 && valid_arg) ? -x : x;
1121 }
1122 
1123 // Return the given value clamped to the range [min ... max]
1124 template<typename T>
1125 inline T clamp(T value, T min, T max) {
1126   assert(min <= max, "must be");
1127   return MIN2(MAX2(value, min), max);
1128 }
1129 
1130 inline bool is_odd (intx x) { return x & 1;      }
1131 inline bool is_even(intx x) { return !is_odd(x); }
1132 
1133 // abs methods which cannot overflow and so are well-defined across
1134 // the entire domain of integer types.
1135 static inline unsigned int uabs(unsigned int n) {
1136   union {
1137     unsigned int result;
1138     int value;
1139   };
1140   result = n;
1141   if (value < 0) result = 0-result;
1142   return result;
1143 }
1144 static inline julong uabs(julong n) {
1145   union {
1146     julong result;
1147     jlong value;
1148   };
1149   result = n;
1150   if (value < 0) result = 0-result;
1151   return result;
1152 }
1153 static inline julong uabs(jlong n) { return uabs((julong)n); }
1154 static inline unsigned int uabs(int n) { return uabs((unsigned int)n); }
1155 
1156 // "to" should be greater than "from."
1157 inline size_t byte_size(void* from, void* to) {
1158   return pointer_delta(to, from, sizeof(char));
1159 }
1160 
1161 // Pack and extract shorts to/from ints:
1162 
1163 inline u2 extract_low_short_from_int(u4 x) {
1164   return u2(x & 0xffff);
1165 }
1166 
1167 inline u2 extract_high_short_from_int(u4 x) {
1168   return u2((x >> 16) & 0xffff);
1169 }
1170 
1171 inline int build_int_from_shorts( u2 low, u2 high ) {
1172   return ((int)((unsigned int)high << 16) | (unsigned int)low);
1173 }
1174 
1175 // swap a & b
1176 template<class T> static void swap(T& a, T& b) {
1177   T tmp = a;
1178   a = b;
1179   b = tmp;
1180 }
1181 
1182 // array_size_impl is a function that takes a reference to T[N] and
1183 // returns a reference to char[N].  It is not ODR-used, so not defined.
1184 template<typename T, size_t N> char (&array_size_impl(T (&)[N]))[N];
1185 
1186 #define ARRAY_SIZE(array) sizeof(array_size_impl(array))
1187 
1188 //----------------------------------------------------------------------------------------------------
1189 // Sum and product which can never overflow: they wrap, just like the
1190 // Java operations.  Note that we don't intend these to be used for
1191 // general-purpose arithmetic: their purpose is to emulate Java
1192 // operations.
1193 
1194 // The goal of this code to avoid undefined or implementation-defined
1195 // behavior.  The use of an lvalue to reference cast is explicitly
1196 // permitted by Lvalues and rvalues [basic.lval].  [Section 3.10 Para
1197 // 15 in C++03]
1198 #define JAVA_INTEGER_OP(OP, NAME, TYPE, UNSIGNED_TYPE)  \
1199 inline TYPE NAME (TYPE in1, TYPE in2) {                 \
1200   UNSIGNED_TYPE ures = static_cast<UNSIGNED_TYPE>(in1); \
1201   ures OP ## = static_cast<UNSIGNED_TYPE>(in2);         \
1202   return reinterpret_cast<TYPE&>(ures);                 \
1203 }
1204 
1205 JAVA_INTEGER_OP(+, java_add, jint, juint)
1206 JAVA_INTEGER_OP(-, java_subtract, jint, juint)
1207 JAVA_INTEGER_OP(*, java_multiply, jint, juint)
1208 JAVA_INTEGER_OP(+, java_add, jlong, julong)
1209 JAVA_INTEGER_OP(-, java_subtract, jlong, julong)
1210 JAVA_INTEGER_OP(*, java_multiply, jlong, julong)
1211 
1212 inline jint  java_negate(jint  v) { return java_subtract((jint) 0, v); }
1213 inline jlong java_negate(jlong v) { return java_subtract((jlong)0, v); }
1214 
1215 #undef JAVA_INTEGER_OP
1216 
1217 // Provide integer shift operations with Java semantics.  No overflow
1218 // issues - left shifts simply discard shifted out bits.  No undefined
1219 // behavior for large or negative shift quantities; instead the actual
1220 // shift distance is the argument modulo the lhs value's size in bits.
1221 // No undefined or implementation defined behavior for shifting negative
1222 // values; left shift discards bits, right shift sign extends.  We use
1223 // the same safe conversion technique as above for java_add and friends.
1224 #define JAVA_INTEGER_SHIFT_OP(OP, NAME, TYPE, XTYPE)    \
1225 inline TYPE NAME (TYPE lhs, jint rhs) {                 \
1226   const uint rhs_mask = (sizeof(TYPE) * 8) - 1;         \
1227   STATIC_ASSERT(rhs_mask == 31 || rhs_mask == 63);      \
1228   XTYPE xres = static_cast<XTYPE>(lhs);                 \
1229   xres OP ## = (rhs & rhs_mask);                        \
1230   return reinterpret_cast<TYPE&>(xres);                 \
1231 }
1232 
1233 JAVA_INTEGER_SHIFT_OP(<<, java_shift_left, jint, juint)
1234 JAVA_INTEGER_SHIFT_OP(<<, java_shift_left, jlong, julong)
1235 
1236 // For signed shift right, assume C++ implementation >> sign extends.
1237 //
1238 // C++14 5.8/3: In the description of "E1 >> E2" it says "If E1 has a signed type
1239 // and a negative value, the resulting value is implementation-defined."
1240 //
1241 // However, C++20 7.6.7/3 further defines integral arithmetic, as part of
1242 // requiring two's-complement behavior.
1243 // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0907r3.html
1244 // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1236r1.html
1245 // The corresponding C++20 text is "Right-shift on signed integral types is an
1246 // arithmetic right shift, which performs sign-extension."
1247 //
1248 // As discussed in the two's complement proposal, all known modern C++ compilers
1249 // already behave that way. And it is unlikely any would go off and do something
1250 // different now, with C++20 tightening things up.
1251 JAVA_INTEGER_SHIFT_OP(>>, java_shift_right, jint, jint)
1252 JAVA_INTEGER_SHIFT_OP(>>, java_shift_right, jlong, jlong)
1253 // For >>> use C++ unsigned >>.
1254 JAVA_INTEGER_SHIFT_OP(>>, java_shift_right_unsigned, jint, juint)
1255 JAVA_INTEGER_SHIFT_OP(>>, java_shift_right_unsigned, jlong, julong)
1256 
1257 #undef JAVA_INTEGER_SHIFT_OP
1258 
1259 //----------------------------------------------------------------------------------------------------
1260 // The goal of this code is to provide saturating operations for int/uint.
1261 // Checks overflow conditions and saturates the result to min_jint/max_jint.
1262 #define SATURATED_INTEGER_OP(OP, NAME, TYPE1, TYPE2) \
1263 inline int NAME (TYPE1 in1, TYPE2 in2) {             \
1264   jlong res = static_cast<jlong>(in1);               \
1265   res OP ## = static_cast<jlong>(in2);               \
1266   if (res > max_jint) {                              \
1267     res = max_jint;                                  \
1268   } else if (res < min_jint) {                       \
1269     res = min_jint;                                  \
1270   }                                                  \
1271   return static_cast<int>(res);                      \
1272 }
1273 
1274 SATURATED_INTEGER_OP(+, saturated_add, int, int)
1275 SATURATED_INTEGER_OP(+, saturated_add, int, uint)
1276 SATURATED_INTEGER_OP(+, saturated_add, uint, int)
1277 SATURATED_INTEGER_OP(+, saturated_add, uint, uint)
1278 
1279 #undef SATURATED_INTEGER_OP
1280 
1281 // Taken from rom section 8-2 of Henry S. Warren, Jr., Hacker's Delight (2nd ed.) (Addison Wesley, 2013), 173-174.
1282 inline uint64_t multiply_high_unsigned(const uint64_t x, const uint64_t y) {
1283   const uint64_t x1 = x >> 32u;
1284   const uint64_t x2 = x & 0xFFFFFFFF;
1285   const uint64_t y1 = y >> 32u;
1286   const uint64_t y2 = y & 0xFFFFFFFF;
1287   const uint64_t z2 = x2 * y2;
1288   const uint64_t t = x1 * y2 + (z2 >> 32u);
1289   uint64_t z1 = t & 0xFFFFFFFF;
1290   const uint64_t z0 = t >> 32u;
1291   z1 += x2 * y1;
1292 
1293   return x1 * y1 + z0 + (z1 >> 32u);
1294 }
1295 
1296 // Taken from java.lang.Math::multiplyHigh which uses the technique from section 8-2 of Henry S. Warren, Jr.,
1297 // Hacker's Delight (2nd ed.) (Addison Wesley, 2013), 173-174 but adapted for signed longs.
1298 inline int64_t multiply_high_signed(const int64_t x, const int64_t y) {
1299   const jlong x1 = java_shift_right((jlong)x, 32);
1300   const jlong x2 = x & 0xFFFFFFFF;
1301   const jlong y1 = java_shift_right((jlong)y, 32);
1302   const jlong y2 = y & 0xFFFFFFFF;
1303 
1304   const uint64_t z2 = (uint64_t)x2 * y2;
1305   const int64_t t = x1 * y2 + (z2 >> 32u); // Unsigned shift
1306   int64_t z1 = t & 0xFFFFFFFF;
1307   const int64_t z0 = java_shift_right((jlong)t, 32);
1308   z1 += x2 * y1;
1309 
1310   return x1 * y1 + z0 + java_shift_right((jlong)z1, 32);
1311 }
1312 
1313 // Dereference vptr
1314 // All C++ compilers that we know of have the vtbl pointer in the first
1315 // word.  If there are exceptions, this function needs to be made compiler
1316 // specific.
1317 static inline void* dereference_vptr(const void* addr) {
1318   return *(void**)addr;
1319 }
1320 
1321 //----------------------------------------------------------------------------------------------------
1322 // String type aliases used by command line flag declarations and
1323 // processing utilities.
1324 
1325 typedef const char* ccstr;
1326 typedef const char* ccstrlist;   // represents string arguments which accumulate
1327 
1328 //----------------------------------------------------------------------------------------------------
1329 // Default hash/equals functions used by ResourceHashtable
1330 
1331 template<typename K> unsigned primitive_hash(const K& k) {
1332   unsigned hash = (unsigned)((uintptr_t)k);
1333   return hash ^ (hash >> 3); // just in case we're dealing with aligned ptrs
1334 }
1335 
1336 template<typename K> bool primitive_equals(const K& k0, const K& k1) {
1337   return k0 == k1;
1338 }
1339 
1340 template<typename K> int primitive_compare(const K& k0, const K& k1) {
1341   return ((k0 < k1) ? -1 : (k0 == k1) ? 0 : 1);
1342 }
1343 
1344 //----------------------------------------------------------------------------------------------------
1345 
1346 // Allow use of C++ thread_local when approved - see JDK-8282469.
1347 #define APPROVED_CPP_THREAD_LOCAL thread_local
1348 
1349 // Converts any type T to a reference type.
1350 template<typename T>
1351 std::add_rvalue_reference_t<T> declval() noexcept;
1352 
1353 // Quickly test to make sure IEEE-754 subnormal numbers are correctly
1354 // handled.
1355 bool IEEE_subnormal_handling_OK();
1356 
1357 #endif // SHARE_UTILITIES_GLOBALDEFINITIONS_HPP