globalDefinitions.hpp revision 13184:7903df1b0c4f
1/*
2 * Copyright (c) 1997, 2017, 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_VM_UTILITIES_GLOBALDEFINITIONS_HPP
26#define SHARE_VM_UTILITIES_GLOBALDEFINITIONS_HPP
27
28#include "utilities/compilerWarnings.hpp"
29#include "utilities/debug.hpp"
30#include "utilities/macros.hpp"
31
32#include COMPILER_HEADER(utilities/globalDefinitions)
33
34// Defaults for macros that might be defined per compiler.
35#ifndef NOINLINE
36#define NOINLINE
37#endif
38#ifndef ALWAYSINLINE
39#define ALWAYSINLINE inline
40#endif
41
42// This file holds all globally used constants & types, class (forward)
43// declarations and a few frequently used utility functions.
44
45//----------------------------------------------------------------------------------------------------
46// Printf-style formatters for fixed- and variable-width types as pointers and
47// integers.  These are derived from the definitions in inttypes.h.  If the platform
48// doesn't provide appropriate definitions, they should be provided in
49// the compiler-specific definitions file (e.g., globalDefinitions_gcc.hpp)
50
51#define BOOL_TO_STR(_b_) ((_b_) ? "true" : "false")
52
53// Format 32-bit quantities.
54#define INT32_FORMAT           "%" PRId32
55#define UINT32_FORMAT          "%" PRIu32
56#define INT32_FORMAT_W(width)  "%" #width PRId32
57#define UINT32_FORMAT_W(width) "%" #width PRIu32
58
59#define PTR32_FORMAT           "0x%08" PRIx32
60#define PTR32_FORMAT_W(width)  "0x%" #width PRIx32
61
62// Format 64-bit quantities.
63#define INT64_FORMAT           "%" PRId64
64#define UINT64_FORMAT          "%" PRIu64
65#define UINT64_FORMAT_X        "%" PRIx64
66#define INT64_FORMAT_W(width)  "%" #width PRId64
67#define UINT64_FORMAT_W(width) "%" #width PRIu64
68
69#define PTR64_FORMAT           "0x%016" PRIx64
70
71// Format jlong, if necessary
72#ifndef JLONG_FORMAT
73#define JLONG_FORMAT           INT64_FORMAT
74#endif
75#ifndef JULONG_FORMAT
76#define JULONG_FORMAT          UINT64_FORMAT
77#endif
78#ifndef JULONG_FORMAT_X
79#define JULONG_FORMAT_X        UINT64_FORMAT_X
80#endif
81
82// Format pointers which change size between 32- and 64-bit.
83#ifdef  _LP64
84#define INTPTR_FORMAT "0x%016" PRIxPTR
85#define PTR_FORMAT    "0x%016" PRIxPTR
86#else   // !_LP64
87#define INTPTR_FORMAT "0x%08"  PRIxPTR
88#define PTR_FORMAT    "0x%08"  PRIxPTR
89#endif  // _LP64
90
91#define INTPTR_FORMAT_W(width)   "%" #width PRIxPTR
92
93#define SSIZE_FORMAT             "%"   PRIdPTR
94#define SIZE_FORMAT              "%"   PRIuPTR
95#define SIZE_FORMAT_HEX          "0x%" PRIxPTR
96#define SSIZE_FORMAT_W(width)    "%"   #width PRIdPTR
97#define SIZE_FORMAT_W(width)     "%"   #width PRIuPTR
98#define SIZE_FORMAT_HEX_W(width) "0x%" #width PRIxPTR
99
100#define INTX_FORMAT           "%" PRIdPTR
101#define UINTX_FORMAT          "%" PRIuPTR
102#define INTX_FORMAT_W(width)  "%" #width PRIdPTR
103#define UINTX_FORMAT_W(width) "%" #width PRIuPTR
104
105//----------------------------------------------------------------------------------------------------
106// Constants
107
108const int LogBytesPerShort   = 1;
109const int LogBytesPerInt     = 2;
110#ifdef _LP64
111const int LogBytesPerWord    = 3;
112#else
113const int LogBytesPerWord    = 2;
114#endif
115const int LogBytesPerLong    = 3;
116
117const int BytesPerShort      = 1 << LogBytesPerShort;
118const int BytesPerInt        = 1 << LogBytesPerInt;
119const int BytesPerWord       = 1 << LogBytesPerWord;
120const int BytesPerLong       = 1 << LogBytesPerLong;
121
122const int LogBitsPerByte     = 3;
123const int LogBitsPerShort    = LogBitsPerByte + LogBytesPerShort;
124const int LogBitsPerInt      = LogBitsPerByte + LogBytesPerInt;
125const int LogBitsPerWord     = LogBitsPerByte + LogBytesPerWord;
126const int LogBitsPerLong     = LogBitsPerByte + LogBytesPerLong;
127
128const int BitsPerByte        = 1 << LogBitsPerByte;
129const int BitsPerShort       = 1 << LogBitsPerShort;
130const int BitsPerInt         = 1 << LogBitsPerInt;
131const int BitsPerWord        = 1 << LogBitsPerWord;
132const int BitsPerLong        = 1 << LogBitsPerLong;
133
134const int WordAlignmentMask  = (1 << LogBytesPerWord) - 1;
135const int LongAlignmentMask  = (1 << LogBytesPerLong) - 1;
136
137const int WordsPerLong       = 2;       // Number of stack entries for longs
138
139const int oopSize            = sizeof(char*); // Full-width oop
140extern int heapOopSize;                       // Oop within a java object
141const int wordSize           = sizeof(char*);
142const int longSize           = sizeof(jlong);
143const int jintSize           = sizeof(jint);
144const int size_tSize         = sizeof(size_t);
145
146const int BytesPerOop        = BytesPerWord;  // Full-width oop
147
148extern int LogBytesPerHeapOop;                // Oop within a java object
149extern int LogBitsPerHeapOop;
150extern int BytesPerHeapOop;
151extern int BitsPerHeapOop;
152
153const int BitsPerJavaInteger = 32;
154const int BitsPerJavaLong    = 64;
155const int BitsPerSize_t      = size_tSize * BitsPerByte;
156
157// Size of a char[] needed to represent a jint as a string in decimal.
158const int jintAsStringSize = 12;
159
160// In fact this should be
161// log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
162// see os::set_memory_serialize_page()
163#ifdef _LP64
164const int SerializePageShiftCount = 4;
165#else
166const int SerializePageShiftCount = 3;
167#endif
168
169// An opaque struct of heap-word width, so that HeapWord* can be a generic
170// pointer into the heap.  We require that object sizes be measured in
171// units of heap words, so that that
172//   HeapWord* hw;
173//   hw += oop(hw)->foo();
174// works, where foo is a method (like size or scavenge) that returns the
175// object size.
176class HeapWord {
177  friend class VMStructs;
178 private:
179  char* i;
180#ifndef PRODUCT
181 public:
182  char* value() { return i; }
183#endif
184};
185
186// Analogous opaque struct for metadata allocated from
187// metaspaces.
188class MetaWord {
189 private:
190  char* i;
191};
192
193// HeapWordSize must be 2^LogHeapWordSize.
194const int HeapWordSize        = sizeof(HeapWord);
195#ifdef _LP64
196const int LogHeapWordSize     = 3;
197#else
198const int LogHeapWordSize     = 2;
199#endif
200const int HeapWordsPerLong    = BytesPerLong / HeapWordSize;
201const int LogHeapWordsPerLong = LogBytesPerLong - LogHeapWordSize;
202
203// The larger HeapWordSize for 64bit requires larger heaps
204// for the same application running in 64bit.  See bug 4967770.
205// The minimum alignment to a heap word size is done.  Other
206// parts of the memory system may require additional alignment
207// and are responsible for those alignments.
208#ifdef _LP64
209#define ScaleForWordSize(x) align_size_down_((x) * 13 / 10, HeapWordSize)
210#else
211#define ScaleForWordSize(x) (x)
212#endif
213
214// The minimum number of native machine words necessary to contain "byte_size"
215// bytes.
216inline size_t heap_word_size(size_t byte_size) {
217  return (byte_size + (HeapWordSize-1)) >> LogHeapWordSize;
218}
219
220//-------------------------------------------
221// Constant for jlong (standardized by C++11)
222
223// Build a 64bit integer constant
224#define CONST64(x)  (x ## LL)
225#define UCONST64(x) (x ## ULL)
226
227const jlong min_jlong = CONST64(0x8000000000000000);
228const jlong max_jlong = CONST64(0x7fffffffffffffff);
229
230const size_t K                  = 1024;
231const size_t M                  = K*K;
232const size_t G                  = M*K;
233const size_t HWperKB            = K / sizeof(HeapWord);
234
235// Constants for converting from a base unit to milli-base units.  For
236// example from seconds to milliseconds and microseconds
237
238const int MILLIUNITS    = 1000;         // milli units per base unit
239const int MICROUNITS    = 1000000;      // micro units per base unit
240const int NANOUNITS     = 1000000000;   // nano units per base unit
241
242const jlong NANOSECS_PER_SEC      = CONST64(1000000000);
243const jint  NANOSECS_PER_MILLISEC = 1000000;
244
245inline const char* proper_unit_for_byte_size(size_t s) {
246#ifdef _LP64
247  if (s >= 10*G) {
248    return "G";
249  }
250#endif
251  if (s >= 10*M) {
252    return "M";
253  } else if (s >= 10*K) {
254    return "K";
255  } else {
256    return "B";
257  }
258}
259
260template <class T>
261inline T byte_size_in_proper_unit(T s) {
262#ifdef _LP64
263  if (s >= 10*G) {
264    return (T)(s/G);
265  }
266#endif
267  if (s >= 10*M) {
268    return (T)(s/M);
269  } else if (s >= 10*K) {
270    return (T)(s/K);
271  } else {
272    return s;
273  }
274}
275
276inline const char* exact_unit_for_byte_size(size_t s) {
277#ifdef _LP64
278  if (s >= G && (s % G) == 0) {
279    return "G";
280  }
281#endif
282  if (s >= M && (s % M) == 0) {
283    return "M";
284  }
285  if (s >= K && (s % K) == 0) {
286    return "K";
287  }
288  return "B";
289}
290
291inline size_t byte_size_in_exact_unit(size_t s) {
292#ifdef _LP64
293  if (s >= G && (s % G) == 0) {
294    return s / G;
295  }
296#endif
297  if (s >= M && (s % M) == 0) {
298    return s / M;
299  }
300  if (s >= K && (s % K) == 0) {
301    return s / K;
302  }
303  return s;
304}
305
306//----------------------------------------------------------------------------------------------------
307// VM type definitions
308
309// intx and uintx are the 'extended' int and 'extended' unsigned int types;
310// they are 32bit wide on a 32-bit platform, and 64bit wide on a 64bit platform.
311
312typedef intptr_t  intx;
313typedef uintptr_t uintx;
314
315const intx  min_intx  = (intx)1 << (sizeof(intx)*BitsPerByte-1);
316const intx  max_intx  = (uintx)min_intx - 1;
317const uintx max_uintx = (uintx)-1;
318
319// Table of values:
320//      sizeof intx         4               8
321// min_intx             0x80000000      0x8000000000000000
322// max_intx             0x7FFFFFFF      0x7FFFFFFFFFFFFFFF
323// max_uintx            0xFFFFFFFF      0xFFFFFFFFFFFFFFFF
324
325typedef unsigned int uint;   NEEDS_CLEANUP
326
327
328//----------------------------------------------------------------------------------------------------
329// Java type definitions
330
331// All kinds of 'plain' byte addresses
332typedef   signed char s_char;
333typedef unsigned char u_char;
334typedef u_char*       address;
335typedef uintptr_t     address_word; // unsigned integer which will hold a pointer
336                                    // except for some implementations of a C++
337                                    // linkage pointer to function. Should never
338                                    // need one of those to be placed in this
339                                    // type anyway.
340
341//  Utility functions to "portably" (?) bit twiddle pointers
342//  Where portable means keep ANSI C++ compilers quiet
343
344inline address       set_address_bits(address x, int m)       { return address(intptr_t(x) | m); }
345inline address       clear_address_bits(address x, int m)     { return address(intptr_t(x) & ~m); }
346
347//  Utility functions to "portably" make cast to/from function pointers.
348
349inline address_word  mask_address_bits(address x, int m)      { return address_word(x) & m; }
350inline address_word  castable_address(address x)              { return address_word(x) ; }
351inline address_word  castable_address(void* x)                { return address_word(x) ; }
352
353// Pointer subtraction.
354// The idea here is to avoid ptrdiff_t, which is signed and so doesn't have
355// the range we might need to find differences from one end of the heap
356// to the other.
357// A typical use might be:
358//     if (pointer_delta(end(), top()) >= size) {
359//       // enough room for an object of size
360//       ...
361// and then additions like
362//       ... top() + size ...
363// are safe because we know that top() is at least size below end().
364inline size_t pointer_delta(const volatile void* left,
365                            const volatile void* right,
366                            size_t element_size) {
367  return (((uintptr_t) left) - ((uintptr_t) right)) / element_size;
368}
369
370// A version specialized for HeapWord*'s.
371inline size_t pointer_delta(const HeapWord* left, const HeapWord* right) {
372  return pointer_delta(left, right, sizeof(HeapWord));
373}
374// A version specialized for MetaWord*'s.
375inline size_t pointer_delta(const MetaWord* left, const MetaWord* right) {
376  return pointer_delta(left, right, sizeof(MetaWord));
377}
378
379//
380// ANSI C++ does not allow casting from one pointer type to a function pointer
381// directly without at best a warning. This macro accomplishes it silently
382// In every case that is present at this point the value be cast is a pointer
383// to a C linkage function. In some case the type used for the cast reflects
384// that linkage and a picky compiler would not complain. In other cases because
385// there is no convenient place to place a typedef with extern C linkage (i.e
386// a platform dependent header file) it doesn't. At this point no compiler seems
387// picky enough to catch these instances (which are few). It is possible that
388// using templates could fix these for all cases. This use of templates is likely
389// so far from the middle of the road that it is likely to be problematic in
390// many C++ compilers.
391//
392#define CAST_TO_FN_PTR(func_type, value) (reinterpret_cast<func_type>(value))
393#define CAST_FROM_FN_PTR(new_type, func_ptr) ((new_type)((address_word)(func_ptr)))
394
395// Unsigned byte types for os and stream.hpp
396
397// Unsigned one, two, four and eigth byte quantities used for describing
398// the .class file format. See JVM book chapter 4.
399
400typedef jubyte  u1;
401typedef jushort u2;
402typedef juint   u4;
403typedef julong  u8;
404
405const jubyte  max_jubyte  = (jubyte)-1;  // 0xFF       largest jubyte
406const jushort max_jushort = (jushort)-1; // 0xFFFF     largest jushort
407const juint   max_juint   = (juint)-1;   // 0xFFFFFFFF largest juint
408const julong  max_julong  = (julong)-1;  // 0xFF....FF largest julong
409
410typedef jbyte  s1;
411typedef jshort s2;
412typedef jint   s4;
413typedef jlong  s8;
414
415const jbyte min_jbyte = -(1 << 7);       // smallest jbyte
416const jbyte max_jbyte = (1 << 7) - 1;    // largest jbyte
417const jshort min_jshort = -(1 << 15);    // smallest jshort
418const jshort max_jshort = (1 << 15) - 1; // largest jshort
419
420const jint min_jint = (jint)1 << (sizeof(jint)*BitsPerByte-1); // 0x80000000 == smallest jint
421const jint max_jint = (juint)min_jint - 1;                     // 0x7FFFFFFF == largest jint
422
423//----------------------------------------------------------------------------------------------------
424// JVM spec restrictions
425
426const int max_method_code_size = 64*K - 1;  // JVM spec, 2nd ed. section 4.8.1 (p.134)
427
428// Default ProtectionDomainCacheSize values
429
430const int defaultProtectionDomainCacheSize = NOT_LP64(137) LP64_ONLY(2017);
431
432//----------------------------------------------------------------------------------------------------
433// Default and minimum StringTableSize values
434
435const int defaultStringTableSize = NOT_LP64(1009) LP64_ONLY(60013);
436const int minimumStringTableSize = 1009;
437
438const int defaultSymbolTableSize = 20011;
439const int minimumSymbolTableSize = 1009;
440
441
442//----------------------------------------------------------------------------------------------------
443// HotSwap - for JVMTI   aka Class File Replacement and PopFrame
444//
445// Determines whether on-the-fly class replacement and frame popping are enabled.
446
447#define HOTSWAP
448
449//----------------------------------------------------------------------------------------------------
450// Object alignment, in units of HeapWords.
451//
452// Minimum is max(BytesPerLong, BytesPerDouble, BytesPerOop) / HeapWordSize, so jlong, jdouble and
453// reference fields can be naturally aligned.
454
455extern int MinObjAlignment;
456extern int MinObjAlignmentInBytes;
457extern int MinObjAlignmentInBytesMask;
458
459extern int LogMinObjAlignment;
460extern int LogMinObjAlignmentInBytes;
461
462const int LogKlassAlignmentInBytes = 3;
463const int LogKlassAlignment        = LogKlassAlignmentInBytes - LogHeapWordSize;
464const int KlassAlignmentInBytes    = 1 << LogKlassAlignmentInBytes;
465const int KlassAlignment           = KlassAlignmentInBytes / HeapWordSize;
466
467// Maximal size of heap where unscaled compression can be used. Also upper bound
468// for heap placement: 4GB.
469const  uint64_t UnscaledOopHeapMax = (uint64_t(max_juint) + 1);
470// Maximal size of heap where compressed oops can be used. Also upper bound for heap
471// placement for zero based compression algorithm: UnscaledOopHeapMax << LogMinObjAlignmentInBytes.
472extern uint64_t OopEncodingHeapMax;
473
474// Maximal size of compressed class space. Above this limit compression is not possible.
475// Also upper bound for placement of zero based class space. (Class space is further limited
476// to be < 3G, see arguments.cpp.)
477const  uint64_t KlassEncodingMetaspaceMax = (uint64_t(max_juint) + 1) << LogKlassAlignmentInBytes;
478
479// Machine dependent stuff
480
481// The maximum size of the code cache.  Can be overridden by targets.
482#define CODE_CACHE_SIZE_LIMIT (2*G)
483// Allow targets to reduce the default size of the code cache.
484#define CODE_CACHE_DEFAULT_LIMIT CODE_CACHE_SIZE_LIMIT
485
486#include CPU_HEADER(globalDefinitions)
487
488// To assure the IRIW property on processors that are not multiple copy
489// atomic, sync instructions must be issued between volatile reads to
490// assure their ordering, instead of after volatile stores.
491// (See "A Tutorial Introduction to the ARM and POWER Relaxed Memory Models"
492// by Luc Maranget, Susmit Sarkar and Peter Sewell, INRIA/Cambridge)
493#ifdef CPU_NOT_MULTIPLE_COPY_ATOMIC
494const bool support_IRIW_for_not_multiple_copy_atomic_cpu = true;
495#else
496const bool support_IRIW_for_not_multiple_copy_atomic_cpu = false;
497#endif
498
499// The byte alignment to be used by Arena::Amalloc.  See bugid 4169348.
500// Note: this value must be a power of 2
501
502#define ARENA_AMALLOC_ALIGNMENT (2*BytesPerWord)
503
504// Signed variants of alignment helpers.  There are two versions of each, a macro
505// for use in places like enum definitions that require compile-time constant
506// expressions and a function for all other places so as to get type checking.
507
508#define align_size_up_(size, alignment) (((size) + ((alignment) - 1)) & ~((alignment) - 1))
509
510inline bool is_size_aligned(size_t size, size_t alignment) {
511  return align_size_up_(size, alignment) == size;
512}
513
514inline bool is_ptr_aligned(const void* ptr, size_t alignment) {
515  return align_size_up_((intptr_t)ptr, (intptr_t)alignment) == (intptr_t)ptr;
516}
517
518inline intptr_t align_size_up(intptr_t size, intptr_t alignment) {
519  return align_size_up_(size, alignment);
520}
521
522#define align_size_down_(size, alignment) ((size) & ~((alignment) - 1))
523
524inline intptr_t align_size_down(intptr_t size, intptr_t alignment) {
525  return align_size_down_(size, alignment);
526}
527
528#define is_size_aligned_(size, alignment) ((size) == (align_size_up_(size, alignment)))
529
530inline void* align_ptr_up(const void* ptr, size_t alignment) {
531  return (void*)align_size_up((intptr_t)ptr, (intptr_t)alignment);
532}
533
534inline void* align_ptr_down(void* ptr, size_t alignment) {
535  return (void*)align_size_down((intptr_t)ptr, (intptr_t)alignment);
536}
537
538inline volatile void* align_ptr_down(volatile void* ptr, size_t alignment) {
539  return (volatile void*)align_size_down((intptr_t)ptr, (intptr_t)alignment);
540}
541
542// Align metaspace objects by rounding up to natural word boundary
543
544inline intptr_t align_metadata_size(intptr_t size) {
545  return align_size_up(size, 1);
546}
547
548// Align objects in the Java Heap by rounding up their size, in HeapWord units.
549// Since the size is given in words this is somewhat of a nop, but
550// distinguishes it from align_object_size.
551inline intptr_t align_object_size(intptr_t size) {
552  return align_size_up(size, MinObjAlignment);
553}
554
555inline bool is_object_aligned(intptr_t addr) {
556  return addr == align_object_size(addr);
557}
558
559// Pad out certain offsets to jlong alignment, in HeapWord units.
560
561inline intptr_t align_object_offset(intptr_t offset) {
562  return align_size_up(offset, HeapWordsPerLong);
563}
564
565// Align down with a lower bound. If the aligning results in 0, return 'alignment'.
566
567inline size_t align_size_down_bounded(size_t size, size_t alignment) {
568  size_t aligned_size = align_size_down_(size, alignment);
569  return aligned_size > 0 ? aligned_size : alignment;
570}
571
572// Clamp an address to be within a specific page
573// 1. If addr is on the page it is returned as is
574// 2. If addr is above the page_address the start of the *next* page will be returned
575// 3. Otherwise, if addr is below the page_address the start of the page will be returned
576inline address clamp_address_in_page(address addr, address page_address, intptr_t page_size) {
577  if (align_size_down(intptr_t(addr), page_size) == align_size_down(intptr_t(page_address), page_size)) {
578    // address is in the specified page, just return it as is
579    return addr;
580  } else if (addr > page_address) {
581    // address is above specified page, return start of next page
582    return (address)align_size_down(intptr_t(page_address), page_size) + page_size;
583  } else {
584    // address is below specified page, return start of page
585    return (address)align_size_down(intptr_t(page_address), page_size);
586  }
587}
588
589
590// The expected size in bytes of a cache line, used to pad data structures.
591#ifndef DEFAULT_CACHE_LINE_SIZE
592  #define DEFAULT_CACHE_LINE_SIZE 64
593#endif
594
595
596//----------------------------------------------------------------------------------------------------
597// Utility macros for compilers
598// used to silence compiler warnings
599
600#define Unused_Variable(var) var
601
602
603//----------------------------------------------------------------------------------------------------
604// Miscellaneous
605
606// 6302670 Eliminate Hotspot __fabsf dependency
607// All fabs() callers should call this function instead, which will implicitly
608// convert the operand to double, avoiding a dependency on __fabsf which
609// doesn't exist in early versions of Solaris 8.
610inline double fabsd(double value) {
611  return fabs(value);
612}
613
614// Returns numerator/denominator as percentage value from 0 to 100. If denominator
615// is zero, return 0.0.
616template<typename T>
617inline double percent_of(T numerator, T denominator) {
618  return denominator != 0 ? (double)numerator / denominator * 100.0 : 0.0;
619}
620
621//----------------------------------------------------------------------------------------------------
622// Special casts
623// Cast floats into same-size integers and vice-versa w/o changing bit-pattern
624typedef union {
625  jfloat f;
626  jint i;
627} FloatIntConv;
628
629typedef union {
630  jdouble d;
631  jlong l;
632  julong ul;
633} DoubleLongConv;
634
635inline jint    jint_cast    (jfloat  x)  { return ((FloatIntConv*)&x)->i; }
636inline jfloat  jfloat_cast  (jint    x)  { return ((FloatIntConv*)&x)->f; }
637
638inline jlong   jlong_cast   (jdouble x)  { return ((DoubleLongConv*)&x)->l;  }
639inline julong  julong_cast  (jdouble x)  { return ((DoubleLongConv*)&x)->ul; }
640inline jdouble jdouble_cast (jlong   x)  { return ((DoubleLongConv*)&x)->d;  }
641
642inline jint low (jlong value)                    { return jint(value); }
643inline jint high(jlong value)                    { return jint(value >> 32); }
644
645// the fancy casts are a hopefully portable way
646// to do unsigned 32 to 64 bit type conversion
647inline void set_low (jlong* value, jint low )    { *value &= (jlong)0xffffffff << 32;
648                                                   *value |= (jlong)(julong)(juint)low; }
649
650inline void set_high(jlong* value, jint high)    { *value &= (jlong)(julong)(juint)0xffffffff;
651                                                   *value |= (jlong)high       << 32; }
652
653inline jlong jlong_from(jint h, jint l) {
654  jlong result = 0; // initialization to avoid warning
655  set_high(&result, h);
656  set_low(&result,  l);
657  return result;
658}
659
660union jlong_accessor {
661  jint  words[2];
662  jlong long_value;
663};
664
665void basic_types_init(); // cannot define here; uses assert
666
667
668// NOTE: replicated in SA in vm/agent/sun/jvm/hotspot/runtime/BasicType.java
669enum BasicType {
670  T_BOOLEAN     =  4,
671  T_CHAR        =  5,
672  T_FLOAT       =  6,
673  T_DOUBLE      =  7,
674  T_BYTE        =  8,
675  T_SHORT       =  9,
676  T_INT         = 10,
677  T_LONG        = 11,
678  T_OBJECT      = 12,
679  T_ARRAY       = 13,
680  T_VOID        = 14,
681  T_ADDRESS     = 15,
682  T_NARROWOOP   = 16,
683  T_METADATA    = 17,
684  T_NARROWKLASS = 18,
685  T_CONFLICT    = 19, // for stack value type with conflicting contents
686  T_ILLEGAL     = 99
687};
688
689inline bool is_java_primitive(BasicType t) {
690  return T_BOOLEAN <= t && t <= T_LONG;
691}
692
693inline bool is_subword_type(BasicType t) {
694  // these guys are processed exactly like T_INT in calling sequences:
695  return (t == T_BOOLEAN || t == T_CHAR || t == T_BYTE || t == T_SHORT);
696}
697
698inline bool is_signed_subword_type(BasicType t) {
699  return (t == T_BYTE || t == T_SHORT);
700}
701
702// Convert a char from a classfile signature to a BasicType
703inline BasicType char2type(char c) {
704  switch( c ) {
705  case 'B': return T_BYTE;
706  case 'C': return T_CHAR;
707  case 'D': return T_DOUBLE;
708  case 'F': return T_FLOAT;
709  case 'I': return T_INT;
710  case 'J': return T_LONG;
711  case 'S': return T_SHORT;
712  case 'Z': return T_BOOLEAN;
713  case 'V': return T_VOID;
714  case 'L': return T_OBJECT;
715  case '[': return T_ARRAY;
716  }
717  return T_ILLEGAL;
718}
719
720extern char type2char_tab[T_CONFLICT+1];     // Map a BasicType to a jchar
721inline char type2char(BasicType t) { return (uint)t < T_CONFLICT+1 ? type2char_tab[t] : 0; }
722extern int type2size[T_CONFLICT+1];         // Map BasicType to result stack elements
723extern const char* type2name_tab[T_CONFLICT+1];     // Map a BasicType to a jchar
724inline const char* type2name(BasicType t) { return (uint)t < T_CONFLICT+1 ? type2name_tab[t] : NULL; }
725extern BasicType name2type(const char* name);
726
727// Auxiliary math routines
728// least common multiple
729extern size_t lcm(size_t a, size_t b);
730
731
732// NOTE: replicated in SA in vm/agent/sun/jvm/hotspot/runtime/BasicType.java
733enum BasicTypeSize {
734  T_BOOLEAN_size     = 1,
735  T_CHAR_size        = 1,
736  T_FLOAT_size       = 1,
737  T_DOUBLE_size      = 2,
738  T_BYTE_size        = 1,
739  T_SHORT_size       = 1,
740  T_INT_size         = 1,
741  T_LONG_size        = 2,
742  T_OBJECT_size      = 1,
743  T_ARRAY_size       = 1,
744  T_NARROWOOP_size   = 1,
745  T_NARROWKLASS_size = 1,
746  T_VOID_size        = 0
747};
748
749
750// maps a BasicType to its instance field storage type:
751// all sub-word integral types are widened to T_INT
752extern BasicType type2field[T_CONFLICT+1];
753extern BasicType type2wfield[T_CONFLICT+1];
754
755
756// size in bytes
757enum ArrayElementSize {
758  T_BOOLEAN_aelem_bytes     = 1,
759  T_CHAR_aelem_bytes        = 2,
760  T_FLOAT_aelem_bytes       = 4,
761  T_DOUBLE_aelem_bytes      = 8,
762  T_BYTE_aelem_bytes        = 1,
763  T_SHORT_aelem_bytes       = 2,
764  T_INT_aelem_bytes         = 4,
765  T_LONG_aelem_bytes        = 8,
766#ifdef _LP64
767  T_OBJECT_aelem_bytes      = 8,
768  T_ARRAY_aelem_bytes       = 8,
769#else
770  T_OBJECT_aelem_bytes      = 4,
771  T_ARRAY_aelem_bytes       = 4,
772#endif
773  T_NARROWOOP_aelem_bytes   = 4,
774  T_NARROWKLASS_aelem_bytes = 4,
775  T_VOID_aelem_bytes        = 0
776};
777
778extern int _type2aelembytes[T_CONFLICT+1]; // maps a BasicType to nof bytes used by its array element
779#ifdef ASSERT
780extern int type2aelembytes(BasicType t, bool allow_address = false); // asserts
781#else
782inline int type2aelembytes(BasicType t, bool allow_address = false) { return _type2aelembytes[t]; }
783#endif
784
785
786// JavaValue serves as a container for arbitrary Java values.
787
788class JavaValue {
789
790 public:
791  typedef union JavaCallValue {
792    jfloat   f;
793    jdouble  d;
794    jint     i;
795    jlong    l;
796    jobject  h;
797  } JavaCallValue;
798
799 private:
800  BasicType _type;
801  JavaCallValue _value;
802
803 public:
804  JavaValue(BasicType t = T_ILLEGAL) { _type = t; }
805
806  JavaValue(jfloat value) {
807    _type    = T_FLOAT;
808    _value.f = value;
809  }
810
811  JavaValue(jdouble value) {
812    _type    = T_DOUBLE;
813    _value.d = value;
814  }
815
816 jfloat get_jfloat() const { return _value.f; }
817 jdouble get_jdouble() const { return _value.d; }
818 jint get_jint() const { return _value.i; }
819 jlong get_jlong() const { return _value.l; }
820 jobject get_jobject() const { return _value.h; }
821 JavaCallValue* get_value_addr() { return &_value; }
822 BasicType get_type() const { return _type; }
823
824 void set_jfloat(jfloat f) { _value.f = f;}
825 void set_jdouble(jdouble d) { _value.d = d;}
826 void set_jint(jint i) { _value.i = i;}
827 void set_jlong(jlong l) { _value.l = l;}
828 void set_jobject(jobject h) { _value.h = h;}
829 void set_type(BasicType t) { _type = t; }
830
831 jboolean get_jboolean() const { return (jboolean) (_value.i);}
832 jbyte get_jbyte() const { return (jbyte) (_value.i);}
833 jchar get_jchar() const { return (jchar) (_value.i);}
834 jshort get_jshort() const { return (jshort) (_value.i);}
835
836};
837
838
839#define STACK_BIAS      0
840// V9 Sparc CPU's running in 64 Bit mode use a stack bias of 7ff
841// in order to extend the reach of the stack pointer.
842#if defined(SPARC) && defined(_LP64)
843#undef STACK_BIAS
844#define STACK_BIAS      0x7ff
845#endif
846
847
848// TosState describes the top-of-stack state before and after the execution of
849// a bytecode or method. The top-of-stack value may be cached in one or more CPU
850// registers. The TosState corresponds to the 'machine representation' of this cached
851// value. There's 4 states corresponding to the JAVA types int, long, float & double
852// as well as a 5th state in case the top-of-stack value is actually on the top
853// of stack (in memory) and thus not cached. The atos state corresponds to the itos
854// state when it comes to machine representation but is used separately for (oop)
855// type specific operations (e.g. verification code).
856
857enum TosState {         // describes the tos cache contents
858  btos = 0,             // byte, bool tos cached
859  ztos = 1,             // byte, bool tos cached
860  ctos = 2,             // char tos cached
861  stos = 3,             // short tos cached
862  itos = 4,             // int tos cached
863  ltos = 5,             // long tos cached
864  ftos = 6,             // float tos cached
865  dtos = 7,             // double tos cached
866  atos = 8,             // object cached
867  vtos = 9,             // tos not cached
868  number_of_states,
869  ilgl                  // illegal state: should not occur
870};
871
872
873inline TosState as_TosState(BasicType type) {
874  switch (type) {
875    case T_BYTE   : return btos;
876    case T_BOOLEAN: return ztos;
877    case T_CHAR   : return ctos;
878    case T_SHORT  : return stos;
879    case T_INT    : return itos;
880    case T_LONG   : return ltos;
881    case T_FLOAT  : return ftos;
882    case T_DOUBLE : return dtos;
883    case T_VOID   : return vtos;
884    case T_ARRAY  : // fall through
885    case T_OBJECT : return atos;
886  }
887  return ilgl;
888}
889
890inline BasicType as_BasicType(TosState state) {
891  switch (state) {
892    case btos : return T_BYTE;
893    case ztos : return T_BOOLEAN;
894    case ctos : return T_CHAR;
895    case stos : return T_SHORT;
896    case itos : return T_INT;
897    case ltos : return T_LONG;
898    case ftos : return T_FLOAT;
899    case dtos : return T_DOUBLE;
900    case atos : return T_OBJECT;
901    case vtos : return T_VOID;
902  }
903  return T_ILLEGAL;
904}
905
906
907// Helper function to convert BasicType info into TosState
908// Note: Cannot define here as it uses global constant at the time being.
909TosState as_TosState(BasicType type);
910
911
912// JavaThreadState keeps track of which part of the code a thread is executing in. This
913// information is needed by the safepoint code.
914//
915// There are 4 essential states:
916//
917//  _thread_new         : Just started, but not executed init. code yet (most likely still in OS init code)
918//  _thread_in_native   : In native code. This is a safepoint region, since all oops will be in jobject handles
919//  _thread_in_vm       : Executing in the vm
920//  _thread_in_Java     : Executing either interpreted or compiled Java code (or could be in a stub)
921//
922// Each state has an associated xxxx_trans state, which is an intermediate state used when a thread is in
923// a transition from one state to another. These extra states makes it possible for the safepoint code to
924// handle certain thread_states without having to suspend the thread - making the safepoint code faster.
925//
926// Given a state, the xxxx_trans state can always be found by adding 1.
927//
928enum JavaThreadState {
929  _thread_uninitialized     =  0, // should never happen (missing initialization)
930  _thread_new               =  2, // just starting up, i.e., in process of being initialized
931  _thread_new_trans         =  3, // corresponding transition state (not used, included for completness)
932  _thread_in_native         =  4, // running in native code
933  _thread_in_native_trans   =  5, // corresponding transition state
934  _thread_in_vm             =  6, // running in VM
935  _thread_in_vm_trans       =  7, // corresponding transition state
936  _thread_in_Java           =  8, // running in Java or in stub code
937  _thread_in_Java_trans     =  9, // corresponding transition state (not used, included for completness)
938  _thread_blocked           = 10, // blocked in vm
939  _thread_blocked_trans     = 11, // corresponding transition state
940  _thread_max_state         = 12  // maximum thread state+1 - used for statistics allocation
941};
942
943
944
945//----------------------------------------------------------------------------------------------------
946// 'Forward' declarations of frequently used classes
947// (in order to reduce interface dependencies & reduce
948// number of unnecessary compilations after changes)
949
950class ClassFileStream;
951
952class Event;
953
954class Thread;
955class  VMThread;
956class  JavaThread;
957class Threads;
958
959class VM_Operation;
960class VMOperationQueue;
961
962class CodeBlob;
963class  CompiledMethod;
964class   nmethod;
965class RuntimeBlob;
966class  OSRAdapter;
967class  I2CAdapter;
968class  C2IAdapter;
969class CompiledIC;
970class relocInfo;
971class ScopeDesc;
972class PcDesc;
973
974class Recompiler;
975class Recompilee;
976class RecompilationPolicy;
977class RFrame;
978class  CompiledRFrame;
979class  InterpretedRFrame;
980
981class vframe;
982class   javaVFrame;
983class     interpretedVFrame;
984class     compiledVFrame;
985class     deoptimizedVFrame;
986class   externalVFrame;
987class     entryVFrame;
988
989class RegisterMap;
990
991class Mutex;
992class Monitor;
993class BasicLock;
994class BasicObjectLock;
995
996class PeriodicTask;
997
998class JavaCallWrapper;
999
1000class   oopDesc;
1001class   metaDataOopDesc;
1002
1003class NativeCall;
1004
1005class zone;
1006
1007class StubQueue;
1008
1009class outputStream;
1010
1011class ResourceArea;
1012
1013class DebugInformationRecorder;
1014class ScopeValue;
1015class CompressedStream;
1016class   DebugInfoReadStream;
1017class   DebugInfoWriteStream;
1018class LocationValue;
1019class ConstantValue;
1020class IllegalValue;
1021
1022class PrivilegedElement;
1023class MonitorArray;
1024
1025class MonitorInfo;
1026
1027class OffsetClosure;
1028class OopMapCache;
1029class InterpreterOopMap;
1030class OopMapCacheEntry;
1031class OSThread;
1032
1033typedef int (*OSThreadStartFunc)(void*);
1034
1035class Space;
1036
1037class JavaValue;
1038class methodHandle;
1039class JavaCallArguments;
1040
1041// Basic support for errors.
1042extern void basic_fatal(const char* msg);
1043
1044//----------------------------------------------------------------------------------------------------
1045// Special constants for debugging
1046
1047const jint     badInt           = -3;                       // generic "bad int" value
1048const long     badAddressVal    = -2;                       // generic "bad address" value
1049const long     badOopVal        = -1;                       // generic "bad oop" value
1050const intptr_t badHeapOopVal    = (intptr_t) CONST64(0x2BAD4B0BBAADBABE); // value used to zap heap after GC
1051const int      badHandleValue   = 0xBC;                     // value used to zap vm handle area
1052const int      badResourceValue = 0xAB;                     // value used to zap resource area
1053const int      freeBlockPad     = 0xBA;                     // value used to pad freed blocks.
1054const int      uninitBlockPad   = 0xF1;                     // value used to zap newly malloc'd blocks.
1055const juint    uninitMetaWordVal= 0xf7f7f7f7;               // value used to zap newly allocated metachunk
1056const intptr_t badJNIHandleVal  = (intptr_t) UCONST64(0xFEFEFEFEFEFEFEFE); // value used to zap jni handle area
1057const juint    badHeapWordVal   = 0xBAADBABE;               // value used to zap heap after GC
1058const juint    badMetaWordVal   = 0xBAADFADE;               // value used to zap metadata heap after GC
1059const int      badCodeHeapNewVal= 0xCC;                     // value used to zap Code heap at allocation
1060const int      badCodeHeapFreeVal = 0xDD;                   // value used to zap Code heap at deallocation
1061
1062
1063// (These must be implemented as #defines because C++ compilers are
1064// not obligated to inline non-integral constants!)
1065#define       badAddress        ((address)::badAddressVal)
1066#define       badOop            (cast_to_oop(::badOopVal))
1067#define       badHeapWord       (::badHeapWordVal)
1068#define       badJNIHandle      (cast_to_oop(::badJNIHandleVal))
1069
1070// Default TaskQueue size is 16K (32-bit) or 128K (64-bit)
1071#define TASKQUEUE_SIZE (NOT_LP64(1<<14) LP64_ONLY(1<<17))
1072
1073//----------------------------------------------------------------------------------------------------
1074// Utility functions for bitfield manipulations
1075
1076const intptr_t AllBits    = ~0; // all bits set in a word
1077const intptr_t NoBits     =  0; // no bits set in a word
1078const jlong    NoLongBits =  0; // no bits set in a long
1079const intptr_t OneBit     =  1; // only right_most bit set in a word
1080
1081// get a word with the n.th or the right-most or left-most n bits set
1082// (note: #define used only so that they can be used in enum constant definitions)
1083#define nth_bit(n)        (((n) >= BitsPerWord) ? 0 : (OneBit << (n)))
1084#define right_n_bits(n)   (nth_bit(n) - 1)
1085#define left_n_bits(n)    (right_n_bits(n) << (((n) >= BitsPerWord) ? 0 : (BitsPerWord - (n))))
1086
1087// bit-operations using a mask m
1088inline void   set_bits    (intptr_t& x, intptr_t m) { x |= m; }
1089inline void clear_bits    (intptr_t& x, intptr_t m) { x &= ~m; }
1090inline intptr_t mask_bits      (intptr_t  x, intptr_t m) { return x & m; }
1091inline jlong    mask_long_bits (jlong     x, jlong    m) { return x & m; }
1092inline bool mask_bits_are_true (intptr_t flags, intptr_t mask) { return (flags & mask) == mask; }
1093
1094// bit-operations using the n.th bit
1095inline void    set_nth_bit(intptr_t& x, int n) { set_bits  (x, nth_bit(n)); }
1096inline void  clear_nth_bit(intptr_t& x, int n) { clear_bits(x, nth_bit(n)); }
1097inline bool is_set_nth_bit(intptr_t  x, int n) { return mask_bits (x, nth_bit(n)) != NoBits; }
1098
1099// returns the bitfield of x starting at start_bit_no with length field_length (no sign-extension!)
1100inline intptr_t bitfield(intptr_t x, int start_bit_no, int field_length) {
1101  return mask_bits(x >> start_bit_no, right_n_bits(field_length));
1102}
1103
1104
1105//----------------------------------------------------------------------------------------------------
1106// Utility functions for integers
1107
1108// Avoid use of global min/max macros which may cause unwanted double
1109// evaluation of arguments.
1110#ifdef max
1111#undef max
1112#endif
1113
1114#ifdef min
1115#undef min
1116#endif
1117
1118// The following defines serve the purpose of preventing use of accidentally
1119// included min max macros from compiling, while continuing to allow innocent
1120// min and max identifiers in the code to compile as intended.
1121#define max max
1122#define min min
1123
1124// It is necessary to use templates here. Having normal overloaded
1125// functions does not work because it is necessary to provide both 32-
1126// and 64-bit overloaded functions, which does not work, and having
1127// explicitly-typed versions of these routines (i.e., MAX2I, MAX2L)
1128// will be even more error-prone than macros.
1129template<class T> inline T MAX2(T a, T b)           { return (a > b) ? a : b; }
1130template<class T> inline T MIN2(T a, T b)           { return (a < b) ? a : b; }
1131template<class T> inline T MAX3(T a, T b, T c)      { return MAX2(MAX2(a, b), c); }
1132template<class T> inline T MIN3(T a, T b, T c)      { return MIN2(MIN2(a, b), c); }
1133template<class T> inline T MAX4(T a, T b, T c, T d) { return MAX2(MAX3(a, b, c), d); }
1134template<class T> inline T MIN4(T a, T b, T c, T d) { return MIN2(MIN3(a, b, c), d); }
1135
1136template<class T> inline T ABS(T x)                 { return (x > 0) ? x : -x; }
1137
1138// true if x is a power of 2, false otherwise
1139inline bool is_power_of_2(intptr_t x) {
1140  return ((x != NoBits) && (mask_bits(x, x - 1) == NoBits));
1141}
1142
1143// long version of is_power_of_2
1144inline bool is_power_of_2_long(jlong x) {
1145  return ((x != NoLongBits) && (mask_long_bits(x, x - 1) == NoLongBits));
1146}
1147
1148// Returns largest i such that 2^i <= x.
1149// If x < 0, the function returns 31 on a 32-bit machine and 63 on a 64-bit machine.
1150// If x == 0, the function returns -1.
1151inline int log2_intptr(intptr_t x) {
1152  int i = -1;
1153  uintptr_t p = 1;
1154  while (p != 0 && p <= (uintptr_t)x) {
1155    // p = 2^(i+1) && p <= x (i.e., 2^(i+1) <= x)
1156    i++; p *= 2;
1157  }
1158  // p = 2^(i+1) && x < p (i.e., 2^i <= x < 2^(i+1))
1159  // If p = 0, overflow has occurred and i = 31 or i = 63 (depending on the machine word size).
1160  return i;
1161}
1162
1163//* largest i such that 2^i <= x
1164//  A negative value of 'x' will return '63'
1165inline int log2_long(jlong x) {
1166  int i = -1;
1167  julong p =  1;
1168  while (p != 0 && p <= (julong)x) {
1169    // p = 2^(i+1) && p <= x (i.e., 2^(i+1) <= x)
1170    i++; p *= 2;
1171  }
1172  // p = 2^(i+1) && x < p (i.e., 2^i <= x < 2^(i+1))
1173  // (if p = 0 then overflow occurred and i = 63)
1174  return i;
1175}
1176
1177//* the argument must be exactly a power of 2
1178inline int exact_log2(intptr_t x) {
1179  assert(is_power_of_2(x), "x must be a power of 2: " INTPTR_FORMAT, x);
1180  return log2_intptr(x);
1181}
1182
1183//* the argument must be exactly a power of 2
1184inline int exact_log2_long(jlong x) {
1185  assert(is_power_of_2_long(x), "x must be a power of 2: " JLONG_FORMAT, x);
1186  return log2_long(x);
1187}
1188
1189
1190// returns integer round-up to the nearest multiple of s (s must be a power of two)
1191inline intptr_t round_to(intptr_t x, uintx s) {
1192  assert(is_power_of_2(s), "s must be a power of 2: " UINTX_FORMAT, s);
1193  const uintx m = s - 1;
1194  return mask_bits(x + m, ~m);
1195}
1196
1197// returns integer round-down to the nearest multiple of s (s must be a power of two)
1198inline intptr_t round_down(intptr_t x, uintx s) {
1199  assert(is_power_of_2(s), "s must be a power of 2: " UINTX_FORMAT, s);
1200  const uintx m = s - 1;
1201  return mask_bits(x, ~m);
1202}
1203
1204
1205inline bool is_odd (intx x) { return x & 1;      }
1206inline bool is_even(intx x) { return !is_odd(x); }
1207
1208// "to" should be greater than "from."
1209inline intx byte_size(void* from, void* to) {
1210  return (address)to - (address)from;
1211}
1212
1213//----------------------------------------------------------------------------------------------------
1214// Avoid non-portable casts with these routines (DEPRECATED)
1215
1216// NOTE: USE Bytes class INSTEAD WHERE POSSIBLE
1217//       Bytes is optimized machine-specifically and may be much faster then the portable routines below.
1218
1219// Given sequence of four bytes, build into a 32-bit word
1220// following the conventions used in class files.
1221// On the 386, this could be realized with a simple address cast.
1222//
1223
1224// This routine takes eight bytes:
1225inline u8 build_u8_from( u1 c1, u1 c2, u1 c3, u1 c4, u1 c5, u1 c6, u1 c7, u1 c8 ) {
1226  return  (( u8(c1) << 56 )  &  ( u8(0xff) << 56 ))
1227       |  (( u8(c2) << 48 )  &  ( u8(0xff) << 48 ))
1228       |  (( u8(c3) << 40 )  &  ( u8(0xff) << 40 ))
1229       |  (( u8(c4) << 32 )  &  ( u8(0xff) << 32 ))
1230       |  (( u8(c5) << 24 )  &  ( u8(0xff) << 24 ))
1231       |  (( u8(c6) << 16 )  &  ( u8(0xff) << 16 ))
1232       |  (( u8(c7) <<  8 )  &  ( u8(0xff) <<  8 ))
1233       |  (( u8(c8) <<  0 )  &  ( u8(0xff) <<  0 ));
1234}
1235
1236// This routine takes four bytes:
1237inline u4 build_u4_from( u1 c1, u1 c2, u1 c3, u1 c4 ) {
1238  return  (( u4(c1) << 24 )  &  0xff000000)
1239       |  (( u4(c2) << 16 )  &  0x00ff0000)
1240       |  (( u4(c3) <<  8 )  &  0x0000ff00)
1241       |  (( u4(c4) <<  0 )  &  0x000000ff);
1242}
1243
1244// And this one works if the four bytes are contiguous in memory:
1245inline u4 build_u4_from( u1* p ) {
1246  return  build_u4_from( p[0], p[1], p[2], p[3] );
1247}
1248
1249// Ditto for two-byte ints:
1250inline u2 build_u2_from( u1 c1, u1 c2 ) {
1251  return  u2((( u2(c1) <<  8 )  &  0xff00)
1252          |  (( u2(c2) <<  0 )  &  0x00ff));
1253}
1254
1255// And this one works if the two bytes are contiguous in memory:
1256inline u2 build_u2_from( u1* p ) {
1257  return  build_u2_from( p[0], p[1] );
1258}
1259
1260// Ditto for floats:
1261inline jfloat build_float_from( u1 c1, u1 c2, u1 c3, u1 c4 ) {
1262  u4 u = build_u4_from( c1, c2, c3, c4 );
1263  return  *(jfloat*)&u;
1264}
1265
1266inline jfloat build_float_from( u1* p ) {
1267  u4 u = build_u4_from( p );
1268  return  *(jfloat*)&u;
1269}
1270
1271
1272// now (64-bit) longs
1273
1274inline jlong build_long_from( u1 c1, u1 c2, u1 c3, u1 c4, u1 c5, u1 c6, u1 c7, u1 c8 ) {
1275  return  (( jlong(c1) << 56 )  &  ( jlong(0xff) << 56 ))
1276       |  (( jlong(c2) << 48 )  &  ( jlong(0xff) << 48 ))
1277       |  (( jlong(c3) << 40 )  &  ( jlong(0xff) << 40 ))
1278       |  (( jlong(c4) << 32 )  &  ( jlong(0xff) << 32 ))
1279       |  (( jlong(c5) << 24 )  &  ( jlong(0xff) << 24 ))
1280       |  (( jlong(c6) << 16 )  &  ( jlong(0xff) << 16 ))
1281       |  (( jlong(c7) <<  8 )  &  ( jlong(0xff) <<  8 ))
1282       |  (( jlong(c8) <<  0 )  &  ( jlong(0xff) <<  0 ));
1283}
1284
1285inline jlong build_long_from( u1* p ) {
1286  return  build_long_from( p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7] );
1287}
1288
1289
1290// Doubles, too!
1291inline jdouble build_double_from( u1 c1, u1 c2, u1 c3, u1 c4, u1 c5, u1 c6, u1 c7, u1 c8 ) {
1292  jlong u = build_long_from( c1, c2, c3, c4, c5, c6, c7, c8 );
1293  return  *(jdouble*)&u;
1294}
1295
1296inline jdouble build_double_from( u1* p ) {
1297  jlong u = build_long_from( p );
1298  return  *(jdouble*)&u;
1299}
1300
1301
1302// Portable routines to go the other way:
1303
1304inline void explode_short_to( u2 x, u1& c1, u1& c2 ) {
1305  c1 = u1(x >> 8);
1306  c2 = u1(x);
1307}
1308
1309inline void explode_short_to( u2 x, u1* p ) {
1310  explode_short_to( x, p[0], p[1]);
1311}
1312
1313inline void explode_int_to( u4 x, u1& c1, u1& c2, u1& c3, u1& c4 ) {
1314  c1 = u1(x >> 24);
1315  c2 = u1(x >> 16);
1316  c3 = u1(x >>  8);
1317  c4 = u1(x);
1318}
1319
1320inline void explode_int_to( u4 x, u1* p ) {
1321  explode_int_to( x, p[0], p[1], p[2], p[3]);
1322}
1323
1324
1325// Pack and extract shorts to/from ints:
1326
1327inline int extract_low_short_from_int(jint x) {
1328  return x & 0xffff;
1329}
1330
1331inline int extract_high_short_from_int(jint x) {
1332  return (x >> 16) & 0xffff;
1333}
1334
1335inline int build_int_from_shorts( jushort low, jushort high ) {
1336  return ((int)((unsigned int)high << 16) | (unsigned int)low);
1337}
1338
1339// Convert pointer to intptr_t, for use in printing pointers.
1340inline intptr_t p2i(const void * p) {
1341  return (intptr_t) p;
1342}
1343
1344// swap a & b
1345template<class T> static void swap(T& a, T& b) {
1346  T tmp = a;
1347  a = b;
1348  b = tmp;
1349}
1350
1351#define ARRAY_SIZE(array) (sizeof(array)/sizeof((array)[0]))
1352
1353//----------------------------------------------------------------------------------------------------
1354// Sum and product which can never overflow: they wrap, just like the
1355// Java operations.  Note that we don't intend these to be used for
1356// general-purpose arithmetic: their purpose is to emulate Java
1357// operations.
1358
1359// The goal of this code to avoid undefined or implementation-defined
1360// behavior.  The use of an lvalue to reference cast is explicitly
1361// permitted by Lvalues and rvalues [basic.lval].  [Section 3.10 Para
1362// 15 in C++03]
1363#define JAVA_INTEGER_OP(OP, NAME, TYPE, UNSIGNED_TYPE)  \
1364inline TYPE NAME (TYPE in1, TYPE in2) {                 \
1365  UNSIGNED_TYPE ures = static_cast<UNSIGNED_TYPE>(in1); \
1366  ures OP ## = static_cast<UNSIGNED_TYPE>(in2);         \
1367  return reinterpret_cast<TYPE&>(ures);                 \
1368}
1369
1370JAVA_INTEGER_OP(+, java_add, jint, juint)
1371JAVA_INTEGER_OP(-, java_subtract, jint, juint)
1372JAVA_INTEGER_OP(*, java_multiply, jint, juint)
1373JAVA_INTEGER_OP(+, java_add, jlong, julong)
1374JAVA_INTEGER_OP(-, java_subtract, jlong, julong)
1375JAVA_INTEGER_OP(*, java_multiply, jlong, julong)
1376
1377#undef JAVA_INTEGER_OP
1378
1379// Dereference vptr
1380// All C++ compilers that we know of have the vtbl pointer in the first
1381// word.  If there are exceptions, this function needs to be made compiler
1382// specific.
1383static inline void* dereference_vptr(const void* addr) {
1384  return *(void**)addr;
1385}
1386
1387#endif // SHARE_VM_UTILITIES_GLOBALDEFINITIONS_HPP
1388