1 /*
   2  * Copyright (c) 2000, 2024, 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/atomic.hpp"
  33 #include "runtime/deoptimization.hpp"
  34 #include "runtime/mutex.hpp"
  35 #include "utilities/align.hpp"
  36 #include "utilities/copy.hpp"
  37 
  38 class BytecodeStream;
  39 
  40 // The MethodData object collects counts and other profile information
  41 // during zeroth-tier (interpreter) and third-tier (C1 with full profiling)
  42 // execution.
  43 //
  44 // The profile is used later by compilation heuristics.  Some heuristics
  45 // enable use of aggressive (or "heroic") optimizations.  An aggressive
  46 // optimization often has a down-side, a corner case that it handles
  47 // poorly, but which is thought to be rare.  The profile provides
  48 // evidence of this rarity for a given method or even BCI.  It allows
  49 // the compiler to back out of the optimization at places where it
  50 // has historically been a poor choice.  Other heuristics try to use
  51 // specific information gathered about types observed at a given site.
  52 //
  53 // All data in the profile is approximate.  It is expected to be accurate
  54 // on the whole, but the system expects occasional inaccuraces, due to
  55 // counter overflow, multiprocessor races during data collection, space
  56 // limitations, missing MDO blocks, etc.  Bad or missing data will degrade
  57 // optimization quality but will not affect correctness.  Also, each MDO
  58 // is marked with its birth-date ("creation_mileage") which can be used
  59 // to assess the quality ("maturity") of its data.
  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 Atomic::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 = 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 != Atomic::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 = 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 != Atomic::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 class ReceiverTypeData : public CounterData {
1153   friend class VMStructs;
1154   friend class JVMCIVMStructs;
1155 protected:
1156   enum {
1157     receiver0_offset = counter_cell_count,
1158     count0_offset,
1159     receiver_type_row_cell_count = (count0_offset + 1) - receiver0_offset
1160   };
1161 
1162 public:
1163   ReceiverTypeData(DataLayout* layout) : CounterData(layout) {
1164     assert(layout->tag() == DataLayout::receiver_type_data_tag ||
1165            layout->tag() == DataLayout::virtual_call_data_tag ||
1166            layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1167   }
1168 
1169   virtual bool is_ReceiverTypeData() const { return true; }
1170 
1171   static int static_cell_count() {
1172     return counter_cell_count + (uint) TypeProfileWidth * receiver_type_row_cell_count;
1173   }
1174 
1175   virtual int cell_count() const {
1176     return static_cell_count();
1177   }
1178 
1179   // Direct accessors
1180   static uint row_limit() {
1181     return (uint) TypeProfileWidth;
1182   }
1183   static int receiver_cell_index(uint row) {
1184     return receiver0_offset + row * receiver_type_row_cell_count;
1185   }
1186   static int receiver_count_cell_index(uint row) {
1187     return count0_offset + row * receiver_type_row_cell_count;
1188   }
1189 
1190   Klass* receiver(uint row) const {
1191     assert(row < row_limit(), "oob");
1192 
1193     Klass* recv = (Klass*)intptr_at(receiver_cell_index(row));
1194     assert(recv == nullptr || recv->is_klass(), "wrong type");
1195     return recv;
1196   }
1197 
1198   void set_receiver(uint row, Klass* k) {
1199     assert((uint)row < row_limit(), "oob");
1200     set_intptr_at(receiver_cell_index(row), (uintptr_t)k);
1201   }
1202 
1203   uint receiver_count(uint row) const {
1204     assert(row < row_limit(), "oob");
1205     return uint_at(receiver_count_cell_index(row));
1206   }
1207 
1208   void set_receiver_count(uint row, uint count) {
1209     assert(row < row_limit(), "oob");
1210     set_uint_at(receiver_count_cell_index(row), count);
1211   }
1212 
1213   void clear_row(uint row) {
1214     assert(row < row_limit(), "oob");
1215     // Clear total count - indicator of polymorphic call site.
1216     // The site may look like as monomorphic after that but
1217     // it allow to have more accurate profiling information because
1218     // there was execution phase change since klasses were unloaded.
1219     // If the site is still polymorphic then MDO will be updated
1220     // to reflect it. But it could be the case that the site becomes
1221     // only bimorphic. Then keeping total count not 0 will be wrong.
1222     // Even if we use monomorphic (when it is not) for compilation
1223     // we will only have trap, deoptimization and recompile again
1224     // with updated MDO after executing method in Interpreter.
1225     // An additional receiver will be recorded in the cleaned row
1226     // during next call execution.
1227     //
1228     // Note: our profiling logic works with empty rows in any slot.
1229     // We do sorting a profiling info (ciCallProfile) for compilation.
1230     //
1231     set_count(0);
1232     set_receiver(row, nullptr);
1233     set_receiver_count(row, 0);
1234   }
1235 
1236   // Code generation support
1237   static ByteSize receiver_offset(uint row) {
1238     return cell_offset(receiver_cell_index(row));
1239   }
1240   static ByteSize receiver_count_offset(uint row) {
1241     return cell_offset(receiver_count_cell_index(row));
1242   }
1243   static ByteSize receiver_type_data_size() {
1244     return cell_offset(static_cell_count());
1245   }
1246 
1247   // GC support
1248   virtual void clean_weak_klass_links(bool always_clean);
1249 
1250   // CDS support
1251   virtual void metaspace_pointers_do(MetaspaceClosure* it);
1252 
1253   void print_receiver_data_on(outputStream* st) const;
1254   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1255 };
1256 
1257 // VirtualCallData
1258 //
1259 // A VirtualCallData is used to access profiling information about a
1260 // virtual call.  For now, it has nothing more than a ReceiverTypeData.
1261 class VirtualCallData : public ReceiverTypeData {
1262 public:
1263   VirtualCallData(DataLayout* layout) : ReceiverTypeData(layout) {
1264     assert(layout->tag() == DataLayout::virtual_call_data_tag ||
1265            layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1266   }
1267 
1268   virtual bool is_VirtualCallData() const { return true; }
1269 
1270   static int static_cell_count() {
1271     // At this point we could add more profile state, e.g., for arguments.
1272     // But for now it's the same size as the base record type.
1273     return ReceiverTypeData::static_cell_count();
1274   }
1275 
1276   virtual int cell_count() const {
1277     return static_cell_count();
1278   }
1279 
1280   // Direct accessors
1281   static ByteSize virtual_call_data_size() {
1282     return cell_offset(static_cell_count());
1283   }
1284 
1285   void print_method_data_on(outputStream* st) const NOT_JVMCI_RETURN;
1286   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1287 };
1288 
1289 // VirtualCallTypeData
1290 //
1291 // A VirtualCallTypeData is used to access profiling information about
1292 // a virtual call for which we collect type information about
1293 // arguments and return value.
1294 class VirtualCallTypeData : public VirtualCallData {
1295 private:
1296   // entries for arguments if any
1297   TypeStackSlotEntries _args;
1298   // entry for return type if any
1299   ReturnTypeEntry _ret;
1300 
1301   int cell_count_global_offset() const {
1302     return VirtualCallData::static_cell_count() + TypeEntriesAtCall::cell_count_local_offset();
1303   }
1304 
1305   // number of cells not counting the header
1306   int cell_count_no_header() const {
1307     return uint_at(cell_count_global_offset());
1308   }
1309 
1310   void check_number_of_arguments(int total) {
1311     assert(number_of_arguments() == total, "should be set in DataLayout::initialize");
1312   }
1313 
1314 public:
1315   VirtualCallTypeData(DataLayout* layout) :
1316     VirtualCallData(layout),
1317     _args(VirtualCallData::static_cell_count()+TypeEntriesAtCall::header_cell_count(), number_of_arguments()),
1318     _ret(cell_count() - ReturnTypeEntry::static_cell_count())
1319   {
1320     assert(layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1321     // Some compilers (VC++) don't want this passed in member initialization list
1322     _args.set_profile_data(this);
1323     _ret.set_profile_data(this);
1324   }
1325 
1326   const TypeStackSlotEntries* args() const {
1327     assert(has_arguments(), "no profiling of arguments");
1328     return &_args;
1329   }
1330 
1331   const ReturnTypeEntry* ret() const {
1332     assert(has_return(), "no profiling of return value");
1333     return &_ret;
1334   }
1335 
1336   virtual bool is_VirtualCallTypeData() const { return true; }
1337 
1338   static int static_cell_count() {
1339     return -1;
1340   }
1341 
1342   static int compute_cell_count(BytecodeStream* stream) {
1343     return VirtualCallData::static_cell_count() + TypeEntriesAtCall::compute_cell_count(stream);
1344   }
1345 
1346   static void initialize(DataLayout* dl, int cell_count) {
1347     TypeEntriesAtCall::initialize(dl, VirtualCallData::static_cell_count(), cell_count);
1348   }
1349 
1350   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo);
1351 
1352   virtual int cell_count() const {
1353     return VirtualCallData::static_cell_count() +
1354       TypeEntriesAtCall::header_cell_count() +
1355       int_at_unchecked(cell_count_global_offset());
1356   }
1357 
1358   int number_of_arguments() const {
1359     return cell_count_no_header() / TypeStackSlotEntries::per_arg_count();
1360   }
1361 
1362   void set_argument_type(int i, Klass* k) {
1363     assert(has_arguments(), "no arguments!");
1364     intptr_t current = _args.type(i);
1365     _args.set_type(i, TypeEntries::with_status(k, current));
1366   }
1367 
1368   void set_return_type(Klass* k) {
1369     assert(has_return(), "no return!");
1370     intptr_t current = _ret.type();
1371     _ret.set_type(TypeEntries::with_status(k, current));
1372   }
1373 
1374   // An entry for a return value takes less space than an entry for an
1375   // argument, so if the remainder of the number of cells divided by
1376   // the number of cells for an argument is not null, a return value
1377   // is profiled in this object.
1378   bool has_return() const {
1379     bool res = (cell_count_no_header() % TypeStackSlotEntries::per_arg_count()) != 0;
1380     assert (!res || TypeEntriesAtCall::return_profiling_enabled(), "no profiling of return values");
1381     return res;
1382   }
1383 
1384   // An entry for a return value takes less space than an entry for an
1385   // argument so if the number of cells exceeds the number of cells
1386   // needed for an argument, this object contains type information for
1387   // at least one argument.
1388   bool has_arguments() const {
1389     bool res = cell_count_no_header() >= TypeStackSlotEntries::per_arg_count();
1390     assert (!res || TypeEntriesAtCall::arguments_profiling_enabled(), "no profiling of arguments");
1391     return res;
1392   }
1393 
1394   // Code generation support
1395   static ByteSize args_data_offset() {
1396     return cell_offset(VirtualCallData::static_cell_count()) + TypeEntriesAtCall::args_data_offset();
1397   }
1398 
1399   ByteSize argument_type_offset(int i) {
1400     return _args.type_offset(i);
1401   }
1402 
1403   ByteSize return_type_offset() {
1404     return _ret.type_offset();
1405   }
1406 
1407   // GC support
1408   virtual void clean_weak_klass_links(bool always_clean) {
1409     ReceiverTypeData::clean_weak_klass_links(always_clean);
1410     if (has_arguments()) {
1411       _args.clean_weak_klass_links(always_clean);
1412     }
1413     if (has_return()) {
1414       _ret.clean_weak_klass_links(always_clean);
1415     }
1416   }
1417 
1418   // CDS support
1419   virtual void metaspace_pointers_do(MetaspaceClosure* it) {
1420     ReceiverTypeData::metaspace_pointers_do(it);
1421     if (has_arguments()) {
1422       _args.metaspace_pointers_do(it);
1423     }
1424     if (has_return()) {
1425       _ret.metaspace_pointers_do(it);
1426     }
1427   }
1428 
1429   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1430 };
1431 
1432 // RetData
1433 //
1434 // A RetData is used to access profiling information for a ret bytecode.
1435 // It is composed of a count of the number of times that the ret has
1436 // been executed, followed by a series of triples of the form
1437 // (bci, count, di) which count the number of times that some bci was the
1438 // target of the ret and cache a corresponding data displacement.
1439 class RetData : public CounterData {
1440 protected:
1441   enum {
1442     bci0_offset = counter_cell_count,
1443     count0_offset,
1444     displacement0_offset,
1445     ret_row_cell_count = (displacement0_offset + 1) - bci0_offset
1446   };
1447 
1448   void set_bci(uint row, int bci) {
1449     assert((uint)row < row_limit(), "oob");
1450     set_int_at(bci0_offset + row * ret_row_cell_count, bci);
1451   }
1452   void release_set_bci(uint row, int bci);
1453   void set_bci_count(uint row, uint count) {
1454     assert((uint)row < row_limit(), "oob");
1455     set_uint_at(count0_offset + row * ret_row_cell_count, count);
1456   }
1457   void set_bci_displacement(uint row, int disp) {
1458     set_int_at(displacement0_offset + row * ret_row_cell_count, disp);
1459   }
1460 
1461 public:
1462   RetData(DataLayout* layout) : CounterData(layout) {
1463     assert(layout->tag() == DataLayout::ret_data_tag, "wrong type");
1464   }
1465 
1466   virtual bool is_RetData() const { return true; }
1467 
1468   enum {
1469     no_bci = -1 // value of bci when bci1/2 are not in use.
1470   };
1471 
1472   static int static_cell_count() {
1473     return counter_cell_count + (uint) BciProfileWidth * ret_row_cell_count;
1474   }
1475 
1476   virtual int cell_count() const {
1477     return static_cell_count();
1478   }
1479 
1480   static uint row_limit() {
1481     return (uint) BciProfileWidth;
1482   }
1483   static int bci_cell_index(uint row) {
1484     return bci0_offset + row * ret_row_cell_count;
1485   }
1486   static int bci_count_cell_index(uint row) {
1487     return count0_offset + row * ret_row_cell_count;
1488   }
1489   static int bci_displacement_cell_index(uint row) {
1490     return displacement0_offset + row * ret_row_cell_count;
1491   }
1492 
1493   // Direct accessors
1494   int bci(uint row) const {
1495     return int_at(bci_cell_index(row));
1496   }
1497   uint bci_count(uint row) const {
1498     return uint_at(bci_count_cell_index(row));
1499   }
1500   int bci_displacement(uint row) const {
1501     return int_at(bci_displacement_cell_index(row));
1502   }
1503 
1504   // Interpreter Runtime support
1505   address fixup_ret(int return_bci, MethodData* mdo);
1506 
1507   // Code generation support
1508   static ByteSize bci_offset(uint row) {
1509     return cell_offset(bci_cell_index(row));
1510   }
1511   static ByteSize bci_count_offset(uint row) {
1512     return cell_offset(bci_count_cell_index(row));
1513   }
1514   static ByteSize bci_displacement_offset(uint row) {
1515     return cell_offset(bci_displacement_cell_index(row));
1516   }
1517 
1518   // Specific initialization.
1519   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1520 
1521   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1522 };
1523 
1524 // BranchData
1525 //
1526 // A BranchData is used to access profiling data for a two-way branch.
1527 // It consists of taken and not_taken counts as well as a data displacement
1528 // for the taken case.
1529 class BranchData : public JumpData {
1530   friend class VMStructs;
1531   friend class JVMCIVMStructs;
1532 protected:
1533   enum {
1534     not_taken_off_set = jump_cell_count,
1535     branch_cell_count
1536   };
1537 
1538   void set_displacement(int displacement) {
1539     set_int_at(displacement_off_set, displacement);
1540   }
1541 
1542 public:
1543   BranchData(DataLayout* layout) : JumpData(layout) {
1544     assert(layout->tag() == DataLayout::branch_data_tag, "wrong type");
1545   }
1546 
1547   virtual bool is_BranchData() const { return true; }
1548 
1549   static int static_cell_count() {
1550     return branch_cell_count;
1551   }
1552 
1553   virtual int cell_count() const {
1554     return static_cell_count();
1555   }
1556 
1557   // Direct accessor
1558   uint not_taken() const {
1559     return uint_at(not_taken_off_set);
1560   }
1561 
1562   void set_not_taken(uint cnt) {
1563     set_uint_at(not_taken_off_set, cnt);
1564   }
1565 
1566   uint inc_not_taken() {
1567     uint cnt = not_taken() + 1;
1568     // Did we wrap? Will compiler screw us??
1569     if (cnt == 0) cnt--;
1570     set_uint_at(not_taken_off_set, cnt);
1571     return cnt;
1572   }
1573 
1574   // Code generation support
1575   static ByteSize not_taken_offset() {
1576     return cell_offset(not_taken_off_set);
1577   }
1578   static ByteSize branch_data_size() {
1579     return cell_offset(branch_cell_count);
1580   }
1581 
1582   // Specific initialization.
1583   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1584 
1585   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1586 };
1587 
1588 // ArrayData
1589 //
1590 // A ArrayData is a base class for accessing profiling data which does
1591 // not have a statically known size.  It consists of an array length
1592 // and an array start.
1593 class ArrayData : public ProfileData {
1594   friend class VMStructs;
1595   friend class JVMCIVMStructs;
1596 protected:
1597   friend class DataLayout;
1598 
1599   enum {
1600     array_len_off_set,
1601     array_start_off_set
1602   };
1603 
1604   uint array_uint_at(int index) const {
1605     int aindex = index + array_start_off_set;
1606     return uint_at(aindex);
1607   }
1608   int array_int_at(int index) const {
1609     int aindex = index + array_start_off_set;
1610     return int_at(aindex);
1611   }
1612   void array_set_int_at(int index, int value) {
1613     int aindex = index + array_start_off_set;
1614     set_int_at(aindex, value);
1615   }
1616 
1617   // Code generation support for subclasses.
1618   static ByteSize array_element_offset(int index) {
1619     return cell_offset(array_start_off_set + index);
1620   }
1621 
1622 public:
1623   ArrayData(DataLayout* layout) : ProfileData(layout) {}
1624 
1625   virtual bool is_ArrayData() const { return true; }
1626 
1627   static int static_cell_count() {
1628     return -1;
1629   }
1630 
1631   int array_len() const {
1632     return int_at_unchecked(array_len_off_set);
1633   }
1634 
1635   virtual int cell_count() const {
1636     return array_len() + 1;
1637   }
1638 
1639   // Code generation support
1640   static ByteSize array_len_offset() {
1641     return cell_offset(array_len_off_set);
1642   }
1643   static ByteSize array_start_offset() {
1644     return cell_offset(array_start_off_set);
1645   }
1646 };
1647 
1648 // MultiBranchData
1649 //
1650 // A MultiBranchData is used to access profiling information for
1651 // a multi-way branch (*switch bytecodes).  It consists of a series
1652 // of (count, displacement) pairs, which count the number of times each
1653 // case was taken and specify the data displacement for each branch target.
1654 class MultiBranchData : public ArrayData {
1655   friend class VMStructs;
1656   friend class JVMCIVMStructs;
1657 protected:
1658   enum {
1659     default_count_off_set,
1660     default_disaplacement_off_set,
1661     case_array_start
1662   };
1663   enum {
1664     relative_count_off_set,
1665     relative_displacement_off_set,
1666     per_case_cell_count
1667   };
1668 
1669   void set_default_displacement(int displacement) {
1670     array_set_int_at(default_disaplacement_off_set, displacement);
1671   }
1672   void set_displacement_at(int index, int displacement) {
1673     array_set_int_at(case_array_start +
1674                      index * per_case_cell_count +
1675                      relative_displacement_off_set,
1676                      displacement);
1677   }
1678 
1679 public:
1680   MultiBranchData(DataLayout* layout) : ArrayData(layout) {
1681     assert(layout->tag() == DataLayout::multi_branch_data_tag, "wrong type");
1682   }
1683 
1684   virtual bool is_MultiBranchData() const { return true; }
1685 
1686   static int compute_cell_count(BytecodeStream* stream);
1687 
1688   int number_of_cases() const {
1689     int alen = array_len() - 2; // get rid of default case here.
1690     assert(alen % per_case_cell_count == 0, "must be even");
1691     return (alen / per_case_cell_count);
1692   }
1693 
1694   uint default_count() const {
1695     return array_uint_at(default_count_off_set);
1696   }
1697   int default_displacement() const {
1698     return array_int_at(default_disaplacement_off_set);
1699   }
1700 
1701   uint count_at(int index) const {
1702     return array_uint_at(case_array_start +
1703                          index * per_case_cell_count +
1704                          relative_count_off_set);
1705   }
1706   int displacement_at(int index) const {
1707     return array_int_at(case_array_start +
1708                         index * per_case_cell_count +
1709                         relative_displacement_off_set);
1710   }
1711 
1712   // Code generation support
1713   static ByteSize default_count_offset() {
1714     return array_element_offset(default_count_off_set);
1715   }
1716   static ByteSize default_displacement_offset() {
1717     return array_element_offset(default_disaplacement_off_set);
1718   }
1719   static ByteSize case_count_offset(int index) {
1720     return case_array_offset() +
1721            (per_case_size() * index) +
1722            relative_count_offset();
1723   }
1724   static ByteSize case_array_offset() {
1725     return array_element_offset(case_array_start);
1726   }
1727   static ByteSize per_case_size() {
1728     return in_ByteSize(per_case_cell_count) * cell_size;
1729   }
1730   static ByteSize relative_count_offset() {
1731     return in_ByteSize(relative_count_off_set) * cell_size;
1732   }
1733   static ByteSize relative_displacement_offset() {
1734     return in_ByteSize(relative_displacement_off_set) * cell_size;
1735   }
1736 
1737   // Specific initialization.
1738   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1739 
1740   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1741 };
1742 
1743 class ArgInfoData : public ArrayData {
1744 
1745 public:
1746   ArgInfoData(DataLayout* layout) : ArrayData(layout) {
1747     assert(layout->tag() == DataLayout::arg_info_data_tag, "wrong type");
1748   }
1749 
1750   virtual bool is_ArgInfoData() const { return true; }
1751 
1752 
1753   int number_of_args() const {
1754     return array_len();
1755   }
1756 
1757   uint arg_modified(int arg) const {
1758     return array_uint_at(arg);
1759   }
1760 
1761   void set_arg_modified(int arg, uint val) {
1762     array_set_int_at(arg, val);
1763   }
1764 
1765   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1766 };
1767 
1768 // ParametersTypeData
1769 //
1770 // A ParametersTypeData is used to access profiling information about
1771 // types of parameters to a method
1772 class ParametersTypeData : public ArrayData {
1773 
1774 private:
1775   TypeStackSlotEntries _parameters;
1776 
1777   static int stack_slot_local_offset(int i) {
1778     assert_profiling_enabled();
1779     return array_start_off_set + TypeStackSlotEntries::stack_slot_local_offset(i);
1780   }
1781 
1782   static int type_local_offset(int i) {
1783     assert_profiling_enabled();
1784     return array_start_off_set + TypeStackSlotEntries::type_local_offset(i);
1785   }
1786 
1787   static bool profiling_enabled();
1788   static void assert_profiling_enabled() {
1789     assert(profiling_enabled(), "method parameters profiling should be on");
1790   }
1791 
1792 public:
1793   ParametersTypeData(DataLayout* layout) : ArrayData(layout), _parameters(1, number_of_parameters()) {
1794     assert(layout->tag() == DataLayout::parameters_type_data_tag, "wrong type");
1795     // Some compilers (VC++) don't want this passed in member initialization list
1796     _parameters.set_profile_data(this);
1797   }
1798 
1799   static int compute_cell_count(Method* m);
1800 
1801   virtual bool is_ParametersTypeData() const { return true; }
1802 
1803   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo);
1804 
1805   int number_of_parameters() const {
1806     return array_len() / TypeStackSlotEntries::per_arg_count();
1807   }
1808 
1809   const TypeStackSlotEntries* parameters() const { return &_parameters; }
1810 
1811   uint stack_slot(int i) const {
1812     return _parameters.stack_slot(i);
1813   }
1814 
1815   void set_type(int i, Klass* k) {
1816     intptr_t current = _parameters.type(i);
1817     _parameters.set_type(i, TypeEntries::with_status((intptr_t)k, current));
1818   }
1819 
1820   virtual void clean_weak_klass_links(bool always_clean) {
1821     _parameters.clean_weak_klass_links(always_clean);
1822   }
1823 
1824   // CDS support
1825   virtual void metaspace_pointers_do(MetaspaceClosure* it) {
1826     _parameters.metaspace_pointers_do(it);
1827   }
1828 
1829   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1830 
1831   static ByteSize stack_slot_offset(int i) {
1832     return cell_offset(stack_slot_local_offset(i));
1833   }
1834 
1835   static ByteSize type_offset(int i) {
1836     return cell_offset(type_local_offset(i));
1837   }
1838 };
1839 
1840 // SpeculativeTrapData
1841 //
1842 // A SpeculativeTrapData is used to record traps due to type
1843 // speculation. It records the root of the compilation: that type
1844 // speculation is wrong in the context of one compilation (for
1845 // method1) doesn't mean it's wrong in the context of another one (for
1846 // method2). Type speculation could have more/different data in the
1847 // context of the compilation of method2 and it's worthwhile to try an
1848 // optimization that failed for compilation of method1 in the context
1849 // of compilation of method2.
1850 // Space for SpeculativeTrapData entries is allocated from the extra
1851 // data space in the MDO. If we run out of space, the trap data for
1852 // the ProfileData at that bci is updated.
1853 class SpeculativeTrapData : public ProfileData {
1854 protected:
1855   enum {
1856     speculative_trap_method,
1857 #ifndef _LP64
1858     // The size of the area for traps is a multiple of the header
1859     // size, 2 cells on 32 bits. Packed at the end of this area are
1860     // argument info entries (with tag
1861     // DataLayout::arg_info_data_tag). The logic in
1862     // MethodData::bci_to_extra_data() that guarantees traps don't
1863     // overflow over argument info entries assumes the size of a
1864     // SpeculativeTrapData is twice the header size. On 32 bits, a
1865     // SpeculativeTrapData must be 4 cells.
1866     padding,
1867 #endif
1868     speculative_trap_cell_count
1869   };
1870 public:
1871   SpeculativeTrapData(DataLayout* layout) : ProfileData(layout) {
1872     assert(layout->tag() == DataLayout::speculative_trap_data_tag, "wrong type");
1873   }
1874 
1875   virtual bool is_SpeculativeTrapData() const { return true; }
1876 
1877   static int static_cell_count() {
1878     return speculative_trap_cell_count;
1879   }
1880 
1881   virtual int cell_count() const {
1882     return static_cell_count();
1883   }
1884 
1885   // Direct accessor
1886   Method* method() const {
1887     return (Method*)intptr_at(speculative_trap_method);
1888   }
1889 
1890   void set_method(Method* m) {
1891     assert(!m->is_old(), "cannot add old methods");
1892     set_intptr_at(speculative_trap_method, (intptr_t)m);
1893   }
1894 
1895   static ByteSize method_offset() {
1896     return cell_offset(speculative_trap_method);
1897   }
1898 
1899   // CDS support
1900   virtual void metaspace_pointers_do(MetaspaceClosure* it);
1901 
1902   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1903 };
1904 
1905 // MethodData*
1906 //
1907 // A MethodData* holds information which has been collected about
1908 // a method.  Its layout looks like this:
1909 //
1910 // -----------------------------
1911 // | header                    |
1912 // | klass                     |
1913 // -----------------------------
1914 // | method                    |
1915 // | size of the MethodData* |
1916 // -----------------------------
1917 // | Data entries...           |
1918 // |   (variable size)         |
1919 // |                           |
1920 // .                           .
1921 // .                           .
1922 // .                           .
1923 // |                           |
1924 // -----------------------------
1925 //
1926 // The data entry area is a heterogeneous array of DataLayouts. Each
1927 // DataLayout in the array corresponds to a specific bytecode in the
1928 // method.  The entries in the array are sorted by the corresponding
1929 // bytecode.  Access to the data is via resource-allocated ProfileData,
1930 // which point to the underlying blocks of DataLayout structures.
1931 //
1932 // During interpretation, if profiling in enabled, the interpreter
1933 // maintains a method data pointer (mdp), which points at the entry
1934 // in the array corresponding to the current bci.  In the course of
1935 // interpretation, when a bytecode is encountered that has profile data
1936 // associated with it, the entry pointed to by mdp is updated, then the
1937 // mdp is adjusted to point to the next appropriate DataLayout.  If mdp
1938 // is null to begin with, the interpreter assumes that the current method
1939 // is not (yet) being profiled.
1940 //
1941 // In MethodData* parlance, "dp" is a "data pointer", the actual address
1942 // of a DataLayout element.  A "di" is a "data index", the offset in bytes
1943 // from the base of the data entry array.  A "displacement" is the byte offset
1944 // in certain ProfileData objects that indicate the amount the mdp must be
1945 // adjusted in the event of a change in control flow.
1946 //
1947 
1948 class CleanExtraDataClosure : public StackObj {
1949 public:
1950   virtual bool is_live(Method* m) = 0;
1951 };
1952 
1953 
1954 #if INCLUDE_JVMCI
1955 // Encapsulates an encoded speculation reason. These are linked together in
1956 // a list that is atomically appended to during deoptimization. Entries are
1957 // never removed from the list.
1958 // @see jdk.vm.ci.hotspot.HotSpotSpeculationLog.HotSpotSpeculationEncoding
1959 class FailedSpeculation: public CHeapObj<mtCompiler> {
1960  private:
1961   // The length of HotSpotSpeculationEncoding.toByteArray(). The data itself
1962   // is an array embedded at the end of this object.
1963   int   _data_len;
1964 
1965   // Next entry in a linked list.
1966   FailedSpeculation* _next;
1967 
1968   FailedSpeculation(address data, int data_len);
1969 
1970   FailedSpeculation** next_adr() { return &_next; }
1971 
1972   // Placement new operator for inlining the speculation data into
1973   // the FailedSpeculation object.
1974   void* operator new(size_t size, size_t fs_size) throw();
1975 
1976  public:
1977   char* data()         { return (char*)(((address) this) + sizeof(FailedSpeculation)); }
1978   int data_len() const { return _data_len; }
1979   FailedSpeculation* next() const { return _next; }
1980 
1981   // Atomically appends a speculation from nm to the list whose head is at (*failed_speculations_address).
1982   // Returns false if the FailedSpeculation object could not be allocated.
1983   static bool add_failed_speculation(nmethod* nm, FailedSpeculation** failed_speculations_address, address speculation, int speculation_len);
1984 
1985   // Frees all entries in the linked list whose head is at (*failed_speculations_address).
1986   static void free_failed_speculations(FailedSpeculation** failed_speculations_address);
1987 };
1988 #endif
1989 
1990 class ciMethodData;
1991 
1992 class MethodData : public Metadata {
1993   friend class VMStructs;
1994   friend class JVMCIVMStructs;
1995 private:
1996   friend class ProfileData;
1997   friend class TypeEntriesAtCall;
1998   friend class ciMethodData;
1999 
2000   // If you add a new field that points to any metaspace object, you
2001   // must add this field to MethodData::metaspace_pointers_do().
2002 
2003   // Back pointer to the Method*
2004   Method* _method;
2005 
2006   // Size of this oop in bytes
2007   int _size;
2008 
2009   // Cached hint for bci_to_dp and bci_to_data
2010   int _hint_di;
2011 
2012   Mutex* volatile _extra_data_lock; // FIXME: CDS support
2013 
2014   MethodData(const methodHandle& method);
2015 public:
2016   MethodData();
2017 
2018   static MethodData* allocate(ClassLoaderData* loader_data, const methodHandle& method, TRAPS);
2019 
2020   virtual bool is_methodData() const { return true; }
2021   void initialize();
2022 
2023   // Whole-method sticky bits and flags
2024   enum {
2025     _trap_hist_limit    = Deoptimization::Reason_TRAP_HISTORY_LENGTH,
2026     _trap_hist_mask     = max_jubyte,
2027     _extra_data_count   = 4     // extra DataLayout headers, for trap history
2028   }; // Public flag values
2029 
2030   // Compiler-related counters.
2031   class CompilerCounters {
2032     friend class VMStructs;
2033     friend class JVMCIVMStructs;
2034 
2035     uint _nof_decompiles;             // count of all nmethod removals
2036     uint _nof_overflow_recompiles;    // recompile count, excluding recomp. bits
2037     uint _nof_overflow_traps;         // trap count, excluding _trap_hist
2038     uint __gap;
2039     union {
2040       intptr_t _align;
2041       // JVMCI separates trap history for OSR compilations from normal compilations
2042       u1 _array[JVMCI_ONLY(2 *) MethodData::_trap_hist_limit];
2043     } _trap_hist;
2044 
2045   public:
2046     CompilerCounters() : _nof_decompiles(0), _nof_overflow_recompiles(0), _nof_overflow_traps(0), __gap(0) {
2047 #ifndef ZERO
2048       // Some Zero platforms do not have expected alignment, and do not use
2049       // this code. static_assert would still fire and fail for them.
2050       static_assert(sizeof(_trap_hist) % HeapWordSize == 0, "align");
2051 #endif
2052       uint size_in_words = sizeof(_trap_hist) / HeapWordSize;
2053       Copy::zero_to_words((HeapWord*) &_trap_hist, size_in_words);
2054     }
2055 
2056     // Return (uint)-1 for overflow.
2057     uint trap_count(int reason) const {
2058       assert((uint)reason < ARRAY_SIZE(_trap_hist._array), "oob");
2059       return (int)((_trap_hist._array[reason]+1) & _trap_hist_mask) - 1;
2060     }
2061 
2062     uint inc_trap_count(int reason) {
2063       // Count another trap, anywhere in this method.
2064       assert(reason >= 0, "must be single trap");
2065       assert((uint)reason < ARRAY_SIZE(_trap_hist._array), "oob");
2066       uint cnt1 = 1 + _trap_hist._array[reason];
2067       if ((cnt1 & _trap_hist_mask) != 0) {  // if no counter overflow...
2068         _trap_hist._array[reason] = (u1)cnt1;
2069         return cnt1;
2070       } else {
2071         return _trap_hist_mask + (++_nof_overflow_traps);
2072       }
2073     }
2074 
2075     uint overflow_trap_count() const {
2076       return _nof_overflow_traps;
2077     }
2078     uint overflow_recompile_count() const {
2079       return _nof_overflow_recompiles;
2080     }
2081     uint inc_overflow_recompile_count() {
2082       return ++_nof_overflow_recompiles;
2083     }
2084     uint decompile_count() const {
2085       return _nof_decompiles;
2086     }
2087     uint inc_decompile_count() {
2088       return ++_nof_decompiles;
2089     }
2090 
2091     // Support for code generation
2092     static ByteSize trap_history_offset() {
2093       return byte_offset_of(CompilerCounters, _trap_hist._array);
2094     }
2095   };
2096 
2097 private:
2098   CompilerCounters _compiler_counters;
2099 
2100   // Support for interprocedural escape analysis, from Thomas Kotzmann.
2101   intx              _eflags;          // flags on escape information
2102   intx              _arg_local;       // bit set of non-escaping arguments
2103   intx              _arg_stack;       // bit set of stack-allocatable arguments
2104   intx              _arg_returned;    // bit set of returned arguments
2105 
2106   int               _creation_mileage; // method mileage at MDO creation
2107 
2108   // How many invocations has this MDO seen?
2109   // These counters are used to determine the exact age of MDO.
2110   // We need those because in tiered a method can be concurrently
2111   // executed at different levels.
2112   InvocationCounter _invocation_counter;
2113   // Same for backedges.
2114   InvocationCounter _backedge_counter;
2115   // Counter values at the time profiling started.
2116   int               _invocation_counter_start;
2117   int               _backedge_counter_start;
2118   uint              _tenure_traps;
2119   int               _invoke_mask;      // per-method Tier0InvokeNotifyFreqLog
2120   int               _backedge_mask;    // per-method Tier0BackedgeNotifyFreqLog
2121 
2122 #if INCLUDE_RTM_OPT
2123   // State of RTM code generation during compilation of the method
2124   int               _rtm_state;
2125 #endif
2126 
2127   // Number of loops and blocks is computed when compiling the first
2128   // time with C1. It is used to determine if method is trivial.
2129   short             _num_loops;
2130   short             _num_blocks;
2131   // Does this method contain anything worth profiling?
2132   enum WouldProfile {unknown, no_profile, profile};
2133   WouldProfile      _would_profile;
2134 
2135 #if INCLUDE_JVMCI
2136   // Support for HotSpotMethodData.setCompiledIRSize(int)
2137   int                _jvmci_ir_size;
2138   FailedSpeculation* _failed_speculations;
2139 #endif
2140 
2141   // Size of _data array in bytes.  (Excludes header and extra_data fields.)
2142   int _data_size;
2143 
2144   // data index for the area dedicated to parameters. -1 if no
2145   // parameter profiling.
2146   enum { no_parameters = -2, parameters_uninitialized = -1 };
2147   int _parameters_type_data_di;
2148 
2149   // data index of exception handler profiling data
2150   int _exception_handler_data_di;
2151 
2152   // Beginning of the data entries
2153   // See comment in ciMethodData::load_data
2154   intptr_t _data[1];
2155 
2156   // Helper for size computation
2157   static int compute_data_size(BytecodeStream* stream);
2158   static int bytecode_cell_count(Bytecodes::Code code);
2159   static bool is_speculative_trap_bytecode(Bytecodes::Code code);
2160   enum { no_profile_data = -1, variable_cell_count = -2 };
2161 
2162   // Helper for initialization
2163   DataLayout* data_layout_at(int data_index) const {
2164     assert(data_index % sizeof(intptr_t) == 0, "unaligned");
2165     return (DataLayout*) (((address)_data) + data_index);
2166   }
2167 
2168   static int single_exception_handler_data_cell_count() {
2169     return BitData::static_cell_count();
2170   }
2171 
2172   static int single_exception_handler_data_size() {
2173     return DataLayout::compute_size_in_bytes(single_exception_handler_data_cell_count());
2174   }
2175 
2176   DataLayout* exception_handler_data_at(int exception_handler_index) const {
2177     return data_layout_at(_exception_handler_data_di + (exception_handler_index * single_exception_handler_data_size()));
2178   }
2179 
2180   int num_exception_handler_data() const {
2181     return exception_handlers_data_size() / single_exception_handler_data_size();
2182   }
2183 
2184   // Initialize an individual data segment.  Returns the size of
2185   // the segment in bytes.
2186   int initialize_data(BytecodeStream* stream, int data_index);
2187 
2188   // Helper for data_at
2189   DataLayout* limit_data_position() const {
2190     return data_layout_at(_data_size);
2191   }
2192   bool out_of_bounds(int data_index) const {
2193     return data_index >= data_size();
2194   }
2195 
2196   // Give each of the data entries a chance to perform specific
2197   // data initialization.
2198   void post_initialize(BytecodeStream* stream);
2199 
2200   // hint accessors
2201   int      hint_di() const  { return _hint_di; }
2202   void set_hint_di(int di)  {
2203     assert(!out_of_bounds(di), "hint_di out of bounds");
2204     _hint_di = di;
2205   }
2206 
2207   DataLayout* data_layout_before(int bci) {
2208     // avoid SEGV on this edge case
2209     if (data_size() == 0)
2210       return nullptr;
2211     DataLayout* layout = data_layout_at(hint_di());
2212     if (layout->bci() <= bci)
2213       return layout;
2214     return data_layout_at(first_di());
2215   }
2216 
2217   // What is the index of the first data entry?
2218   int first_di() const { return 0; }
2219 
2220   ProfileData* bci_to_extra_data_find(int bci, Method* m, DataLayout*& dp);
2221   // Find or create an extra ProfileData:
2222   ProfileData* bci_to_extra_data(int bci, Method* m, bool create_if_missing);
2223 
2224   // return the argument info cell
2225   ArgInfoData *arg_info();
2226 
2227   enum {
2228     no_type_profile = 0,
2229     type_profile_jsr292 = 1,
2230     type_profile_all = 2
2231   };
2232 
2233   static bool profile_jsr292(const methodHandle& m, int bci);
2234   static bool profile_unsafe(const methodHandle& m, int bci);
2235   static bool profile_memory_access(const methodHandle& m, int bci);
2236   static int profile_arguments_flag();
2237   static bool profile_all_arguments();
2238   static bool profile_arguments_for_invoke(const methodHandle& m, int bci);
2239   static int profile_return_flag();
2240   static bool profile_all_return();
2241   static bool profile_return_for_invoke(const methodHandle& m, int bci);
2242   static int profile_parameters_flag();
2243   static bool profile_parameters_jsr292_only();
2244   static bool profile_all_parameters();
2245 
2246   void clean_extra_data_helper(DataLayout* dp, int shift, bool reset = false);
2247   void verify_extra_data_clean(CleanExtraDataClosure* cl);
2248 
2249   DataLayout* exception_handler_bci_to_data_helper(int bci);
2250 
2251 public:
2252   void clean_extra_data(CleanExtraDataClosure* cl);
2253 
2254   static int header_size() {
2255     return sizeof(MethodData)/wordSize;
2256   }
2257 
2258   // Compute the size of a MethodData* before it is created.
2259   static int compute_allocation_size_in_bytes(const methodHandle& method);
2260   static int compute_allocation_size_in_words(const methodHandle& method);
2261   static int compute_extra_data_count(int data_size, int empty_bc_count, bool needs_speculative_traps);
2262 
2263   // Determine if a given bytecode can have profile information.
2264   static bool bytecode_has_profile(Bytecodes::Code code) {
2265     return bytecode_cell_count(code) != no_profile_data;
2266   }
2267 
2268   // reset into original state
2269   void init();
2270 
2271   // My size
2272   int size_in_bytes() const { return _size; }
2273   int size() const    { return align_metadata_size(align_up(_size, BytesPerWord)/BytesPerWord); }
2274 
2275   int      creation_mileage() const { return _creation_mileage; }
2276   void set_creation_mileage(int x)  { _creation_mileage = x; }
2277 
2278   int invocation_count() {
2279     if (invocation_counter()->carry()) {
2280       return InvocationCounter::count_limit;
2281     }
2282     return invocation_counter()->count();
2283   }
2284   int backedge_count() {
2285     if (backedge_counter()->carry()) {
2286       return InvocationCounter::count_limit;
2287     }
2288     return backedge_counter()->count();
2289   }
2290 
2291   int invocation_count_start() {
2292     if (invocation_counter()->carry()) {
2293       return 0;
2294     }
2295     return _invocation_counter_start;
2296   }
2297 
2298   int backedge_count_start() {
2299     if (backedge_counter()->carry()) {
2300       return 0;
2301     }
2302     return _backedge_counter_start;
2303   }
2304 
2305   int invocation_count_delta() { return invocation_count() - invocation_count_start(); }
2306   int backedge_count_delta()   { return backedge_count()   - backedge_count_start();   }
2307 
2308   void reset_start_counters() {
2309     _invocation_counter_start = invocation_count();
2310     _backedge_counter_start = backedge_count();
2311   }
2312 
2313   InvocationCounter* invocation_counter()     { return &_invocation_counter; }
2314   InvocationCounter* backedge_counter()       { return &_backedge_counter;   }
2315 
2316 #if INCLUDE_JVMCI
2317   FailedSpeculation** get_failed_speculations_address() {
2318     return &_failed_speculations;
2319   }
2320 #endif
2321 
2322 #if INCLUDE_RTM_OPT
2323   int rtm_state() const {
2324     return _rtm_state;
2325   }
2326   void set_rtm_state(RTMState rstate) {
2327     _rtm_state = (int)rstate;
2328   }
2329   void atomic_set_rtm_state(RTMState rstate) {
2330     Atomic::store(&_rtm_state, (int)rstate);
2331   }
2332 
2333   static ByteSize rtm_state_offset() {
2334     return byte_offset_of(MethodData, _rtm_state);
2335   }
2336 #endif
2337 
2338 #if INCLUDE_CDS
2339   void remove_unshareable_info();
2340   void restore_unshareable_info(TRAPS);
2341 #endif
2342 
2343   void set_would_profile(bool p)              { _would_profile = p ? profile : no_profile; }
2344   bool would_profile() const                  { return _would_profile != no_profile; }
2345 
2346   int num_loops() const                       { return _num_loops;  }
2347   void set_num_loops(short n)                 { _num_loops = n;     }
2348   int num_blocks() const                      { return _num_blocks; }
2349   void set_num_blocks(short n)                { _num_blocks = n;    }
2350 
2351   bool is_mature() const;  // consult mileage and ProfileMaturityPercentage
2352   static int mileage_of(Method* m);
2353 
2354   // Support for interprocedural escape analysis, from Thomas Kotzmann.
2355   enum EscapeFlag {
2356     estimated    = 1 << 0,
2357     return_local = 1 << 1,
2358     return_allocated = 1 << 2,
2359     allocated_escapes = 1 << 3,
2360     unknown_modified = 1 << 4
2361   };
2362 
2363   intx eflags()                                  { return _eflags; }
2364   intx arg_local()                               { return _arg_local; }
2365   intx arg_stack()                               { return _arg_stack; }
2366   intx arg_returned()                            { return _arg_returned; }
2367   uint arg_modified(int a);
2368   void set_eflags(intx v)                        { _eflags = v; }
2369   void set_arg_local(intx v)                     { _arg_local = v; }
2370   void set_arg_stack(intx v)                     { _arg_stack = v; }
2371   void set_arg_returned(intx v)                  { _arg_returned = v; }
2372   void set_arg_modified(int a, uint v);
2373   void clear_escape_info()                       { _eflags = _arg_local = _arg_stack = _arg_returned = 0; }
2374 
2375   // Location and size of data area
2376   address data_base() const {
2377     return (address) _data;
2378   }
2379   int data_size() const {
2380     return _data_size;
2381   }
2382 
2383   int parameters_size_in_bytes() const {
2384     return pointer_delta_as_int((address) parameters_data_limit(), (address) parameters_data_base());
2385   }
2386 
2387   int exception_handlers_data_size() const {
2388     return pointer_delta_as_int((address) exception_handler_data_limit(), (address) exception_handler_data_base());
2389   }
2390 
2391   // Accessors
2392   Method* method() const { return _method; }
2393 
2394   // Get the data at an arbitrary (sort of) data index.
2395   ProfileData* data_at(int data_index) const;
2396 
2397   // Walk through the data in order.
2398   ProfileData* first_data() const { return data_at(first_di()); }
2399   ProfileData* next_data(ProfileData* current) const;
2400   DataLayout*  next_data_layout(DataLayout* current) const;
2401   bool is_valid(ProfileData* current) const { return current != nullptr; }
2402   bool is_valid(DataLayout*  current) const { return current != nullptr; }
2403 
2404   // Convert a dp (data pointer) to a di (data index).
2405   int dp_to_di(address dp) const {
2406     return (int)(dp - ((address)_data));
2407   }
2408 
2409   // bci to di/dp conversion.
2410   address bci_to_dp(int bci);
2411   int bci_to_di(int bci) {
2412     return dp_to_di(bci_to_dp(bci));
2413   }
2414 
2415   // Get the data at an arbitrary bci, or null if there is none.
2416   ProfileData* bci_to_data(int bci);
2417 
2418   // Same, but try to create an extra_data record if one is needed:
2419   ProfileData* allocate_bci_to_data(int bci, Method* m) {
2420     check_extra_data_locked();
2421 
2422     ProfileData* data = nullptr;
2423     // If m not null, try to allocate a SpeculativeTrapData entry
2424     if (m == nullptr) {
2425       data = bci_to_data(bci);
2426     }
2427     if (data != nullptr) {
2428       return data;
2429     }
2430     data = bci_to_extra_data(bci, m, true);
2431     if (data != nullptr) {
2432       return data;
2433     }
2434     // If SpeculativeTrapData allocation fails try to allocate a
2435     // regular entry
2436     data = bci_to_data(bci);
2437     if (data != nullptr) {
2438       return data;
2439     }
2440     return bci_to_extra_data(bci, nullptr, true);
2441   }
2442 
2443   BitData* exception_handler_bci_to_data_or_null(int bci);
2444   BitData exception_handler_bci_to_data(int bci);
2445 
2446   // Add a handful of extra data records, for trap tracking.
2447   // Only valid after 'set_size' is called at the end of MethodData::initialize
2448   DataLayout* extra_data_base() const  {
2449     check_extra_data_locked();
2450     return limit_data_position();
2451   }
2452   DataLayout* extra_data_limit() const { return (DataLayout*)((address)this + size_in_bytes()); }
2453   // pointers to sections in extra data
2454   DataLayout* args_data_limit() const  { return parameters_data_base(); }
2455   DataLayout* parameters_data_base() const {
2456     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2457     return _parameters_type_data_di != no_parameters ? data_layout_at(_parameters_type_data_di) : parameters_data_limit();
2458   }
2459   DataLayout* parameters_data_limit() const {
2460     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2461     return exception_handler_data_base();
2462   }
2463   DataLayout* exception_handler_data_base() const { return data_layout_at(_exception_handler_data_di); }
2464   DataLayout* exception_handler_data_limit() const { return extra_data_limit(); }
2465 
2466   int extra_data_size() const          { return (int)((address)extra_data_limit() - (address)limit_data_position()); }
2467   static DataLayout* next_extra(DataLayout* dp);
2468 
2469   // Return (uint)-1 for overflow.
2470   uint trap_count(int reason) const {
2471     return _compiler_counters.trap_count(reason);
2472   }
2473   // For loops:
2474   static uint trap_reason_limit() { return _trap_hist_limit; }
2475   static uint trap_count_limit()  { return _trap_hist_mask; }
2476   uint inc_trap_count(int reason) {
2477     return _compiler_counters.inc_trap_count(reason);
2478   }
2479 
2480   uint overflow_trap_count() const {
2481     return _compiler_counters.overflow_trap_count();
2482   }
2483   uint overflow_recompile_count() const {
2484     return _compiler_counters.overflow_recompile_count();
2485   }
2486   uint inc_overflow_recompile_count() {
2487     return _compiler_counters.inc_overflow_recompile_count();
2488   }
2489   uint decompile_count() const {
2490     return _compiler_counters.decompile_count();
2491   }
2492   uint inc_decompile_count() {
2493     uint dec_count = _compiler_counters.inc_decompile_count();
2494     if (dec_count > (uint)PerMethodRecompilationCutoff) {
2495       method()->set_not_compilable("decompile_count > PerMethodRecompilationCutoff", CompLevel_full_optimization);
2496     }
2497     return dec_count;
2498   }
2499   uint tenure_traps() const {
2500     return _tenure_traps;
2501   }
2502   void inc_tenure_traps() {
2503     _tenure_traps += 1;
2504   }
2505 
2506   // Return pointer to area dedicated to parameters in MDO
2507   ParametersTypeData* parameters_type_data() const {
2508     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2509     return _parameters_type_data_di != no_parameters ? data_layout_at(_parameters_type_data_di)->data_in()->as_ParametersTypeData() : nullptr;
2510   }
2511 
2512   int parameters_type_data_di() const {
2513     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2514     return _parameters_type_data_di != no_parameters ? _parameters_type_data_di : exception_handlers_data_di();
2515   }
2516 
2517   int exception_handlers_data_di() const {
2518     return _exception_handler_data_di;
2519   }
2520 
2521   // Support for code generation
2522   static ByteSize data_offset() {
2523     return byte_offset_of(MethodData, _data[0]);
2524   }
2525 
2526   static ByteSize trap_history_offset() {
2527     return byte_offset_of(MethodData, _compiler_counters) + CompilerCounters::trap_history_offset();
2528   }
2529 
2530   static ByteSize invocation_counter_offset() {
2531     return byte_offset_of(MethodData, _invocation_counter);
2532   }
2533 
2534   static ByteSize backedge_counter_offset() {
2535     return byte_offset_of(MethodData, _backedge_counter);
2536   }
2537 
2538   static ByteSize invoke_mask_offset() {
2539     return byte_offset_of(MethodData, _invoke_mask);
2540   }
2541 
2542   static ByteSize backedge_mask_offset() {
2543     return byte_offset_of(MethodData, _backedge_mask);
2544   }
2545 
2546   static ByteSize parameters_type_data_di_offset() {
2547     return byte_offset_of(MethodData, _parameters_type_data_di);
2548   }
2549 
2550   virtual void metaspace_pointers_do(MetaspaceClosure* iter);
2551   virtual MetaspaceObj::Type type() const { return MethodDataType; }
2552 
2553   // Deallocation support
2554   void deallocate_contents(ClassLoaderData* loader_data);
2555   void release_C_heap_structures();
2556 
2557   // GC support
2558   void set_size(int object_size_in_bytes) { _size = object_size_in_bytes; }
2559 
2560   // Printing
2561   void print_on      (outputStream* st) const;
2562   void print_value_on(outputStream* st) const;
2563 
2564   // printing support for method data
2565   void print_data_on(outputStream* st) const;
2566 
2567   const char* internal_name() const { return "{method data}"; }
2568 
2569   // verification
2570   void verify_on(outputStream* st);
2571   void verify_data_on(outputStream* st);
2572 
2573   static bool profile_parameters_for_method(const methodHandle& m);
2574   static bool profile_arguments();
2575   static bool profile_arguments_jsr292_only();
2576   static bool profile_return();
2577   static bool profile_parameters();
2578   static bool profile_return_jsr292_only();
2579 
2580   void clean_method_data(bool always_clean);
2581   void clean_weak_method_links();
2582   Mutex* extra_data_lock();
2583   void check_extra_data_locked() const NOT_DEBUG_RETURN;
2584 };
2585 
2586 #endif // SHARE_OOPS_METHODDATA_HPP