1 /*
   2  * Copyright (c) 2000, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_OOPS_METHODDATA_HPP
  26 #define SHARE_OOPS_METHODDATA_HPP
  27 
  28 #include "interpreter/bytecodes.hpp"
  29 #include "interpreter/invocationCounter.hpp"
  30 #include "oops/metadata.hpp"
  31 #include "oops/method.hpp"
  32 #include "runtime/atomicAccess.hpp"
  33 #include "runtime/deoptimization.hpp"
  34 #include "runtime/mutex.hpp"
  35 #include "utilities/align.hpp"
  36 #include "utilities/copy.hpp"
  37 #include "utilities/integerCast.hpp"
  38 
  39 class BytecodeStream;
  40 
  41 // The MethodData object collects counts and other profile information
  42 // during zeroth-tier (interpreter) and third-tier (C1 with full profiling)
  43 // execution.
  44 //
  45 // The profile is used later by compilation heuristics.  Some heuristics
  46 // enable use of aggressive (or "heroic") optimizations.  An aggressive
  47 // optimization often has a down-side, a corner case that it handles
  48 // poorly, but which is thought to be rare.  The profile provides
  49 // evidence of this rarity for a given method or even BCI.  It allows
  50 // the compiler to back out of the optimization at places where it
  51 // has historically been a poor choice.  Other heuristics try to use
  52 // specific information gathered about types observed at a given site.
  53 //
  54 // All data in the profile is approximate.  It is expected to be accurate
  55 // on the whole, but the system expects occasional inaccuraces, due to
  56 // counter overflow, multiprocessor races during data collection, space
  57 // limitations, missing MDO blocks, etc.  Bad or missing data will degrade
  58 // optimization quality but will not affect correctness.  Also, each MDO
  59 // can be checked for its "maturity" by calling is_mature().
  60 //
  61 // Short (<32-bit) counters are designed to overflow to a known "saturated"
  62 // state.  Also, certain recorded per-BCI events are given one-bit counters
  63 // which overflow to a saturated state which applied to all counters at
  64 // that BCI.  In other words, there is a small lattice which approximates
  65 // the ideal of an infinite-precision counter for each event at each BCI,
  66 // and the lattice quickly "bottoms out" in a state where all counters
  67 // are taken to be indefinitely large.
  68 //
  69 // The reader will find many data races in profile gathering code, starting
  70 // with invocation counter incrementation.  None of these races harm correct
  71 // execution of the compiled code.
  72 
  73 // forward decl
  74 class ProfileData;
  75 
  76 // DataLayout
  77 //
  78 // Overlay for generic profiling data.
  79 class DataLayout {
  80   friend class VMStructs;
  81   friend class JVMCIVMStructs;
  82 
  83 private:
  84   // Every data layout begins with a header.  This header
  85   // contains a tag, which is used to indicate the size/layout
  86   // of the data, 8 bits of flags, which can be used in any way,
  87   // 32 bits of trap history (none/one reason/many reasons),
  88   // and a bci, which is used to tie this piece of data to a
  89   // specific bci in the bytecodes.
  90   union {
  91     u8 _bits;
  92     struct {
  93       u1 _tag;
  94       u1 _flags;
  95       u2 _bci;
  96       u4 _traps;
  97     } _struct;
  98   } _header;
  99 
 100   // The data layout has an arbitrary number of cells, each sized
 101   // to accommodate a pointer or an integer.
 102   intptr_t _cells[1];
 103 
 104   // Some types of data layouts need a length field.
 105   static bool needs_array_len(u1 tag);
 106 
 107 public:
 108   enum {
 109     counter_increment = 1
 110   };
 111 
 112   enum {
 113     cell_size = sizeof(intptr_t)
 114   };
 115 
 116   // Tag values
 117   enum : u1 {
 118     no_tag,
 119     bit_data_tag,
 120     counter_data_tag,
 121     jump_data_tag,
 122     receiver_type_data_tag,
 123     virtual_call_data_tag,
 124     ret_data_tag,
 125     branch_data_tag,
 126     multi_branch_data_tag,
 127     arg_info_data_tag,
 128     call_type_data_tag,
 129     virtual_call_type_data_tag,
 130     parameters_type_data_tag,
 131     speculative_trap_data_tag
 132   };
 133 
 134   enum {
 135     // The trap state breaks down as [recompile:1 | reason:31].
 136     // This further breakdown is defined in deoptimization.cpp.
 137     // See Deoptimization::trap_state_reason for an assert that
 138     // trap_bits is big enough to hold reasons < Reason_RECORDED_LIMIT.
 139     //
 140     // The trap_state is collected only if ProfileTraps is true.
 141     trap_bits = 1+31,  // 31: enough to distinguish [0..Reason_RECORDED_LIMIT].
 142     trap_mask = -1,
 143     first_flag = 0
 144   };
 145 
 146   // Size computation
 147   static int header_size_in_bytes() {
 148     return header_size_in_cells() * cell_size;
 149   }
 150   static int header_size_in_cells() {
 151     return LP64_ONLY(1) NOT_LP64(2);
 152   }
 153 
 154   static int compute_size_in_bytes(int cell_count) {
 155     return header_size_in_bytes() + cell_count * cell_size;
 156   }
 157 
 158   // Initialization
 159   void initialize(u1 tag, u2 bci, int cell_count);
 160 
 161   // Accessors
 162   u1 tag() {
 163     return _header._struct._tag;
 164   }
 165 
 166   // Return 32 bits of trap state.
 167   // The state tells if traps with zero, one, or many reasons have occurred.
 168   // It also tells whether zero or many recompilations have occurred.
 169   // The associated trap histogram in the MDO itself tells whether
 170   // traps are common or not.  If a BCI shows that a trap X has
 171   // occurred, and the MDO shows N occurrences of X, we make the
 172   // simplifying assumption that all N occurrences can be blamed
 173   // on that BCI.
 174   uint trap_state() const {
 175     return _header._struct._traps;
 176   }
 177 
 178   void set_trap_state(uint new_state) {
 179     assert(ProfileTraps, "used only under +ProfileTraps");
 180     uint old_flags = _header._struct._traps;
 181     _header._struct._traps = new_state | old_flags;
 182   }
 183 
 184   u1 flags() const {
 185     return AtomicAccess::load_acquire(&_header._struct._flags);
 186   }
 187 
 188   u2 bci() const {
 189     return _header._struct._bci;
 190   }
 191 
 192   void set_header(u8 value) {
 193     _header._bits = value;
 194   }
 195   u8 header() {
 196     return _header._bits;
 197   }
 198   void set_cell_at(int index, intptr_t value) {
 199     _cells[index] = value;
 200   }
 201   void release_set_cell_at(int index, intptr_t value);
 202   intptr_t cell_at(int index) const {
 203     return _cells[index];
 204   }
 205   intptr_t* cell_at_adr(int index) const {
 206     return const_cast<intptr_t*>(&_cells[index]);
 207   }
 208 
 209   bool set_flag_at(u1 flag_number) {
 210     const u1 bit = integer_cast<u1>(1 << flag_number);
 211     u1 compare_value;
 212     do {
 213       compare_value = _header._struct._flags;
 214       if ((compare_value & bit) == bit) {
 215         // already set.
 216         return false;
 217       }
 218     } while (compare_value != AtomicAccess::cmpxchg(&_header._struct._flags, compare_value, static_cast<u1>(compare_value | bit)));
 219     return true;
 220   }
 221 
 222   bool clear_flag_at(u1 flag_number) {
 223     const u1 bit = integer_cast<u1>(1 << flag_number);
 224     u1 compare_value;
 225     u1 exchange_value;
 226     do {
 227       compare_value = _header._struct._flags;
 228       if ((compare_value & bit) == 0) {
 229         // already cleaed.
 230         return false;
 231       }
 232       exchange_value = compare_value & ~bit;
 233     } while (compare_value != AtomicAccess::cmpxchg(&_header._struct._flags, compare_value, exchange_value));
 234     return true;
 235   }
 236 
 237   bool flag_at(u1 flag_number) const {
 238     return (flags() & (1 << flag_number)) != 0;
 239   }
 240 
 241   // Low-level support for code generation.
 242   static ByteSize header_offset() {
 243     return byte_offset_of(DataLayout, _header);
 244   }
 245   static ByteSize tag_offset() {
 246     return byte_offset_of(DataLayout, _header._struct._tag);
 247   }
 248   static ByteSize flags_offset() {
 249     return byte_offset_of(DataLayout, _header._struct._flags);
 250   }
 251   static ByteSize bci_offset() {
 252     return byte_offset_of(DataLayout, _header._struct._bci);
 253   }
 254   static ByteSize cell_offset(int index) {
 255     return byte_offset_of(DataLayout, _cells) + in_ByteSize(index * cell_size);
 256   }
 257   // Return a value which, when or-ed as a byte into _flags, sets the flag.
 258   static u1 flag_number_to_constant(u1 flag_number) {
 259     DataLayout temp; temp.set_header(0);
 260     temp.set_flag_at(flag_number);
 261     return temp._header._struct._flags;
 262   }
 263   // Return a value which, when or-ed as a word into _header, sets the flag.
 264   static u8 flag_mask_to_header_mask(u1 byte_constant) {
 265     DataLayout temp; temp.set_header(0);
 266     temp._header._struct._flags = byte_constant;
 267     return temp._header._bits;
 268   }
 269 
 270   ProfileData* data_in();
 271 
 272   int size_in_bytes() {
 273     int cells = cell_count();
 274     assert(cells >= 0, "invalid number of cells");
 275     return DataLayout::compute_size_in_bytes(cells);
 276   }
 277   int cell_count();
 278 
 279   // GC support
 280   void clean_weak_klass_links(bool always_clean);
 281 };
 282 
 283 
 284 // ProfileData class hierarchy
 285 class ProfileData;
 286 class   BitData;
 287 class     CounterData;
 288 class       ReceiverTypeData;
 289 class         VirtualCallData;
 290 class           VirtualCallTypeData;
 291 class       RetData;
 292 class       CallTypeData;
 293 class   JumpData;
 294 class     BranchData;
 295 class   ArrayData;
 296 class     MultiBranchData;
 297 class     ArgInfoData;
 298 class     ParametersTypeData;
 299 class   SpeculativeTrapData;
 300 
 301 // ProfileData
 302 //
 303 // A ProfileData object is created to refer to a section of profiling
 304 // data in a structured way.
 305 class ProfileData : public ResourceObj {
 306   friend class TypeEntries;
 307   friend class ReturnTypeEntry;
 308   friend class TypeStackSlotEntries;
 309 private:
 310   enum {
 311     tab_width_one = 16,
 312     tab_width_two = 36
 313   };
 314 
 315   // This is a pointer to a section of profiling data.
 316   DataLayout* _data;
 317 
 318   char* print_data_on_helper(const MethodData* md) const;
 319 
 320 protected:
 321   DataLayout* data() { return _data; }
 322   const DataLayout* data() const { return _data; }
 323 
 324   enum {
 325     cell_size = DataLayout::cell_size
 326   };
 327 
 328 public:
 329   // How many cells are in this?
 330   virtual int cell_count() const {
 331     ShouldNotReachHere();
 332     return -1;
 333   }
 334 
 335   // Return the size of this data.
 336   int size_in_bytes() {
 337     return DataLayout::compute_size_in_bytes(cell_count());
 338   }
 339 
 340 protected:
 341   // Low-level accessors for underlying data
 342   void set_intptr_at(int index, intptr_t value) {
 343     assert(0 <= index && index < cell_count(), "oob");
 344     data()->set_cell_at(index, value);
 345   }
 346   void release_set_intptr_at(int index, intptr_t value);
 347   intptr_t intptr_at(int index) const {
 348     assert(0 <= index && index < cell_count(), "oob");
 349     return data()->cell_at(index);
 350   }
 351   intptr_t* intptr_at_adr(int index) const {
 352     assert(0 <= index && index < cell_count(), "oob");
 353     return data()->cell_at_adr(index);
 354   }
 355   void set_uint_at(int index, uint value) {
 356     set_intptr_at(index, (intptr_t) value);
 357   }
 358   void release_set_uint_at(int index, uint value);
 359   uint uint_at(int index) const {
 360     return (uint)intptr_at(index);
 361   }
 362   void set_int_at(int index, int value) {
 363     set_intptr_at(index, (intptr_t) value);
 364   }
 365   void release_set_int_at(int index, int value);
 366   int int_at(int index) const {
 367     return (int)intptr_at(index);
 368   }
 369   int int_at_unchecked(int index) const {
 370     return (int)data()->cell_at(index);
 371   }
 372 
 373   void set_flag_at(u1 flag_number) {
 374     data()->set_flag_at(flag_number);
 375   }
 376   bool flag_at(u1 flag_number) const {
 377     return data()->flag_at(flag_number);
 378   }
 379 
 380   // two convenient imports for use by subclasses:
 381   static ByteSize cell_offset(int index) {
 382     return DataLayout::cell_offset(index);
 383   }
 384   static u1 flag_number_to_constant(u1 flag_number) {
 385     return DataLayout::flag_number_to_constant(flag_number);
 386   }
 387 
 388   ProfileData(DataLayout* data) {
 389     _data = data;
 390   }
 391 
 392 public:
 393   // Constructor for invalid ProfileData.
 394   ProfileData();
 395 
 396   u2 bci() const {
 397     return data()->bci();
 398   }
 399 
 400   address dp() {
 401     return (address)_data;
 402   }
 403 
 404   int trap_state() const {
 405     return data()->trap_state();
 406   }
 407   void set_trap_state(int new_state) {
 408     data()->set_trap_state(new_state);
 409   }
 410 
 411   // Type checking
 412   virtual bool is_BitData()         const { return false; }
 413   virtual bool is_CounterData()     const { return false; }
 414   virtual bool is_JumpData()        const { return false; }
 415   virtual bool is_ReceiverTypeData()const { return false; }
 416   virtual bool is_VirtualCallData() const { return false; }
 417   virtual bool is_RetData()         const { return false; }
 418   virtual bool is_BranchData()      const { return false; }
 419   virtual bool is_ArrayData()       const { return false; }
 420   virtual bool is_MultiBranchData() const { return false; }
 421   virtual bool is_ArgInfoData()     const { return false; }
 422   virtual bool is_CallTypeData()    const { return false; }
 423   virtual bool is_VirtualCallTypeData()const { return false; }
 424   virtual bool is_ParametersTypeData() const { return false; }
 425   virtual bool is_SpeculativeTrapData()const { return false; }
 426 
 427 
 428   BitData* as_BitData() const {
 429     assert(is_BitData(), "wrong type");
 430     return is_BitData()         ? (BitData*)        this : nullptr;
 431   }
 432   CounterData* as_CounterData() const {
 433     assert(is_CounterData(), "wrong type");
 434     return is_CounterData()     ? (CounterData*)    this : nullptr;
 435   }
 436   JumpData* as_JumpData() const {
 437     assert(is_JumpData(), "wrong type");
 438     return is_JumpData()        ? (JumpData*)       this : nullptr;
 439   }
 440   ReceiverTypeData* as_ReceiverTypeData() const {
 441     assert(is_ReceiverTypeData(), "wrong type");
 442     return is_ReceiverTypeData() ? (ReceiverTypeData*)this : nullptr;
 443   }
 444   VirtualCallData* as_VirtualCallData() const {
 445     assert(is_VirtualCallData(), "wrong type");
 446     return is_VirtualCallData() ? (VirtualCallData*)this : nullptr;
 447   }
 448   RetData* as_RetData() const {
 449     assert(is_RetData(), "wrong type");
 450     return is_RetData()         ? (RetData*)        this : nullptr;
 451   }
 452   BranchData* as_BranchData() const {
 453     assert(is_BranchData(), "wrong type");
 454     return is_BranchData()      ? (BranchData*)     this : nullptr;
 455   }
 456   ArrayData* as_ArrayData() const {
 457     assert(is_ArrayData(), "wrong type");
 458     return is_ArrayData()       ? (ArrayData*)      this : nullptr;
 459   }
 460   MultiBranchData* as_MultiBranchData() const {
 461     assert(is_MultiBranchData(), "wrong type");
 462     return is_MultiBranchData() ? (MultiBranchData*)this : nullptr;
 463   }
 464   ArgInfoData* as_ArgInfoData() const {
 465     assert(is_ArgInfoData(), "wrong type");
 466     return is_ArgInfoData() ? (ArgInfoData*)this : nullptr;
 467   }
 468   CallTypeData* as_CallTypeData() const {
 469     assert(is_CallTypeData(), "wrong type");
 470     return is_CallTypeData() ? (CallTypeData*)this : nullptr;
 471   }
 472   VirtualCallTypeData* as_VirtualCallTypeData() const {
 473     assert(is_VirtualCallTypeData(), "wrong type");
 474     return is_VirtualCallTypeData() ? (VirtualCallTypeData*)this : nullptr;
 475   }
 476   ParametersTypeData* as_ParametersTypeData() const {
 477     assert(is_ParametersTypeData(), "wrong type");
 478     return is_ParametersTypeData() ? (ParametersTypeData*)this : nullptr;
 479   }
 480   SpeculativeTrapData* as_SpeculativeTrapData() const {
 481     assert(is_SpeculativeTrapData(), "wrong type");
 482     return is_SpeculativeTrapData() ? (SpeculativeTrapData*)this : nullptr;
 483   }
 484 
 485 
 486   // Subclass specific initialization
 487   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo) {}
 488 
 489   // GC support
 490   virtual void clean_weak_klass_links(bool always_clean) {}
 491 
 492   // CDS support
 493   virtual void metaspace_pointers_do(MetaspaceClosure* it) {}
 494 
 495     // CI translation: ProfileData can represent both MethodDataOop data
 496   // as well as CIMethodData data. This function is provided for translating
 497   // an oop in a ProfileData to the ci equivalent. Generally speaking,
 498   // most ProfileData don't require any translation, so we provide the null
 499   // translation here, and the required translators are in the ci subclasses.
 500   virtual void translate_from(const ProfileData* data) {}
 501 
 502   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const {
 503     ShouldNotReachHere();
 504   }
 505 
 506   void print_data_on(outputStream* st, const MethodData* md) const;
 507 
 508   void print_shared(outputStream* st, const char* name, const char* extra) const;
 509   void tab(outputStream* st, bool first = false) const;
 510 };
 511 
 512 // BitData
 513 //
 514 // A BitData holds a flag or two in its header.
 515 class BitData : public ProfileData {
 516   friend class VMStructs;
 517   friend class JVMCIVMStructs;
 518 protected:
 519   enum : u1 {
 520     // null_seen:
 521     //  saw a null operand (cast/aastore/instanceof)
 522       null_seen_flag                  = DataLayout::first_flag + 0,
 523       exception_handler_entered_flag  = null_seen_flag + 1,
 524       deprecated_method_callsite_flag = exception_handler_entered_flag + 1
 525 #if INCLUDE_JVMCI
 526     // bytecode threw any exception
 527     , exception_seen_flag             = deprecated_method_callsite_flag + 1
 528 #endif
 529   };
 530   enum { bit_cell_count = 0 };  // no additional data fields needed.
 531 public:
 532   BitData(DataLayout* layout) : ProfileData(layout) {
 533   }
 534 
 535   virtual bool is_BitData() const { return true; }
 536 
 537   static int static_cell_count() {
 538     return bit_cell_count;
 539   }
 540 
 541   virtual int cell_count() const {
 542     return static_cell_count();
 543   }
 544 
 545   // Accessor
 546 
 547   // The null_seen flag bit is specially known to the interpreter.
 548   // Consulting it allows the compiler to avoid setting up null_check traps.
 549   bool null_seen()     { return flag_at(null_seen_flag); }
 550   void set_null_seen()    { set_flag_at(null_seen_flag); }
 551   bool deprecated_method_call_site() const { return flag_at(deprecated_method_callsite_flag); }
 552   bool set_deprecated_method_call_site() { return data()->set_flag_at(deprecated_method_callsite_flag); }
 553   bool clear_deprecated_method_call_site() { return data()->clear_flag_at(deprecated_method_callsite_flag); }
 554 
 555 #if INCLUDE_JVMCI
 556   // true if an exception was thrown at the specific BCI
 557   bool exception_seen() { return flag_at(exception_seen_flag); }
 558   void set_exception_seen() { set_flag_at(exception_seen_flag); }
 559 #endif
 560 
 561   // true if a ex handler block at this bci was entered
 562   bool exception_handler_entered() { return flag_at(exception_handler_entered_flag); }
 563   void set_exception_handler_entered() { set_flag_at(exception_handler_entered_flag); }
 564 
 565   // Code generation support
 566   static u1 null_seen_byte_constant() {
 567     return flag_number_to_constant(null_seen_flag);
 568   }
 569 
 570   static ByteSize bit_data_size() {
 571     return cell_offset(bit_cell_count);
 572   }
 573 
 574   void print_data_on(outputStream* st, const char* extra = nullptr) const;
 575 };
 576 
 577 // CounterData
 578 //
 579 // A CounterData corresponds to a simple counter.
 580 class CounterData : public BitData {
 581   friend class VMStructs;
 582   friend class JVMCIVMStructs;
 583 protected:
 584   enum {
 585     count_off,
 586     counter_cell_count
 587   };
 588 public:
 589   CounterData(DataLayout* layout) : BitData(layout) {}
 590 
 591   virtual bool is_CounterData() const { return true; }
 592 
 593   static int static_cell_count() {
 594     return counter_cell_count;
 595   }
 596 
 597   virtual int cell_count() const {
 598     return static_cell_count();
 599   }
 600 
 601   // Direct accessor
 602   int count() const {
 603     intptr_t raw_data = intptr_at(count_off);
 604     if (raw_data > max_jint) {
 605       raw_data = max_jint;
 606     } else if (raw_data < min_jint) {
 607       raw_data = min_jint;
 608     }
 609     return int(raw_data);
 610   }
 611 
 612   // Code generation support
 613   static ByteSize count_offset() {
 614     return cell_offset(count_off);
 615   }
 616   static ByteSize counter_data_size() {
 617     return cell_offset(counter_cell_count);
 618   }
 619 
 620   void set_count(int count) {
 621     set_int_at(count_off, count);
 622   }
 623 
 624   void print_data_on(outputStream* st, const char* extra = nullptr) const;
 625 };
 626 
 627 // JumpData
 628 //
 629 // A JumpData is used to access profiling information for a direct
 630 // branch.  It is a counter, used for counting the number of branches,
 631 // plus a data displacement, used for realigning the data pointer to
 632 // the corresponding target bci.
 633 class JumpData : public ProfileData {
 634   friend class VMStructs;
 635   friend class JVMCIVMStructs;
 636 protected:
 637   enum {
 638     taken_off_set,
 639     displacement_off_set,
 640     jump_cell_count
 641   };
 642 
 643   void set_displacement(int displacement) {
 644     set_int_at(displacement_off_set, displacement);
 645   }
 646 
 647 public:
 648   JumpData(DataLayout* layout) : ProfileData(layout) {
 649     assert(layout->tag() == DataLayout::jump_data_tag ||
 650       layout->tag() == DataLayout::branch_data_tag, "wrong type");
 651   }
 652 
 653   virtual bool is_JumpData() const { return true; }
 654 
 655   static int static_cell_count() {
 656     return jump_cell_count;
 657   }
 658 
 659   virtual int cell_count() const {
 660     return static_cell_count();
 661   }
 662 
 663   // Direct accessor
 664   uint taken() const {
 665     return uint_at(taken_off_set);
 666   }
 667 
 668   void set_taken(uint cnt) {
 669     set_uint_at(taken_off_set, cnt);
 670   }
 671 
 672   // Saturating counter
 673   uint inc_taken() {
 674     uint cnt = taken() + 1;
 675     // Did we wrap? Will compiler screw us??
 676     if (cnt == 0) cnt--;
 677     set_uint_at(taken_off_set, cnt);
 678     return cnt;
 679   }
 680 
 681   int displacement() const {
 682     return int_at(displacement_off_set);
 683   }
 684 
 685   // Code generation support
 686   static ByteSize taken_offset() {
 687     return cell_offset(taken_off_set);
 688   }
 689 
 690   static ByteSize displacement_offset() {
 691     return cell_offset(displacement_off_set);
 692   }
 693 
 694   // Specific initialization.
 695   void post_initialize(BytecodeStream* stream, MethodData* mdo);
 696 
 697   void print_data_on(outputStream* st, const char* extra = nullptr) const;
 698 };
 699 
 700 // Entries in a ProfileData object to record types: it can either be
 701 // none (no profile), unknown (conflicting profile data) or a klass if
 702 // a single one is seen. Whether a null reference was seen is also
 703 // recorded. No counter is associated with the type and a single type
 704 // is tracked (unlike VirtualCallData).
 705 class TypeEntries {
 706 
 707 public:
 708 
 709   // A single cell is used to record information for a type:
 710   // - the cell is initialized to 0
 711   // - when a type is discovered it is stored in the cell
 712   // - bit zero of the cell is used to record whether a null reference
 713   // was encountered or not
 714   // - bit 1 is set to record a conflict in the type information
 715 
 716   enum {
 717     null_seen = 1,
 718     type_mask = ~null_seen,
 719     type_unknown = 2,
 720     status_bits = null_seen | type_unknown,
 721     type_klass_mask = ~status_bits
 722   };
 723 
 724   // what to initialize a cell to
 725   static intptr_t type_none() {
 726     return 0;
 727   }
 728 
 729   // null seen = bit 0 set?
 730   static bool was_null_seen(intptr_t v) {
 731     return (v & null_seen) != 0;
 732   }
 733 
 734   // conflicting type information = bit 1 set?
 735   static bool is_type_unknown(intptr_t v) {
 736     return (v & type_unknown) != 0;
 737   }
 738 
 739   // not type information yet = all bits cleared, ignoring bit 0?
 740   static bool is_type_none(intptr_t v) {
 741     return (v & type_mask) == 0;
 742   }
 743 
 744   // recorded type: cell without bit 0 and 1
 745   static intptr_t klass_part(intptr_t v) {
 746     intptr_t r = v & type_klass_mask;
 747     return r;
 748   }
 749 
 750   // type recorded
 751   static Klass* valid_klass(intptr_t k) {
 752     if (!is_type_none(k) &&
 753         !is_type_unknown(k)) {
 754       Klass* res = (Klass*)klass_part(k);
 755       assert(res != nullptr, "invalid");
 756       return res;
 757     } else {
 758       return nullptr;
 759     }
 760   }
 761 
 762   static intptr_t with_status(intptr_t k, intptr_t in) {
 763     return k | (in & status_bits);
 764   }
 765 
 766   static intptr_t with_status(Klass* k, intptr_t in) {
 767     return with_status((intptr_t)k, in);
 768   }
 769 
 770   static void print_klass(outputStream* st, intptr_t k);
 771 
 772 protected:
 773   // ProfileData object these entries are part of
 774   ProfileData* _pd;
 775   // offset within the ProfileData object where the entries start
 776   const int _base_off;
 777 
 778   TypeEntries(int base_off)
 779     : _pd(nullptr), _base_off(base_off) {}
 780 
 781   void set_intptr_at(int index, intptr_t value) {
 782     _pd->set_intptr_at(index, value);
 783   }
 784 
 785   intptr_t intptr_at(int index) const {
 786     return _pd->intptr_at(index);
 787   }
 788 
 789 public:
 790   void set_profile_data(ProfileData* pd) {
 791     _pd = pd;
 792   }
 793 };
 794 
 795 // Type entries used for arguments passed at a call and parameters on
 796 // method entry. 2 cells per entry: one for the type encoded as in
 797 // TypeEntries and one initialized with the stack slot where the
 798 // profiled object is to be found so that the interpreter can locate
 799 // it quickly.
 800 class TypeStackSlotEntries : public TypeEntries {
 801 
 802 private:
 803   enum {
 804     stack_slot_entry,
 805     type_entry,
 806     per_arg_cell_count
 807   };
 808 
 809   // offset of cell for stack slot for entry i within ProfileData object
 810   int stack_slot_offset(int i) const {
 811     return _base_off + stack_slot_local_offset(i);
 812   }
 813 
 814   const int _number_of_entries;
 815 
 816   // offset of cell for type for entry i within ProfileData object
 817   int type_offset_in_cells(int i) const {
 818     return _base_off + type_local_offset(i);
 819   }
 820 
 821 public:
 822 
 823   TypeStackSlotEntries(int base_off, int nb_entries)
 824     : TypeEntries(base_off), _number_of_entries(nb_entries) {}
 825 
 826   static int compute_cell_count(Symbol* signature, bool include_receiver, int max);
 827 
 828   void post_initialize(Symbol* signature, bool has_receiver, bool include_receiver);
 829 
 830   int number_of_entries() const { return _number_of_entries; }
 831 
 832   // offset of cell for stack slot for entry i within this block of cells for a TypeStackSlotEntries
 833   static int stack_slot_local_offset(int i) {
 834     return i * per_arg_cell_count + stack_slot_entry;
 835   }
 836 
 837   // offset of cell for type for entry i within this block of cells for a TypeStackSlotEntries
 838   static int type_local_offset(int i) {
 839     return i * per_arg_cell_count + type_entry;
 840   }
 841 
 842   // stack slot for entry i
 843   uint stack_slot(int i) const {
 844     assert(i >= 0 && i < _number_of_entries, "oob");
 845     return _pd->uint_at(stack_slot_offset(i));
 846   }
 847 
 848   // set stack slot for entry i
 849   void set_stack_slot(int i, uint num) {
 850     assert(i >= 0 && i < _number_of_entries, "oob");
 851     _pd->set_uint_at(stack_slot_offset(i), num);
 852   }
 853 
 854   // type for entry i
 855   intptr_t type(int i) const {
 856     assert(i >= 0 && i < _number_of_entries, "oob");
 857     return _pd->intptr_at(type_offset_in_cells(i));
 858   }
 859 
 860   intptr_t* type_adr(int i) const {
 861     assert(i >= 0 && i < _number_of_entries, "oob");
 862     return _pd->intptr_at_adr(type_offset_in_cells(i));
 863   }
 864 
 865   // set type for entry i
 866   void set_type(int i, intptr_t k) {
 867     assert(i >= 0 && i < _number_of_entries, "oob");
 868     _pd->set_intptr_at(type_offset_in_cells(i), k);
 869   }
 870 
 871   static ByteSize per_arg_size() {
 872     return in_ByteSize(per_arg_cell_count * DataLayout::cell_size);
 873   }
 874 
 875   static int per_arg_count() {
 876     return per_arg_cell_count;
 877   }
 878 
 879   ByteSize type_offset(int i) const {
 880     return DataLayout::cell_offset(type_offset_in_cells(i));
 881   }
 882 
 883   // GC support
 884   void clean_weak_klass_links(bool always_clean);
 885 
 886   // CDS support
 887   virtual void metaspace_pointers_do(MetaspaceClosure* it);
 888 
 889   void print_data_on(outputStream* st) const;
 890 };
 891 
 892 // Type entry used for return from a call. A single cell to record the
 893 // type.
 894 class ReturnTypeEntry : public TypeEntries {
 895 
 896 private:
 897   enum {
 898     cell_count = 1
 899   };
 900 
 901 public:
 902   ReturnTypeEntry(int base_off)
 903     : TypeEntries(base_off) {}
 904 
 905   void post_initialize() {
 906     set_type(type_none());
 907   }
 908 
 909   intptr_t type() const {
 910     return _pd->intptr_at(_base_off);
 911   }
 912 
 913   intptr_t* type_adr() const {
 914     return _pd->intptr_at_adr(_base_off);
 915   }
 916 
 917   void set_type(intptr_t k) {
 918     _pd->set_intptr_at(_base_off, k);
 919   }
 920 
 921   static int static_cell_count() {
 922     return cell_count;
 923   }
 924 
 925   static ByteSize size() {
 926     return in_ByteSize(cell_count * DataLayout::cell_size);
 927   }
 928 
 929   ByteSize type_offset() {
 930     return DataLayout::cell_offset(_base_off);
 931   }
 932 
 933   // GC support
 934   void clean_weak_klass_links(bool always_clean);
 935 
 936   // CDS support
 937   virtual void metaspace_pointers_do(MetaspaceClosure* it);
 938 
 939   void print_data_on(outputStream* st) const;
 940 };
 941 
 942 // Entries to collect type information at a call: contains arguments
 943 // (TypeStackSlotEntries), a return type (ReturnTypeEntry) and a
 944 // number of cells. Because the number of cells for the return type is
 945 // smaller than the number of cells for the type of an arguments, the
 946 // number of cells is used to tell how many arguments are profiled and
 947 // whether a return value is profiled. See has_arguments() and
 948 // has_return().
 949 class TypeEntriesAtCall {
 950 private:
 951   static int stack_slot_local_offset(int i) {
 952     return header_cell_count() + TypeStackSlotEntries::stack_slot_local_offset(i);
 953   }
 954 
 955   static int argument_type_local_offset(int i) {
 956     return header_cell_count() + TypeStackSlotEntries::type_local_offset(i);
 957   }
 958 
 959 public:
 960 
 961   static int header_cell_count() {
 962     return 1;
 963   }
 964 
 965   static int cell_count_local_offset() {
 966     return 0;
 967   }
 968 
 969   static int compute_cell_count(BytecodeStream* stream);
 970 
 971   static void initialize(DataLayout* dl, int base, int cell_count) {
 972     int off = base + cell_count_local_offset();
 973     dl->set_cell_at(off, cell_count - base - header_cell_count());
 974   }
 975 
 976   static bool arguments_profiling_enabled();
 977   static bool return_profiling_enabled();
 978 
 979   // Code generation support
 980   static ByteSize cell_count_offset() {
 981     return in_ByteSize(cell_count_local_offset() * DataLayout::cell_size);
 982   }
 983 
 984   static ByteSize args_data_offset() {
 985     return in_ByteSize(header_cell_count() * DataLayout::cell_size);
 986   }
 987 
 988   static ByteSize stack_slot_offset(int i) {
 989     return in_ByteSize(stack_slot_local_offset(i) * DataLayout::cell_size);
 990   }
 991 
 992   static ByteSize argument_type_offset(int i) {
 993     return in_ByteSize(argument_type_local_offset(i) * DataLayout::cell_size);
 994   }
 995 
 996   static ByteSize return_only_size() {
 997     return ReturnTypeEntry::size() + in_ByteSize(header_cell_count() * DataLayout::cell_size);
 998   }
 999 
1000 };
1001 
1002 // CallTypeData
1003 //
1004 // A CallTypeData is used to access profiling information about a non
1005 // virtual call for which we collect type information about arguments
1006 // and return value.
1007 class CallTypeData : public CounterData {
1008 private:
1009   // entries for arguments if any
1010   TypeStackSlotEntries _args;
1011   // entry for return type if any
1012   ReturnTypeEntry _ret;
1013 
1014   int cell_count_global_offset() const {
1015     return CounterData::static_cell_count() + TypeEntriesAtCall::cell_count_local_offset();
1016   }
1017 
1018   // number of cells not counting the header
1019   int cell_count_no_header() const {
1020     return uint_at(cell_count_global_offset());
1021   }
1022 
1023   void check_number_of_arguments(int total) {
1024     assert(number_of_arguments() == total, "should be set in DataLayout::initialize");
1025   }
1026 
1027 public:
1028   CallTypeData(DataLayout* layout) :
1029     CounterData(layout),
1030     _args(CounterData::static_cell_count()+TypeEntriesAtCall::header_cell_count(), number_of_arguments()),
1031     _ret(cell_count() - ReturnTypeEntry::static_cell_count())
1032   {
1033     assert(layout->tag() == DataLayout::call_type_data_tag, "wrong type");
1034     // Some compilers (VC++) don't want this passed in member initialization list
1035     _args.set_profile_data(this);
1036     _ret.set_profile_data(this);
1037   }
1038 
1039   const TypeStackSlotEntries* args() const {
1040     assert(has_arguments(), "no profiling of arguments");
1041     return &_args;
1042   }
1043 
1044   const ReturnTypeEntry* ret() const {
1045     assert(has_return(), "no profiling of return value");
1046     return &_ret;
1047   }
1048 
1049   virtual bool is_CallTypeData() const { return true; }
1050 
1051   static int static_cell_count() {
1052     return -1;
1053   }
1054 
1055   static int compute_cell_count(BytecodeStream* stream) {
1056     return CounterData::static_cell_count() + TypeEntriesAtCall::compute_cell_count(stream);
1057   }
1058 
1059   static void initialize(DataLayout* dl, int cell_count) {
1060     TypeEntriesAtCall::initialize(dl, CounterData::static_cell_count(), cell_count);
1061   }
1062 
1063   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo);
1064 
1065   virtual int cell_count() const {
1066     return CounterData::static_cell_count() +
1067       TypeEntriesAtCall::header_cell_count() +
1068       int_at_unchecked(cell_count_global_offset());
1069   }
1070 
1071   int number_of_arguments() const {
1072     return cell_count_no_header() / TypeStackSlotEntries::per_arg_count();
1073   }
1074 
1075   void set_argument_type(int i, Klass* k) {
1076     assert(has_arguments(), "no arguments!");
1077     intptr_t current = _args.type(i);
1078     _args.set_type(i, TypeEntries::with_status(k, current));
1079   }
1080 
1081   void set_return_type(Klass* k) {
1082     assert(has_return(), "no return!");
1083     intptr_t current = _ret.type();
1084     _ret.set_type(TypeEntries::with_status(k, current));
1085   }
1086 
1087   // An entry for a return value takes less space than an entry for an
1088   // argument so if the number of cells exceeds the number of cells
1089   // needed for an argument, this object contains type information for
1090   // at least one argument.
1091   bool has_arguments() const {
1092     bool res = cell_count_no_header() >= TypeStackSlotEntries::per_arg_count();
1093     assert (!res || TypeEntriesAtCall::arguments_profiling_enabled(), "no profiling of arguments");
1094     return res;
1095   }
1096 
1097   // An entry for a return value takes less space than an entry for an
1098   // argument, so if the remainder of the number of cells divided by
1099   // the number of cells for an argument is not null, a return value
1100   // is profiled in this object.
1101   bool has_return() const {
1102     bool res = (cell_count_no_header() % TypeStackSlotEntries::per_arg_count()) != 0;
1103     assert (!res || TypeEntriesAtCall::return_profiling_enabled(), "no profiling of return values");
1104     return res;
1105   }
1106 
1107   // Code generation support
1108   static ByteSize args_data_offset() {
1109     return cell_offset(CounterData::static_cell_count()) + TypeEntriesAtCall::args_data_offset();
1110   }
1111 
1112   ByteSize argument_type_offset(int i) {
1113     return _args.type_offset(i);
1114   }
1115 
1116   ByteSize return_type_offset() {
1117     return _ret.type_offset();
1118   }
1119 
1120   // GC support
1121   virtual void clean_weak_klass_links(bool always_clean) {
1122     if (has_arguments()) {
1123       _args.clean_weak_klass_links(always_clean);
1124     }
1125     if (has_return()) {
1126       _ret.clean_weak_klass_links(always_clean);
1127     }
1128   }
1129 
1130   // CDS support
1131   virtual void metaspace_pointers_do(MetaspaceClosure* it) {
1132     if (has_arguments()) {
1133       _args.metaspace_pointers_do(it);
1134     }
1135     if (has_return()) {
1136       _ret.metaspace_pointers_do(it);
1137     }
1138   }
1139 
1140   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1141 };
1142 
1143 // ReceiverTypeData
1144 //
1145 // A ReceiverTypeData is used to access profiling information about a
1146 // dynamic type check.  It consists of a series of (Klass*, count)
1147 // pairs which are used to store a type profile for the receiver of
1148 // the check, the associated count is incremented every time the type
1149 // is seen. A per ReceiverTypeData counter is incremented on type
1150 // overflow (when there's no more room for a not yet profiled Klass*).
1151 //
1152 // Updated by platform-specific code, for example MacroAssembler::profile_receiver_type.
1153 //
1154 class ReceiverTypeData : public CounterData {
1155   friend class VMStructs;
1156   friend class JVMCIVMStructs;
1157 protected:
1158   enum {
1159     receiver0_offset = counter_cell_count,
1160     count0_offset,
1161     receiver_type_row_cell_count = (count0_offset + 1) - receiver0_offset
1162   };
1163 
1164 public:
1165   ReceiverTypeData(DataLayout* layout) : CounterData(layout) {
1166     assert(layout->tag() == DataLayout::receiver_type_data_tag ||
1167            layout->tag() == DataLayout::virtual_call_data_tag ||
1168            layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1169   }
1170 
1171   virtual bool is_ReceiverTypeData() const { return true; }
1172 
1173   static int static_cell_count() {
1174     return counter_cell_count + (uint) TypeProfileWidth * receiver_type_row_cell_count;
1175   }
1176 
1177   virtual int cell_count() const {
1178     return static_cell_count();
1179   }
1180 
1181   // Direct accessors
1182   static uint row_limit() {
1183     return (uint) TypeProfileWidth;
1184   }
1185   static int receiver_cell_index(uint row) {
1186     return receiver0_offset + row * receiver_type_row_cell_count;
1187   }
1188   static int receiver_count_cell_index(uint row) {
1189     return count0_offset + row * receiver_type_row_cell_count;
1190   }
1191 
1192   Klass* receiver(uint row) const {
1193     assert(row < row_limit(), "oob");
1194 
1195     Klass* recv = (Klass*)intptr_at(receiver_cell_index(row));
1196     assert(recv == nullptr || recv->is_klass(), "wrong type");
1197     return recv;
1198   }
1199 
1200   void set_receiver(uint row, Klass* k) {
1201     assert((uint)row < row_limit(), "oob");
1202     set_intptr_at(receiver_cell_index(row), (uintptr_t)k);
1203   }
1204 
1205   uint receiver_count(uint row) const {
1206     assert(row < row_limit(), "oob");
1207     return uint_at(receiver_count_cell_index(row));
1208   }
1209 
1210   void set_receiver_count(uint row, uint count) {
1211     assert(row < row_limit(), "oob");
1212     set_uint_at(receiver_count_cell_index(row), count);
1213   }
1214 
1215   void clear_row(uint row) {
1216     assert(row < row_limit(), "oob");
1217     // Clear total count - indicator of polymorphic call site.
1218     // The site may look like as monomorphic after that but
1219     // it allow to have more accurate profiling information because
1220     // there was execution phase change since klasses were unloaded.
1221     // If the site is still polymorphic then MDO will be updated
1222     // to reflect it. But it could be the case that the site becomes
1223     // only bimorphic. Then keeping total count not 0 will be wrong.
1224     // Even if we use monomorphic (when it is not) for compilation
1225     // we will only have trap, deoptimization and recompile again
1226     // with updated MDO after executing method in Interpreter.
1227     // An additional receiver will be recorded in the cleaned row
1228     // during next call execution.
1229     //
1230     // Note: our profiling logic works with empty rows in any slot.
1231     // We do sorting a profiling info (ciCallProfile) for compilation.
1232     //
1233     set_count(0);
1234     set_receiver(row, nullptr);
1235     set_receiver_count(row, 0);
1236   }
1237 
1238   // Code generation support
1239   static ByteSize receiver_offset(uint row) {
1240     return cell_offset(receiver_cell_index(row));
1241   }
1242   static ByteSize receiver_count_offset(uint row) {
1243     return cell_offset(receiver_count_cell_index(row));
1244   }
1245   static ByteSize receiver_type_data_size() {
1246     return cell_offset(static_cell_count());
1247   }
1248 
1249   // GC support
1250   virtual void clean_weak_klass_links(bool always_clean);
1251 
1252   // CDS support
1253   virtual void metaspace_pointers_do(MetaspaceClosure* it);
1254 
1255   void print_receiver_data_on(outputStream* st) const;
1256   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1257 };
1258 
1259 // VirtualCallData
1260 //
1261 // A VirtualCallData is used to access profiling information about a
1262 // virtual call.  For now, it has nothing more than a ReceiverTypeData.
1263 class VirtualCallData : public ReceiverTypeData {
1264 public:
1265   VirtualCallData(DataLayout* layout) : ReceiverTypeData(layout) {
1266     assert(layout->tag() == DataLayout::virtual_call_data_tag ||
1267            layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1268   }
1269 
1270   virtual bool is_VirtualCallData() const { return true; }
1271 
1272   static int static_cell_count() {
1273     // At this point we could add more profile state, e.g., for arguments.
1274     // But for now it's the same size as the base record type.
1275     return ReceiverTypeData::static_cell_count();
1276   }
1277 
1278   virtual int cell_count() const {
1279     return static_cell_count();
1280   }
1281 
1282   // Direct accessors
1283   static ByteSize virtual_call_data_size() {
1284     return cell_offset(static_cell_count());
1285   }
1286 
1287   void print_method_data_on(outputStream* st) const NOT_JVMCI_RETURN;
1288   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1289 };
1290 
1291 // VirtualCallTypeData
1292 //
1293 // A VirtualCallTypeData is used to access profiling information about
1294 // a virtual call for which we collect type information about
1295 // arguments and return value.
1296 class VirtualCallTypeData : public VirtualCallData {
1297 private:
1298   // entries for arguments if any
1299   TypeStackSlotEntries _args;
1300   // entry for return type if any
1301   ReturnTypeEntry _ret;
1302 
1303   int cell_count_global_offset() const {
1304     return VirtualCallData::static_cell_count() + TypeEntriesAtCall::cell_count_local_offset();
1305   }
1306 
1307   // number of cells not counting the header
1308   int cell_count_no_header() const {
1309     return uint_at(cell_count_global_offset());
1310   }
1311 
1312   void check_number_of_arguments(int total) {
1313     assert(number_of_arguments() == total, "should be set in DataLayout::initialize");
1314   }
1315 
1316 public:
1317   VirtualCallTypeData(DataLayout* layout) :
1318     VirtualCallData(layout),
1319     _args(VirtualCallData::static_cell_count()+TypeEntriesAtCall::header_cell_count(), number_of_arguments()),
1320     _ret(cell_count() - ReturnTypeEntry::static_cell_count())
1321   {
1322     assert(layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1323     // Some compilers (VC++) don't want this passed in member initialization list
1324     _args.set_profile_data(this);
1325     _ret.set_profile_data(this);
1326   }
1327 
1328   const TypeStackSlotEntries* args() const {
1329     assert(has_arguments(), "no profiling of arguments");
1330     return &_args;
1331   }
1332 
1333   const ReturnTypeEntry* ret() const {
1334     assert(has_return(), "no profiling of return value");
1335     return &_ret;
1336   }
1337 
1338   virtual bool is_VirtualCallTypeData() const { return true; }
1339 
1340   static int static_cell_count() {
1341     return -1;
1342   }
1343 
1344   static int compute_cell_count(BytecodeStream* stream) {
1345     return VirtualCallData::static_cell_count() + TypeEntriesAtCall::compute_cell_count(stream);
1346   }
1347 
1348   static void initialize(DataLayout* dl, int cell_count) {
1349     TypeEntriesAtCall::initialize(dl, VirtualCallData::static_cell_count(), cell_count);
1350   }
1351 
1352   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo);
1353 
1354   virtual int cell_count() const {
1355     return VirtualCallData::static_cell_count() +
1356       TypeEntriesAtCall::header_cell_count() +
1357       int_at_unchecked(cell_count_global_offset());
1358   }
1359 
1360   int number_of_arguments() const {
1361     return cell_count_no_header() / TypeStackSlotEntries::per_arg_count();
1362   }
1363 
1364   void set_argument_type(int i, Klass* k) {
1365     assert(has_arguments(), "no arguments!");
1366     intptr_t current = _args.type(i);
1367     _args.set_type(i, TypeEntries::with_status(k, current));
1368   }
1369 
1370   void set_return_type(Klass* k) {
1371     assert(has_return(), "no return!");
1372     intptr_t current = _ret.type();
1373     _ret.set_type(TypeEntries::with_status(k, current));
1374   }
1375 
1376   // An entry for a return value takes less space than an entry for an
1377   // argument, so if the remainder of the number of cells divided by
1378   // the number of cells for an argument is not null, a return value
1379   // is profiled in this object.
1380   bool has_return() const {
1381     bool res = (cell_count_no_header() % TypeStackSlotEntries::per_arg_count()) != 0;
1382     assert (!res || TypeEntriesAtCall::return_profiling_enabled(), "no profiling of return values");
1383     return res;
1384   }
1385 
1386   // An entry for a return value takes less space than an entry for an
1387   // argument so if the number of cells exceeds the number of cells
1388   // needed for an argument, this object contains type information for
1389   // at least one argument.
1390   bool has_arguments() const {
1391     bool res = cell_count_no_header() >= TypeStackSlotEntries::per_arg_count();
1392     assert (!res || TypeEntriesAtCall::arguments_profiling_enabled(), "no profiling of arguments");
1393     return res;
1394   }
1395 
1396   // Code generation support
1397   static ByteSize args_data_offset() {
1398     return cell_offset(VirtualCallData::static_cell_count()) + TypeEntriesAtCall::args_data_offset();
1399   }
1400 
1401   ByteSize argument_type_offset(int i) {
1402     return _args.type_offset(i);
1403   }
1404 
1405   ByteSize return_type_offset() {
1406     return _ret.type_offset();
1407   }
1408 
1409   // GC support
1410   virtual void clean_weak_klass_links(bool always_clean) {
1411     ReceiverTypeData::clean_weak_klass_links(always_clean);
1412     if (has_arguments()) {
1413       _args.clean_weak_klass_links(always_clean);
1414     }
1415     if (has_return()) {
1416       _ret.clean_weak_klass_links(always_clean);
1417     }
1418   }
1419 
1420   // CDS support
1421   virtual void metaspace_pointers_do(MetaspaceClosure* it) {
1422     ReceiverTypeData::metaspace_pointers_do(it);
1423     if (has_arguments()) {
1424       _args.metaspace_pointers_do(it);
1425     }
1426     if (has_return()) {
1427       _ret.metaspace_pointers_do(it);
1428     }
1429   }
1430 
1431   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1432 };
1433 
1434 // RetData
1435 //
1436 // A RetData is used to access profiling information for a ret bytecode.
1437 // It is composed of a count of the number of times that the ret has
1438 // been executed, followed by a series of triples of the form
1439 // (bci, count, di) which count the number of times that some bci was the
1440 // target of the ret and cache a corresponding data displacement.
1441 class RetData : public CounterData {
1442 protected:
1443   enum {
1444     bci0_offset = counter_cell_count,
1445     count0_offset,
1446     displacement0_offset,
1447     ret_row_cell_count = (displacement0_offset + 1) - bci0_offset
1448   };
1449 
1450   void set_bci(uint row, int bci) {
1451     assert((uint)row < row_limit(), "oob");
1452     set_int_at(bci0_offset + row * ret_row_cell_count, bci);
1453   }
1454   void release_set_bci(uint row, int bci);
1455   void set_bci_count(uint row, uint count) {
1456     assert((uint)row < row_limit(), "oob");
1457     set_uint_at(count0_offset + row * ret_row_cell_count, count);
1458   }
1459   void set_bci_displacement(uint row, int disp) {
1460     set_int_at(displacement0_offset + row * ret_row_cell_count, disp);
1461   }
1462 
1463 public:
1464   RetData(DataLayout* layout) : CounterData(layout) {
1465     assert(layout->tag() == DataLayout::ret_data_tag, "wrong type");
1466   }
1467 
1468   virtual bool is_RetData() const { return true; }
1469 
1470   enum {
1471     no_bci = -1 // value of bci when bci1/2 are not in use.
1472   };
1473 
1474   static int static_cell_count() {
1475     return counter_cell_count + (uint) BciProfileWidth * ret_row_cell_count;
1476   }
1477 
1478   virtual int cell_count() const {
1479     return static_cell_count();
1480   }
1481 
1482   static uint row_limit() {
1483     return (uint) BciProfileWidth;
1484   }
1485   static int bci_cell_index(uint row) {
1486     return bci0_offset + row * ret_row_cell_count;
1487   }
1488   static int bci_count_cell_index(uint row) {
1489     return count0_offset + row * ret_row_cell_count;
1490   }
1491   static int bci_displacement_cell_index(uint row) {
1492     return displacement0_offset + row * ret_row_cell_count;
1493   }
1494 
1495   // Direct accessors
1496   int bci(uint row) const {
1497     return int_at(bci_cell_index(row));
1498   }
1499   uint bci_count(uint row) const {
1500     return uint_at(bci_count_cell_index(row));
1501   }
1502   int bci_displacement(uint row) const {
1503     return int_at(bci_displacement_cell_index(row));
1504   }
1505 
1506   // Interpreter Runtime support
1507   address fixup_ret(int return_bci, MethodData* mdo);
1508 
1509   // Code generation support
1510   static ByteSize bci_offset(uint row) {
1511     return cell_offset(bci_cell_index(row));
1512   }
1513   static ByteSize bci_count_offset(uint row) {
1514     return cell_offset(bci_count_cell_index(row));
1515   }
1516   static ByteSize bci_displacement_offset(uint row) {
1517     return cell_offset(bci_displacement_cell_index(row));
1518   }
1519 
1520   // Specific initialization.
1521   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1522 
1523   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1524 };
1525 
1526 // BranchData
1527 //
1528 // A BranchData is used to access profiling data for a two-way branch.
1529 // It consists of taken and not_taken counts as well as a data displacement
1530 // for the taken case.
1531 class BranchData : public JumpData {
1532   friend class VMStructs;
1533   friend class JVMCIVMStructs;
1534 protected:
1535   enum {
1536     not_taken_off_set = jump_cell_count,
1537     branch_cell_count
1538   };
1539 
1540   void set_displacement(int displacement) {
1541     set_int_at(displacement_off_set, displacement);
1542   }
1543 
1544 public:
1545   BranchData(DataLayout* layout) : JumpData(layout) {
1546     assert(layout->tag() == DataLayout::branch_data_tag, "wrong type");
1547   }
1548 
1549   virtual bool is_BranchData() const { return true; }
1550 
1551   static int static_cell_count() {
1552     return branch_cell_count;
1553   }
1554 
1555   virtual int cell_count() const {
1556     return static_cell_count();
1557   }
1558 
1559   // Direct accessor
1560   uint not_taken() const {
1561     return uint_at(not_taken_off_set);
1562   }
1563 
1564   void set_not_taken(uint cnt) {
1565     set_uint_at(not_taken_off_set, cnt);
1566   }
1567 
1568   uint inc_not_taken() {
1569     uint cnt = not_taken() + 1;
1570     // Did we wrap? Will compiler screw us??
1571     if (cnt == 0) cnt--;
1572     set_uint_at(not_taken_off_set, cnt);
1573     return cnt;
1574   }
1575 
1576   // Code generation support
1577   static ByteSize not_taken_offset() {
1578     return cell_offset(not_taken_off_set);
1579   }
1580   static ByteSize branch_data_size() {
1581     return cell_offset(branch_cell_count);
1582   }
1583 
1584   // Specific initialization.
1585   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1586 
1587   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1588 };
1589 
1590 // ArrayData
1591 //
1592 // A ArrayData is a base class for accessing profiling data which does
1593 // not have a statically known size.  It consists of an array length
1594 // and an array start.
1595 class ArrayData : public ProfileData {
1596   friend class VMStructs;
1597   friend class JVMCIVMStructs;
1598 protected:
1599   friend class DataLayout;
1600 
1601   enum {
1602     array_len_off_set,
1603     array_start_off_set
1604   };
1605 
1606   uint array_uint_at(int index) const {
1607     int aindex = index + array_start_off_set;
1608     return uint_at(aindex);
1609   }
1610   int array_int_at(int index) const {
1611     int aindex = index + array_start_off_set;
1612     return int_at(aindex);
1613   }
1614   void array_set_int_at(int index, int value) {
1615     int aindex = index + array_start_off_set;
1616     set_int_at(aindex, value);
1617   }
1618 
1619   // Code generation support for subclasses.
1620   static ByteSize array_element_offset(int index) {
1621     return cell_offset(array_start_off_set + index);
1622   }
1623 
1624 public:
1625   ArrayData(DataLayout* layout) : ProfileData(layout) {}
1626 
1627   virtual bool is_ArrayData() const { return true; }
1628 
1629   static int static_cell_count() {
1630     return -1;
1631   }
1632 
1633   int array_len() const {
1634     return int_at_unchecked(array_len_off_set);
1635   }
1636 
1637   virtual int cell_count() const {
1638     return array_len() + 1;
1639   }
1640 
1641   // Code generation support
1642   static ByteSize array_len_offset() {
1643     return cell_offset(array_len_off_set);
1644   }
1645   static ByteSize array_start_offset() {
1646     return cell_offset(array_start_off_set);
1647   }
1648 };
1649 
1650 // MultiBranchData
1651 //
1652 // A MultiBranchData is used to access profiling information for
1653 // a multi-way branch (*switch bytecodes).  It consists of a series
1654 // of (count, displacement) pairs, which count the number of times each
1655 // case was taken and specify the data displacement for each branch target.
1656 class MultiBranchData : public ArrayData {
1657   friend class VMStructs;
1658   friend class JVMCIVMStructs;
1659 protected:
1660   enum {
1661     default_count_off_set,
1662     default_disaplacement_off_set,
1663     case_array_start
1664   };
1665   enum {
1666     relative_count_off_set,
1667     relative_displacement_off_set,
1668     per_case_cell_count
1669   };
1670 
1671   void set_default_displacement(int displacement) {
1672     array_set_int_at(default_disaplacement_off_set, displacement);
1673   }
1674   void set_displacement_at(int index, int displacement) {
1675     array_set_int_at(case_array_start +
1676                      index * per_case_cell_count +
1677                      relative_displacement_off_set,
1678                      displacement);
1679   }
1680 
1681 public:
1682   MultiBranchData(DataLayout* layout) : ArrayData(layout) {
1683     assert(layout->tag() == DataLayout::multi_branch_data_tag, "wrong type");
1684   }
1685 
1686   virtual bool is_MultiBranchData() const { return true; }
1687 
1688   static int compute_cell_count(BytecodeStream* stream);
1689 
1690   int number_of_cases() const {
1691     int alen = array_len() - 2; // get rid of default case here.
1692     assert(alen % per_case_cell_count == 0, "must be even");
1693     return (alen / per_case_cell_count);
1694   }
1695 
1696   uint default_count() const {
1697     return array_uint_at(default_count_off_set);
1698   }
1699   int default_displacement() const {
1700     return array_int_at(default_disaplacement_off_set);
1701   }
1702 
1703   uint count_at(int index) const {
1704     return array_uint_at(case_array_start +
1705                          index * per_case_cell_count +
1706                          relative_count_off_set);
1707   }
1708   int displacement_at(int index) const {
1709     return array_int_at(case_array_start +
1710                         index * per_case_cell_count +
1711                         relative_displacement_off_set);
1712   }
1713 
1714   // Code generation support
1715   static ByteSize default_count_offset() {
1716     return array_element_offset(default_count_off_set);
1717   }
1718   static ByteSize default_displacement_offset() {
1719     return array_element_offset(default_disaplacement_off_set);
1720   }
1721   static ByteSize case_count_offset(int index) {
1722     return case_array_offset() +
1723            (per_case_size() * index) +
1724            relative_count_offset();
1725   }
1726   static ByteSize case_array_offset() {
1727     return array_element_offset(case_array_start);
1728   }
1729   static ByteSize per_case_size() {
1730     return in_ByteSize(per_case_cell_count) * cell_size;
1731   }
1732   static ByteSize relative_count_offset() {
1733     return in_ByteSize(relative_count_off_set) * cell_size;
1734   }
1735   static ByteSize relative_displacement_offset() {
1736     return in_ByteSize(relative_displacement_off_set) * cell_size;
1737   }
1738 
1739   // Specific initialization.
1740   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1741 
1742   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1743 };
1744 
1745 class ArgInfoData : public ArrayData {
1746 
1747 public:
1748   ArgInfoData(DataLayout* layout) : ArrayData(layout) {
1749     assert(layout->tag() == DataLayout::arg_info_data_tag, "wrong type");
1750   }
1751 
1752   virtual bool is_ArgInfoData() const { return true; }
1753 
1754 
1755   int size_of_args() const {
1756     return array_len();
1757   }
1758 
1759   uint arg_modified(int arg) const {
1760     return array_uint_at(arg);
1761   }
1762 
1763   void set_arg_modified(int arg, uint val) {
1764     array_set_int_at(arg, val);
1765   }
1766 
1767   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1768 };
1769 
1770 // ParametersTypeData
1771 //
1772 // A ParametersTypeData is used to access profiling information about
1773 // types of parameters to a method
1774 class ParametersTypeData : public ArrayData {
1775 
1776 private:
1777   TypeStackSlotEntries _parameters;
1778 
1779   static int stack_slot_local_offset(int i) {
1780     assert_profiling_enabled();
1781     return array_start_off_set + TypeStackSlotEntries::stack_slot_local_offset(i);
1782   }
1783 
1784   static int type_local_offset(int i) {
1785     assert_profiling_enabled();
1786     return array_start_off_set + TypeStackSlotEntries::type_local_offset(i);
1787   }
1788 
1789   static bool profiling_enabled();
1790   static void assert_profiling_enabled() {
1791     assert(profiling_enabled(), "method parameters profiling should be on");
1792   }
1793 
1794 public:
1795   ParametersTypeData(DataLayout* layout) : ArrayData(layout), _parameters(1, number_of_parameters()) {
1796     assert(layout->tag() == DataLayout::parameters_type_data_tag, "wrong type");
1797     // Some compilers (VC++) don't want this passed in member initialization list
1798     _parameters.set_profile_data(this);
1799   }
1800 
1801   static int compute_cell_count(Method* m);
1802 
1803   virtual bool is_ParametersTypeData() const { return true; }
1804 
1805   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo);
1806 
1807   int number_of_parameters() const {
1808     return array_len() / TypeStackSlotEntries::per_arg_count();
1809   }
1810 
1811   const TypeStackSlotEntries* parameters() const { return &_parameters; }
1812 
1813   uint stack_slot(int i) const {
1814     return _parameters.stack_slot(i);
1815   }
1816 
1817   void set_type(int i, Klass* k) {
1818     intptr_t current = _parameters.type(i);
1819     _parameters.set_type(i, TypeEntries::with_status((intptr_t)k, current));
1820   }
1821 
1822   virtual void clean_weak_klass_links(bool always_clean) {
1823     _parameters.clean_weak_klass_links(always_clean);
1824   }
1825 
1826   // CDS support
1827   virtual void metaspace_pointers_do(MetaspaceClosure* it) {
1828     _parameters.metaspace_pointers_do(it);
1829   }
1830 
1831   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1832 
1833   static ByteSize stack_slot_offset(int i) {
1834     return cell_offset(stack_slot_local_offset(i));
1835   }
1836 
1837   static ByteSize type_offset(int i) {
1838     return cell_offset(type_local_offset(i));
1839   }
1840 };
1841 
1842 // SpeculativeTrapData
1843 //
1844 // A SpeculativeTrapData is used to record traps due to type
1845 // speculation. It records the root of the compilation: that type
1846 // speculation is wrong in the context of one compilation (for
1847 // method1) doesn't mean it's wrong in the context of another one (for
1848 // method2). Type speculation could have more/different data in the
1849 // context of the compilation of method2 and it's worthwhile to try an
1850 // optimization that failed for compilation of method1 in the context
1851 // of compilation of method2.
1852 // Space for SpeculativeTrapData entries is allocated from the extra
1853 // data space in the MDO. If we run out of space, the trap data for
1854 // the ProfileData at that bci is updated.
1855 class SpeculativeTrapData : public ProfileData {
1856 protected:
1857   enum {
1858     speculative_trap_method,
1859 #ifndef _LP64
1860     // The size of the area for traps is a multiple of the header
1861     // size, 2 cells on 32 bits. Packed at the end of this area are
1862     // argument info entries (with tag
1863     // DataLayout::arg_info_data_tag). The logic in
1864     // MethodData::bci_to_extra_data() that guarantees traps don't
1865     // overflow over argument info entries assumes the size of a
1866     // SpeculativeTrapData is twice the header size. On 32 bits, a
1867     // SpeculativeTrapData must be 4 cells.
1868     padding,
1869 #endif
1870     speculative_trap_cell_count
1871   };
1872 public:
1873   SpeculativeTrapData(DataLayout* layout) : ProfileData(layout) {
1874     assert(layout->tag() == DataLayout::speculative_trap_data_tag, "wrong type");
1875   }
1876 
1877   virtual bool is_SpeculativeTrapData() const { return true; }
1878 
1879   static int static_cell_count() {
1880     return speculative_trap_cell_count;
1881   }
1882 
1883   virtual int cell_count() const {
1884     return static_cell_count();
1885   }
1886 
1887   // Direct accessor
1888   Method* method() const {
1889     return (Method*)intptr_at(speculative_trap_method);
1890   }
1891 
1892   void set_method(Method* m) {
1893     assert(!m->is_old(), "cannot add old methods");
1894     set_intptr_at(speculative_trap_method, (intptr_t)m);
1895   }
1896 
1897   static ByteSize method_offset() {
1898     return cell_offset(speculative_trap_method);
1899   }
1900 
1901   // CDS support
1902   virtual void metaspace_pointers_do(MetaspaceClosure* it);
1903 
1904   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1905 };
1906 
1907 // MethodData*
1908 //
1909 // A MethodData* holds information which has been collected about
1910 // a method.  Its layout looks like this:
1911 //
1912 // -----------------------------
1913 // | header                    |
1914 // | klass                     |
1915 // -----------------------------
1916 // | method                    |
1917 // | size of the MethodData* |
1918 // -----------------------------
1919 // | Data entries...           |
1920 // |   (variable size)         |
1921 // |                           |
1922 // .                           .
1923 // .                           .
1924 // .                           .
1925 // |                           |
1926 // -----------------------------
1927 //
1928 // The data entry area is a heterogeneous array of DataLayouts. Each
1929 // DataLayout in the array corresponds to a specific bytecode in the
1930 // method.  The entries in the array are sorted by the corresponding
1931 // bytecode.  Access to the data is via resource-allocated ProfileData,
1932 // which point to the underlying blocks of DataLayout structures.
1933 //
1934 // During interpretation, if profiling in enabled, the interpreter
1935 // maintains a method data pointer (mdp), which points at the entry
1936 // in the array corresponding to the current bci.  In the course of
1937 // interpretation, when a bytecode is encountered that has profile data
1938 // associated with it, the entry pointed to by mdp is updated, then the
1939 // mdp is adjusted to point to the next appropriate DataLayout.  If mdp
1940 // is null to begin with, the interpreter assumes that the current method
1941 // is not (yet) being profiled.
1942 //
1943 // In MethodData* parlance, "dp" is a "data pointer", the actual address
1944 // of a DataLayout element.  A "di" is a "data index", the offset in bytes
1945 // from the base of the data entry array.  A "displacement" is the byte offset
1946 // in certain ProfileData objects that indicate the amount the mdp must be
1947 // adjusted in the event of a change in control flow.
1948 //
1949 
1950 class CleanExtraDataClosure : public StackObj {
1951 public:
1952   virtual bool is_live(Method* m) = 0;
1953 };
1954 
1955 
1956 #if INCLUDE_JVMCI
1957 // Encapsulates an encoded speculation reason. These are linked together in
1958 // a list that is atomically appended to during deoptimization. Entries are
1959 // never removed from the list.
1960 // @see jdk.vm.ci.hotspot.HotSpotSpeculationLog.HotSpotSpeculationEncoding
1961 class FailedSpeculation: public CHeapObj<mtCompiler> {
1962  private:
1963   // The length of HotSpotSpeculationEncoding.toByteArray(). The data itself
1964   // is an array embedded at the end of this object.
1965   int   _data_len;
1966 
1967   // Next entry in a linked list.
1968   FailedSpeculation* _next;
1969 
1970   FailedSpeculation(address data, int data_len);
1971 
1972   FailedSpeculation** next_adr() { return &_next; }
1973 
1974   // Placement new operator for inlining the speculation data into
1975   // the FailedSpeculation object.
1976   void* operator new(size_t size, size_t fs_size) throw();
1977 
1978  public:
1979   char* data()         { return (char*)(((address) this) + sizeof(FailedSpeculation)); }
1980   int data_len() const { return _data_len; }
1981   FailedSpeculation* next() const { return _next; }
1982 
1983   // Atomically appends a speculation from nm to the list whose head is at (*failed_speculations_address).
1984   // Returns false if the FailedSpeculation object could not be allocated.
1985   static bool add_failed_speculation(nmethod* nm, FailedSpeculation** failed_speculations_address, address speculation, int speculation_len);
1986 
1987   // Frees all entries in the linked list whose head is at (*failed_speculations_address).
1988   static void free_failed_speculations(FailedSpeculation** failed_speculations_address);
1989 };
1990 #endif
1991 
1992 class ciMethodData;
1993 
1994 class MethodData : public Metadata {
1995   friend class VMStructs;
1996   friend class JVMCIVMStructs;
1997   friend class ProfileData;
1998   friend class TypeEntriesAtCall;
1999   friend class ciMethodData;
2000   friend class VM_ReinitializeMDO;
2001 
2002   // If you add a new field that points to any metaspace object, you
2003   // must add this field to MethodData::metaspace_pointers_do().
2004 
2005   // Back pointer to the Method*
2006   Method* _method;
2007 
2008   // Size of this oop in bytes
2009   int _size;
2010 
2011   // Cached hint for bci_to_dp and bci_to_data
2012   int _hint_di;
2013 
2014   Mutex* volatile _extra_data_lock;
2015 
2016   MethodData(const methodHandle& method);
2017 
2018   void initialize();
2019 
2020 public:
2021   MethodData();
2022 
2023   static MethodData* allocate(ClassLoaderData* loader_data, const methodHandle& method, TRAPS);
2024 
2025   virtual bool is_methodData() const { return true; }
2026 
2027   // Safely reinitialize the data in the MDO.  This is intended as a testing facility as the
2028   // reinitialization is performed at a safepoint so it's isn't cheap and it doesn't ensure that all
2029   // readers will see consistent profile data.
2030   void reinitialize();
2031 
2032   // Whole-method sticky bits and flags
2033   enum {
2034     _trap_hist_limit    = Deoptimization::Reason_TRAP_HISTORY_LENGTH,
2035     _trap_hist_mask     = max_jubyte,
2036     _extra_data_count   = 4     // extra DataLayout headers, for trap history
2037   }; // Public flag values
2038 
2039   // Compiler-related counters.
2040   class CompilerCounters {
2041     friend class VMStructs;
2042     friend class JVMCIVMStructs;
2043 
2044     uint _nof_decompiles;             // count of all nmethod removals
2045     uint _nof_overflow_recompiles;    // recompile count, excluding recomp. bits
2046     uint _nof_overflow_traps;         // trap count, excluding _trap_hist
2047     union {
2048       intptr_t _align;
2049       // JVMCI separates trap history for OSR compilations from normal compilations
2050       u1 _array[JVMCI_ONLY(2 *) MethodData::_trap_hist_limit];
2051     } _trap_hist;
2052 
2053   public:
2054     CompilerCounters() : _nof_decompiles(0), _nof_overflow_recompiles(0), _nof_overflow_traps(0) {
2055 #ifndef ZERO
2056       // Some Zero platforms do not have expected alignment, and do not use
2057       // this code. static_assert would still fire and fail for them.
2058       static_assert(sizeof(_trap_hist) % HeapWordSize == 0, "align");
2059 #endif
2060       uint size_in_words = sizeof(_trap_hist) / HeapWordSize;
2061       Copy::zero_to_words((HeapWord*) &_trap_hist, size_in_words);
2062     }
2063 
2064     // Return (uint)-1 for overflow.
2065     uint trap_count(int reason) const {
2066       assert((uint)reason < ARRAY_SIZE(_trap_hist._array), "oob");
2067       return (int)((_trap_hist._array[reason]+1) & _trap_hist_mask) - 1;
2068     }
2069 
2070     uint inc_trap_count(int reason) {
2071       // Count another trap, anywhere in this method.
2072       assert(reason >= 0, "must be single trap");
2073       assert((uint)reason < ARRAY_SIZE(_trap_hist._array), "oob");
2074       uint cnt1 = 1 + _trap_hist._array[reason];
2075       if ((cnt1 & _trap_hist_mask) != 0) {  // if no counter overflow...
2076         _trap_hist._array[reason] = (u1)cnt1;
2077         return cnt1;
2078       } else {
2079         return _trap_hist_mask + (++_nof_overflow_traps);
2080       }
2081     }
2082 
2083     uint overflow_trap_count() const {
2084       return _nof_overflow_traps;
2085     }
2086     uint overflow_recompile_count() const {
2087       return _nof_overflow_recompiles;
2088     }
2089     uint inc_overflow_recompile_count() {
2090       return ++_nof_overflow_recompiles;
2091     }
2092     uint decompile_count() const {
2093       return _nof_decompiles;
2094     }
2095     uint inc_decompile_count() {
2096       return ++_nof_decompiles;
2097     }
2098 
2099     // Support for code generation
2100     static ByteSize trap_history_offset() {
2101       return byte_offset_of(CompilerCounters, _trap_hist._array);
2102     }
2103   };
2104 
2105 private:
2106   CompilerCounters _compiler_counters;
2107 
2108   // Support for interprocedural escape analysis, from Thomas Kotzmann.
2109   intx              _eflags;          // flags on escape information
2110   intx              _arg_local;       // bit set of non-escaping arguments
2111   intx              _arg_stack;       // bit set of stack-allocatable arguments
2112   intx              _arg_returned;    // bit set of returned arguments
2113 
2114   // How many invocations has this MDO seen?
2115   // These counters are used to determine the exact age of MDO.
2116   // We need those because in tiered a method can be concurrently
2117   // executed at different levels.
2118   InvocationCounter _invocation_counter;
2119   // Same for backedges.
2120   InvocationCounter _backedge_counter;
2121   // Counter values at the time profiling started.
2122   int               _invocation_counter_start;
2123   int               _backedge_counter_start;
2124   uint              _tenure_traps;
2125   int               _invoke_mask;      // per-method Tier0InvokeNotifyFreqLog
2126   int               _backedge_mask;    // per-method Tier0BackedgeNotifyFreqLog
2127 
2128   // Number of loops and blocks is computed when compiling the first
2129   // time with C1. It is used to determine if method is trivial.
2130   short             _num_loops;
2131   short             _num_blocks;
2132   // Does this method contain anything worth profiling?
2133   enum WouldProfile {unknown, no_profile, profile};
2134   WouldProfile      _would_profile;
2135 
2136 #if INCLUDE_JVMCI
2137   // Support for HotSpotMethodData.setCompiledIRSize(int)
2138   FailedSpeculation* _failed_speculations;
2139   int                _jvmci_ir_size;
2140 #endif
2141 
2142   // Size of _data array in bytes.  (Excludes header and extra_data fields.)
2143   int _data_size;
2144 
2145   // data index for the area dedicated to parameters. -1 if no
2146   // parameter profiling.
2147   enum { no_parameters = -2, parameters_uninitialized = -1 };
2148   int _parameters_type_data_di;
2149 
2150   // data index of exception handler profiling data
2151   int _exception_handler_data_di;
2152 
2153   // Beginning of the data entries
2154   // See comment in ciMethodData::load_data
2155   intptr_t _data[1];
2156 
2157   // Helper for size computation
2158   static int compute_data_size(BytecodeStream* stream);
2159   static int bytecode_cell_count(Bytecodes::Code code);
2160   static bool is_speculative_trap_bytecode(Bytecodes::Code code);
2161   enum { no_profile_data = -1, variable_cell_count = -2 };
2162 
2163   // Helper for initialization
2164   DataLayout* data_layout_at(int data_index) const {
2165     assert(data_index % sizeof(intptr_t) == 0, "unaligned");
2166     return (DataLayout*) (((address)_data) + data_index);
2167   }
2168 
2169   static int single_exception_handler_data_cell_count() {
2170     return BitData::static_cell_count();
2171   }
2172 
2173   static int single_exception_handler_data_size() {
2174     return DataLayout::compute_size_in_bytes(single_exception_handler_data_cell_count());
2175   }
2176 
2177   DataLayout* exception_handler_data_at(int exception_handler_index) const {
2178     return data_layout_at(_exception_handler_data_di + (exception_handler_index * single_exception_handler_data_size()));
2179   }
2180 
2181   int num_exception_handler_data() const {
2182     return exception_handlers_data_size() / single_exception_handler_data_size();
2183   }
2184 
2185   // Initialize an individual data segment.  Returns the size of
2186   // the segment in bytes.
2187   int initialize_data(BytecodeStream* stream, int data_index);
2188 
2189   // Helper for data_at
2190   DataLayout* limit_data_position() const {
2191     return data_layout_at(_data_size);
2192   }
2193   bool out_of_bounds(int data_index) const {
2194     return data_index >= data_size();
2195   }
2196 
2197   // Give each of the data entries a chance to perform specific
2198   // data initialization.
2199   void post_initialize(BytecodeStream* stream);
2200 
2201   // hint accessors
2202   int      hint_di() const  { return _hint_di; }
2203   void set_hint_di(int di)  {
2204     assert(!out_of_bounds(di), "hint_di out of bounds");
2205     _hint_di = di;
2206   }
2207 
2208   DataLayout* data_layout_before(int bci) {
2209     // avoid SEGV on this edge case
2210     if (data_size() == 0)
2211       return nullptr;
2212     DataLayout* layout = data_layout_at(hint_di());
2213     if (layout->bci() <= bci)
2214       return layout;
2215     return data_layout_at(first_di());
2216   }
2217 
2218   // What is the index of the first data entry?
2219   int first_di() const { return 0; }
2220 
2221   ProfileData* bci_to_extra_data_find(int bci, Method* m, DataLayout*& dp);
2222   // Find or create an extra ProfileData:
2223   ProfileData* bci_to_extra_data(int bci, Method* m, bool create_if_missing);
2224 
2225   // return the argument info cell
2226   ArgInfoData *arg_info();
2227 
2228   enum {
2229     no_type_profile = 0,
2230     type_profile_jsr292 = 1,
2231     type_profile_all = 2
2232   };
2233 
2234   static bool profile_jsr292(const methodHandle& m, int bci);
2235   static bool profile_unsafe(const methodHandle& m, int bci);
2236   static bool profile_memory_access(const methodHandle& m, int bci);
2237   static int profile_arguments_flag();
2238   static bool profile_all_arguments();
2239   static bool profile_arguments_for_invoke(const methodHandle& m, int bci);
2240   static int profile_return_flag();
2241   static bool profile_all_return();
2242   static bool profile_return_for_invoke(const methodHandle& m, int bci);
2243   static int profile_parameters_flag();
2244   static bool profile_parameters_jsr292_only();
2245   static bool profile_all_parameters();
2246 
2247   void clean_extra_data_helper(DataLayout* dp, int shift, bool reset = false);
2248   void verify_extra_data_clean(CleanExtraDataClosure* cl);
2249 
2250   DataLayout* exception_handler_bci_to_data_helper(int bci);
2251 
2252 public:
2253   void clean_extra_data(CleanExtraDataClosure* cl);
2254 
2255   static int header_size() {
2256     return sizeof(MethodData)/wordSize;
2257   }
2258 
2259   // Compute the size of a MethodData* before it is created.
2260   static int compute_allocation_size_in_bytes(const methodHandle& method);
2261   static int compute_allocation_size_in_words(const methodHandle& method);
2262   static int compute_extra_data_count(int data_size, int empty_bc_count, bool needs_speculative_traps);
2263 
2264   // Determine if a given bytecode can have profile information.
2265   static bool bytecode_has_profile(Bytecodes::Code code) {
2266     return bytecode_cell_count(code) != no_profile_data;
2267   }
2268 
2269   // reset into original state
2270   void init();
2271 
2272   // My size
2273   int size_in_bytes() const { return _size; }
2274   int size() const    { return align_metadata_size(align_up(_size, BytesPerWord)/BytesPerWord); }
2275 
2276   int invocation_count() {
2277     if (invocation_counter()->carry()) {
2278       return InvocationCounter::count_limit;
2279     }
2280     return invocation_counter()->count();
2281   }
2282   int backedge_count() {
2283     if (backedge_counter()->carry()) {
2284       return InvocationCounter::count_limit;
2285     }
2286     return backedge_counter()->count();
2287   }
2288 
2289   int invocation_count_start() {
2290     if (invocation_counter()->carry()) {
2291       return 0;
2292     }
2293     return _invocation_counter_start;
2294   }
2295 
2296   int backedge_count_start() {
2297     if (backedge_counter()->carry()) {
2298       return 0;
2299     }
2300     return _backedge_counter_start;
2301   }
2302 
2303   int invocation_count_delta() { return invocation_count() - invocation_count_start(); }
2304   int backedge_count_delta()   { return backedge_count()   - backedge_count_start();   }
2305 
2306   void reset_start_counters() {
2307     _invocation_counter_start = invocation_count();
2308     _backedge_counter_start = backedge_count();
2309   }
2310 
2311   InvocationCounter* invocation_counter()     { return &_invocation_counter; }
2312   InvocationCounter* backedge_counter()       { return &_backedge_counter;   }
2313 
2314 #if INCLUDE_JVMCI
2315   FailedSpeculation** get_failed_speculations_address() {
2316     return &_failed_speculations;
2317   }
2318 #endif
2319 
2320 #if INCLUDE_CDS
2321   void remove_unshareable_info();
2322   void restore_unshareable_info(TRAPS);
2323 #endif
2324 
2325   void set_would_profile(bool p)              { _would_profile = p ? profile : no_profile; }
2326   bool would_profile() const                  { return _would_profile != no_profile; }
2327 
2328   int num_loops() const                       { return _num_loops;  }
2329   void set_num_loops(short n)                 { _num_loops = n;     }
2330   int num_blocks() const                      { return _num_blocks; }
2331   void set_num_blocks(short n)                { _num_blocks = n;    }
2332 
2333   bool is_mature() const;
2334 
2335   // Support for interprocedural escape analysis, from Thomas Kotzmann.
2336   enum EscapeFlag {
2337     estimated    = 1 << 0,
2338     return_local = 1 << 1,
2339     return_allocated = 1 << 2,
2340     allocated_escapes = 1 << 3,
2341     unknown_modified = 1 << 4
2342   };
2343 
2344   intx eflags()                                  { return _eflags; }
2345   intx arg_local()                               { return _arg_local; }
2346   intx arg_stack()                               { return _arg_stack; }
2347   intx arg_returned()                            { return _arg_returned; }
2348   uint arg_modified(int a);
2349   void set_eflags(intx v)                        { _eflags = v; }
2350   void set_arg_local(intx v)                     { _arg_local = v; }
2351   void set_arg_stack(intx v)                     { _arg_stack = v; }
2352   void set_arg_returned(intx v)                  { _arg_returned = v; }
2353   void set_arg_modified(int a, uint v);
2354   void clear_escape_info()                       { _eflags = _arg_local = _arg_stack = _arg_returned = 0; }
2355 
2356   // Location and size of data area
2357   address data_base() const {
2358     return (address) _data;
2359   }
2360   int data_size() const {
2361     return _data_size;
2362   }
2363 
2364   int parameters_size_in_bytes() const {
2365     return pointer_delta_as_int((address) parameters_data_limit(), (address) parameters_data_base());
2366   }
2367 
2368   int exception_handlers_data_size() const {
2369     return pointer_delta_as_int((address) exception_handler_data_limit(), (address) exception_handler_data_base());
2370   }
2371 
2372   // Accessors
2373   Method* method() const { return _method; }
2374 
2375   // Get the data at an arbitrary (sort of) data index.
2376   ProfileData* data_at(int data_index) const;
2377 
2378   // Walk through the data in order.
2379   ProfileData* first_data() const { return data_at(first_di()); }
2380   ProfileData* next_data(ProfileData* current) const;
2381   DataLayout*  next_data_layout(DataLayout* current) const;
2382   bool is_valid(ProfileData* current) const { return current != nullptr; }
2383   bool is_valid(DataLayout*  current) const { return current != nullptr; }
2384 
2385   // Convert a dp (data pointer) to a di (data index).
2386   int dp_to_di(address dp) const {
2387     return (int)(dp - ((address)_data));
2388   }
2389 
2390   // bci to di/dp conversion.
2391   address bci_to_dp(int bci);
2392   int bci_to_di(int bci) {
2393     return dp_to_di(bci_to_dp(bci));
2394   }
2395 
2396   // Get the data at an arbitrary bci, or null if there is none.
2397   ProfileData* bci_to_data(int bci);
2398 
2399   // Same, but try to create an extra_data record if one is needed:
2400   ProfileData* allocate_bci_to_data(int bci, Method* m) {
2401     check_extra_data_locked();
2402 
2403     ProfileData* data = nullptr;
2404     // If m not null, try to allocate a SpeculativeTrapData entry
2405     if (m == nullptr) {
2406       data = bci_to_data(bci);
2407     }
2408     if (data != nullptr) {
2409       return data;
2410     }
2411     data = bci_to_extra_data(bci, m, true);
2412     if (data != nullptr) {
2413       return data;
2414     }
2415     // If SpeculativeTrapData allocation fails try to allocate a
2416     // regular entry
2417     data = bci_to_data(bci);
2418     if (data != nullptr) {
2419       return data;
2420     }
2421     return bci_to_extra_data(bci, nullptr, true);
2422   }
2423 
2424   BitData* exception_handler_bci_to_data_or_null(int bci);
2425   BitData exception_handler_bci_to_data(int bci);
2426 
2427   // Add a handful of extra data records, for trap tracking.
2428   // Only valid after 'set_size' is called at the end of MethodData::initialize
2429   DataLayout* extra_data_base() const  {
2430     check_extra_data_locked();
2431     return limit_data_position();
2432   }
2433   DataLayout* extra_data_limit() const { return (DataLayout*)((address)this + size_in_bytes()); }
2434   // pointers to sections in extra data
2435   DataLayout* args_data_limit() const  { return parameters_data_base(); }
2436   DataLayout* parameters_data_base() const {
2437     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2438     return _parameters_type_data_di != no_parameters ? data_layout_at(_parameters_type_data_di) : parameters_data_limit();
2439   }
2440   DataLayout* parameters_data_limit() const {
2441     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2442     return exception_handler_data_base();
2443   }
2444   DataLayout* exception_handler_data_base() const { return data_layout_at(_exception_handler_data_di); }
2445   DataLayout* exception_handler_data_limit() const { return extra_data_limit(); }
2446 
2447   int extra_data_size() const          { return (int)((address)extra_data_limit() - (address)limit_data_position()); }
2448   static DataLayout* next_extra(DataLayout* dp);
2449 
2450   // Return (uint)-1 for overflow.
2451   uint trap_count(int reason) const {
2452     return _compiler_counters.trap_count(reason);
2453   }
2454   // For loops:
2455   static uint trap_reason_limit() { return _trap_hist_limit; }
2456   static uint trap_count_limit()  { return _trap_hist_mask; }
2457   uint inc_trap_count(int reason) {
2458     return _compiler_counters.inc_trap_count(reason);
2459   }
2460 
2461   uint overflow_trap_count() const {
2462     return _compiler_counters.overflow_trap_count();
2463   }
2464   uint overflow_recompile_count() const {
2465     return _compiler_counters.overflow_recompile_count();
2466   }
2467   uint inc_overflow_recompile_count() {
2468     return _compiler_counters.inc_overflow_recompile_count();
2469   }
2470   uint decompile_count() const {
2471     return _compiler_counters.decompile_count();
2472   }
2473   uint inc_decompile_count() {
2474     uint dec_count = _compiler_counters.inc_decompile_count();
2475     if (dec_count > (uint)PerMethodRecompilationCutoff) {
2476       method()->set_not_compilable("decompile_count > PerMethodRecompilationCutoff", CompLevel_full_optimization);
2477     }
2478     return dec_count;
2479   }
2480   uint tenure_traps() const {
2481     return _tenure_traps;
2482   }
2483   void inc_tenure_traps() {
2484     _tenure_traps += 1;
2485   }
2486 
2487   // Return pointer to area dedicated to parameters in MDO
2488   ParametersTypeData* parameters_type_data() const {
2489     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2490     return _parameters_type_data_di != no_parameters ? data_layout_at(_parameters_type_data_di)->data_in()->as_ParametersTypeData() : nullptr;
2491   }
2492 
2493   int parameters_type_data_di() const {
2494     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2495     return _parameters_type_data_di != no_parameters ? _parameters_type_data_di : exception_handlers_data_di();
2496   }
2497 
2498   int exception_handlers_data_di() const {
2499     return _exception_handler_data_di;
2500   }
2501 
2502   // Support for code generation
2503   static ByteSize data_offset() {
2504     return byte_offset_of(MethodData, _data[0]);
2505   }
2506 
2507   static ByteSize trap_history_offset() {
2508     return byte_offset_of(MethodData, _compiler_counters) + CompilerCounters::trap_history_offset();
2509   }
2510 
2511   static ByteSize invocation_counter_offset() {
2512     return byte_offset_of(MethodData, _invocation_counter);
2513   }
2514 
2515   static ByteSize backedge_counter_offset() {
2516     return byte_offset_of(MethodData, _backedge_counter);
2517   }
2518 
2519   static ByteSize invoke_mask_offset() {
2520     return byte_offset_of(MethodData, _invoke_mask);
2521   }
2522 
2523   static ByteSize backedge_mask_offset() {
2524     return byte_offset_of(MethodData, _backedge_mask);
2525   }
2526 
2527   static ByteSize parameters_type_data_di_offset() {
2528     return byte_offset_of(MethodData, _parameters_type_data_di);
2529   }
2530 
2531   virtual void metaspace_pointers_do(MetaspaceClosure* iter);
2532   virtual MetaspaceObj::Type type() const { return MethodDataType; }
2533 
2534   // Deallocation support
2535   void deallocate_contents(ClassLoaderData* loader_data);
2536   void release_C_heap_structures();
2537 
2538   // GC support
2539   void set_size(int object_size_in_bytes) { _size = object_size_in_bytes; }
2540 
2541   // Printing
2542   void print_on      (outputStream* st) const;
2543   void print_value_on(outputStream* st) const;
2544 
2545   // printing support for method data
2546   void print_data_on(outputStream* st) const;
2547 
2548   const char* internal_name() const { return "{method data}"; }
2549 
2550   // verification
2551   void verify_on(outputStream* st);
2552   void verify_data_on(outputStream* st);
2553 
2554   static bool profile_parameters_for_method(const methodHandle& m);
2555   static bool profile_arguments();
2556   static bool profile_arguments_jsr292_only();
2557   static bool profile_return();
2558   static bool profile_parameters();
2559   static bool profile_return_jsr292_only();
2560 
2561   void clean_method_data(bool always_clean);
2562   void clean_weak_method_links();
2563   Mutex* extra_data_lock();
2564   void check_extra_data_locked() const NOT_DEBUG_RETURN;
2565 };
2566 
2567 #endif // SHARE_OOPS_METHODDATA_HPP