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