1 /*
   2  * Copyright (c) 2000, 2022, 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 "precompiled.hpp"
  26 #include "ci/ciMethodData.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "compiler/compilationPolicy.hpp"
  29 #include "compiler/compilerDefinitions.inline.hpp"
  30 #include "compiler/compilerOracle.hpp"
  31 #include "interpreter/bytecode.hpp"
  32 #include "interpreter/bytecodeStream.hpp"
  33 #include "interpreter/linkResolver.hpp"
  34 #include "memory/metaspaceClosure.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "oops/klass.inline.hpp"
  37 #include "oops/methodData.inline.hpp"
  38 #include "prims/jvmtiRedefineClasses.hpp"
  39 #include "runtime/atomic.hpp"
  40 #include "runtime/deoptimization.hpp"
  41 #include "runtime/handles.inline.hpp"
  42 #include "runtime/orderAccess.hpp"
  43 #include "runtime/safepointVerifiers.hpp"
  44 #include "runtime/signature.hpp"
  45 #include "utilities/align.hpp"
  46 #include "utilities/copy.hpp"
  47 
  48 // ==================================================================
  49 // DataLayout
  50 //
  51 // Overlay for generic profiling data.
  52 
  53 // Some types of data layouts need a length field.
  54 bool DataLayout::needs_array_len(u1 tag) {
  55   return (tag == multi_branch_data_tag) || (tag == arg_info_data_tag) || (tag == parameters_type_data_tag);
  56 }
  57 
  58 // Perform generic initialization of the data.  More specific
  59 // initialization occurs in overrides of ProfileData::post_initialize.
  60 void DataLayout::initialize(u1 tag, u2 bci, int cell_count) {
  61   _header._bits = (intptr_t)0;
  62   _header._struct._tag = tag;
  63   _header._struct._bci = bci;
  64   for (int i = 0; i < cell_count; i++) {
  65     set_cell_at(i, (intptr_t)0);
  66   }
  67   if (needs_array_len(tag)) {
  68     set_cell_at(ArrayData::array_len_off_set, cell_count - 1); // -1 for header.
  69   }
  70   if (tag == call_type_data_tag) {
  71     CallTypeData::initialize(this, cell_count);
  72   } else if (tag == virtual_call_type_data_tag) {
  73     VirtualCallTypeData::initialize(this, cell_count);
  74   }
  75 }
  76 
  77 void DataLayout::clean_weak_klass_links(bool always_clean) {
  78   ResourceMark m;
  79   data_in()->clean_weak_klass_links(always_clean);
  80 }
  81 
  82 
  83 // ==================================================================
  84 // ProfileData
  85 //
  86 // A ProfileData object is created to refer to a section of profiling
  87 // data in a structured way.
  88 
  89 // Constructor for invalid ProfileData.
  90 ProfileData::ProfileData() {
  91   _data = NULL;
  92 }
  93 
  94 char* ProfileData::print_data_on_helper(const MethodData* md) const {
  95   DataLayout* dp  = md->extra_data_base();
  96   DataLayout* end = md->args_data_limit();
  97   stringStream ss;
  98   for (;; dp = MethodData::next_extra(dp)) {
  99     assert(dp < end, "moved past end of extra data");
 100     switch(dp->tag()) {
 101     case DataLayout::speculative_trap_data_tag:
 102       if (dp->bci() == bci()) {
 103         SpeculativeTrapData* data = new SpeculativeTrapData(dp);
 104         int trap = data->trap_state();
 105         char buf[100];
 106         ss.print("trap/");
 107         data->method()->print_short_name(&ss);
 108         ss.print("(%s) ", Deoptimization::format_trap_state(buf, sizeof(buf), trap));
 109       }
 110       break;
 111     case DataLayout::bit_data_tag:
 112       break;
 113     case DataLayout::no_tag:
 114     case DataLayout::arg_info_data_tag:
 115       return ss.as_string();
 116       break;
 117     default:
 118       fatal("unexpected tag %d", dp->tag());
 119     }
 120   }
 121   return NULL;
 122 }
 123 
 124 void ProfileData::print_data_on(outputStream* st, const MethodData* md) const {
 125   print_data_on(st, print_data_on_helper(md));
 126 }
 127 
 128 void ProfileData::print_shared(outputStream* st, const char* name, const char* extra) const {
 129   st->print("bci: %d", bci());
 130   st->fill_to(tab_width_one);
 131   st->print("%s", name);
 132   tab(st);
 133   int trap = trap_state();
 134   if (trap != 0) {
 135     char buf[100];
 136     st->print("trap(%s) ", Deoptimization::format_trap_state(buf, sizeof(buf), trap));
 137   }
 138   if (extra != NULL) {
 139     st->print("%s", extra);
 140   }
 141   int flags = data()->flags();
 142   if (flags != 0) {
 143     st->print("flags(%d) ", flags);
 144   }
 145 }
 146 
 147 void ProfileData::tab(outputStream* st, bool first) const {
 148   st->fill_to(first ? tab_width_one : tab_width_two);
 149 }
 150 
 151 // ==================================================================
 152 // BitData
 153 //
 154 // A BitData corresponds to a one-bit flag.  This is used to indicate
 155 // whether a checkcast bytecode has seen a null value.
 156 
 157 
 158 void BitData::print_data_on(outputStream* st, const char* extra) const {
 159   print_shared(st, "BitData", extra);
 160   st->cr();
 161 }
 162 
 163 // ==================================================================
 164 // CounterData
 165 //
 166 // A CounterData corresponds to a simple counter.
 167 
 168 void CounterData::print_data_on(outputStream* st, const char* extra) const {
 169   print_shared(st, "CounterData", extra);
 170   st->print_cr("count(%u)", count());
 171 }
 172 
 173 // ==================================================================
 174 // JumpData
 175 //
 176 // A JumpData is used to access profiling information for a direct
 177 // branch.  It is a counter, used for counting the number of branches,
 178 // plus a data displacement, used for realigning the data pointer to
 179 // the corresponding target bci.
 180 
 181 void JumpData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 182   assert(stream->bci() == bci(), "wrong pos");
 183   int target;
 184   Bytecodes::Code c = stream->code();
 185   if (c == Bytecodes::_goto_w || c == Bytecodes::_jsr_w) {
 186     target = stream->dest_w();
 187   } else {
 188     target = stream->dest();
 189   }
 190   int my_di = mdo->dp_to_di(dp());
 191   int target_di = mdo->bci_to_di(target);
 192   int offset = target_di - my_di;
 193   set_displacement(offset);
 194 }
 195 
 196 void JumpData::print_data_on(outputStream* st, const char* extra) const {
 197   print_shared(st, "JumpData", extra);
 198   st->print_cr("taken(%u) displacement(%d)", taken(), displacement());
 199 }
 200 
 201 int TypeStackSlotEntries::compute_cell_count(Symbol* signature, bool include_receiver, int max) {
 202   // Parameter profiling include the receiver
 203   int args_count = include_receiver ? 1 : 0;
 204   ResourceMark rm;
 205   ReferenceArgumentCount rac(signature);
 206   args_count += rac.count();
 207   args_count = MIN2(args_count, max);
 208   return args_count * per_arg_cell_count;
 209 }
 210 
 211 int TypeEntriesAtCall::compute_cell_count(BytecodeStream* stream) {
 212   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
 213   assert(TypeStackSlotEntries::per_arg_count() > ReturnTypeEntry::static_cell_count(), "code to test for arguments/results broken");
 214   const methodHandle m = stream->method();
 215   int bci = stream->bci();
 216   Bytecode_invoke inv(m, bci);
 217   int args_cell = 0;
 218   if (MethodData::profile_arguments_for_invoke(m, bci)) {
 219     args_cell = TypeStackSlotEntries::compute_cell_count(inv.signature(), false, TypeProfileArgsLimit);
 220   }
 221   int ret_cell = 0;
 222   if (MethodData::profile_return_for_invoke(m, bci) && is_reference_type(inv.result_type())) {
 223     ret_cell = ReturnTypeEntry::static_cell_count();
 224   }
 225   int header_cell = 0;
 226   if (args_cell + ret_cell > 0) {
 227     header_cell = header_cell_count();
 228   }
 229 
 230   return header_cell + args_cell + ret_cell;
 231 }
 232 
 233 class ArgumentOffsetComputer : public SignatureIterator {
 234 private:
 235   int _max;
 236   int _offset;
 237   GrowableArray<int> _offsets;
 238 
 239   friend class SignatureIterator;  // so do_parameters_on can call do_type
 240   void do_type(BasicType type) {
 241     if (is_reference_type(type) && _offsets.length() < _max) {
 242       _offsets.push(_offset);
 243     }
 244     _offset += parameter_type_word_count(type);
 245   }
 246 
 247  public:
 248   ArgumentOffsetComputer(Symbol* signature, int max)
 249     : SignatureIterator(signature),
 250       _max(max), _offset(0),
 251       _offsets(max) {
 252     do_parameters_on(this);  // non-virtual template execution
 253   }
 254 
 255   int off_at(int i) const { return _offsets.at(i); }
 256 };
 257 
 258 void TypeStackSlotEntries::post_initialize(Symbol* signature, bool has_receiver, bool include_receiver) {
 259   ResourceMark rm;
 260   int start = 0;
 261   // Parameter profiling include the receiver
 262   if (include_receiver && has_receiver) {
 263     set_stack_slot(0, 0);
 264     set_type(0, type_none());
 265     start += 1;
 266   }
 267   ArgumentOffsetComputer aos(signature, _number_of_entries-start);
 268   for (int i = start; i < _number_of_entries; i++) {
 269     set_stack_slot(i, aos.off_at(i-start) + (has_receiver ? 1 : 0));
 270     set_type(i, type_none());
 271   }
 272 }
 273 
 274 void CallTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 275   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
 276   Bytecode_invoke inv(stream->method(), stream->bci());
 277 
 278   if (has_arguments()) {
 279 #ifdef ASSERT
 280     ResourceMark rm;
 281     ReferenceArgumentCount rac(inv.signature());
 282     int count = MIN2(rac.count(), (int)TypeProfileArgsLimit);
 283     assert(count > 0, "room for args type but none found?");
 284     check_number_of_arguments(count);
 285 #endif
 286     _args.post_initialize(inv.signature(), inv.has_receiver(), false);
 287   }
 288 
 289   if (has_return()) {
 290     assert(is_reference_type(inv.result_type()), "room for a ret type but doesn't return obj?");
 291     _ret.post_initialize();
 292   }
 293 }
 294 
 295 void VirtualCallTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 296   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
 297   Bytecode_invoke inv(stream->method(), stream->bci());
 298 
 299   if (has_arguments()) {
 300 #ifdef ASSERT
 301     ResourceMark rm;
 302     ReferenceArgumentCount rac(inv.signature());
 303     int count = MIN2(rac.count(), (int)TypeProfileArgsLimit);
 304     assert(count > 0, "room for args type but none found?");
 305     check_number_of_arguments(count);
 306 #endif
 307     _args.post_initialize(inv.signature(), inv.has_receiver(), false);
 308   }
 309 
 310   if (has_return()) {
 311     assert(is_reference_type(inv.result_type()), "room for a ret type but doesn't return obj?");
 312     _ret.post_initialize();
 313   }
 314 }
 315 
 316 void TypeStackSlotEntries::clean_weak_klass_links(bool always_clean) {
 317   for (int i = 0; i < _number_of_entries; i++) {
 318     intptr_t p = type(i);
 319     Klass* k = (Klass*)klass_part(p);
 320     if (k != NULL && (always_clean || !k->is_loader_alive())) {
 321       set_type(i, with_status((Klass*)NULL, p));
 322     }
 323   }
 324 }
 325 
 326 void ReturnTypeEntry::clean_weak_klass_links(bool always_clean) {
 327   intptr_t p = type();
 328   Klass* k = (Klass*)klass_part(p);
 329   if (k != NULL && (always_clean || !k->is_loader_alive())) {
 330     set_type(with_status((Klass*)NULL, p));
 331   }
 332 }
 333 
 334 bool TypeEntriesAtCall::return_profiling_enabled() {
 335   return MethodData::profile_return();
 336 }
 337 
 338 bool TypeEntriesAtCall::arguments_profiling_enabled() {
 339   return MethodData::profile_arguments();
 340 }
 341 
 342 void TypeEntries::print_klass(outputStream* st, intptr_t k) {
 343   if (is_type_none(k)) {
 344     st->print("none");
 345   } else if (is_type_unknown(k)) {
 346     st->print("unknown");
 347   } else {
 348     valid_klass(k)->print_value_on(st);
 349   }
 350   if (was_null_seen(k)) {
 351     st->print(" (null seen)");
 352   }
 353 }
 354 
 355 void TypeStackSlotEntries::print_data_on(outputStream* st) const {
 356   for (int i = 0; i < _number_of_entries; i++) {
 357     _pd->tab(st);
 358     st->print("%d: stack(%u) ", i, stack_slot(i));
 359     print_klass(st, type(i));
 360     st->cr();
 361   }
 362 }
 363 
 364 void ReturnTypeEntry::print_data_on(outputStream* st) const {
 365   _pd->tab(st);
 366   print_klass(st, type());
 367   st->cr();
 368 }
 369 
 370 void CallTypeData::print_data_on(outputStream* st, const char* extra) const {
 371   CounterData::print_data_on(st, extra);
 372   if (has_arguments()) {
 373     tab(st, true);
 374     st->print("argument types");
 375     _args.print_data_on(st);
 376   }
 377   if (has_return()) {
 378     tab(st, true);
 379     st->print("return type");
 380     _ret.print_data_on(st);
 381   }
 382 }
 383 
 384 void VirtualCallTypeData::print_data_on(outputStream* st, const char* extra) const {
 385   VirtualCallData::print_data_on(st, extra);
 386   if (has_arguments()) {
 387     tab(st, true);
 388     st->print("argument types");
 389     _args.print_data_on(st);
 390   }
 391   if (has_return()) {
 392     tab(st, true);
 393     st->print("return type");
 394     _ret.print_data_on(st);
 395   }
 396 }
 397 
 398 // ==================================================================
 399 // ReceiverTypeData
 400 //
 401 // A ReceiverTypeData is used to access profiling information about a
 402 // dynamic type check.  It consists of a counter which counts the total times
 403 // that the check is reached, and a series of (Klass*, count) pairs
 404 // which are used to store a type profile for the receiver of the check.
 405 
 406 void ReceiverTypeData::clean_weak_klass_links(bool always_clean) {
 407     for (uint row = 0; row < row_limit(); row++) {
 408     Klass* p = receiver(row);
 409     if (p != NULL && (always_clean || !p->is_loader_alive())) {
 410       clear_row(row);
 411     }
 412   }
 413 }
 414 
 415 void ReceiverTypeData::print_receiver_data_on(outputStream* st) const {
 416   uint row;
 417   int entries = 0;
 418   for (row = 0; row < row_limit(); row++) {
 419     if (receiver(row) != NULL)  entries++;
 420   }
 421 #if INCLUDE_JVMCI
 422   st->print_cr("count(%u) nonprofiled_count(%u) entries(%u)", count(), nonprofiled_count(), entries);
 423 #else
 424   st->print_cr("count(%u) entries(%u)", count(), entries);
 425 #endif
 426   int total = count();
 427   for (row = 0; row < row_limit(); row++) {
 428     if (receiver(row) != NULL) {
 429       total += receiver_count(row);
 430     }
 431   }
 432   for (row = 0; row < row_limit(); row++) {
 433     if (receiver(row) != NULL) {
 434       tab(st);
 435       receiver(row)->print_value_on(st);
 436       st->print_cr("(%u %4.2f)", receiver_count(row), (float) receiver_count(row) / (float) total);
 437     }
 438   }
 439 }
 440 void ReceiverTypeData::print_data_on(outputStream* st, const char* extra) const {
 441   print_shared(st, "ReceiverTypeData", extra);
 442   print_receiver_data_on(st);
 443 }
 444 
 445 void VirtualCallData::print_data_on(outputStream* st, const char* extra) const {
 446   print_shared(st, "VirtualCallData", extra);
 447   print_receiver_data_on(st);
 448 }
 449 
 450 // ==================================================================
 451 // RetData
 452 //
 453 // A RetData is used to access profiling information for a ret bytecode.
 454 // It is composed of a count of the number of times that the ret has
 455 // been executed, followed by a series of triples of the form
 456 // (bci, count, di) which count the number of times that some bci was the
 457 // target of the ret and cache a corresponding displacement.
 458 
 459 void RetData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 460   for (uint row = 0; row < row_limit(); row++) {
 461     set_bci_displacement(row, -1);
 462     set_bci(row, no_bci);
 463   }
 464   // release so other threads see a consistent state.  bci is used as
 465   // a valid flag for bci_displacement.
 466   OrderAccess::release();
 467 }
 468 
 469 // This routine needs to atomically update the RetData structure, so the
 470 // caller needs to hold the RetData_lock before it gets here.  Since taking
 471 // the lock can block (and allow GC) and since RetData is a ProfileData is a
 472 // wrapper around a derived oop, taking the lock in _this_ method will
 473 // basically cause the 'this' pointer's _data field to contain junk after the
 474 // lock.  We require the caller to take the lock before making the ProfileData
 475 // structure.  Currently the only caller is InterpreterRuntime::update_mdp_for_ret
 476 address RetData::fixup_ret(int return_bci, MethodData* h_mdo) {
 477   // First find the mdp which corresponds to the return bci.
 478   address mdp = h_mdo->bci_to_dp(return_bci);
 479 
 480   // Now check to see if any of the cache slots are open.
 481   for (uint row = 0; row < row_limit(); row++) {
 482     if (bci(row) == no_bci) {
 483       set_bci_displacement(row, mdp - dp());
 484       set_bci_count(row, DataLayout::counter_increment);
 485       // Barrier to ensure displacement is written before the bci; allows
 486       // the interpreter to read displacement without fear of race condition.
 487       release_set_bci(row, return_bci);
 488       break;
 489     }
 490   }
 491   return mdp;
 492 }
 493 
 494 void RetData::print_data_on(outputStream* st, const char* extra) const {
 495   print_shared(st, "RetData", extra);
 496   uint row;
 497   int entries = 0;
 498   for (row = 0; row < row_limit(); row++) {
 499     if (bci(row) != no_bci)  entries++;
 500   }
 501   st->print_cr("count(%u) entries(%u)", count(), entries);
 502   for (row = 0; row < row_limit(); row++) {
 503     if (bci(row) != no_bci) {
 504       tab(st);
 505       st->print_cr("bci(%d: count(%u) displacement(%d))",
 506                    bci(row), bci_count(row), bci_displacement(row));
 507     }
 508   }
 509 }
 510 
 511 // ==================================================================
 512 // BranchData
 513 //
 514 // A BranchData is used to access profiling data for a two-way branch.
 515 // It consists of taken and not_taken counts as well as a data displacement
 516 // for the taken case.
 517 
 518 void BranchData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 519   assert(stream->bci() == bci(), "wrong pos");
 520   int target = stream->dest();
 521   int my_di = mdo->dp_to_di(dp());
 522   int target_di = mdo->bci_to_di(target);
 523   int offset = target_di - my_di;
 524   set_displacement(offset);
 525 }
 526 
 527 void BranchData::print_data_on(outputStream* st, const char* extra) const {
 528   print_shared(st, "BranchData", extra);
 529   st->print_cr("taken(%u) displacement(%d)",
 530                taken(), displacement());
 531   tab(st);
 532   st->print_cr("not taken(%u)", not_taken());
 533 }
 534 
 535 // ==================================================================
 536 // MultiBranchData
 537 //
 538 // A MultiBranchData is used to access profiling information for
 539 // a multi-way branch (*switch bytecodes).  It consists of a series
 540 // of (count, displacement) pairs, which count the number of times each
 541 // case was taken and specify the data displacement for each branch target.
 542 
 543 int MultiBranchData::compute_cell_count(BytecodeStream* stream) {
 544   int cell_count = 0;
 545   if (stream->code() == Bytecodes::_tableswitch) {
 546     Bytecode_tableswitch sw(stream->method()(), stream->bcp());
 547     cell_count = 1 + per_case_cell_count * (1 + sw.length()); // 1 for default
 548   } else {
 549     Bytecode_lookupswitch sw(stream->method()(), stream->bcp());
 550     cell_count = 1 + per_case_cell_count * (sw.number_of_pairs() + 1); // 1 for default
 551   }
 552   return cell_count;
 553 }
 554 
 555 void MultiBranchData::post_initialize(BytecodeStream* stream,
 556                                       MethodData* mdo) {
 557   assert(stream->bci() == bci(), "wrong pos");
 558   int target;
 559   int my_di;
 560   int target_di;
 561   int offset;
 562   if (stream->code() == Bytecodes::_tableswitch) {
 563     Bytecode_tableswitch sw(stream->method()(), stream->bcp());
 564     int len = sw.length();
 565     assert(array_len() == per_case_cell_count * (len + 1), "wrong len");
 566     for (int count = 0; count < len; count++) {
 567       target = sw.dest_offset_at(count) + bci();
 568       my_di = mdo->dp_to_di(dp());
 569       target_di = mdo->bci_to_di(target);
 570       offset = target_di - my_di;
 571       set_displacement_at(count, offset);
 572     }
 573     target = sw.default_offset() + bci();
 574     my_di = mdo->dp_to_di(dp());
 575     target_di = mdo->bci_to_di(target);
 576     offset = target_di - my_di;
 577     set_default_displacement(offset);
 578 
 579   } else {
 580     Bytecode_lookupswitch sw(stream->method()(), stream->bcp());
 581     int npairs = sw.number_of_pairs();
 582     assert(array_len() == per_case_cell_count * (npairs + 1), "wrong len");
 583     for (int count = 0; count < npairs; count++) {
 584       LookupswitchPair pair = sw.pair_at(count);
 585       target = pair.offset() + bci();
 586       my_di = mdo->dp_to_di(dp());
 587       target_di = mdo->bci_to_di(target);
 588       offset = target_di - my_di;
 589       set_displacement_at(count, offset);
 590     }
 591     target = sw.default_offset() + bci();
 592     my_di = mdo->dp_to_di(dp());
 593     target_di = mdo->bci_to_di(target);
 594     offset = target_di - my_di;
 595     set_default_displacement(offset);
 596   }
 597 }
 598 
 599 void MultiBranchData::print_data_on(outputStream* st, const char* extra) const {
 600   print_shared(st, "MultiBranchData", extra);
 601   st->print_cr("default_count(%u) displacement(%d)",
 602                default_count(), default_displacement());
 603   int cases = number_of_cases();
 604   for (int i = 0; i < cases; i++) {
 605     tab(st);
 606     st->print_cr("count(%u) displacement(%d)",
 607                  count_at(i), displacement_at(i));
 608   }
 609 }
 610 
 611 void ArgInfoData::print_data_on(outputStream* st, const char* extra) const {
 612   print_shared(st, "ArgInfoData", extra);
 613   int nargs = number_of_args();
 614   for (int i = 0; i < nargs; i++) {
 615     st->print("  0x%x", arg_modified(i));
 616   }
 617   st->cr();
 618 }
 619 
 620 int ParametersTypeData::compute_cell_count(Method* m) {
 621   if (!MethodData::profile_parameters_for_method(methodHandle(Thread::current(), m))) {
 622     return 0;
 623   }
 624   int max = TypeProfileParmsLimit == -1 ? INT_MAX : TypeProfileParmsLimit;
 625   int obj_args = TypeStackSlotEntries::compute_cell_count(m->signature(), !m->is_static(), max);
 626   if (obj_args > 0) {
 627     return obj_args + 1; // 1 cell for array len
 628   }
 629   return 0;
 630 }
 631 
 632 void ParametersTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 633   _parameters.post_initialize(mdo->method()->signature(), !mdo->method()->is_static(), true);
 634 }
 635 
 636 bool ParametersTypeData::profiling_enabled() {
 637   return MethodData::profile_parameters();
 638 }
 639 
 640 void ParametersTypeData::print_data_on(outputStream* st, const char* extra) const {
 641   print_shared(st, "ParametersTypeData", extra);
 642   tab(st);
 643   _parameters.print_data_on(st);
 644   st->cr();
 645 }
 646 
 647 void SpeculativeTrapData::print_data_on(outputStream* st, const char* extra) const {
 648   print_shared(st, "SpeculativeTrapData", extra);
 649   tab(st);
 650   method()->print_short_name(st);
 651   st->cr();
 652 }
 653 
 654 // ==================================================================
 655 // MethodData*
 656 //
 657 // A MethodData* holds information which has been collected about
 658 // a method.
 659 
 660 MethodData* MethodData::allocate(ClassLoaderData* loader_data, const methodHandle& method, TRAPS) {
 661   int size = MethodData::compute_allocation_size_in_words(method);
 662 
 663   return new (loader_data, size, MetaspaceObj::MethodDataType, THREAD)
 664     MethodData(method);
 665 }
 666 
 667 int MethodData::bytecode_cell_count(Bytecodes::Code code) {
 668   if (CompilerConfig::is_c1_simple_only() && !ProfileInterpreter) {
 669     return no_profile_data;
 670   }
 671   switch (code) {
 672   case Bytecodes::_checkcast:
 673   case Bytecodes::_instanceof:
 674   case Bytecodes::_aastore:
 675     if (TypeProfileCasts) {
 676       return ReceiverTypeData::static_cell_count();
 677     } else {
 678       return BitData::static_cell_count();
 679     }
 680   case Bytecodes::_invokespecial:
 681   case Bytecodes::_invokestatic:
 682     if (MethodData::profile_arguments() || MethodData::profile_return()) {
 683       return variable_cell_count;
 684     } else {
 685       return CounterData::static_cell_count();
 686     }
 687   case Bytecodes::_goto:
 688   case Bytecodes::_goto_w:
 689   case Bytecodes::_jsr:
 690   case Bytecodes::_jsr_w:
 691     return JumpData::static_cell_count();
 692   case Bytecodes::_invokevirtual:
 693   case Bytecodes::_invokeinterface:
 694     if (MethodData::profile_arguments() || MethodData::profile_return()) {
 695       return variable_cell_count;
 696     } else {
 697       return VirtualCallData::static_cell_count();
 698     }
 699   case Bytecodes::_invokedynamic:
 700     if (MethodData::profile_arguments() || MethodData::profile_return()) {
 701       return variable_cell_count;
 702     } else {
 703       return CounterData::static_cell_count();
 704     }
 705   case Bytecodes::_ret:
 706     return RetData::static_cell_count();
 707   case Bytecodes::_ifeq:
 708   case Bytecodes::_ifne:
 709   case Bytecodes::_iflt:
 710   case Bytecodes::_ifge:
 711   case Bytecodes::_ifgt:
 712   case Bytecodes::_ifle:
 713   case Bytecodes::_if_icmpeq:
 714   case Bytecodes::_if_icmpne:
 715   case Bytecodes::_if_icmplt:
 716   case Bytecodes::_if_icmpge:
 717   case Bytecodes::_if_icmpgt:
 718   case Bytecodes::_if_icmple:
 719   case Bytecodes::_if_acmpeq:
 720   case Bytecodes::_if_acmpne:
 721   case Bytecodes::_ifnull:
 722   case Bytecodes::_ifnonnull:
 723     return BranchData::static_cell_count();
 724   case Bytecodes::_lookupswitch:
 725   case Bytecodes::_tableswitch:
 726     return variable_cell_count;
 727   default:
 728     return no_profile_data;
 729   }
 730 }
 731 
 732 // Compute the size of the profiling information corresponding to
 733 // the current bytecode.
 734 int MethodData::compute_data_size(BytecodeStream* stream) {
 735   int cell_count = bytecode_cell_count(stream->code());
 736   if (cell_count == no_profile_data) {
 737     return 0;
 738   }
 739   if (cell_count == variable_cell_count) {
 740     switch (stream->code()) {
 741     case Bytecodes::_lookupswitch:
 742     case Bytecodes::_tableswitch:
 743       cell_count = MultiBranchData::compute_cell_count(stream);
 744       break;
 745     case Bytecodes::_invokespecial:
 746     case Bytecodes::_invokestatic:
 747     case Bytecodes::_invokedynamic:
 748       assert(MethodData::profile_arguments() || MethodData::profile_return(), "should be collecting args profile");
 749       if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
 750           profile_return_for_invoke(stream->method(), stream->bci())) {
 751         cell_count = CallTypeData::compute_cell_count(stream);
 752       } else {
 753         cell_count = CounterData::static_cell_count();
 754       }
 755       break;
 756     case Bytecodes::_invokevirtual:
 757     case Bytecodes::_invokeinterface: {
 758       assert(MethodData::profile_arguments() || MethodData::profile_return(), "should be collecting args profile");
 759       if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
 760           profile_return_for_invoke(stream->method(), stream->bci())) {
 761         cell_count = VirtualCallTypeData::compute_cell_count(stream);
 762       } else {
 763         cell_count = VirtualCallData::static_cell_count();
 764       }
 765       break;
 766     }
 767     default:
 768       fatal("unexpected bytecode for var length profile data");
 769     }
 770   }
 771   // Note:  cell_count might be zero, meaning that there is just
 772   //        a DataLayout header, with no extra cells.
 773   assert(cell_count >= 0, "sanity");
 774   return DataLayout::compute_size_in_bytes(cell_count);
 775 }
 776 
 777 bool MethodData::is_speculative_trap_bytecode(Bytecodes::Code code) {
 778   // Bytecodes for which we may use speculation
 779   switch (code) {
 780   case Bytecodes::_checkcast:
 781   case Bytecodes::_instanceof:
 782   case Bytecodes::_aastore:
 783   case Bytecodes::_invokevirtual:
 784   case Bytecodes::_invokeinterface:
 785   case Bytecodes::_if_acmpeq:
 786   case Bytecodes::_if_acmpne:
 787   case Bytecodes::_ifnull:
 788   case Bytecodes::_ifnonnull:
 789   case Bytecodes::_invokestatic:
 790 #ifdef COMPILER2
 791     if (CompilerConfig::is_c2_enabled()) {
 792       return UseTypeSpeculation;
 793     }
 794 #endif
 795   default:
 796     return false;
 797   }
 798   return false;
 799 }
 800 
 801 #if INCLUDE_JVMCI
 802 
 803 void* FailedSpeculation::operator new(size_t size, size_t fs_size) throw() {
 804   return CHeapObj<mtCompiler>::operator new(fs_size, std::nothrow);
 805 }
 806 
 807 FailedSpeculation::FailedSpeculation(address speculation, int speculation_len) : _data_len(speculation_len), _next(NULL) {
 808   memcpy(data(), speculation, speculation_len);
 809 }
 810 
 811 // A heuristic check to detect nmethods that outlive a failed speculations list.
 812 static void guarantee_failed_speculations_alive(nmethod* nm, FailedSpeculation** failed_speculations_address) {
 813   jlong head = (jlong)(address) *failed_speculations_address;
 814   if ((head & 0x1) == 0x1) {
 815     stringStream st;
 816     if (nm != NULL) {
 817       st.print("%d", nm->compile_id());
 818       Method* method = nm->method();
 819       st.print_raw("{");
 820       if (method != NULL) {
 821         method->print_name(&st);
 822       } else {
 823         const char* jvmci_name = nm->jvmci_name();
 824         if (jvmci_name != NULL) {
 825           st.print_raw(jvmci_name);
 826         }
 827       }
 828       st.print_raw("}");
 829     } else {
 830       st.print("<unknown>");
 831     }
 832     fatal("Adding to failed speculations list that appears to have been freed. Source: %s", st.as_string());
 833   }
 834 }
 835 
 836 bool FailedSpeculation::add_failed_speculation(nmethod* nm, FailedSpeculation** failed_speculations_address, address speculation, int speculation_len) {
 837   assert(failed_speculations_address != NULL, "must be");
 838   size_t fs_size = sizeof(FailedSpeculation) + speculation_len;
 839   FailedSpeculation* fs = new (fs_size) FailedSpeculation(speculation, speculation_len);
 840   if (fs == NULL) {
 841     // no memory -> ignore failed speculation
 842     return false;
 843   }
 844 
 845   guarantee(is_aligned(fs, sizeof(FailedSpeculation*)), "FailedSpeculation objects must be pointer aligned");
 846   guarantee_failed_speculations_alive(nm, failed_speculations_address);
 847 
 848   FailedSpeculation** cursor = failed_speculations_address;
 849   do {
 850     if (*cursor == NULL) {
 851       FailedSpeculation* old_fs = Atomic::cmpxchg(cursor, (FailedSpeculation*) NULL, fs);
 852       if (old_fs == NULL) {
 853         // Successfully appended fs to end of the list
 854         return true;
 855       }
 856       cursor = old_fs->next_adr();
 857     } else {
 858       cursor = (*cursor)->next_adr();
 859     }
 860   } while (true);
 861 }
 862 
 863 void FailedSpeculation::free_failed_speculations(FailedSpeculation** failed_speculations_address) {
 864   assert(failed_speculations_address != NULL, "must be");
 865   FailedSpeculation* fs = *failed_speculations_address;
 866   while (fs != NULL) {
 867     FailedSpeculation* next = fs->next();
 868     delete fs;
 869     fs = next;
 870   }
 871 
 872   // Write an unaligned value to failed_speculations_address to denote
 873   // that it is no longer a valid pointer. This is allows for the check
 874   // in add_failed_speculation against adding to a freed failed
 875   // speculations list.
 876   long* head = (long*) failed_speculations_address;
 877   (*head) = (*head) | 0x1;
 878 }
 879 #endif // INCLUDE_JVMCI
 880 
 881 int MethodData::compute_extra_data_count(int data_size, int empty_bc_count, bool needs_speculative_traps) {
 882 #if INCLUDE_JVMCI
 883   if (ProfileTraps) {
 884     // Assume that up to 30% of the possibly trapping BCIs with no MDP will need to allocate one.
 885     int extra_data_count = MIN2(empty_bc_count, MAX2(4, (empty_bc_count * 30) / 100));
 886 
 887     // Make sure we have a minimum number of extra data slots to
 888     // allocate SpeculativeTrapData entries. We would want to have one
 889     // entry per compilation that inlines this method and for which
 890     // some type speculation assumption fails. So the room we need for
 891     // the SpeculativeTrapData entries doesn't directly depend on the
 892     // size of the method. Because it's hard to estimate, we reserve
 893     // space for an arbitrary number of entries.
 894     int spec_data_count = (needs_speculative_traps ? SpecTrapLimitExtraEntries : 0) *
 895       (SpeculativeTrapData::static_cell_count() + DataLayout::header_size_in_cells());
 896 
 897     return MAX2(extra_data_count, spec_data_count);
 898   } else {
 899     return 0;
 900   }
 901 #else // INCLUDE_JVMCI
 902   if (ProfileTraps) {
 903     // Assume that up to 3% of BCIs with no MDP will need to allocate one.
 904     int extra_data_count = (uint)(empty_bc_count * 3) / 128 + 1;
 905     // If the method is large, let the extra BCIs grow numerous (to ~1%).
 906     int one_percent_of_data
 907       = (uint)data_size / (DataLayout::header_size_in_bytes()*128);
 908     if (extra_data_count < one_percent_of_data)
 909       extra_data_count = one_percent_of_data;
 910     if (extra_data_count > empty_bc_count)
 911       extra_data_count = empty_bc_count;  // no need for more
 912 
 913     // Make sure we have a minimum number of extra data slots to
 914     // allocate SpeculativeTrapData entries. We would want to have one
 915     // entry per compilation that inlines this method and for which
 916     // some type speculation assumption fails. So the room we need for
 917     // the SpeculativeTrapData entries doesn't directly depend on the
 918     // size of the method. Because it's hard to estimate, we reserve
 919     // space for an arbitrary number of entries.
 920     int spec_data_count = (needs_speculative_traps ? SpecTrapLimitExtraEntries : 0) *
 921       (SpeculativeTrapData::static_cell_count() + DataLayout::header_size_in_cells());
 922 
 923     return MAX2(extra_data_count, spec_data_count);
 924   } else {
 925     return 0;
 926   }
 927 #endif // INCLUDE_JVMCI
 928 }
 929 
 930 // Compute the size of the MethodData* necessary to store
 931 // profiling information about a given method.  Size is in bytes.
 932 int MethodData::compute_allocation_size_in_bytes(const methodHandle& method) {
 933   int data_size = 0;
 934   BytecodeStream stream(method);
 935   Bytecodes::Code c;
 936   int empty_bc_count = 0;  // number of bytecodes lacking data
 937   bool needs_speculative_traps = false;
 938   while ((c = stream.next()) >= 0) {
 939     int size_in_bytes = compute_data_size(&stream);
 940     data_size += size_in_bytes;
 941     if (size_in_bytes == 0 JVMCI_ONLY(&& Bytecodes::can_trap(c)))  empty_bc_count += 1;
 942     needs_speculative_traps = needs_speculative_traps || is_speculative_trap_bytecode(c);
 943   }
 944   int object_size = in_bytes(data_offset()) + data_size;
 945 
 946   // Add some extra DataLayout cells (at least one) to track stray traps.
 947   int extra_data_count = compute_extra_data_count(data_size, empty_bc_count, needs_speculative_traps);
 948   object_size += extra_data_count * DataLayout::compute_size_in_bytes(0);
 949 
 950   // Add a cell to record information about modified arguments.
 951   int arg_size = method->size_of_parameters();
 952   object_size += DataLayout::compute_size_in_bytes(arg_size+1);
 953 
 954   // Reserve room for an area of the MDO dedicated to profiling of
 955   // parameters
 956   int args_cell = ParametersTypeData::compute_cell_count(method());
 957   if (args_cell > 0) {
 958     object_size += DataLayout::compute_size_in_bytes(args_cell);
 959   }
 960   return object_size;
 961 }
 962 
 963 // Compute the size of the MethodData* necessary to store
 964 // profiling information about a given method.  Size is in words
 965 int MethodData::compute_allocation_size_in_words(const methodHandle& method) {
 966   int byte_size = compute_allocation_size_in_bytes(method);
 967   int word_size = align_up(byte_size, BytesPerWord) / BytesPerWord;
 968   return align_metadata_size(word_size);
 969 }
 970 
 971 // Initialize an individual data segment.  Returns the size of
 972 // the segment in bytes.
 973 int MethodData::initialize_data(BytecodeStream* stream,
 974                                        int data_index) {
 975   if (CompilerConfig::is_c1_simple_only() && !ProfileInterpreter) {
 976     return 0;
 977   }
 978   int cell_count = -1;
 979   int tag = DataLayout::no_tag;
 980   DataLayout* data_layout = data_layout_at(data_index);
 981   Bytecodes::Code c = stream->code();
 982   switch (c) {
 983   case Bytecodes::_checkcast:
 984   case Bytecodes::_instanceof:
 985   case Bytecodes::_aastore:
 986     if (TypeProfileCasts) {
 987       cell_count = ReceiverTypeData::static_cell_count();
 988       tag = DataLayout::receiver_type_data_tag;
 989     } else {
 990       cell_count = BitData::static_cell_count();
 991       tag = DataLayout::bit_data_tag;
 992     }
 993     break;
 994   case Bytecodes::_invokespecial:
 995   case Bytecodes::_invokestatic: {
 996     int counter_data_cell_count = CounterData::static_cell_count();
 997     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
 998         profile_return_for_invoke(stream->method(), stream->bci())) {
 999       cell_count = CallTypeData::compute_cell_count(stream);
1000     } else {
1001       cell_count = counter_data_cell_count;
1002     }
1003     if (cell_count > counter_data_cell_count) {
1004       tag = DataLayout::call_type_data_tag;
1005     } else {
1006       tag = DataLayout::counter_data_tag;
1007     }
1008     break;
1009   }
1010   case Bytecodes::_goto:
1011   case Bytecodes::_goto_w:
1012   case Bytecodes::_jsr:
1013   case Bytecodes::_jsr_w:
1014     cell_count = JumpData::static_cell_count();
1015     tag = DataLayout::jump_data_tag;
1016     break;
1017   case Bytecodes::_invokevirtual:
1018   case Bytecodes::_invokeinterface: {
1019     int virtual_call_data_cell_count = VirtualCallData::static_cell_count();
1020     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1021         profile_return_for_invoke(stream->method(), stream->bci())) {
1022       cell_count = VirtualCallTypeData::compute_cell_count(stream);
1023     } else {
1024       cell_count = virtual_call_data_cell_count;
1025     }
1026     if (cell_count > virtual_call_data_cell_count) {
1027       tag = DataLayout::virtual_call_type_data_tag;
1028     } else {
1029       tag = DataLayout::virtual_call_data_tag;
1030     }
1031     break;
1032   }
1033   case Bytecodes::_invokedynamic: {
1034     // %%% should make a type profile for any invokedynamic that takes a ref argument
1035     int counter_data_cell_count = CounterData::static_cell_count();
1036     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1037         profile_return_for_invoke(stream->method(), stream->bci())) {
1038       cell_count = CallTypeData::compute_cell_count(stream);
1039     } else {
1040       cell_count = counter_data_cell_count;
1041     }
1042     if (cell_count > counter_data_cell_count) {
1043       tag = DataLayout::call_type_data_tag;
1044     } else {
1045       tag = DataLayout::counter_data_tag;
1046     }
1047     break;
1048   }
1049   case Bytecodes::_ret:
1050     cell_count = RetData::static_cell_count();
1051     tag = DataLayout::ret_data_tag;
1052     break;
1053   case Bytecodes::_ifeq:
1054   case Bytecodes::_ifne:
1055   case Bytecodes::_iflt:
1056   case Bytecodes::_ifge:
1057   case Bytecodes::_ifgt:
1058   case Bytecodes::_ifle:
1059   case Bytecodes::_if_icmpeq:
1060   case Bytecodes::_if_icmpne:
1061   case Bytecodes::_if_icmplt:
1062   case Bytecodes::_if_icmpge:
1063   case Bytecodes::_if_icmpgt:
1064   case Bytecodes::_if_icmple:
1065   case Bytecodes::_if_acmpeq:
1066   case Bytecodes::_if_acmpne:
1067   case Bytecodes::_ifnull:
1068   case Bytecodes::_ifnonnull:
1069     cell_count = BranchData::static_cell_count();
1070     tag = DataLayout::branch_data_tag;
1071     break;
1072   case Bytecodes::_lookupswitch:
1073   case Bytecodes::_tableswitch:
1074     cell_count = MultiBranchData::compute_cell_count(stream);
1075     tag = DataLayout::multi_branch_data_tag;
1076     break;
1077   default:
1078     break;
1079   }
1080   assert(tag == DataLayout::multi_branch_data_tag ||
1081          ((MethodData::profile_arguments() || MethodData::profile_return()) &&
1082           (tag == DataLayout::call_type_data_tag ||
1083            tag == DataLayout::counter_data_tag ||
1084            tag == DataLayout::virtual_call_type_data_tag ||
1085            tag == DataLayout::virtual_call_data_tag)) ||
1086          cell_count == bytecode_cell_count(c), "cell counts must agree");
1087   if (cell_count >= 0) {
1088     assert(tag != DataLayout::no_tag, "bad tag");
1089     assert(bytecode_has_profile(c), "agree w/ BHP");
1090     data_layout->initialize(tag, stream->bci(), cell_count);
1091     return DataLayout::compute_size_in_bytes(cell_count);
1092   } else {
1093     assert(!bytecode_has_profile(c), "agree w/ !BHP");
1094     return 0;
1095   }
1096 }
1097 
1098 // Get the data at an arbitrary (sort of) data index.
1099 ProfileData* MethodData::data_at(int data_index) const {
1100   if (out_of_bounds(data_index)) {
1101     return NULL;
1102   }
1103   DataLayout* data_layout = data_layout_at(data_index);
1104   return data_layout->data_in();
1105 }
1106 
1107 int DataLayout::cell_count() {
1108   switch (tag()) {
1109   case DataLayout::no_tag:
1110   default:
1111     ShouldNotReachHere();
1112     return 0;
1113   case DataLayout::bit_data_tag:
1114     return BitData::static_cell_count();
1115   case DataLayout::counter_data_tag:
1116     return CounterData::static_cell_count();
1117   case DataLayout::jump_data_tag:
1118     return JumpData::static_cell_count();
1119   case DataLayout::receiver_type_data_tag:
1120     return ReceiverTypeData::static_cell_count();
1121   case DataLayout::virtual_call_data_tag:
1122     return VirtualCallData::static_cell_count();
1123   case DataLayout::ret_data_tag:
1124     return RetData::static_cell_count();
1125   case DataLayout::branch_data_tag:
1126     return BranchData::static_cell_count();
1127   case DataLayout::multi_branch_data_tag:
1128     return ((new MultiBranchData(this))->cell_count());
1129   case DataLayout::arg_info_data_tag:
1130     return ((new ArgInfoData(this))->cell_count());
1131   case DataLayout::call_type_data_tag:
1132     return ((new CallTypeData(this))->cell_count());
1133   case DataLayout::virtual_call_type_data_tag:
1134     return ((new VirtualCallTypeData(this))->cell_count());
1135   case DataLayout::parameters_type_data_tag:
1136     return ((new ParametersTypeData(this))->cell_count());
1137   case DataLayout::speculative_trap_data_tag:
1138     return SpeculativeTrapData::static_cell_count();
1139   }
1140 }
1141 ProfileData* DataLayout::data_in() {
1142   switch (tag()) {
1143   case DataLayout::no_tag:
1144   default:
1145     ShouldNotReachHere();
1146     return NULL;
1147   case DataLayout::bit_data_tag:
1148     return new BitData(this);
1149   case DataLayout::counter_data_tag:
1150     return new CounterData(this);
1151   case DataLayout::jump_data_tag:
1152     return new JumpData(this);
1153   case DataLayout::receiver_type_data_tag:
1154     return new ReceiverTypeData(this);
1155   case DataLayout::virtual_call_data_tag:
1156     return new VirtualCallData(this);
1157   case DataLayout::ret_data_tag:
1158     return new RetData(this);
1159   case DataLayout::branch_data_tag:
1160     return new BranchData(this);
1161   case DataLayout::multi_branch_data_tag:
1162     return new MultiBranchData(this);
1163   case DataLayout::arg_info_data_tag:
1164     return new ArgInfoData(this);
1165   case DataLayout::call_type_data_tag:
1166     return new CallTypeData(this);
1167   case DataLayout::virtual_call_type_data_tag:
1168     return new VirtualCallTypeData(this);
1169   case DataLayout::parameters_type_data_tag:
1170     return new ParametersTypeData(this);
1171   case DataLayout::speculative_trap_data_tag:
1172     return new SpeculativeTrapData(this);
1173   }
1174 }
1175 
1176 // Iteration over data.
1177 ProfileData* MethodData::next_data(ProfileData* current) const {
1178   int current_index = dp_to_di(current->dp());
1179   int next_index = current_index + current->size_in_bytes();
1180   ProfileData* next = data_at(next_index);
1181   return next;
1182 }
1183 
1184 DataLayout* MethodData::next_data_layout(DataLayout* current) const {
1185   int current_index = dp_to_di((address)current);
1186   int next_index = current_index + current->size_in_bytes();
1187   if (out_of_bounds(next_index)) {
1188     return NULL;
1189   }
1190   DataLayout* next = data_layout_at(next_index);
1191   return next;
1192 }
1193 
1194 // Give each of the data entries a chance to perform specific
1195 // data initialization.
1196 void MethodData::post_initialize(BytecodeStream* stream) {
1197   ResourceMark rm;
1198   ProfileData* data;
1199   for (data = first_data(); is_valid(data); data = next_data(data)) {
1200     stream->set_start(data->bci());
1201     stream->next();
1202     data->post_initialize(stream, this);
1203   }
1204   if (_parameters_type_data_di != no_parameters) {
1205     parameters_type_data()->post_initialize(NULL, this);
1206   }
1207 }
1208 
1209 // Initialize the MethodData* corresponding to a given method.
1210 MethodData::MethodData(const methodHandle& method)
1211   : _method(method()),
1212     // Holds Compile_lock
1213     _extra_data_lock(Mutex::safepoint-2, "MDOExtraData_lock"),
1214     _compiler_counters(),
1215     _parameters_type_data_di(parameters_uninitialized) {
1216   initialize();
1217 }
1218 
1219 void MethodData::initialize() {
1220   Thread* thread = Thread::current();
1221   NoSafepointVerifier no_safepoint;  // init function atomic wrt GC
1222   ResourceMark rm(thread);
1223 
1224   init();
1225   set_creation_mileage(mileage_of(method()));
1226 
1227   // Go through the bytecodes and allocate and initialize the
1228   // corresponding data cells.
1229   int data_size = 0;
1230   int empty_bc_count = 0;  // number of bytecodes lacking data
1231   _data[0] = 0;  // apparently not set below.
1232   BytecodeStream stream(methodHandle(thread, method()));
1233   Bytecodes::Code c;
1234   bool needs_speculative_traps = false;
1235   while ((c = stream.next()) >= 0) {
1236     int size_in_bytes = initialize_data(&stream, data_size);
1237     data_size += size_in_bytes;
1238     if (size_in_bytes == 0 JVMCI_ONLY(&& Bytecodes::can_trap(c)))  empty_bc_count += 1;
1239     needs_speculative_traps = needs_speculative_traps || is_speculative_trap_bytecode(c);
1240   }
1241   _data_size = data_size;
1242   int object_size = in_bytes(data_offset()) + data_size;
1243 
1244   // Add some extra DataLayout cells (at least one) to track stray traps.
1245   int extra_data_count = compute_extra_data_count(data_size, empty_bc_count, needs_speculative_traps);
1246   int extra_size = extra_data_count * DataLayout::compute_size_in_bytes(0);
1247 
1248   // Let's zero the space for the extra data
1249   if (extra_size > 0) {
1250     Copy::zero_to_bytes(((address)_data) + data_size, extra_size);
1251   }
1252 
1253   // Add a cell to record information about modified arguments.
1254   // Set up _args_modified array after traps cells so that
1255   // the code for traps cells works.
1256   DataLayout *dp = data_layout_at(data_size + extra_size);
1257 
1258   int arg_size = method()->size_of_parameters();
1259   dp->initialize(DataLayout::arg_info_data_tag, 0, arg_size+1);
1260 
1261   int arg_data_size = DataLayout::compute_size_in_bytes(arg_size+1);
1262   object_size += extra_size + arg_data_size;
1263 
1264   int parms_cell = ParametersTypeData::compute_cell_count(method());
1265   // If we are profiling parameters, we reserved an area near the end
1266   // of the MDO after the slots for bytecodes (because there's no bci
1267   // for method entry so they don't fit with the framework for the
1268   // profiling of bytecodes). We store the offset within the MDO of
1269   // this area (or -1 if no parameter is profiled)
1270   if (parms_cell > 0) {
1271     object_size += DataLayout::compute_size_in_bytes(parms_cell);
1272     _parameters_type_data_di = data_size + extra_size + arg_data_size;
1273     DataLayout *dp = data_layout_at(data_size + extra_size + arg_data_size);
1274     dp->initialize(DataLayout::parameters_type_data_tag, 0, parms_cell);
1275   } else {
1276     _parameters_type_data_di = no_parameters;
1277   }
1278 
1279   // Set an initial hint. Don't use set_hint_di() because
1280   // first_di() may be out of bounds if data_size is 0.
1281   // In that situation, _hint_di is never used, but at
1282   // least well-defined.
1283   _hint_di = first_di();
1284 
1285   post_initialize(&stream);
1286 
1287   assert(object_size == compute_allocation_size_in_bytes(methodHandle(thread, _method)), "MethodData: computed size != initialized size");
1288   set_size(object_size);
1289 }
1290 
1291 void MethodData::init() {
1292   _compiler_counters = CompilerCounters(); // reset compiler counters
1293   _invocation_counter.init();
1294   _backedge_counter.init();
1295   _invocation_counter_start = 0;
1296   _backedge_counter_start = 0;
1297 
1298   // Set per-method invoke- and backedge mask.
1299   double scale = 1.0;
1300   methodHandle mh(Thread::current(), _method);
1301   CompilerOracle::has_option_value(mh, CompileCommand::CompileThresholdScaling, scale);
1302   _invoke_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
1303   _backedge_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
1304 
1305   _tenure_traps = 0;
1306   _num_loops = 0;
1307   _num_blocks = 0;
1308   _would_profile = unknown;
1309 
1310 #if INCLUDE_JVMCI
1311   _jvmci_ir_size = 0;
1312   _failed_speculations = NULL;
1313 #endif
1314 
1315 #if INCLUDE_RTM_OPT
1316   _rtm_state = NoRTM; // No RTM lock eliding by default
1317   if (UseRTMLocking &&
1318       !CompilerOracle::has_option(mh, CompileCommand::NoRTMLockEliding)) {
1319     if (CompilerOracle::has_option(mh, CompileCommand::UseRTMLockEliding) || !UseRTMDeopt) {
1320       // Generate RTM lock eliding code without abort ratio calculation code.
1321       _rtm_state = UseRTM;
1322     } else if (UseRTMDeopt) {
1323       // Generate RTM lock eliding code and include abort ratio calculation
1324       // code if UseRTMDeopt is on.
1325       _rtm_state = ProfileRTM;
1326     }
1327   }
1328 #endif
1329 
1330   // Initialize escape flags.
1331   clear_escape_info();
1332 }
1333 
1334 // Get a measure of how much mileage the method has on it.
1335 int MethodData::mileage_of(Method* method) {
1336   return MAX2(method->invocation_count(), method->backedge_count());
1337 }
1338 
1339 bool MethodData::is_mature() const {
1340   return CompilationPolicy::is_mature(_method);
1341 }
1342 
1343 // Translate a bci to its corresponding data index (di).
1344 address MethodData::bci_to_dp(int bci) {
1345   ResourceMark rm;
1346   DataLayout* data = data_layout_before(bci);
1347   DataLayout* prev = NULL;
1348   for ( ; is_valid(data); data = next_data_layout(data)) {
1349     if (data->bci() >= bci) {
1350       if (data->bci() == bci)  set_hint_di(dp_to_di((address)data));
1351       else if (prev != NULL)   set_hint_di(dp_to_di((address)prev));
1352       return (address)data;
1353     }
1354     prev = data;
1355   }
1356   return (address)limit_data_position();
1357 }
1358 
1359 // Translate a bci to its corresponding data, or NULL.
1360 ProfileData* MethodData::bci_to_data(int bci) {
1361   DataLayout* data = data_layout_before(bci);
1362   for ( ; is_valid(data); data = next_data_layout(data)) {
1363     if (data->bci() == bci) {
1364       set_hint_di(dp_to_di((address)data));
1365       return data->data_in();
1366     } else if (data->bci() > bci) {
1367       break;
1368     }
1369   }
1370   return bci_to_extra_data(bci, NULL, false);
1371 }
1372 
1373 DataLayout* MethodData::next_extra(DataLayout* dp) {
1374   int nb_cells = 0;
1375   switch(dp->tag()) {
1376   case DataLayout::bit_data_tag:
1377   case DataLayout::no_tag:
1378     nb_cells = BitData::static_cell_count();
1379     break;
1380   case DataLayout::speculative_trap_data_tag:
1381     nb_cells = SpeculativeTrapData::static_cell_count();
1382     break;
1383   default:
1384     fatal("unexpected tag %d", dp->tag());
1385   }
1386   return (DataLayout*)((address)dp + DataLayout::compute_size_in_bytes(nb_cells));
1387 }
1388 
1389 ProfileData* MethodData::bci_to_extra_data_helper(int bci, Method* m, DataLayout*& dp, bool concurrent) {
1390   DataLayout* end = args_data_limit();
1391 
1392   for (;; dp = next_extra(dp)) {
1393     assert(dp < end, "moved past end of extra data");
1394     // No need for "Atomic::load_acquire" ops,
1395     // since the data structure is monotonic.
1396     switch(dp->tag()) {
1397     case DataLayout::no_tag:
1398       return NULL;
1399     case DataLayout::arg_info_data_tag:
1400       dp = end;
1401       return NULL; // ArgInfoData is at the end of extra data section.
1402     case DataLayout::bit_data_tag:
1403       if (m == NULL && dp->bci() == bci) {
1404         return new BitData(dp);
1405       }
1406       break;
1407     case DataLayout::speculative_trap_data_tag:
1408       if (m != NULL) {
1409         SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1410         // data->method() may be null in case of a concurrent
1411         // allocation. Maybe it's for the same method. Try to use that
1412         // entry in that case.
1413         if (dp->bci() == bci) {
1414           if (data->method() == NULL) {
1415             assert(concurrent, "impossible because no concurrent allocation");
1416             return NULL;
1417           } else if (data->method() == m) {
1418             return data;
1419           }
1420         }
1421       }
1422       break;
1423     default:
1424       fatal("unexpected tag %d", dp->tag());
1425     }
1426   }
1427   return NULL;
1428 }
1429 
1430 
1431 // Translate a bci to its corresponding extra data, or NULL.
1432 ProfileData* MethodData::bci_to_extra_data(int bci, Method* m, bool create_if_missing) {
1433   // This code assumes an entry for a SpeculativeTrapData is 2 cells
1434   assert(2*DataLayout::compute_size_in_bytes(BitData::static_cell_count()) ==
1435          DataLayout::compute_size_in_bytes(SpeculativeTrapData::static_cell_count()),
1436          "code needs to be adjusted");
1437 
1438   // Do not create one of these if method has been redefined.
1439   if (m != NULL && m->is_old()) {
1440     return NULL;
1441   }
1442 
1443   DataLayout* dp  = extra_data_base();
1444   DataLayout* end = args_data_limit();
1445 
1446   // Allocation in the extra data space has to be atomic because not
1447   // all entries have the same size and non atomic concurrent
1448   // allocation would result in a corrupted extra data space.
1449   ProfileData* result = bci_to_extra_data_helper(bci, m, dp, true);
1450   if (result != NULL) {
1451     return result;
1452   }
1453 
1454   if (create_if_missing && dp < end) {
1455     MutexLocker ml(&_extra_data_lock);
1456     // Check again now that we have the lock. Another thread may
1457     // have added extra data entries.
1458     ProfileData* result = bci_to_extra_data_helper(bci, m, dp, false);
1459     if (result != NULL || dp >= end) {
1460       return result;
1461     }
1462 
1463     assert(dp->tag() == DataLayout::no_tag || (dp->tag() == DataLayout::speculative_trap_data_tag && m != NULL), "should be free");
1464     assert(next_extra(dp)->tag() == DataLayout::no_tag || next_extra(dp)->tag() == DataLayout::arg_info_data_tag, "should be free or arg info");
1465     u1 tag = m == NULL ? DataLayout::bit_data_tag : DataLayout::speculative_trap_data_tag;
1466     // SpeculativeTrapData is 2 slots. Make sure we have room.
1467     if (m != NULL && next_extra(dp)->tag() != DataLayout::no_tag) {
1468       return NULL;
1469     }
1470     DataLayout temp;
1471     temp.initialize(tag, bci, 0);
1472 
1473     dp->set_header(temp.header());
1474     assert(dp->tag() == tag, "sane");
1475     assert(dp->bci() == bci, "no concurrent allocation");
1476     if (tag == DataLayout::bit_data_tag) {
1477       return new BitData(dp);
1478     } else {
1479       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1480       data->set_method(m);
1481       return data;
1482     }
1483   }
1484   return NULL;
1485 }
1486 
1487 ArgInfoData *MethodData::arg_info() {
1488   DataLayout* dp    = extra_data_base();
1489   DataLayout* end   = args_data_limit();
1490   for (; dp < end; dp = next_extra(dp)) {
1491     if (dp->tag() == DataLayout::arg_info_data_tag)
1492       return new ArgInfoData(dp);
1493   }
1494   return NULL;
1495 }
1496 
1497 // Printing
1498 
1499 void MethodData::print_on(outputStream* st) const {
1500   assert(is_methodData(), "should be method data");
1501   st->print("method data for ");
1502   method()->print_value_on(st);
1503   st->cr();
1504   print_data_on(st);
1505 }
1506 
1507 void MethodData::print_value_on(outputStream* st) const {
1508   assert(is_methodData(), "should be method data");
1509   st->print("method data for ");
1510   method()->print_value_on(st);
1511 }
1512 
1513 void MethodData::print_data_on(outputStream* st) const {
1514   ResourceMark rm;
1515   ProfileData* data = first_data();
1516   if (_parameters_type_data_di != no_parameters) {
1517     parameters_type_data()->print_data_on(st);
1518   }
1519   for ( ; is_valid(data); data = next_data(data)) {
1520     st->print("%d", dp_to_di(data->dp()));
1521     st->fill_to(6);
1522     data->print_data_on(st, this);
1523   }
1524   st->print_cr("--- Extra data:");
1525   DataLayout* dp    = extra_data_base();
1526   DataLayout* end   = args_data_limit();
1527   for (;; dp = next_extra(dp)) {
1528     assert(dp < end, "moved past end of extra data");
1529     // No need for "Atomic::load_acquire" ops,
1530     // since the data structure is monotonic.
1531     switch(dp->tag()) {
1532     case DataLayout::no_tag:
1533       continue;
1534     case DataLayout::bit_data_tag:
1535       data = new BitData(dp);
1536       break;
1537     case DataLayout::speculative_trap_data_tag:
1538       data = new SpeculativeTrapData(dp);
1539       break;
1540     case DataLayout::arg_info_data_tag:
1541       data = new ArgInfoData(dp);
1542       dp = end; // ArgInfoData is at the end of extra data section.
1543       break;
1544     default:
1545       fatal("unexpected tag %d", dp->tag());
1546     }
1547     st->print("%d", dp_to_di(data->dp()));
1548     st->fill_to(6);
1549     data->print_data_on(st);
1550     if (dp >= end) return;
1551   }
1552 }
1553 
1554 // Verification
1555 
1556 void MethodData::verify_on(outputStream* st) {
1557   guarantee(is_methodData(), "object must be method data");
1558   // guarantee(m->is_perm(), "should be in permspace");
1559   this->verify_data_on(st);
1560 }
1561 
1562 void MethodData::verify_data_on(outputStream* st) {
1563   NEEDS_CLEANUP;
1564   // not yet implemented.
1565 }
1566 
1567 bool MethodData::profile_jsr292(const methodHandle& m, int bci) {
1568   if (m->is_compiled_lambda_form()) {
1569     return true;
1570   }
1571 
1572   Bytecode_invoke inv(m , bci);
1573   return inv.is_invokedynamic() || inv.is_invokehandle();
1574 }
1575 
1576 bool MethodData::profile_unsafe(const methodHandle& m, int bci) {
1577   Bytecode_invoke inv(m , bci);
1578   if (inv.is_invokevirtual()) {
1579     Symbol* klass = inv.klass();
1580     if (klass == vmSymbols::jdk_internal_misc_Unsafe() ||
1581         klass == vmSymbols::sun_misc_Unsafe() ||
1582         klass == vmSymbols::jdk_internal_misc_ScopedMemoryAccess()) {
1583       Symbol* name = inv.name();
1584       if (name->starts_with("get") || name->starts_with("put")) {
1585         return true;
1586       }
1587     }
1588   }
1589   return false;
1590 }
1591 
1592 int MethodData::profile_arguments_flag() {
1593   return TypeProfileLevel % 10;
1594 }
1595 
1596 bool MethodData::profile_arguments() {
1597   return profile_arguments_flag() > no_type_profile && profile_arguments_flag() <= type_profile_all;
1598 }
1599 
1600 bool MethodData::profile_arguments_jsr292_only() {
1601   return profile_arguments_flag() == type_profile_jsr292;
1602 }
1603 
1604 bool MethodData::profile_all_arguments() {
1605   return profile_arguments_flag() == type_profile_all;
1606 }
1607 
1608 bool MethodData::profile_arguments_for_invoke(const methodHandle& m, int bci) {
1609   if (!profile_arguments()) {
1610     return false;
1611   }
1612 
1613   if (profile_all_arguments()) {
1614     return true;
1615   }
1616 
1617   if (profile_unsafe(m, bci)) {
1618     return true;
1619   }
1620 
1621   assert(profile_arguments_jsr292_only(), "inconsistent");
1622   return profile_jsr292(m, bci);
1623 }
1624 
1625 int MethodData::profile_return_flag() {
1626   return (TypeProfileLevel % 100) / 10;
1627 }
1628 
1629 bool MethodData::profile_return() {
1630   return profile_return_flag() > no_type_profile && profile_return_flag() <= type_profile_all;
1631 }
1632 
1633 bool MethodData::profile_return_jsr292_only() {
1634   return profile_return_flag() == type_profile_jsr292;
1635 }
1636 
1637 bool MethodData::profile_all_return() {
1638   return profile_return_flag() == type_profile_all;
1639 }
1640 
1641 bool MethodData::profile_return_for_invoke(const methodHandle& m, int bci) {
1642   if (!profile_return()) {
1643     return false;
1644   }
1645 
1646   if (profile_all_return()) {
1647     return true;
1648   }
1649 
1650   assert(profile_return_jsr292_only(), "inconsistent");
1651   return profile_jsr292(m, bci);
1652 }
1653 
1654 int MethodData::profile_parameters_flag() {
1655   return TypeProfileLevel / 100;
1656 }
1657 
1658 bool MethodData::profile_parameters() {
1659   return profile_parameters_flag() > no_type_profile && profile_parameters_flag() <= type_profile_all;
1660 }
1661 
1662 bool MethodData::profile_parameters_jsr292_only() {
1663   return profile_parameters_flag() == type_profile_jsr292;
1664 }
1665 
1666 bool MethodData::profile_all_parameters() {
1667   return profile_parameters_flag() == type_profile_all;
1668 }
1669 
1670 bool MethodData::profile_parameters_for_method(const methodHandle& m) {
1671   if (!profile_parameters()) {
1672     return false;
1673   }
1674 
1675   if (profile_all_parameters()) {
1676     return true;
1677   }
1678 
1679   assert(profile_parameters_jsr292_only(), "inconsistent");
1680   return m->is_compiled_lambda_form();
1681 }
1682 
1683 void MethodData::metaspace_pointers_do(MetaspaceClosure* it) {
1684   log_trace(cds)("Iter(MethodData): %p", this);
1685   it->push(&_method);
1686 }
1687 
1688 void MethodData::clean_extra_data_helper(DataLayout* dp, int shift, bool reset) {
1689   if (shift == 0) {
1690     return;
1691   }
1692   if (!reset) {
1693     // Move all cells of trap entry at dp left by "shift" cells
1694     intptr_t* start = (intptr_t*)dp;
1695     intptr_t* end = (intptr_t*)next_extra(dp);
1696     for (intptr_t* ptr = start; ptr < end; ptr++) {
1697       *(ptr-shift) = *ptr;
1698     }
1699   } else {
1700     // Reset "shift" cells stopping at dp
1701     intptr_t* start = ((intptr_t*)dp) - shift;
1702     intptr_t* end = (intptr_t*)dp;
1703     for (intptr_t* ptr = start; ptr < end; ptr++) {
1704       *ptr = 0;
1705     }
1706   }
1707 }
1708 
1709 // Check for entries that reference an unloaded method
1710 class CleanExtraDataKlassClosure : public CleanExtraDataClosure {
1711   bool _always_clean;
1712 public:
1713   CleanExtraDataKlassClosure(bool always_clean) : _always_clean(always_clean) {}
1714   bool is_live(Method* m) {
1715     return !(_always_clean) && m->method_holder()->is_loader_alive();
1716   }
1717 };
1718 
1719 // Check for entries that reference a redefined method
1720 class CleanExtraDataMethodClosure : public CleanExtraDataClosure {
1721 public:
1722   CleanExtraDataMethodClosure() {}
1723   bool is_live(Method* m) { return !m->is_old(); }
1724 };
1725 
1726 
1727 // Remove SpeculativeTrapData entries that reference an unloaded or
1728 // redefined method
1729 void MethodData::clean_extra_data(CleanExtraDataClosure* cl) {
1730   DataLayout* dp  = extra_data_base();
1731   DataLayout* end = args_data_limit();
1732 
1733   int shift = 0;
1734   for (; dp < end; dp = next_extra(dp)) {
1735     switch(dp->tag()) {
1736     case DataLayout::speculative_trap_data_tag: {
1737       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1738       Method* m = data->method();
1739       assert(m != NULL, "should have a method");
1740       if (!cl->is_live(m)) {
1741         // "shift" accumulates the number of cells for dead
1742         // SpeculativeTrapData entries that have been seen so
1743         // far. Following entries must be shifted left by that many
1744         // cells to remove the dead SpeculativeTrapData entries.
1745         shift += (int)((intptr_t*)next_extra(dp) - (intptr_t*)dp);
1746       } else {
1747         // Shift this entry left if it follows dead
1748         // SpeculativeTrapData entries
1749         clean_extra_data_helper(dp, shift);
1750       }
1751       break;
1752     }
1753     case DataLayout::bit_data_tag:
1754       // Shift this entry left if it follows dead SpeculativeTrapData
1755       // entries
1756       clean_extra_data_helper(dp, shift);
1757       continue;
1758     case DataLayout::no_tag:
1759     case DataLayout::arg_info_data_tag:
1760       // We are at end of the live trap entries. The previous "shift"
1761       // cells contain entries that are either dead or were shifted
1762       // left. They need to be reset to no_tag
1763       clean_extra_data_helper(dp, shift, true);
1764       return;
1765     default:
1766       fatal("unexpected tag %d", dp->tag());
1767     }
1768   }
1769 }
1770 
1771 // Verify there's no unloaded or redefined method referenced by a
1772 // SpeculativeTrapData entry
1773 void MethodData::verify_extra_data_clean(CleanExtraDataClosure* cl) {
1774 #ifdef ASSERT
1775   DataLayout* dp  = extra_data_base();
1776   DataLayout* end = args_data_limit();
1777 
1778   for (; dp < end; dp = next_extra(dp)) {
1779     switch(dp->tag()) {
1780     case DataLayout::speculative_trap_data_tag: {
1781       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1782       Method* m = data->method();
1783       assert(m != NULL && cl->is_live(m), "Method should exist");
1784       break;
1785     }
1786     case DataLayout::bit_data_tag:
1787       continue;
1788     case DataLayout::no_tag:
1789     case DataLayout::arg_info_data_tag:
1790       return;
1791     default:
1792       fatal("unexpected tag %d", dp->tag());
1793     }
1794   }
1795 #endif
1796 }
1797 
1798 void MethodData::clean_method_data(bool always_clean) {
1799   ResourceMark rm;
1800   for (ProfileData* data = first_data();
1801        is_valid(data);
1802        data = next_data(data)) {
1803     data->clean_weak_klass_links(always_clean);
1804   }
1805   ParametersTypeData* parameters = parameters_type_data();
1806   if (parameters != NULL) {
1807     parameters->clean_weak_klass_links(always_clean);
1808   }
1809 
1810   CleanExtraDataKlassClosure cl(always_clean);
1811   clean_extra_data(&cl);
1812   verify_extra_data_clean(&cl);
1813 }
1814 
1815 // This is called during redefinition to clean all "old" redefined
1816 // methods out of MethodData for all methods.
1817 void MethodData::clean_weak_method_links() {
1818   ResourceMark rm;
1819   CleanExtraDataMethodClosure cl;
1820   clean_extra_data(&cl);
1821   verify_extra_data_clean(&cl);
1822 }