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