1 /*
   2  * Copyright (c) 2001, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "ci/ciMetadata.hpp"
  26 #include "ci/ciMethodData.hpp"
  27 #include "ci/ciObjArrayKlass.hpp"
  28 #include "ci/ciReplay.hpp"
  29 #include "ci/ciUtilities.inline.hpp"
  30 #include "compiler/compiler_globals.hpp"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "oops/klass.inline.hpp"
  34 #include "oops/methodData.inline.hpp"
  35 #include "oops/trainingData.hpp"
  36 #include "runtime/deoptimization.hpp"
  37 #include "utilities/copy.hpp"
  38 
  39 // ciMethodData
  40 
  41 // ------------------------------------------------------------------
  42 // ciMethodData::ciMethodData
  43 //
  44 ciMethodData::ciMethodData(MethodData* md)
  45 : ciMetadata(md),
  46   _data_size(0), _extra_data_size(0), _data(nullptr),
  47   _parameters_data_offset(0),
  48   _exception_handlers_data_offset(0),
  49   // Set an initial hint. Don't use set_hint_di() because
  50   // first_di() may be out of bounds if data_size is 0.
  51   _hint_di(first_di()),
  52   _state(empty_state),
  53   _saw_free_extra_data(false),
  54   // Initialize the escape information (to "don't know.");
  55   _eflags(0), _arg_local(0), _arg_stack(0), _arg_returned(0),
  56   _invocation_counter(0),
  57   _orig() {}
  58 
  59 
  60 static bool is_klass_loaded(Klass* k) {
  61   return TrainingData::is_klass_loaded(k);
  62 }
  63 
  64 // Check for entries that reference an unloaded method
  65 class PrepareExtraDataClosure : public CleanExtraDataClosure {
  66   MethodData*            _mdo;
  67   SafepointStateTracker  _safepoint_tracker;
  68   GrowableArray<Method*> _uncached_methods;
  69 
  70 public:
  71   PrepareExtraDataClosure(MethodData* mdo)
  72     : _mdo(mdo),
  73       _safepoint_tracker(SafepointSynchronize::safepoint_state_tracker()),
  74       _uncached_methods()
  75   { }
  76 
  77   bool is_live(Method* m) {
  78     Klass* holder = m->method_holder();
  79     if (holder == nullptr || !holder->is_loader_present_and_alive() || !is_klass_loaded(holder)) {
  80       return false;
  81     }
  82     if (CURRENT_ENV->cached_metadata(m) == nullptr) {
  83       // Uncached entries need to be pre-populated.
  84       _uncached_methods.append(m);
  85     }
  86     return true;
  87   }
  88 
  89   bool has_safepointed() {
  90     return _safepoint_tracker.safepoint_state_changed();
  91   }
  92 
  93   bool finish() {
  94     if (_uncached_methods.length() == 0) {
  95       // Preparation finished iff all Methods* were already cached.
  96       return true;
  97     }
  98     // We are currently holding the extra_data_lock and ensuring
  99     // no safepoint breaks the lock.
 100     _mdo->check_extra_data_locked();
 101 
 102     // We now want to cache some method data. This could cause a safepoint.
 103     // We temporarily release the lock and allow safepoints, and revert that
 104     // at the end of the scope. This is safe, since we currently do not hold
 105     // any extra_method_data: finish is called only after clean_extra_data,
 106     // and the outer scope that first aquired the lock should not hold any
 107     // extra_method_data while cleaning is performed, as the offsets can change.
 108     MutexUnlocker mu(_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 109 
 110     for (int i = 0; i < _uncached_methods.length(); ++i) {
 111       if (has_safepointed()) {
 112         // The metadata in the growable array might contain stale
 113         // entries after a safepoint.
 114         return false;
 115       }
 116       Method* method = _uncached_methods.at(i);
 117       // Populating ciEnv caches may cause safepoints due
 118       // to taking the Compile_lock with safepoint checks.
 119       (void)CURRENT_ENV->get_method(method);
 120     }
 121     return false;
 122   }
 123 };
 124 
 125 void ciMethodData::prepare_metadata() {
 126   MethodData* mdo = get_MethodData();
 127 
 128   for (;;) {
 129     ResourceMark rm;
 130     PrepareExtraDataClosure cl(mdo);
 131     mdo->clean_extra_data(&cl);
 132     if (cl.finish()) {
 133       // When encountering uncached metadata, the Compile_lock might be
 134       // acquired when creating ciMetadata handles, causing safepoints
 135       // which requires a new round of preparation to clean out potentially
 136       // new unloading metadata.
 137       return;
 138     }
 139   }
 140 }
 141 
 142 void ciMethodData::load_remaining_extra_data() {
 143   MethodData* mdo = get_MethodData();
 144 
 145   // Lock to read ProfileData, and ensure lock is not unintentionally broken by a safepoint
 146   MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 147 
 148   // Deferred metadata cleaning due to concurrent class unloading.
 149   prepare_metadata();
 150   // After metadata preparation, there is no stale metadata,
 151   // and no safepoints can introduce more stale metadata.
 152   NoSafepointVerifier no_safepoint;
 153 
 154   assert((mdo->data_size() == _data_size) && (mdo->extra_data_size() == _extra_data_size), "sanity, unchanged");
 155   assert(extra_data_base() == (DataLayout*)((address) _data + _data_size), "sanity");
 156 
 157   // Copy the extra data once it is prepared (i.e. cache populated, no release of extra data lock anymore)
 158   Copy::disjoint_words_atomic((HeapWord*) mdo->extra_data_base(),
 159                               (HeapWord*) extra_data_base(),
 160                               // copy everything from extra_data_base() up to parameters_data_base()
 161                               pointer_delta(parameters_data_base(), extra_data_base(), HeapWordSize));
 162 
 163   // skip parameter data copying. Already done in 'load_data'
 164 
 165   // copy exception handler data
 166   Copy::disjoint_words_atomic((HeapWord*) mdo->exception_handler_data_base(),
 167                               (HeapWord*) exception_handler_data_base(),
 168                               exception_handler_data_size() / HeapWordSize);
 169 
 170   // speculative trap entries also hold a pointer to a Method so need to be translated
 171   DataLayout* dp_src  = mdo->extra_data_base();
 172   DataLayout* end_src = mdo->args_data_limit();
 173   DataLayout* dp_dst  = extra_data_base();
 174   for (;; dp_src = MethodData::next_extra(dp_src), dp_dst = MethodData::next_extra(dp_dst)) {
 175     assert(dp_src < end_src, "moved past end of extra data");
 176     assert(((intptr_t)dp_dst) - ((intptr_t)extra_data_base()) == ((intptr_t)dp_src) - ((intptr_t)mdo->extra_data_base()), "source and destination don't match");
 177 
 178     int tag = dp_src->tag();
 179     switch(tag) {
 180     case DataLayout::speculative_trap_data_tag: {
 181       ciSpeculativeTrapData data_dst(dp_dst);
 182       SpeculativeTrapData   data_src(dp_src);
 183       data_dst.translate_from(&data_src);
 184       break;
 185     }
 186     case DataLayout::bit_data_tag:
 187       break;
 188     case DataLayout::no_tag:
 189     case DataLayout::arg_info_data_tag:
 190       // An empty slot or ArgInfoData entry marks the end of the trap data
 191       {
 192         return; // Need a block to avoid SS compiler bug
 193       }
 194     default:
 195       fatal("bad tag = %d", tag);
 196     }
 197   }
 198 }
 199 
 200 bool ciMethodData::load_data() {
 201   MethodData* mdo = get_MethodData();
 202   if (mdo == nullptr) {
 203     return false;
 204   }
 205 
 206   // To do: don't copy the data if it is not "ripe" -- require a minimum #
 207   // of invocations.
 208 
 209   // Snapshot the data and extra parameter data first without the extra trap and arg info data.
 210   // Those are copied in a second step. Actually, an approximate snapshot of the data is taken.
 211   // Any concurrently executing threads may be changing the data as we copy it.
 212   //
 213   // The first snapshot step requires two copies (data entries and parameter data entries) since
 214   // the MDO is laid out as follows:
 215   //
 216   //  data_base:        ---------------------------
 217   //                    |       data entries      |
 218   //                    |           ...           |
 219   //  extra_data_base:  ---------------------------
 220   //                    |    trap data entries    |
 221   //                    |           ...           |
 222   //                    | one arg info data entry |
 223   //                    |    data for each arg    |
 224   //                    |           ...           |
 225   //  args_data_limit:  ---------------------------
 226   //                    |  parameter data entries |
 227   //                    |           ...           |
 228   //  param_data_limit: ---------------------------
 229   //                    | ex handler data entries |
 230   //                    |           ...           |
 231   //  extra_data_limit: ---------------------------
 232   //
 233   // _data_size = extra_data_base - data_base
 234   // _extra_data_size = extra_data_limit - extra_data_base
 235   // total_size = _data_size + _extra_data_size
 236   // args_data_limit = param_data_base
 237   // param_data_limit = exception_handler_data_base
 238   // extra_data_limit = extra_data_limit
 239 
 240 #ifndef ZERO
 241   // Some Zero platforms do not have expected alignment, and do not use
 242   // this code. static_assert would still fire and fail for them.
 243   static_assert(sizeof(_orig) % HeapWordSize == 0, "align");
 244 #endif
 245   Copy::disjoint_words_atomic((HeapWord*) &mdo->_compiler_counters,
 246                               (HeapWord*) &_orig,
 247                               sizeof(_orig) / HeapWordSize);
 248   Arena* arena = CURRENT_ENV->arena();
 249   _data_size = mdo->data_size();
 250   _extra_data_size = mdo->extra_data_size();
 251   int total_size = _data_size + _extra_data_size;
 252   _data = (intptr_t *) arena->Amalloc(total_size);
 253   Copy::disjoint_words_atomic((HeapWord*) mdo->data_base(),
 254                               (HeapWord*) _data,
 255                               _data_size / HeapWordSize);
 256   // Copy offsets. This is used below
 257   _parameters_data_offset = mdo->parameters_type_data_di();
 258   _exception_handlers_data_offset = mdo->exception_handlers_data_di();
 259 
 260   int parameters_data_size = mdo->parameters_size_in_bytes();
 261   if (parameters_data_size > 0) {
 262     // Snapshot the parameter data
 263     Copy::disjoint_words_atomic((HeapWord*) mdo->parameters_data_base(),
 264                                 (HeapWord*) parameters_data_base(),
 265                                 parameters_data_size / HeapWordSize);
 266   }
 267   // Traverse the profile data, translating any oops into their
 268   // ci equivalents.
 269   ResourceMark rm;
 270   ciProfileData* ci_data = first_data();
 271   ProfileData* data = mdo->first_data();
 272   while (is_valid(ci_data)) {
 273     ci_data->translate_from(data);
 274     ci_data = next_data(ci_data);
 275     data = mdo->next_data(data);
 276   }
 277   if (mdo->parameters_type_data() != nullptr) {
 278     DataLayout* parameters_data = data_layout_at(_parameters_data_offset);
 279     ciParametersTypeData* parameters = new ciParametersTypeData(parameters_data);
 280     parameters->translate_from(mdo->parameters_type_data());
 281   }
 282 
 283   assert((DataLayout*) ((address)_data + total_size - parameters_data_size - exception_handler_data_size()) == args_data_limit(),
 284       "sanity - parameter data starts after the argument data of the single ArgInfoData entry");
 285   load_remaining_extra_data();
 286 
 287   // Note:  Extra data are all BitData, and do not need translation.
 288   _invocation_counter = mdo->invocation_count();
 289   if (_invocation_counter == 0 && mdo->backedge_count() > 0) {
 290     // Avoid skewing counter data during OSR compilation.
 291     // Sometimes, MDO is allocated during the very first invocation and OSR compilation is triggered
 292     // solely by backedge counter while invocation counter stays zero. In such case, it's important
 293     // to observe non-zero invocation count to properly scale profile counts (see ciMethod::scale_count()).
 294     _invocation_counter = 1;
 295   }
 296 
 297   _state = mdo->is_mature() ? mature_state : immature_state;
 298   _eflags = mdo->eflags();
 299   _arg_local = mdo->arg_local();
 300   _arg_stack = mdo->arg_stack();
 301   _arg_returned  = mdo->arg_returned();
 302   if (ReplayCompiles) {
 303     ciReplay::initialize(this);
 304     if (is_empty()) {
 305       return false;
 306     }
 307   }
 308   return true;
 309 }
 310 
 311 void ciReceiverTypeData::translate_receiver_data_from(const ProfileData* data) {
 312   for (uint row = 0; row < row_limit(); row++) {
 313     Klass* k = data->as_ReceiverTypeData()->receiver(row);
 314     if (k != nullptr && k->class_loader_data() != nullptr && is_klass_loaded(k)) {
 315       if (k->is_loader_alive()) {
 316         ciKlass* klass = CURRENT_ENV->get_klass(k);
 317         set_receiver(row, klass);
 318       } else {
 319         // With concurrent class unloading, the MDO could have stale metadata; override it
 320         clear_row(row);
 321       }
 322     } else {
 323       set_receiver(row, nullptr);
 324     }
 325   }
 326 }
 327 
 328 void ciTypeStackSlotEntries::translate_type_data_from(const TypeStackSlotEntries* entries) {
 329   for (int i = 0; i < number_of_entries(); i++) {
 330     intptr_t k = entries->type(i);
 331     Klass* klass = (Klass*)klass_part(k);
 332     if (klass == nullptr || !klass->is_loader_present_and_alive() || !is_klass_loaded(klass)) {
 333       // With concurrent class unloading, the MDO could have stale metadata; override it
 334       TypeStackSlotEntries::set_type(i, TypeStackSlotEntries::with_status((Klass*)nullptr, k));
 335     } else {
 336       TypeStackSlotEntries::set_type(i, translate_klass(k));
 337     }
 338   }
 339 }
 340 
 341 void ciSingleTypeEntry::translate_type_data_from(const SingleTypeEntry* ret) {
 342   intptr_t k = ret->type();
 343   Klass* klass = (Klass*)klass_part(k);
 344   if (klass == nullptr || !klass->is_loader_present_and_alive() || !is_klass_loaded(klass)) {
 345     // With concurrent class unloading, the MDO could have stale metadata; override it
 346     set_type(SingleTypeEntry::with_status((Klass*)nullptr, k));
 347   } else {
 348     set_type(translate_klass(k));
 349   }
 350 }
 351 
 352 void ciSpeculativeTrapData::translate_from(const ProfileData* data) {
 353   Method* m = data->as_SpeculativeTrapData()->method();
 354   ciMethod* ci_m = CURRENT_ENV->get_method(m);
 355   set_method(ci_m);
 356 }
 357 
 358 // Get the data at an arbitrary (sort of) data index.
 359 ciProfileData* ciMethodData::data_at(int data_index) {
 360   if (out_of_bounds(data_index)) {
 361     return nullptr;
 362   }
 363   DataLayout* data_layout = data_layout_at(data_index);
 364   return data_from(data_layout);
 365 }
 366 
 367 ciProfileData* ciMethodData::data_from(DataLayout* data_layout) {
 368   switch (data_layout->tag()) {
 369   case DataLayout::no_tag:
 370   default:
 371     ShouldNotReachHere();
 372     return nullptr;
 373   case DataLayout::bit_data_tag:
 374     return new ciBitData(data_layout);
 375   case DataLayout::counter_data_tag:
 376     return new ciCounterData(data_layout);
 377   case DataLayout::jump_data_tag:
 378     return new ciJumpData(data_layout);
 379   case DataLayout::receiver_type_data_tag:
 380     return new ciReceiverTypeData(data_layout);
 381   case DataLayout::virtual_call_data_tag:
 382     return new ciVirtualCallData(data_layout);
 383   case DataLayout::ret_data_tag:
 384     return new ciRetData(data_layout);
 385   case DataLayout::branch_data_tag:
 386     return new ciBranchData(data_layout);
 387   case DataLayout::multi_branch_data_tag:
 388     return new ciMultiBranchData(data_layout);
 389   case DataLayout::arg_info_data_tag:
 390     return new ciArgInfoData(data_layout);
 391   case DataLayout::call_type_data_tag:
 392     return new ciCallTypeData(data_layout);
 393   case DataLayout::virtual_call_type_data_tag:
 394     return new ciVirtualCallTypeData(data_layout);
 395   case DataLayout::parameters_type_data_tag:
 396     return new ciParametersTypeData(data_layout);
 397   case DataLayout::array_store_data_tag:
 398     return new ciArrayStoreData(data_layout);
 399   case DataLayout::array_load_data_tag:
 400     return new ciArrayLoadData(data_layout);
 401   case DataLayout::acmp_data_tag:
 402     return new ciACmpData(data_layout);
 403   };
 404 }
 405 
 406 // Iteration over data.
 407 ciProfileData* ciMethodData::next_data(ciProfileData* current) {
 408   int current_index = dp_to_di(current->dp());
 409   int next_index = current_index + current->size_in_bytes();
 410   ciProfileData* next = data_at(next_index);
 411   return next;
 412 }
 413 
 414 DataLayout* ciMethodData::next_data_layout_helper(DataLayout* current, bool extra) {
 415   int current_index = dp_to_di((address)current);
 416   int next_index = current_index + current->size_in_bytes();
 417   if (extra ? out_of_bounds_extra(next_index) : out_of_bounds(next_index)) {
 418     return nullptr;
 419   }
 420   DataLayout* next = data_layout_at(next_index);
 421   return next;
 422 }
 423 
 424 DataLayout* ciMethodData::next_data_layout(DataLayout* current) {
 425   return next_data_layout_helper(current, false);
 426 }
 427 
 428 DataLayout* ciMethodData::next_extra_data_layout(DataLayout* current) {
 429   return next_data_layout_helper(current, true);
 430 }
 431 
 432 ciProfileData* ciMethodData::bci_to_extra_data(int bci, ciMethod* m, bool& two_free_slots) {
 433   DataLayout* dp  = extra_data_base();
 434   DataLayout* end = args_data_limit();
 435   two_free_slots = false;
 436   for (;dp < end; dp = MethodData::next_extra(dp)) {
 437     switch(dp->tag()) {
 438     case DataLayout::no_tag:
 439       _saw_free_extra_data = true;  // observed an empty slot (common case)
 440       two_free_slots = (MethodData::next_extra(dp)->tag() == DataLayout::no_tag);
 441       return nullptr;
 442     case DataLayout::arg_info_data_tag:
 443       return nullptr; // ArgInfoData is after the trap data right before the parameter data.
 444     case DataLayout::bit_data_tag:
 445       if (m == nullptr && dp->bci() == bci) {
 446         return new ciBitData(dp);
 447       }
 448       break;
 449     case DataLayout::speculative_trap_data_tag: {
 450       ciSpeculativeTrapData* data = new ciSpeculativeTrapData(dp);
 451       // data->method() might be null if the MDO is snapshotted
 452       // concurrently with a trap
 453       if (m != nullptr && data->method() == m && dp->bci() == bci) {
 454         return data;
 455       }
 456       break;
 457     }
 458     default:
 459       fatal("bad tag = %d", dp->tag());
 460     }
 461   }
 462   return nullptr;
 463 }
 464 
 465 // Translate a bci to its corresponding data, or nullptr.
 466 ciProfileData* ciMethodData::bci_to_data(int bci, ciMethod* m) {
 467   // If m is not nullptr we look for a SpeculativeTrapData entry
 468   if (m == nullptr) {
 469     DataLayout* data_layout = data_layout_before(bci);
 470     for ( ; is_valid(data_layout); data_layout = next_data_layout(data_layout)) {
 471       if (data_layout->bci() == bci) {
 472         set_hint_di(dp_to_di((address)data_layout));
 473         return data_from(data_layout);
 474       } else if (data_layout->bci() > bci) {
 475         break;
 476       }
 477     }
 478   }
 479   bool two_free_slots = false;
 480   ciProfileData* result = bci_to_extra_data(bci, m, two_free_slots);
 481   if (result != nullptr) {
 482     return result;
 483   }
 484   if (m != nullptr && !two_free_slots) {
 485     // We were looking for a SpeculativeTrapData entry we didn't
 486     // find. Room is not available for more SpeculativeTrapData
 487     // entries, look in the non SpeculativeTrapData entries.
 488     return bci_to_data(bci, nullptr);
 489   }
 490   return nullptr;
 491 }
 492 
 493 ciBitData ciMethodData::exception_handler_bci_to_data(int bci) {
 494   assert(ProfileExceptionHandlers, "not profiling");
 495   assert(_data != nullptr, "must be initialized");
 496   for (DataLayout* data = exception_handler_data_base(); data < exception_handler_data_limit(); data = next_extra_data_layout(data)) {
 497     assert(data != nullptr, "out of bounds?");
 498     if (data->bci() == bci) {
 499       return ciBitData(data);
 500     }
 501   }
 502   // called with invalid bci or wrong Method/MethodData
 503   ShouldNotReachHere();
 504   return ciBitData(nullptr);
 505 }
 506 
 507 // Conservatively decode the trap_state of a ciProfileData.
 508 int ciMethodData::has_trap_at(ciProfileData* data, int reason) {
 509   typedef Deoptimization::DeoptReason DR_t;
 510   int per_bc_reason
 511     = Deoptimization::reason_recorded_per_bytecode_if_any((DR_t) reason);
 512   if (trap_count(reason) == 0) {
 513     // Impossible for this trap to have occurred, regardless of trap_state.
 514     // Note:  This happens if the MDO is empty.
 515     return 0;
 516   } else if (per_bc_reason == Deoptimization::Reason_none) {
 517     // We cannot conclude anything; a trap happened somewhere, maybe here.
 518     return -1;
 519   } else if (data == nullptr) {
 520     // No profile here, not even an extra_data record allocated on the fly.
 521     // If there are empty extra_data records, and there had been a trap,
 522     // there would have been a non-null data pointer.  If there are no
 523     // free extra_data records, we must return a conservative -1.
 524     if (_saw_free_extra_data)
 525       return 0;                 // Q.E.D.
 526     else
 527       return -1;                // bail with a conservative answer
 528   } else {
 529     return Deoptimization::trap_state_has_reason(data->trap_state(), per_bc_reason);
 530   }
 531 }
 532 
 533 int ciMethodData::trap_recompiled_at(ciProfileData* data) {
 534   if (data == nullptr) {
 535     return (_saw_free_extra_data? 0: -1);  // (see previous method)
 536   } else {
 537     return Deoptimization::trap_state_is_recompiled(data->trap_state())? 1: 0;
 538   }
 539 }
 540 
 541 void ciMethodData::clear_escape_info() {
 542   VM_ENTRY_MARK;
 543   MethodData* mdo = get_MethodData();
 544   if (mdo != nullptr) {
 545     mdo->clear_escape_info();
 546     ArgInfoData *aid = arg_info();
 547     int arg_count = (aid == nullptr) ? 0 : aid->number_of_args();
 548     for (int i = 0; i < arg_count; i++) {
 549       set_arg_modified(i, 0);
 550     }
 551   }
 552   _eflags = _arg_local = _arg_stack = _arg_returned = 0;
 553 }
 554 
 555 // copy our escape info to the MethodData* if it exists
 556 void ciMethodData::update_escape_info() {
 557   VM_ENTRY_MARK;
 558   MethodData* mdo = get_MethodData();
 559   if ( mdo != nullptr) {
 560     mdo->set_eflags(_eflags);
 561     mdo->set_arg_local(_arg_local);
 562     mdo->set_arg_stack(_arg_stack);
 563     mdo->set_arg_returned(_arg_returned);
 564     int arg_count = mdo->method()->size_of_parameters();
 565     for (int i = 0; i < arg_count; i++) {
 566       mdo->set_arg_modified(i, arg_modified(i));
 567     }
 568   }
 569 }
 570 
 571 void ciMethodData::set_compilation_stats(short loops, short blocks) {
 572   VM_ENTRY_MARK;
 573   MethodData* mdo = get_MethodData();
 574   if (mdo != nullptr) {
 575     mdo->set_num_loops(loops);
 576     mdo->set_num_blocks(blocks);
 577   }
 578 }
 579 
 580 void ciMethodData::set_would_profile(bool p) {
 581   VM_ENTRY_MARK;
 582   MethodData* mdo = get_MethodData();
 583   if (mdo != nullptr) {
 584     mdo->set_would_profile(p);
 585   }
 586 }
 587 
 588 void ciMethodData::set_argument_type(int bci, int i, ciKlass* k) {
 589   VM_ENTRY_MARK;
 590   MethodData* mdo = get_MethodData();
 591   if (mdo != nullptr) {
 592     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
 593     MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 594 
 595     ProfileData* data = mdo->bci_to_data(bci);
 596     if (data != nullptr) {
 597       if (data->is_CallTypeData()) {
 598         data->as_CallTypeData()->set_argument_type(i, k->get_Klass());
 599       } else {
 600         assert(data->is_VirtualCallTypeData(), "no arguments!");
 601         data->as_VirtualCallTypeData()->set_argument_type(i, k->get_Klass());
 602       }
 603     }
 604   }
 605 }
 606 
 607 void ciMethodData::set_parameter_type(int i, ciKlass* k) {
 608   VM_ENTRY_MARK;
 609   MethodData* mdo = get_MethodData();
 610   if (mdo != nullptr) {
 611     mdo->parameters_type_data()->set_type(i, k->get_Klass());
 612   }
 613 }
 614 
 615 void ciMethodData::set_return_type(int bci, ciKlass* k) {
 616   VM_ENTRY_MARK;
 617   MethodData* mdo = get_MethodData();
 618   if (mdo != nullptr) {
 619     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
 620     MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 621 
 622     ProfileData* data = mdo->bci_to_data(bci);
 623     if (data != nullptr) {
 624       if (data->is_CallTypeData()) {
 625         data->as_CallTypeData()->set_return_type(k->get_Klass());
 626       } else {
 627         assert(data->is_VirtualCallTypeData(), "no arguments!");
 628         data->as_VirtualCallTypeData()->set_return_type(k->get_Klass());
 629       }
 630     }
 631   }
 632 }
 633 
 634 bool ciMethodData::has_escape_info() {
 635   return eflag_set(MethodData::estimated);
 636 }
 637 
 638 void ciMethodData::set_eflag(MethodData::EscapeFlag f) {
 639   set_bits(_eflags, f);
 640 }
 641 
 642 bool ciMethodData::eflag_set(MethodData::EscapeFlag f) const {
 643   return mask_bits(_eflags, f) != 0;
 644 }
 645 
 646 void ciMethodData::set_arg_local(int i) {
 647   set_nth_bit(_arg_local, i);
 648 }
 649 
 650 void ciMethodData::set_arg_stack(int i) {
 651   set_nth_bit(_arg_stack, i);
 652 }
 653 
 654 void ciMethodData::set_arg_returned(int i) {
 655   set_nth_bit(_arg_returned, i);
 656 }
 657 
 658 void ciMethodData::set_arg_modified(int arg, uint val) {
 659   ArgInfoData *aid = arg_info();
 660   if (aid == nullptr)
 661     return;
 662   assert(arg >= 0 && arg < aid->number_of_args(), "valid argument number");
 663   aid->set_arg_modified(arg, val);
 664 }
 665 
 666 bool ciMethodData::is_arg_local(int i) const {
 667   return is_set_nth_bit(_arg_local, i);
 668 }
 669 
 670 bool ciMethodData::is_arg_stack(int i) const {
 671   return is_set_nth_bit(_arg_stack, i);
 672 }
 673 
 674 bool ciMethodData::is_arg_returned(int i) const {
 675   return is_set_nth_bit(_arg_returned, i);
 676 }
 677 
 678 uint ciMethodData::arg_modified(int arg) const {
 679   ArgInfoData *aid = arg_info();
 680   if (aid == nullptr)
 681     return 0;
 682   assert(arg >= 0 && arg < aid->number_of_args(), "valid argument number");
 683   return aid->arg_modified(arg);
 684 }
 685 
 686 ciParametersTypeData* ciMethodData::parameters_type_data() const {
 687   return parameter_data_size() != 0 ? new ciParametersTypeData(data_layout_at(_parameters_data_offset)) : nullptr;
 688 }
 689 
 690 ByteSize ciMethodData::offset_of_slot(ciProfileData* data, ByteSize slot_offset_in_data) {
 691   // Get offset within MethodData* of the data array
 692   ByteSize data_offset = MethodData::data_offset();
 693 
 694   // Get cell offset of the ProfileData within data array
 695   int cell_offset = dp_to_di(data->dp());
 696 
 697   // Add in counter_offset, the # of bytes into the ProfileData of counter or flag
 698   int offset = in_bytes(data_offset) + cell_offset + in_bytes(slot_offset_in_data);
 699 
 700   return in_ByteSize(offset);
 701 }
 702 
 703 ciArgInfoData *ciMethodData::arg_info() const {
 704   // Should be last, have to skip all traps.
 705   DataLayout* dp  = extra_data_base();
 706   DataLayout* end = args_data_limit();
 707   for (; dp < end; dp = MethodData::next_extra(dp)) {
 708     if (dp->tag() == DataLayout::arg_info_data_tag)
 709       return new ciArgInfoData(dp);
 710   }
 711   return nullptr;
 712 }
 713 
 714 
 715 // Implementation of the print method.
 716 void ciMethodData::print_impl(outputStream* st) {
 717   ciMetadata::print_impl(st);
 718 }
 719 
 720 void ciMethodData::dump_replay_data_type_helper(outputStream* out, int round, int& count, ProfileData* pdata, ByteSize offset, ciKlass* k) {
 721   if (k != nullptr) {
 722     if (round == 0) {
 723       count++;
 724     } else {
 725       if (Arguments::is_valhalla_enabled() && k->is_obj_array_klass()) {
 726         // For value class arrays, we also record the array property to load the correct array class during replay.
 727         ArrayKlass::ArrayProperties array_properties = k->as_obj_array_klass()->properties();
 728         out->print(" %d %s %d", static_cast<int>(dp_to_di(pdata->dp() + in_bytes(offset)) / sizeof(intptr_t)),
 729                                       CURRENT_ENV->replay_name(k), static_cast<int>(array_properties));
 730       } else {
 731         out->print(" %d %s", static_cast<int>(dp_to_di(pdata->dp() + in_bytes(offset)) / sizeof(intptr_t)),
 732                              CURRENT_ENV->replay_name(k));
 733       }
 734     }
 735   }
 736 }
 737 
 738 template<class T> void ciMethodData::dump_replay_data_receiver_type_helper(outputStream* out, int round, int& count, T* vdata) {
 739   for (uint i = 0; i < vdata->row_limit(); i++) {
 740     dump_replay_data_type_helper(out, round, count, vdata, vdata->receiver_offset(i), vdata->receiver(i));
 741   }
 742 }
 743 
 744 template<class T> void ciMethodData::dump_replay_data_call_type_helper(outputStream* out, int round, int& count, T* call_type_data) {
 745   if (call_type_data->has_arguments()) {
 746     for (int i = 0; i < call_type_data->number_of_arguments(); i++) {
 747       dump_replay_data_type_helper(out, round, count, call_type_data, call_type_data->argument_type_offset(i), call_type_data->valid_argument_type(i));
 748     }
 749   }
 750   if (call_type_data->has_return()) {
 751     dump_replay_data_type_helper(out, round, count, call_type_data, call_type_data->return_type_offset(), call_type_data->valid_return_type());
 752   }
 753 }
 754 
 755 void ciMethodData::dump_replay_data_extra_data_helper(outputStream* out, int round, int& count) {
 756   DataLayout* dp  = extra_data_base();
 757   DataLayout* end = args_data_limit();
 758 
 759   for (;dp < end; dp = MethodData::next_extra(dp)) {
 760     switch(dp->tag()) {
 761     case DataLayout::no_tag:
 762     case DataLayout::arg_info_data_tag:
 763       return;
 764     case DataLayout::bit_data_tag:
 765       break;
 766     case DataLayout::speculative_trap_data_tag: {
 767       ciSpeculativeTrapData* data = new ciSpeculativeTrapData(dp);
 768       ciMethod* m = data->method();
 769       if (m != nullptr) {
 770         if (round == 0) {
 771           count++;
 772         } else {
 773           out->print(" %d ", (int)(dp_to_di(((address)dp) + in_bytes(ciSpeculativeTrapData::method_offset())) / sizeof(intptr_t)));
 774           m->dump_name_as_ascii(out);
 775         }
 776       }
 777       break;
 778     }
 779     default:
 780       fatal("bad tag = %d", dp->tag());
 781     }
 782   }
 783 }
 784 
 785 void ciMethodData::dump_replay_data(outputStream* out) {
 786   ResourceMark rm;
 787   MethodData* mdo = get_MethodData();
 788   Method* method = mdo->method();
 789   out->print("ciMethodData ");
 790   ciMethod::dump_name_as_ascii(out, method);
 791   out->print(" %d %d", _state, _invocation_counter);
 792 
 793   // dump the contents of the MDO header as raw data
 794   unsigned char* orig = (unsigned char*)&_orig;
 795   int length = sizeof(_orig);
 796   out->print(" orig %d", length);
 797   for (int i = 0; i < length; i++) {
 798     out->print(" %d", orig[i]);
 799   }
 800 
 801   // dump the MDO data as raw data
 802   int elements = (data_size() + extra_data_size()) / sizeof(intptr_t);
 803   out->print(" data %d", elements);
 804   for (int i = 0; i < elements; i++) {
 805     // We could use INTPTR_FORMAT here but that's zero justified
 806     // which makes comparing it with the SA version of this output
 807     // harder. data()'s element type is intptr_t.
 808     out->print(" 0x%zx", data()[i]);
 809   }
 810 
 811   // The MDO contained oop references as ciObjects, so scan for those
 812   // and emit pairs of offset and klass name so that they can be
 813   // reconstructed at runtime.  The first round counts the number of
 814   // oop references and the second actually emits them.
 815   ciParametersTypeData* parameters = parameters_type_data();
 816   for (int count = 0, round = 0; round < 2; round++) {
 817     if (round == 1) out->print(" oops %d", count);
 818     ProfileData* pdata = first_data();
 819     for ( ; is_valid(pdata); pdata = next_data(pdata)) {
 820       if (pdata->is_VirtualCallData()) {
 821         ciVirtualCallData* vdata = (ciVirtualCallData*)pdata;
 822         dump_replay_data_receiver_type_helper<ciVirtualCallData>(out, round, count, vdata);
 823         if (pdata->is_VirtualCallTypeData()) {
 824           ciVirtualCallTypeData* call_type_data = (ciVirtualCallTypeData*)pdata;
 825           dump_replay_data_call_type_helper<ciVirtualCallTypeData>(out, round, count, call_type_data);
 826         }
 827       } else if (pdata->is_CallTypeData()) {
 828         ciCallTypeData* call_type_data = (ciCallTypeData*)pdata;
 829         dump_replay_data_call_type_helper<ciCallTypeData>(out, round, count, call_type_data);
 830       } else if (pdata->is_ArrayStoreData()) {
 831         ciArrayStoreData* array_store_data = (ciArrayStoreData*)pdata;
 832         dump_replay_data_type_helper(out, round, count, array_store_data, ciArrayStoreData::array_offset(),
 833                                      array_store_data->array()->valid_type());
 834         dump_replay_data_receiver_type_helper<ciArrayStoreData>(out, round, count, array_store_data);
 835       } else if (pdata->is_ArrayLoadData()) {
 836         ciArrayLoadData* array_load_data = (ciArrayLoadData*)pdata;
 837         dump_replay_data_type_helper(out, round, count, array_load_data, ciArrayLoadData::array_offset(),
 838                                      array_load_data->array()->valid_type());
 839         dump_replay_data_type_helper(out, round, count, array_load_data, ciArrayLoadData::element_offset(),
 840                                      array_load_data->element()->valid_type());
 841       } else if (pdata->is_ACmpData()) {
 842         ciACmpData* acmp_data = (ciACmpData*)pdata;
 843         dump_replay_data_type_helper(out, round, count, acmp_data, ciACmpData::left_offset(),
 844                                      acmp_data->left()->valid_type());
 845         dump_replay_data_type_helper(out, round, count, acmp_data, ciACmpData::right_offset(),
 846                                      acmp_data->right()->valid_type());
 847       } else if (pdata->is_ReceiverTypeData()) {
 848         ciReceiverTypeData* vdata = (ciReceiverTypeData*)pdata;
 849         dump_replay_data_receiver_type_helper<ciReceiverTypeData>(out, round, count, vdata);
 850       }
 851     }
 852     if (parameters != nullptr) {
 853       for (int i = 0; i < parameters->number_of_parameters(); i++) {
 854         dump_replay_data_type_helper(out, round, count, parameters, ParametersTypeData::type_offset(i), parameters->valid_parameter_type(i));
 855       }
 856     }
 857   }
 858   for (int count = 0, round = 0; round < 2; round++) {
 859     if (round == 1) out->print(" methods %d", count);
 860     dump_replay_data_extra_data_helper(out, round, count);
 861   }
 862   out->cr();
 863 }
 864 
 865 #ifndef PRODUCT
 866 void ciMethodData::print() {
 867   print_data_on(tty);
 868 }
 869 
 870 void ciMethodData::print_data_on(outputStream* st) {
 871   ResourceMark rm;
 872   ciParametersTypeData* parameters = parameters_type_data();
 873   if (parameters != nullptr) {
 874     parameters->print_data_on(st);
 875   }
 876   ciProfileData* data;
 877   for (data = first_data(); is_valid(data); data = next_data(data)) {
 878     st->print("%d", dp_to_di(data->dp()));
 879     st->fill_to(6);
 880     data->print_data_on(st);
 881   }
 882   st->print_cr("--- Extra data:");
 883   DataLayout* dp  = extra_data_base();
 884   DataLayout* end = args_data_limit();
 885   for (;; dp = MethodData::next_extra(dp)) {
 886     assert(dp < end, "moved past end of extra data");
 887     switch (dp->tag()) {
 888     case DataLayout::no_tag:
 889       continue;
 890     case DataLayout::bit_data_tag:
 891       data = new BitData(dp);
 892       break;
 893     case DataLayout::arg_info_data_tag:
 894       data = new ciArgInfoData(dp);
 895       dp = end; // ArgInfoData is after the trap data right before the parameter data.
 896       break;
 897     case DataLayout::speculative_trap_data_tag:
 898       data = new ciSpeculativeTrapData(dp);
 899       break;
 900     default:
 901       fatal("unexpected tag %d", dp->tag());
 902     }
 903     st->print("%d", dp_to_di(data->dp()));
 904     st->fill_to(6);
 905     data->print_data_on(st);
 906     if (dp >= end) return;
 907   }
 908 }
 909 
 910 void ciTypeEntries::print_ciklass(outputStream* st, intptr_t k) {
 911   if (TypeEntries::is_type_none(k)) {
 912     st->print("none");
 913   } else if (TypeEntries::is_type_unknown(k)) {
 914     st->print("unknown");
 915   } else {
 916     valid_ciklass(k)->print_name_on(st);
 917   }
 918   if (TypeEntries::was_null_seen(k)) {
 919     st->print(" (null seen)");
 920   }
 921 }
 922 
 923 void ciTypeStackSlotEntries::print_data_on(outputStream* st) const {
 924   for (int i = 0; i < number_of_entries(); i++) {
 925     _pd->tab(st);
 926     st->print("%d: stack (%u) ", i, stack_slot(i));
 927     print_ciklass(st, type(i));
 928     st->cr();
 929   }
 930 }
 931 
 932 void ciSingleTypeEntry::print_data_on(outputStream* st) const {
 933   _pd->tab(st);
 934   st->print("ret ");
 935   print_ciklass(st, type());
 936   st->cr();
 937 }
 938 
 939 void ciCallTypeData::print_data_on(outputStream* st, const char* extra) const {
 940   print_shared(st, "ciCallTypeData", extra);
 941   if (has_arguments()) {
 942     tab(st, true);
 943     st->print_cr("argument types");
 944     args()->print_data_on(st);
 945   }
 946   if (has_return()) {
 947     tab(st, true);
 948     st->print_cr("return type");
 949     ret()->print_data_on(st);
 950   }
 951 }
 952 
 953 void ciReceiverTypeData::print_receiver_data_on(outputStream* st) const {
 954   uint row;
 955   int entries = 0;
 956   for (row = 0; row < row_limit(); row++) {
 957     if (receiver(row) != nullptr)  entries++;
 958   }
 959   st->print_cr("count(%u) entries(%u)", count(), entries);
 960   for (row = 0; row < row_limit(); row++) {
 961     if (receiver(row) != nullptr) {
 962       tab(st);
 963       receiver(row)->print_name_on(st);
 964       st->print_cr("(%u)", receiver_count(row));
 965     }
 966   }
 967 }
 968 
 969 void ciReceiverTypeData::print_data_on(outputStream* st, const char* extra) const {
 970   print_shared(st, "ciReceiverTypeData", extra);
 971   print_receiver_data_on(st);
 972 }
 973 
 974 void ciVirtualCallData::print_data_on(outputStream* st, const char* extra) const {
 975   print_shared(st, "ciVirtualCallData", extra);
 976   rtd_super()->print_receiver_data_on(st);
 977 }
 978 
 979 void ciVirtualCallTypeData::print_data_on(outputStream* st, const char* extra) const {
 980   print_shared(st, "ciVirtualCallTypeData", extra);
 981   rtd_super()->print_receiver_data_on(st);
 982   if (has_arguments()) {
 983     tab(st, true);
 984     st->print("argument types");
 985     args()->print_data_on(st);
 986   }
 987   if (has_return()) {
 988     tab(st, true);
 989     st->print("return type");
 990     ret()->print_data_on(st);
 991   }
 992 }
 993 
 994 void ciParametersTypeData::print_data_on(outputStream* st, const char* extra) const {
 995   st->print_cr("ciParametersTypeData");
 996   parameters()->print_data_on(st);
 997 }
 998 
 999 void ciSpeculativeTrapData::print_data_on(outputStream* st, const char* extra) const {
1000   st->print_cr("ciSpeculativeTrapData");
1001   tab(st);
1002   method()->print_short_name(st);
1003   st->cr();
1004 }
1005 
1006 void ciArrayStoreData::print_data_on(outputStream* st, const char* extra) const {
1007   print_shared(st, "ciArrayStoreData", extra);
1008   st->cr();
1009   tab(st, true);
1010   st->print("array");
1011   array()->print_data_on(st);
1012   tab(st, true);
1013   st->print("element");
1014   rtd_super()->print_receiver_data_on(st);
1015 }
1016 
1017 void ciArrayLoadData::print_data_on(outputStream* st, const char* extra) const {
1018   print_shared(st, "ciArrayLoadData", extra);
1019   st->cr();
1020   tab(st, true);
1021   st->print("array");
1022   array()->print_data_on(st);
1023   tab(st, true);
1024   st->print("element");
1025   element()->print_data_on(st);
1026 }
1027 
1028 void ciACmpData::print_data_on(outputStream* st, const char* extra) const {
1029   BranchData::print_data_on(st, extra);
1030   st->cr();
1031   tab(st, true);
1032   st->print("left");
1033   left()->print_data_on(st);
1034   tab(st, true);
1035   st->print("right");
1036   right()->print_data_on(st);
1037 }
1038 #endif