1 /*
   2  * Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 #include "precompiled.hpp"
  25 #include "classfile/javaClasses.inline.hpp"
  26 #include "code/compiledIC.hpp"
  27 #include "compiler/compileBroker.hpp"
  28 #include "compiler/compilerThread.hpp"
  29 #include "compiler/oopMap.hpp"
  30 #include "jvmci/jvmciCodeInstaller.hpp"
  31 #include "jvmci/jvmciCompilerToVM.hpp"
  32 #include "jvmci/jvmciRuntime.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/compressedOops.inline.hpp"
  35 #include "oops/klass.inline.hpp"
  36 #include "prims/jvmtiExport.hpp"
  37 #include "prims/methodHandles.hpp"
  38 #include "runtime/interfaceSupport.inline.hpp"
  39 #include "runtime/jniHandles.inline.hpp"
  40 #include "runtime/os.hpp"
  41 #include "runtime/sharedRuntime.hpp"
  42 #include "utilities/align.hpp"
  43 
  44 // frequently used constants
  45 // Allocate them with new so they are never destroyed (otherwise, a
  46 // forced exit could destroy these objects while they are still in
  47 // use).
  48 ConstantOopWriteValue* CodeInstaller::_oop_null_scope_value = new (mtJVMCI) ConstantOopWriteValue(NULL);
  49 ConstantIntValue*      CodeInstaller::_int_m1_scope_value = new (mtJVMCI) ConstantIntValue(-1);
  50 ConstantIntValue*      CodeInstaller::_int_0_scope_value =  new (mtJVMCI) ConstantIntValue((jint)0);
  51 ConstantIntValue*      CodeInstaller::_int_1_scope_value =  new (mtJVMCI) ConstantIntValue(1);
  52 ConstantIntValue*      CodeInstaller::_int_2_scope_value =  new (mtJVMCI) ConstantIntValue(2);
  53 LocationValue*         CodeInstaller::_illegal_value = new (mtJVMCI) LocationValue(Location());
  54 MarkerValue*           CodeInstaller::_virtual_byte_array_marker = new (mtJVMCI) MarkerValue();
  55 
  56 static bool is_set(u1 flags, u1 bit) {
  57   return flags & bit;
  58 }
  59 
  60 oop HotSpotCompiledCodeStream::get_oop(int id, JVMCI_TRAPS) const {
  61   if (_object_pool.is_null()) {
  62     JVMCI_ERROR_NULL("object pool is null%s", context());
  63   }
  64   if (!_object_pool.is_null() && 0 <= id && id < _object_pool->length()) {
  65     return _object_pool->obj_at(id);
  66   }
  67   JVMCI_ERROR_NULL("unknown direct object id %d%s", id, context());
  68 }
  69 
  70 u4 HotSpotCompiledCodeStream::offset() const {
  71   u4 res = 0;
  72   for (Chunk* c = _head; c != nullptr; c = c->next()) {
  73     if (c == _chunk) {
  74       res += _pos - c->data();
  75       break;
  76     } else {
  77       res += c->size();
  78     }
  79   }
  80   return res;
  81 }
  82 
  83 bool HotSpotCompiledCodeStream::available() const {
  84   u4 rem = _chunk->data_end() - _pos;
  85   for (Chunk* c = _chunk->next(); c != nullptr; c = c->next()) {
  86     rem += c->size();
  87   }
  88   return rem;
  89 }
  90 
  91 void HotSpotCompiledCodeStream::dump_buffer(outputStream* st) const {
  92   st->print_cr("HotSpotCompiledCode stream for %s:", code_desc());
  93   int chunk_index = 0;
  94   for (Chunk* c = _head; c != nullptr; c = c->next()) {
  95     const u1* data     = c->data();
  96     const u1* data_end = c->data_end();
  97 
  98     int to_dump = data_end - data;
  99     st->print_cr("# chunk %d, %d bytes", chunk_index, to_dump);
 100     st->print_data((void*) data, to_dump, true, false);
 101     chunk_index++;
 102   }
 103 }
 104 
 105 void HotSpotCompiledCodeStream::dump_buffer_tail(int len, outputStream* st) const {
 106   const u1* start;
 107   int avail = _pos - _chunk->data();
 108   if (len >= avail) {
 109     len = avail;
 110     start = _chunk->data();
 111   } else {
 112     start = _pos - len;
 113 
 114     // Ensure start is 16-byte aligned wrt chunk start
 115     int start_offset = start - _chunk->data();
 116     start -= (start_offset % 16);
 117     len = _pos - start;
 118   }
 119 
 120   st->print_cr("Last %d bytes up to current read position " INTPTR_FORMAT " in HotSpotCompiledCode stream for %s:", len, p2i(_pos), code_desc());
 121   st->print_data((void*) start, len, true, false);
 122 }
 123 
 124 const char* HotSpotCompiledCodeStream::context() const {
 125   stringStream st;
 126   st.cr();
 127   st.print_cr("at " INTPTR_FORMAT " in HotSpotCompiledCode stream", p2i(_pos));
 128   dump_buffer_tail(100, &st);
 129   return st.as_string();
 130 }
 131 
 132 void HotSpotCompiledCodeStream::before_read(u1 size) {
 133   if (_pos + size > _chunk->data_end()) {
 134     Chunk* next = _chunk->next();
 135     if (next == nullptr || size > next->size()) {
 136       dump_buffer();
 137       fatal("%s: reading %d bytes overflows buffer at " INTPTR_FORMAT, code_desc(), size, p2i(_pos));
 138     }
 139     _chunk = next;
 140     _pos = _chunk->data();
 141   }
 142 }
 143 
 144 // Reads a size followed by an ascii string from the stream and
 145 // checks that they match `expect_size` and `expect_name` respectively. This
 146 // implements a rudimentary type checking of the stream between the stream producer
 147 // (Java) and the consumer (C++).
 148 void HotSpotCompiledCodeStream::check_data(u2 expect_size, const char* expect_name) {
 149   u2 actual_size = get_u1();
 150   u2 ascii_len = get_u1();
 151   const char* actual_name = (const char*) _pos;
 152   char* end = (char*) _pos + ascii_len;
 153   _pos = (const u1*) end;
 154   if (strlen(expect_name) != ascii_len || strncmp(expect_name, actual_name, ascii_len) != 0) {
 155     dump_buffer();
 156     fatal("%s: expected \"%s\" at " INTPTR_FORMAT ", got \"%.*s\" (len: %d)",
 157         code_desc(), expect_name, p2i(actual_name), ascii_len, actual_name, ascii_len);
 158   }
 159   if (actual_size != expect_size) {
 160     dump_buffer();
 161     fatal("%s: expected \"%s\" at " INTPTR_FORMAT " to have size %u, got %u",
 162         code_desc(), expect_name, p2i(actual_name), expect_size, actual_size);
 163   }
 164 }
 165 
 166 const char* HotSpotCompiledCodeStream::read_utf8(const char* name, JVMCI_TRAPS) {
 167   jint utf_len = read_s4(name);
 168   if (utf_len == -1) {
 169     return nullptr;
 170   }
 171   guarantee(utf_len >= 0, "bad utf_len: %d", utf_len);
 172 
 173   const char* utf = (const char*) _pos;
 174   char* end = (char*) _pos + utf_len;
 175   _pos = (const u1*) (end + 1);
 176   if (*end != '\0') {
 177     JVMCI_ERROR_NULL("UTF8 string at " INTPTR_FORMAT " of length %d missing 0 terminator: \"%.*s\"%s",
 178         p2i(utf), utf_len, utf_len, utf, context());
 179   }
 180   return utf;
 181 }
 182 
 183 Method* HotSpotCompiledCodeStream::read_method(const char* name) {
 184   return (Method*) read_u8(name);
 185 }
 186 
 187 Klass* HotSpotCompiledCodeStream::read_klass(const char* name) {
 188   return (Klass*) read_u8(name);
 189 }
 190 
 191 ScopeValue* HotSpotCompiledCodeStream::virtual_object_at(int id, JVMCI_TRAPS) const {
 192   if (_virtual_objects == nullptr) {
 193     JVMCI_ERROR_NULL("virtual object id %d read outside scope of decoding DebugInfo%s", id, context());
 194   }
 195   if (id < 0 || id >= _virtual_objects->length()) {
 196     JVMCI_ERROR_NULL("invalid virtual object id %d%s", id, context());
 197   }
 198   return _virtual_objects->at(id);
 199 }
 200 
 201 #ifndef PRODUCT
 202 void CodeInstaller::verify_bci_constants(JVMCIEnv* env) {
 203 #define CHECK_IN_SYNC(name) do { \
 204   int expect = env->get_BytecodeFrame_ ## name ##_BCI(); \
 205   int actual = name##_BCI; \
 206   if (expect != actual) fatal("CodeInstaller::" #name "_BCI(%d) != BytecodeFrame." #name "_BCI(%d)", expect, actual); \
 207 } while(0)
 208 
 209   CHECK_IN_SYNC(UNWIND);
 210   CHECK_IN_SYNC(BEFORE);
 211   CHECK_IN_SYNC(AFTER);
 212   CHECK_IN_SYNC(AFTER_EXCEPTION);
 213   CHECK_IN_SYNC(UNKNOWN);
 214   CHECK_IN_SYNC(INVALID_FRAMESTATE);
 215 #undef CHECK_IN_SYNC
 216 }
 217 #endif
 218 
 219 VMReg CodeInstaller::getVMRegFromLocation(HotSpotCompiledCodeStream* stream, int total_frame_size, JVMCI_TRAPS) {
 220   u2 reg = stream->read_u2("register");
 221   u2 offset = stream->read_u2("offset");
 222 
 223   if (reg != NO_REGISTER) {
 224     VMReg vmReg = CodeInstaller::get_hotspot_reg(reg, JVMCI_CHECK_NULL);
 225     if (offset % 4 == 0) {
 226       return vmReg->next(offset / 4);
 227     } else {
 228       JVMCI_ERROR_NULL("unaligned subregister offset %d in oop map%s", offset, stream->context());
 229     }
 230   } else {
 231     if (offset % 4 == 0) {
 232       VMReg vmReg = VMRegImpl::stack2reg(offset / 4);
 233       if (!OopMapValue::legal_vm_reg_name(vmReg)) {
 234         // This restriction only applies to VMRegs that are used in OopMap but
 235         // since that's the only use of VMRegs it's simplest to put this test
 236         // here.  This test should also be equivalent legal_vm_reg_name but JVMCI
 237         // clients can use max_oop_map_stack_stack_offset to detect this problem
 238         // directly.  The asserts just ensure that the tests are in agreement.
 239         assert(offset > CompilerToVM::Data::max_oop_map_stack_offset(), "illegal VMReg");
 240         JVMCI_ERROR_NULL("stack offset %d is too large to be encoded in OopMap (max %d)%s",
 241                          offset, CompilerToVM::Data::max_oop_map_stack_offset(), stream->context());
 242       }
 243       assert(OopMapValue::legal_vm_reg_name(vmReg), "illegal VMReg");
 244       return vmReg;
 245     } else {
 246       JVMCI_ERROR_NULL("unaligned stack offset %d in oop map%s", offset, stream->context());
 247     }
 248   }
 249 }
 250 
 251 OopMap* CodeInstaller::create_oop_map(HotSpotCompiledCodeStream* stream, u1 debug_info_flags, JVMCI_TRAPS) {
 252   assert(is_set(debug_info_flags, DI_HAS_REFERENCE_MAP), "must be");
 253   u2 max_register_size = stream->read_u2("maxRegisterSize");
 254   if (!_has_wide_vector && SharedRuntime::is_wide_vector(max_register_size)) {
 255     if (SharedRuntime::polling_page_vectors_safepoint_handler_blob() == NULL) {
 256       JVMCI_ERROR_NULL("JVMCI is producing code using vectors larger than the runtime supports%s", stream->context());
 257     }
 258     _has_wide_vector = true;
 259   }
 260   u2 length = stream->read_u2("referenceMap:length");
 261 
 262   OopMap* map = new OopMap(_total_frame_size, _parameter_count);
 263   for (int i = 0; i < length; i++) {
 264     bool has_derived = stream->read_bool("hasDerived");
 265     u2 bytes = stream->read_u2("sizeInBytes");
 266     VMReg vmReg = getVMRegFromLocation(stream, _total_frame_size, JVMCI_CHECK_NULL);
 267     if (has_derived) {
 268       // derived oop
 269       if (bytes == LP64_ONLY(8) NOT_LP64(4)) {
 270         VMReg baseReg = getVMRegFromLocation(stream, _total_frame_size, JVMCI_CHECK_NULL);
 271         map->set_derived_oop(vmReg, baseReg);
 272       } else {
 273         JVMCI_ERROR_NULL("invalid derived oop size in ReferenceMap: %d%s", bytes, stream->context());
 274       }
 275 #ifdef _LP64
 276     } else if (bytes == 8) {
 277       // wide oop
 278       map->set_oop(vmReg);
 279     } else if (bytes == 4) {
 280       // narrow oop
 281       map->set_narrowoop(vmReg);
 282 #else
 283     } else if (bytes == 4) {
 284       map->set_oop(vmReg);
 285 #endif
 286     } else {
 287       JVMCI_ERROR_NULL("invalid oop size in ReferenceMap: %d%s", bytes, stream->context());
 288     }
 289   }
 290 
 291   if (is_set(debug_info_flags, DI_HAS_CALLEE_SAVE_INFO)) {
 292     length = stream->read_u2("calleeSaveInfo:length");
 293     for (jint i = 0; i < length; i++) {
 294       u2 jvmci_reg_number = stream->read_u2("register");
 295       VMReg hotspot_reg = CodeInstaller::get_hotspot_reg(jvmci_reg_number, JVMCI_CHECK_NULL);
 296       // HotSpot stack slots are 4 bytes
 297       u2 jvmci_slot = stream->read_u2("slot");
 298       jint hotspot_slot = jvmci_slot * VMRegImpl::slots_per_word;
 299       VMReg hotspot_slot_as_reg = VMRegImpl::stack2reg(hotspot_slot);
 300       map->set_callee_saved(hotspot_slot_as_reg, hotspot_reg);
 301 #ifdef _LP64
 302       // (copied from generate_oop_map() in c1_Runtime1_x86.cpp)
 303       VMReg hotspot_slot_hi_as_reg = VMRegImpl::stack2reg(hotspot_slot + 1);
 304       map->set_callee_saved(hotspot_slot_hi_as_reg, hotspot_reg->next());
 305 #endif
 306     }
 307   }
 308   return map;
 309 }
 310 
 311 void* CodeInstaller::record_metadata_reference(CodeSection* section, address dest, HotSpotCompiledCodeStream* stream, u1 tag, JVMCI_TRAPS) {
 312   /*
 313    * This method needs to return a raw (untyped) pointer, since the value of a pointer to the base
 314    * class is in general not equal to the pointer of the subclass. When patching metaspace pointers,
 315    * the compiler expects a direct pointer to the subclass (Klass* or Method*), not a pointer to the
 316    * base class (Metadata* or MetaspaceObj*).
 317    */
 318   if (tag == PATCH_KLASS) {
 319     Klass* klass = stream->read_klass("patch:klass");
 320     int index = _oop_recorder->find_index(klass);
 321     section->relocate(dest, metadata_Relocation::spec(index));
 322     JVMCI_event_3("metadata[%d of %d] = %s", index, _oop_recorder->metadata_count(), klass->name()->as_C_string());
 323     return klass;
 324   } else if (tag == PATCH_METHOD) {
 325     Method* method = stream->read_method("patch:method");
 326     int index = _oop_recorder->find_index(method);
 327     section->relocate(dest, metadata_Relocation::spec(index));
 328     JVMCI_event_3("metadata[%d of %d] = %s", index, _oop_recorder->metadata_count(), method->name()->as_C_string());
 329     return method;
 330   } else {
 331     JVMCI_ERROR_NULL("unexpected metadata reference tag: %d%s", tag, stream->context());
 332   }
 333 }
 334 
 335 #ifdef _LP64
 336 narrowKlass CodeInstaller::record_narrow_metadata_reference(CodeSection* section, address dest, HotSpotCompiledCodeStream* stream, u1 tag, JVMCI_TRAPS) {
 337   if (tag != PATCH_NARROW_KLASS) {
 338     JVMCI_ERROR_0("unexpected compressed pointer tag %d%s", tag, stream->context());
 339   }
 340   Klass* klass = stream->read_klass("patch:klass");
 341   int index = _oop_recorder->find_index(klass);
 342   section->relocate(dest, metadata_Relocation::spec(index));
 343   JVMCI_event_3("narrowKlass[%d of %d] = %s", index, _oop_recorder->metadata_count(), klass->name()->as_C_string());
 344   return CompressedKlassPointers::encode(klass);
 345 }
 346 #endif
 347 
 348 ScopeValue* CodeInstaller::to_primitive_value(HotSpotCompiledCodeStream* stream, jlong raw, BasicType type, ScopeValue* &second, JVMCI_TRAPS) {
 349   if (type == T_INT || type == T_FLOAT) {
 350     jint prim = (jint) raw;
 351     switch (prim) {
 352       case -1: return _int_m1_scope_value;
 353       case  0: return _int_0_scope_value;
 354       case  1: return _int_1_scope_value;
 355       case  2: return _int_2_scope_value;
 356       default: return new ConstantIntValue(prim);
 357     }
 358   } else if (type == T_LONG || type == T_DOUBLE) {
 359     jlong prim = raw;
 360     second = _int_1_scope_value;
 361     return new ConstantLongValue(prim);
 362   } else {
 363     JVMCI_ERROR_NULL("unexpected primitive constant type %s%s", basictype_to_str(type), stream->context());
 364   }
 365 }
 366 
 367 Handle CodeInstaller::read_oop(HotSpotCompiledCodeStream* stream, u1 tag, JVMCI_TRAPS) {
 368   oop obj;
 369   if (tag == OBJECT_ID) {
 370     obj = stream->get_oop(stream->read_u1("id"), JVMCI_CHECK_(Handle()));
 371   } else if (tag == OBJECT_ID2) {
 372     obj = stream->get_oop(stream->read_u2("id:2"), JVMCI_CHECK_(Handle()));
 373   } else if (tag == JOBJECT) {
 374     jlong object_handle = stream->read_u8("jobject");
 375     obj = jvmci_env()->resolve_oop_handle(object_handle);
 376   } else {
 377     JVMCI_ERROR_(Handle(), "unexpected oop tag: %d", tag)
 378   }
 379   if (obj == nullptr) {
 380     JVMCI_THROW_MSG_(InternalError, "Constant was unexpectedly NULL", Handle());
 381   } else {
 382     oopDesc::verify(obj);
 383   }
 384   return Handle(stream->thread(), obj);
 385 }
 386 
 387 ScopeValue* CodeInstaller::get_scope_value(HotSpotCompiledCodeStream* stream, u1 tag, BasicType type, ScopeValue* &second, JVMCI_TRAPS) {
 388   second = NULL;
 389   switch (tag) {
 390     case ILLEGAL: {
 391       if (type != T_ILLEGAL) {
 392         JVMCI_ERROR_NULL("unexpected illegal value, expected %s%s", basictype_to_str(type), stream->context());
 393       }
 394       return _illegal_value;
 395     }
 396     case REGISTER_PRIMITIVE:
 397     case REGISTER_NARROW_OOP:
 398     case REGISTER_OOP: {
 399       u2 number = stream->read_u2("register");
 400       VMReg hotspotRegister = get_hotspot_reg(number, JVMCI_CHECK_NULL);
 401       if (is_general_purpose_reg(hotspotRegister)) {
 402         Location::Type locationType;
 403         if (type == T_OBJECT) {
 404           locationType = tag == REGISTER_NARROW_OOP ? Location::narrowoop : Location::oop;
 405         } else if (type == T_LONG) {
 406           locationType = Location::lng;
 407         } else if (type == T_INT || type == T_FLOAT || type == T_SHORT || type == T_CHAR || type == T_BYTE || type == T_BOOLEAN) {
 408           locationType = Location::int_in_long;
 409         } else {
 410           JVMCI_ERROR_NULL("unexpected type %s in CPU register%s", basictype_to_str(type), stream->context());
 411         }
 412         ScopeValue* value = new LocationValue(Location::new_reg_loc(locationType, hotspotRegister));
 413         if (type == T_LONG) {
 414           second = value;
 415         }
 416         return value;
 417       } else {
 418         Location::Type locationType;
 419         if (type == T_FLOAT) {
 420           // this seems weird, but the same value is used in c1_LinearScan
 421           locationType = Location::normal;
 422         } else if (type == T_DOUBLE) {
 423           locationType = Location::dbl;
 424         } else {
 425           JVMCI_ERROR_NULL("unexpected type %s in floating point register%s", basictype_to_str(type), stream->context());
 426         }
 427         ScopeValue* value = new LocationValue(Location::new_reg_loc(locationType, hotspotRegister));
 428         if (type == T_DOUBLE) {
 429           second = value;
 430         }
 431         return value;
 432       }
 433     }
 434     case STACK_SLOT_PRIMITIVE:
 435     case STACK_SLOT_NARROW_OOP:
 436     case STACK_SLOT_OOP: {
 437       jint offset = (jshort) stream->read_s2("offset");
 438       if (stream->read_bool("addRawFrameSize")) {
 439         offset += _total_frame_size;
 440       }
 441       Location::Type locationType;
 442       if (type == T_OBJECT) {
 443         locationType = tag == STACK_SLOT_NARROW_OOP ? Location::narrowoop : Location::oop;
 444       } else if (type == T_LONG) {
 445         locationType = Location::lng;
 446       } else if (type == T_DOUBLE) {
 447         locationType = Location::dbl;
 448       } else if (type == T_INT || type == T_FLOAT || type == T_SHORT || type == T_CHAR || type == T_BYTE || type == T_BOOLEAN) {
 449         locationType = Location::normal;
 450       } else {
 451         JVMCI_ERROR_NULL("unexpected type %s in stack slot%s", basictype_to_str(type), stream->context());
 452       }
 453       ScopeValue* value = new LocationValue(Location::new_stk_loc(locationType, offset));
 454       if (type == T_DOUBLE || type == T_LONG) {
 455         second = value;
 456       }
 457       return value;
 458     }
 459     case NULL_CONSTANT:      { return _oop_null_scope_value; }
 460     case RAW_CONSTANT:       { return new ConstantLongValue(stream->read_u8("primitive")); }
 461     case PRIMITIVE_0:        { ScopeValue* v = to_primitive_value(stream, 0, type, second, JVMCI_CHECK_NULL); return v; }
 462     case PRIMITIVE4:         { ScopeValue* v = to_primitive_value(stream, stream->read_s4("primitive4"), type, second, JVMCI_CHECK_NULL); return v; }
 463     case PRIMITIVE8:         { ScopeValue* v = to_primitive_value(stream, stream->read_s8("primitive8"), type, second, JVMCI_CHECK_NULL); return v; }
 464     case VIRTUAL_OBJECT_ID:  { ScopeValue* v = stream->virtual_object_at(stream->read_u1("id"),   JVMCI_CHECK_NULL); return v; }
 465     case VIRTUAL_OBJECT_ID2: { ScopeValue* v = stream->virtual_object_at(stream->read_u2("id:2"), JVMCI_CHECK_NULL); return v; }
 466 
 467     case OBJECT_ID:
 468     case OBJECT_ID2:
 469     case JOBJECT: {
 470       Handle obj = read_oop(stream, tag, JVMCI_CHECK_NULL);
 471       return new ConstantOopWriteValue(JNIHandles::make_local(obj()));
 472     }
 473     default: {
 474       JVMCI_ERROR_NULL("unexpected tag in scope: %d%s", tag, stream->context())
 475     }
 476   }
 477 }
 478 
 479 void CodeInstaller::record_object_value(ObjectValue* sv, HotSpotCompiledCodeStream* stream, JVMCI_TRAPS) {
 480   oop javaMirror = JNIHandles::resolve(sv->klass()->as_ConstantOopWriteValue()->value());
 481   Klass* klass = java_lang_Class::as_Klass(javaMirror);
 482   bool isLongArray = klass == Universe::longArrayKlassObj();
 483   bool isByteArray = klass == Universe::byteArrayKlassObj();
 484 
 485   u2 length = stream->read_u2("values:length");
 486   for (jint i = 0; i < length; i++) {
 487     ScopeValue* cur_second = NULL;
 488     BasicType type = (BasicType) stream->read_u1("basicType");
 489     ScopeValue* value;
 490     u1 tag = stream->read_u1("tag");
 491     if (tag == ILLEGAL) {
 492       if (isByteArray && type == T_ILLEGAL) {
 493         /*
 494          * The difference between a virtualized large access and a deferred write is the kind stored in the slotKinds
 495          * of the virtual object: in the virtualization case, the kind is illegal, in the deferred write case, the kind
 496          * is access stack kind (an int).
 497          */
 498         value = _virtual_byte_array_marker;
 499       } else {
 500         value = _illegal_value;
 501         if (type == T_DOUBLE || type == T_LONG) {
 502             cur_second = _illegal_value;
 503         }
 504       }
 505     } else {
 506       value = get_scope_value(stream, tag, type, cur_second, JVMCI_CHECK);
 507     }
 508 
 509     if (isLongArray && cur_second == NULL) {
 510       // we're trying to put ints into a long array... this isn't really valid, but it's used for some optimizations.
 511       // add an int 0 constant
 512       cur_second = _int_0_scope_value;
 513     }
 514 
 515     if (isByteArray && cur_second != NULL && (type == T_DOUBLE || type == T_LONG)) {
 516       // we are trying to write a long in a byte Array. We will need to count the illegals to restore the type of
 517       // the thing we put inside.
 518       cur_second = NULL;
 519     }
 520 
 521     if (cur_second != NULL) {
 522       sv->field_values()->append(cur_second);
 523     }
 524     assert(value != NULL, "missing value");
 525     sv->field_values()->append(value);
 526   }
 527 }
 528 
 529 GrowableArray<ScopeValue*>* CodeInstaller::read_local_or_stack_values(HotSpotCompiledCodeStream* stream, u1 frame_flags, bool is_locals, JVMCI_TRAPS) {
 530   u2 length;
 531   if (is_locals) {
 532     if (!is_set(frame_flags, DIF_HAS_LOCALS)) {
 533       return nullptr;
 534     }
 535     length = stream->read_u2("numLocals");
 536   } else {
 537     if (!is_set(frame_flags, DIF_HAS_STACK)) {
 538       return nullptr;
 539     }
 540     length = stream->read_u2("numStack");
 541   }
 542   GrowableArray<ScopeValue*>* values = new GrowableArray<ScopeValue*> (length);
 543   for (int i = 0; i < length; i++) {
 544     ScopeValue* second = nullptr;
 545     BasicType type = (BasicType) stream->read_u1("basicType");
 546     u1 tag = stream->read_u1("tag");
 547     ScopeValue* first = get_scope_value(stream, tag, type, second, JVMCI_CHECK_NULL);
 548     if (second != nullptr) {
 549       if (i == length) {
 550         JVMCI_ERROR_NULL("double-slot value not followed by Value.ILLEGAL%s", stream->context());
 551       }
 552       i++;
 553       stream->read_u1("basicType");
 554       tag = stream->read_u1("tag");
 555       if (tag != ILLEGAL) {
 556         JVMCI_ERROR_NULL("double-slot value not followed by Value.ILLEGAL%s", stream->context());
 557       }
 558       values->append(second);
 559     }
 560     values->append(first);
 561   }
 562   return values;
 563 }
 564 
 565 GrowableArray<MonitorValue*>* CodeInstaller::read_monitor_values(HotSpotCompiledCodeStream* stream, u1 frame_flags, JVMCI_TRAPS) {
 566   if (!is_set(frame_flags, DIF_HAS_LOCKS)) {
 567     return nullptr;
 568   }
 569   if (!_has_monitors) {
 570     _has_monitors = true;
 571   }
 572   u2 length = stream->read_u2("numLocks");
 573   GrowableArray<MonitorValue*>* monitors = new GrowableArray<MonitorValue*>(length);
 574   for (int i = 0; i < length; i++) {
 575     bool eliminated = stream->read_bool("isEliminated");
 576     ScopeValue* second = NULL;
 577     ScopeValue* owner_value = get_scope_value(stream, stream->read_u1("tag"), T_OBJECT, second, JVMCI_CHECK_NULL);
 578     assert(second == NULL, "monitor cannot occupy two stack slots");
 579 
 580     ScopeValue* lock_data_value = get_scope_value(stream, stream->read_u1("tag"), T_LONG, second, JVMCI_CHECK_NULL);
 581     assert(second == lock_data_value, "monitor is LONG value that occupies two stack slots");
 582     assert(lock_data_value->is_location(), "invalid monitor location");
 583     Location lock_data_loc = ((LocationValue*) lock_data_value)->location();
 584 
 585     monitors->append(new MonitorValue(owner_value, lock_data_loc, eliminated));
 586   }
 587   return monitors;
 588 }
 589 
 590 void CodeInstaller::initialize_dependencies(HotSpotCompiledCodeStream* stream, u1 code_flags, OopRecorder* oop_recorder, JVMCI_TRAPS) {
 591   JavaThread* thread = stream->thread();
 592   CompilerThread* compilerThread = thread->is_Compiler_thread() ? CompilerThread::cast(thread) : NULL;
 593   _oop_recorder = oop_recorder;
 594   _dependencies = new Dependencies(&_arena, _oop_recorder, compilerThread != NULL ? compilerThread->log() : NULL);
 595   if (is_set(code_flags, HCC_HAS_ASSUMPTIONS)) {
 596     u2 length = stream->read_u2("assumptions:length");
 597     for (int i = 0; i < length; ++i) {
 598       u1 tag = stream->read_u1("tag");
 599       switch (tag) {
 600         case NO_FINALIZABLE_SUBCLASS: {
 601           Klass* receiver_type = stream->read_klass("receiverType");
 602           _dependencies->assert_has_no_finalizable_subclasses(receiver_type);
 603           break;
 604         }
 605         case CONCRETE_SUBTYPE: {
 606           Klass* context = stream->read_klass("context");
 607           Klass* subtype = stream->read_klass("subtype");
 608           assert(context->is_abstract(), "must be");
 609           _dependencies->assert_abstract_with_unique_concrete_subtype(context, subtype);
 610           break;
 611         }
 612         case LEAF_TYPE: {
 613           Klass* context = stream->read_klass("context");
 614           _dependencies->assert_leaf_type(context);
 615           break;
 616         }
 617         case CONCRETE_METHOD: {
 618           Klass* context = stream->read_klass("context");
 619           Method* impl = stream->read_method("impl");
 620           _dependencies->assert_unique_concrete_method(context, impl);
 621           break;
 622         }
 623         case CALLSITE_TARGET_VALUE: {
 624           u1 obj_tag = stream->read_u1("tag");
 625           Handle callSite = read_oop(stream, obj_tag, JVMCI_CHECK);
 626           obj_tag = stream->read_u1("tag");
 627           Handle methodHandle = read_oop(stream, obj_tag, JVMCI_CHECK);
 628           _dependencies->assert_call_site_target_value(callSite(), methodHandle());
 629           break;
 630         }
 631         default: {
 632           JVMCI_ERROR("unexpected assumption tag %d%s", tag, stream->context());
 633         }
 634       }
 635     }
 636   }
 637   if (is_set(code_flags, HCC_HAS_METHODS)) {
 638     u2 length = stream->read_u2("methods:length");
 639     for (int i = 0; i < length; ++i) {
 640       Method* method = stream->read_method("method");
 641       if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
 642         _dependencies->assert_evol_method(method);
 643       }
 644     }
 645   }
 646 }
 647 
 648 JVMCI::CodeInstallResult CodeInstaller::install(JVMCICompiler* compiler,
 649     jlong compiled_code_buffer,
 650     bool with_type_info,
 651     JVMCIObject compiled_code,
 652     objArrayHandle object_pool,
 653     CodeBlob*& cb,
 654     JVMCIObject installed_code,
 655     FailedSpeculation** failed_speculations,
 656     char* speculations,
 657     int speculations_len,
 658     JVMCI_TRAPS) {
 659 
 660   JavaThread* thread = JavaThread::current();
 661   HotSpotCompiledCodeStream* stream = new HotSpotCompiledCodeStream(thread, (const u1*) compiled_code_buffer, with_type_info, object_pool);
 662 
 663   u1 code_flags = stream->read_u1("code:flags");
 664   bool is_nmethod = is_set(code_flags, HCC_IS_NMETHOD);
 665   const char* name = stream->read_utf8("name", JVMCI_CHECK_OK);
 666 
 667   methodHandle method;
 668   jint entry_bci = -1;
 669   JVMCICompileState* compile_state = nullptr;
 670   bool has_unsafe_access = false;
 671   jint id = -1;
 672 
 673   if (is_nmethod) {
 674     method = methodHandle(thread, stream->read_method("method"));
 675     entry_bci = is_nmethod ? stream->read_s4("entryBCI") : -1;
 676     compile_state = (JVMCICompileState*) stream->read_u8("compileState");
 677     has_unsafe_access = stream->read_bool("hasUnsafeAccess");
 678     id = stream->read_s4("id");
 679   }
 680   stream->set_code_desc(name, method);
 681 
 682   CodeBuffer buffer("JVMCI Compiler CodeBuffer");
 683   OopRecorder* recorder = new OopRecorder(&_arena, true);
 684   initialize_dependencies(stream, code_flags, recorder, JVMCI_CHECK_OK);
 685 
 686   // Get instructions and constants CodeSections early because we need it.
 687   _instructions = buffer.insts();
 688   _constants = buffer.consts();
 689 
 690   initialize_fields(stream, code_flags, method, buffer, JVMCI_CHECK_OK);
 691   JVMCI::CodeInstallResult result = initialize_buffer(compiled_code, buffer, stream, code_flags, JVMCI_CHECK_OK);
 692 
 693   u4 available = stream->available();
 694   if (result == JVMCI::ok && available != 0) {
 695     JVMCI_ERROR_OK("%d bytes remaining in stream%s", available, stream->context());
 696   }
 697 
 698   if (result != JVMCI::ok) {
 699     return result;
 700   }
 701 
 702   int stack_slots = _total_frame_size / HeapWordSize; // conversion to words
 703 
 704   if (!is_nmethod) {
 705     if (name == nullptr) {
 706       JVMCI_ERROR_OK("stub should have a name");
 707     }
 708     name = os::strdup(name); // Note: this leaks. See JDK-8289632
 709     cb = RuntimeStub::new_runtime_stub(name,
 710                                        &buffer,
 711                                        _offsets.value(CodeOffsets::Frame_Complete),
 712                                        stack_slots,
 713                                        _debug_recorder->_oopmaps,
 714                                        false);
 715     result = JVMCI::ok;
 716   } else {
 717     if (compile_state != NULL) {
 718       jvmci_env()->set_compile_state(compile_state);
 719     }
 720 
 721     if (id == -1) {
 722       // Make sure a valid compile_id is associated with every compile
 723       id = CompileBroker::assign_compile_id_unlocked(thread, method, entry_bci);
 724       jvmci_env()->set_HotSpotCompiledNmethod_id(compiled_code, id);
 725     }
 726     if (!jvmci_env()->isa_HotSpotNmethod(installed_code)) {
 727       JVMCI_THROW_MSG_(IllegalArgumentException, "InstalledCode object must be a HotSpotNmethod when installing a HotSpotCompiledNmethod", JVMCI::ok);
 728     }
 729 
 730     JVMCIObject mirror = installed_code;
 731     nmethod* nm = NULL; // nm is an out parameter of register_method
 732     result = runtime()->register_method(jvmci_env(),
 733                                         method,
 734                                         nm,
 735                                         entry_bci,
 736                                         &_offsets,
 737                                         _orig_pc_offset,
 738                                         &buffer,
 739                                         stack_slots,
 740                                         _debug_recorder->_oopmaps,
 741                                         &_exception_handler_table,
 742                                         &_implicit_exception_table,
 743                                         compiler,
 744                                         _debug_recorder,
 745                                         _dependencies,
 746                                         id,
 747                                         _has_monitors,
 748                                         has_unsafe_access,
 749                                         _has_wide_vector,
 750                                         compiled_code,
 751                                         mirror,
 752                                         failed_speculations,
 753                                         speculations,
 754                                         speculations_len);
 755     if (result == JVMCI::ok) {
 756       cb = nm;
 757       if (compile_state == NULL) {
 758         // This compile didn't come through the CompileBroker so perform the printing here
 759         DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, compiler);
 760         nm->maybe_print_nmethod(directive);
 761         DirectivesStack::release(directive);
 762       }
 763     }
 764   }
 765 
 766   if (cb != NULL) {
 767     // Make sure the pre-calculated constants section size was correct.
 768     guarantee((cb->code_begin() - cb->content_begin()) >= _constants_size, "%d < %d", (int)(cb->code_begin() - cb->content_begin()), _constants_size);
 769   }
 770   return result;
 771 }
 772 
 773 void CodeInstaller::initialize_fields(HotSpotCompiledCodeStream* stream, u1 code_flags, methodHandle& method, CodeBuffer& buffer, JVMCI_TRAPS) {
 774   if (!method.is_null()) {
 775     _parameter_count = method->size_of_parameters();
 776     JVMCI_event_2("installing code for %s", method->name_and_sig_as_C_string());
 777   } else {
 778     // Must be a HotSpotCompiledCode for a stub.
 779     // Only used in OopMap constructor for non-product builds
 780     _parameter_count = 0;
 781   }
 782   _sites_count = stream->read_s4("sites:length");
 783   _code_size = stream->read_s4("targetCodeSize");
 784   _total_frame_size = stream->read_s4("totalFrameSize");
 785   if (!is_set(code_flags, HCC_HAS_DEOPT_RESCUE_SLOT)) {
 786     _orig_pc_offset = -1;
 787   } else {
 788     _orig_pc_offset = stream->read_s2("offset");
 789     if (stream->read_bool("addRawFrameSize")) {
 790       _orig_pc_offset += _total_frame_size;
 791     }
 792     if (_orig_pc_offset < 0) {
 793       JVMCI_ERROR("invalid deopt rescue slot: %d%s", _orig_pc_offset, stream->context());
 794     }
 795   }
 796 
 797   // Pre-calculate the constants section size.  This is required for PC-relative addressing.
 798   u4 data_section_size = stream->read_u4("dataSectionSize");
 799   u1 data_section_alignment = stream->read_u1("dataSectionAlignment");
 800   buffer.set_const_section_alignment(data_section_alignment);
 801   if ((_constants->alignment() % data_section_alignment) != 0) {
 802     JVMCI_ERROR("invalid data section alignment: %d [constants alignment: %d]%s",
 803         data_section_alignment, _constants->alignment(), stream->context());
 804   }
 805   _constants_size = data_section_size;
 806   _next_call_type = INVOKE_INVALID;
 807   _has_wide_vector = false;
 808 }
 809 
 810 u1 CodeInstaller::as_read_oop_tag(HotSpotCompiledCodeStream* stream, u1 patch_object_tag, JVMCI_TRAPS) {
 811   switch (patch_object_tag) {
 812     case PATCH_OBJECT_ID:
 813     case PATCH_NARROW_OBJECT_ID: {
 814       return OBJECT_ID;
 815     }
 816     case PATCH_OBJECT_ID2:
 817     case PATCH_NARROW_OBJECT_ID2: {
 818       return OBJECT_ID2;
 819     }
 820     case PATCH_NARROW_JOBJECT:
 821     case PATCH_JOBJECT: {
 822       return JOBJECT;
 823     }
 824     default: {
 825       JVMCI_ERROR_0("unknown object patch tag: %d%s", patch_object_tag, stream->context());
 826     }
 827   }
 828 }
 829 
 830 int CodeInstaller::estimate_stubs_size(HotSpotCompiledCodeStream* stream, JVMCI_TRAPS) {
 831   // Estimate the number of static call stubs that might be emitted.
 832   u2 static_call_stubs = stream->read_u2("numStaticCallStubs");
 833   u2 trampoline_stubs = stream->read_u2("numTrampolineStubs");
 834   int size = static_call_stubs * CompiledStaticCall::to_interp_stub_size();
 835   size += trampoline_stubs * CompiledStaticCall::to_trampoline_stub_size();
 836   return size;
 837 }
 838 
 839 // perform data and call relocation on the CodeBuffer
 840 JVMCI::CodeInstallResult CodeInstaller::initialize_buffer(JVMCIObject compiled_code, CodeBuffer& buffer, HotSpotCompiledCodeStream* stream, u1 code_flags, JVMCI_TRAPS) {
 841   JavaThread* thread = stream->thread();
 842   HandleMark hm(thread);
 843   int locs_buffer_size = _sites_count * (relocInfo::length_limit + sizeof(relocInfo));
 844 
 845 
 846   // Allocate enough space in the stub section for the static call
 847   // stubs.  Stubs have extra relocs but they are managed by the stub
 848   // section itself so they don't need to be accounted for in the
 849   // locs_buffer above.
 850   int stubs_size = estimate_stubs_size(stream, JVMCI_CHECK_OK);
 851 
 852   assert((CodeBuffer::SECT_INSTS == CodeBuffer::SECT_STUBS - 1) &&
 853          (CodeBuffer::SECT_CONSTS == CodeBuffer::SECT_INSTS - 1), "sections order: consts, insts, stubs");
 854   // buffer content: [constants + code_align] + [code + stubs_align] + [stubs]
 855   int total_size = align_up(_constants_size, buffer.insts()->alignment()) +
 856                    align_up(_code_size, buffer.stubs()->alignment()) +
 857                    stubs_size;
 858 
 859   if (total_size > JVMCINMethodSizeLimit) {
 860     return JVMCI::code_too_large;
 861   }
 862 
 863   buffer.initialize(total_size, locs_buffer_size);
 864   if (buffer.blob() == NULL) {
 865     return JVMCI::cache_full;
 866   }
 867   buffer.initialize_stubs_size(stubs_size);
 868   buffer.initialize_consts_size(_constants_size);
 869 
 870   _debug_recorder = new DebugInformationRecorder(_oop_recorder);
 871   _debug_recorder->set_oopmaps(new OopMapSet());
 872 
 873   buffer.initialize_oop_recorder(_oop_recorder);
 874 
 875   // copy the constant data into the newly created CodeBuffer
 876   address end_data = _constants->start() + _constants_size;
 877   JVMCIObject data_section = jvmci_env()->get_HotSpotCompiledCode_dataSection(compiled_code);
 878   JVMCIENV->copy_bytes_to(data_section, (jbyte*) _constants->start(), 0, _constants_size);
 879   _constants->set_end(end_data);
 880 
 881   // copy the code into the newly created CodeBuffer
 882   address end_pc = _instructions->start() + _code_size;
 883   guarantee(_instructions->allocates2(end_pc), "initialize should have reserved enough space for all the code");
 884 
 885   JVMCIPrimitiveArray code = jvmci_env()->get_HotSpotCompiledCode_targetCode(compiled_code);
 886   JVMCIENV->copy_bytes_to(code, (jbyte*) _instructions->start(), 0, _code_size);
 887   _instructions->set_end(end_pc);
 888 
 889 
 890   u2 length = stream->read_u2("dataSectionPatches:length");
 891   for (int i = 0; i < length; i++) {
 892     address dest = _constants->start() + stream->read_u4("patch:pcOffset");
 893     u1 tag = stream->read_u1("tag");
 894 
 895     switch (tag) {
 896       case PATCH_METHOD:
 897       case PATCH_KLASS: {
 898         *((void**) dest) = record_metadata_reference(_constants, dest, stream, tag, JVMCI_CHECK_OK);
 899         break;
 900       }
 901       case PATCH_NARROW_KLASS: {
 902 #ifdef _LP64
 903         *((narrowKlass*) dest) = record_narrow_metadata_reference(_constants, dest, stream, tag, JVMCI_CHECK_OK);
 904 #else
 905         JVMCI_ERROR_OK("unexpected compressed Klass* in 32-bit mode");
 906 #endif
 907         break;
 908       }
 909       case PATCH_OBJECT_ID:
 910       case PATCH_OBJECT_ID2:
 911       case PATCH_NARROW_OBJECT_ID:
 912       case PATCH_NARROW_OBJECT_ID2:
 913       case PATCH_JOBJECT:
 914       case PATCH_NARROW_JOBJECT: {
 915         bool narrow = tag == PATCH_NARROW_OBJECT_ID || tag == PATCH_NARROW_OBJECT_ID2  || tag == PATCH_NARROW_JOBJECT;
 916         u1 read_tag = as_read_oop_tag(stream, tag, JVMCI_CHECK_OK);
 917         record_oop_patch(stream, dest, read_tag, narrow, JVMCI_CHECK_OK);
 918         break;
 919       }
 920       default: {
 921         JVMCI_ERROR_OK("invalid constant tag: %d%s", tag, stream->context());
 922         break;
 923       }
 924     }
 925   }
 926 
 927   jint last_pc_offset = -1;
 928   for (int i = 0; i < _sites_count; i++) {
 929     u4 pc_offset = stream->read_s4("site:pcOffset");
 930     u1 tag = stream->read_u1("tag");
 931     switch (tag) {
 932       case SITE_FOREIGN_CALL:
 933       case SITE_FOREIGN_CALL_NO_DEBUG_INFO:
 934       case SITE_CALL: {
 935         site_Call(buffer, tag, pc_offset, stream, JVMCI_CHECK_OK);
 936         break;
 937       }
 938       case SITE_SAFEPOINT:
 939       case SITE_IMPLICIT_EXCEPTION:
 940       case SITE_IMPLICIT_EXCEPTION_DISPATCH: {
 941         site_Safepoint(buffer, pc_offset, stream, tag, JVMCI_CHECK_OK);
 942         break;
 943       }
 944       case SITE_INFOPOINT: {
 945         site_Infopoint(buffer, pc_offset, stream, JVMCI_CHECK_OK);
 946         break;
 947       }
 948       case SITE_MARK: {
 949         site_Mark(buffer, pc_offset, stream, JVMCI_CHECK_OK);
 950         break;
 951       }
 952       case SITE_DATA_PATCH: {
 953         site_DataPatch(buffer, pc_offset, stream, JVMCI_CHECK_OK);
 954         break;
 955       }
 956       case SITE_EXCEPTION_HANDLER: {
 957         site_ExceptionHandler(pc_offset, stream);
 958         break;
 959       }
 960       default: {
 961         JVMCI_ERROR_OK("unexpected site tag at " INTPTR_FORMAT ": %d", p2i(stream->pos() - 1), tag);
 962       }
 963     }
 964 
 965     last_pc_offset = pc_offset;
 966 
 967     if ((i % 32 == 0) && SafepointMechanism::should_process(thread)) {
 968       // Force a safepoint to mitigate pause time installing large code
 969       ThreadToNativeFromVM ttnfv(thread);
 970     }
 971   }
 972 
 973   if (is_set(code_flags, HCC_HAS_COMMENTS)) {
 974     u2 length = stream->read_u2("comments:length");
 975     for (int i = 0; i < length; i++) {
 976       u4 pc_offset = stream->read_u4("comment:pcOffset");
 977       const char* text = stream->read_utf8("comment:text", JVMCI_CHECK_OK);
 978 #ifndef PRODUCT
 979       buffer.block_comment(pc_offset, text);
 980 #endif
 981     }
 982   }
 983   if (_has_auto_box) {
 984     JavaThread* THREAD = thread; // For exception macros.
 985     JVMCI::ensure_box_caches_initialized(CHECK_(JVMCI::ok));
 986   }
 987   return JVMCI::ok;
 988 }
 989 
 990 void CodeInstaller::record_oop_patch(HotSpotCompiledCodeStream* stream, address dest, u1 read_tag, bool narrow, JVMCI_TRAPS) {
 991   Handle obj = read_oop(stream, read_tag, JVMCI_CHECK);
 992   jobject value = JNIHandles::make_local(obj());
 993   int oop_index = _oop_recorder->find_index(value);
 994   if (narrow) {
 995 #ifdef _LP64
 996     _constants->relocate(dest, oop_Relocation::spec(oop_index), relocInfo::narrow_oop_in_const);
 997 #else
 998     JVMCI_ERROR("unexpected compressed oop in 32-bit mode");
 999 #endif
1000   } else {
1001     _constants->relocate(dest, oop_Relocation::spec(oop_index));
1002   }
1003 }
1004 
1005 void CodeInstaller::site_ExceptionHandler(jint pc_offset, HotSpotCompiledCodeStream* stream) {
1006   u4 handler_offset = stream->read_u4("site:handlerPos");
1007 
1008   // Subtable header
1009   _exception_handler_table.add_entry(HandlerTableEntry(1, pc_offset, 0));
1010 
1011   // Subtable entry
1012   _exception_handler_table.add_entry(HandlerTableEntry(-1, handler_offset, 0));
1013 }
1014 
1015 void CodeInstaller::read_virtual_objects(HotSpotCompiledCodeStream* stream, JVMCI_TRAPS) {
1016   u2 length = stream->read_u2("virtualObjects:length");
1017   if (length == 0) {
1018     return;
1019   }
1020   GrowableArray<ScopeValue*> *objects = new GrowableArray<ScopeValue*>(length, length, NULL);
1021   stream->set_virtual_objects(objects);
1022   // Create the unique ObjectValues
1023   JavaThread* thread = stream->thread();
1024   for (int id = 0; id < length; id++) {
1025     Klass* klass = stream->read_klass("type");
1026     bool is_auto_box = stream->read_bool("isAutoBox");
1027     if (is_auto_box) {
1028       _has_auto_box = true;
1029     }
1030     oop javaMirror = klass->java_mirror();
1031     ScopeValue *klass_sv = new ConstantOopWriteValue(JNIHandles::make_local(javaMirror));
1032     ObjectValue* sv = is_auto_box ? new AutoBoxObjectValue(id, klass_sv) : new ObjectValue(id, klass_sv);
1033     objects->at_put(id, sv);
1034   }
1035   // All the values which could be referenced by the VirtualObjects
1036   // exist, so now describe all the VirtualObjects themselves.
1037   for (int id = 0; id < length; id++) {
1038     record_object_value(objects->at(id)->as_ObjectValue(), stream, JVMCI_CHECK);
1039   }
1040   _debug_recorder->dump_object_pool(objects);
1041 
1042   stream->set_virtual_objects(objects);
1043 }
1044 
1045 int CodeInstaller::map_jvmci_bci(int bci) {
1046   if (bci < 0) {
1047     switch (bci) {
1048       case BEFORE_BCI: return BeforeBci;
1049       case AFTER_BCI: return AfterBci;
1050       case UNWIND_BCI: return UnwindBci;
1051       case AFTER_EXCEPTION_BCI: return AfterExceptionBci;
1052       case UNKNOWN_BCI: return UnknownBci;
1053       case INVALID_FRAMESTATE_BCI: return InvalidFrameStateBci;
1054     }
1055     ShouldNotReachHere();
1056   }
1057   return bci;
1058 }
1059 
1060 void CodeInstaller::record_scope(jint pc_offset, HotSpotCompiledCodeStream* stream, u1 debug_info_flags, bool full_info, bool is_mh_invoke, bool return_oop, JVMCI_TRAPS) {
1061   if (full_info) {
1062     read_virtual_objects(stream, JVMCI_CHECK);
1063   }
1064   if (is_set(debug_info_flags, DI_HAS_FRAMES)) {
1065     u2 depth = stream->read_u2("depth");
1066     for (int i = 0; i < depth; i++) {
1067       Thread* thread = Thread::current();
1068       methodHandle method(thread, stream->read_method("method"));
1069       jint bci = map_jvmci_bci(stream->read_s4("bci"));
1070       if (bci == BEFORE_BCI) {
1071         bci = SynchronizationEntryBCI;
1072       }
1073 
1074       JVMCI_event_2("Recording scope pc_offset=%d bci=%d method=%s", pc_offset, bci, method->name_and_sig_as_C_string());
1075 
1076       bool reexecute = false;
1077       bool rethrow_exception = false;
1078 
1079       DebugToken* locals_token = NULL;
1080       DebugToken* stack_token = NULL;
1081       DebugToken* monitors_token = NULL;
1082 
1083       if (full_info) {
1084         u1 frame_flags = stream->read_u1("flags");
1085         rethrow_exception = is_set(frame_flags, DIF_RETHROW_EXCEPTION);
1086 
1087         if (bci >= 0) {
1088           reexecute = !is_set(frame_flags, DIF_DURING_CALL);
1089         }
1090 
1091         GrowableArray<ScopeValue*>* locals = read_local_or_stack_values(stream, frame_flags, true, JVMCI_CHECK);
1092         GrowableArray<ScopeValue*>* stack = read_local_or_stack_values(stream, frame_flags, false, JVMCI_CHECK);
1093         GrowableArray<MonitorValue*>* monitors = read_monitor_values(stream, frame_flags, JVMCI_CHECK);
1094 
1095         locals_token = _debug_recorder->create_scope_values(locals);
1096         stack_token = _debug_recorder->create_scope_values(stack);
1097         monitors_token = _debug_recorder->create_monitor_values(monitors);
1098       }
1099 
1100       // has_ea_local_in_scope and arg_escape should be added to JVMCI
1101       const bool return_scalarized     = false;
1102       const bool has_ea_local_in_scope = false;
1103       const bool arg_escape            = false;
1104       _debug_recorder->describe_scope(pc_offset, method, NULL, bci, reexecute, rethrow_exception, is_mh_invoke, return_oop,
1105                                       return_scalarized, has_ea_local_in_scope, arg_escape,
1106                                       locals_token, stack_token, monitors_token);
1107     }
1108   }
1109   if (full_info) {
1110     // Clear the virtual objects as they are specific to one DebugInfo
1111     stream->set_virtual_objects(nullptr);
1112   }
1113 }
1114 
1115 void CodeInstaller::site_Safepoint(CodeBuffer& buffer, jint pc_offset, HotSpotCompiledCodeStream* stream, u1 tag, JVMCI_TRAPS) {
1116   u1 flags = stream->read_u1("debugInfo:flags");
1117   OopMap *map = create_oop_map(stream, flags, JVMCI_CHECK);
1118   _debug_recorder->add_safepoint(pc_offset, map);
1119   record_scope(pc_offset, stream, flags, true, JVMCI_CHECK);
1120   _debug_recorder->end_safepoint(pc_offset);
1121   if (_orig_pc_offset < 0) {
1122     JVMCI_ERROR("method contains safepoint, but has no deopt rescue slot");
1123   }
1124   if (tag == SITE_IMPLICIT_EXCEPTION_DISPATCH) {
1125     jint dispatch_offset = stream->read_s4("dispatchOffset");
1126     _implicit_exception_table.append(pc_offset, dispatch_offset);
1127   } else if (tag == SITE_IMPLICIT_EXCEPTION) {
1128     _implicit_exception_table.add_deoptimize(pc_offset);
1129   }
1130 }
1131 
1132 void CodeInstaller::site_Infopoint(CodeBuffer& buffer, jint pc_offset, HotSpotCompiledCodeStream* stream, JVMCI_TRAPS) {
1133   u1 flags = stream->read_u1("debugInfo:flags");
1134   _debug_recorder->add_non_safepoint(pc_offset);
1135   record_scope(pc_offset, stream, flags, false, JVMCI_CHECK);
1136   _debug_recorder->end_non_safepoint(pc_offset);
1137 }
1138 
1139 void CodeInstaller::site_Call(CodeBuffer& buffer, u1 tag, jint pc_offset, HotSpotCompiledCodeStream* stream, JVMCI_TRAPS) {
1140   JavaThread* thread = stream->thread();
1141   jlong target = stream->read_u8("target");
1142   methodHandle method;
1143   bool direct_call = false;
1144   if (tag == SITE_CALL) {
1145     method = methodHandle(thread, (Method*) target);
1146     assert(Method::is_valid_method(method()), "invalid method");
1147     direct_call = stream->read_bool("direct");
1148     if (method.is_null()) {
1149       JVMCI_THROW(NullPointerException);
1150     }
1151   }
1152 
1153   NativeInstruction* inst = nativeInstruction_at(_instructions->start() + pc_offset);
1154   jint next_pc_offset = CodeInstaller::pd_next_offset(inst, pc_offset, JVMCI_CHECK);
1155 
1156   if (tag != SITE_FOREIGN_CALL_NO_DEBUG_INFO) {
1157     u1 flags = stream->read_u1("debugInfo:flags");
1158     OopMap *map = create_oop_map(stream, flags, JVMCI_CHECK);
1159     _debug_recorder->add_safepoint(next_pc_offset, map);
1160 
1161     if (!method.is_null()) {
1162       vmIntrinsics::ID iid = method->intrinsic_id();
1163       bool is_mh_invoke = false;
1164       if (direct_call) {
1165         is_mh_invoke = !method->is_static() && (iid == vmIntrinsics::_compiledLambdaForm ||
1166                 (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::is_signature_polymorphic_intrinsic(iid)));
1167       }
1168       bool return_oop = method->is_returning_oop();
1169       record_scope(next_pc_offset, stream, flags, true, is_mh_invoke, return_oop, JVMCI_CHECK);
1170     } else {
1171       record_scope(next_pc_offset, stream, flags, true, JVMCI_CHECK);
1172     }
1173   }
1174 
1175   if (tag != SITE_CALL) {
1176     jlong foreign_call_destination = target;
1177     CodeInstaller::pd_relocate_ForeignCall(inst, foreign_call_destination, JVMCI_CHECK);
1178   } else {
1179     CodeInstaller::pd_relocate_JavaMethod(buffer, method, pc_offset, JVMCI_CHECK);
1180     if (_next_call_type == INVOKESTATIC || _next_call_type == INVOKESPECIAL) {
1181       // Need a static call stub for transitions from compiled to interpreted.
1182       CompiledStaticCall::emit_to_interp_stub(buffer, _instructions->start() + pc_offset);
1183     }
1184   }
1185 
1186   _next_call_type = INVOKE_INVALID;
1187 
1188   if (tag != SITE_FOREIGN_CALL_NO_DEBUG_INFO) {
1189     _debug_recorder->end_safepoint(next_pc_offset);
1190   }
1191 }
1192 
1193 void CodeInstaller::site_DataPatch(CodeBuffer& buffer, jint pc_offset, HotSpotCompiledCodeStream* stream, JVMCI_TRAPS) {
1194   u1 tag = stream->read_u1("tag");
1195   switch (tag) {
1196     case PATCH_OBJECT_ID:
1197     case PATCH_OBJECT_ID2:
1198     case PATCH_NARROW_OBJECT_ID:
1199     case PATCH_NARROW_OBJECT_ID2:
1200     case PATCH_JOBJECT:
1201     case PATCH_NARROW_JOBJECT: {
1202       bool narrow = tag == PATCH_NARROW_OBJECT_ID || tag == PATCH_NARROW_OBJECT_ID2  || tag == PATCH_NARROW_JOBJECT;
1203       u1 read_tag = as_read_oop_tag(stream, tag, JVMCI_CHECK);
1204       Handle obj = read_oop(stream, read_tag, JVMCI_CHECK);
1205       pd_patch_OopConstant(pc_offset, obj, narrow, JVMCI_CHECK);
1206       break;
1207     }
1208     case PATCH_METHOD:
1209     case PATCH_KLASS:
1210     case PATCH_NARROW_KLASS: {
1211       pd_patch_MetaspaceConstant(pc_offset, stream, tag, JVMCI_CHECK);
1212       break;
1213     }
1214     case PATCH_DATA_SECTION_REFERENCE: {
1215       int data_offset = stream->read_u4("data:offset");
1216       if (0 <= data_offset && data_offset < _constants_size) {
1217         if (!is_aligned(data_offset, CompilerToVM::Data::get_data_section_item_alignment())) {
1218           JVMCI_ERROR("data offset 0x%x is not %d-byte aligned%s", data_offset, relocInfo::addr_unit(), stream->context());
1219         }
1220         pd_patch_DataSectionReference(pc_offset, data_offset, JVMCI_CHECK);
1221       } else {
1222         JVMCI_ERROR("data offset 0x%x points outside data section (size 0x%x)%s", data_offset, _constants_size, stream->context());
1223       }
1224       break;
1225     }
1226     default: {
1227       JVMCI_ERROR("unknown data patch tag: %d%s", tag, stream->context());
1228     }
1229   }
1230 }
1231 
1232 void CodeInstaller::site_Mark(CodeBuffer& buffer, jint pc_offset, HotSpotCompiledCodeStream* stream, JVMCI_TRAPS) {
1233   u1 id = stream->read_u1("mark:id");
1234   address pc = _instructions->start() + pc_offset;
1235 
1236   switch (id) {
1237     case UNVERIFIED_ENTRY:
1238       _offsets.set_value(CodeOffsets::Entry, pc_offset);
1239       break;
1240     case VERIFIED_ENTRY:
1241       _offsets.set_value(CodeOffsets::Verified_Entry, pc_offset);
1242       _offsets.set_value(CodeOffsets::Verified_Inline_Entry, pc_offset);
1243       _offsets.set_value(CodeOffsets::Verified_Inline_Entry_RO, pc_offset);
1244       break;
1245     case OSR_ENTRY:
1246       _offsets.set_value(CodeOffsets::OSR_Entry, pc_offset);
1247       break;
1248     case EXCEPTION_HANDLER_ENTRY:
1249       _offsets.set_value(CodeOffsets::Exceptions, pc_offset);
1250       break;
1251     case DEOPT_HANDLER_ENTRY:
1252       _offsets.set_value(CodeOffsets::Deopt, pc_offset);
1253       break;
1254     case DEOPT_MH_HANDLER_ENTRY:
1255       _offsets.set_value(CodeOffsets::DeoptMH, pc_offset);
1256       break;
1257     case FRAME_COMPLETE:
1258       _offsets.set_value(CodeOffsets::Frame_Complete, pc_offset);
1259       break;
1260     case INVOKEVIRTUAL:
1261     case INVOKEINTERFACE:
1262     case INLINE_INVOKE:
1263     case INVOKESTATIC:
1264     case INVOKESPECIAL:
1265       _next_call_type = (MarkId) id;
1266       _invoke_mark_pc = pc;
1267       break;
1268     case POLL_NEAR:
1269     case POLL_FAR:
1270     case POLL_RETURN_NEAR:
1271     case POLL_RETURN_FAR:
1272       pd_relocate_poll(pc, id, JVMCI_CHECK);
1273       break;
1274     case CARD_TABLE_SHIFT:
1275     case CARD_TABLE_ADDRESS:
1276     case HEAP_TOP_ADDRESS:
1277     case HEAP_END_ADDRESS:
1278     case NARROW_KLASS_BASE_ADDRESS:
1279     case NARROW_OOP_BASE_ADDRESS:
1280     case CRC_TABLE_ADDRESS:
1281     case LOG_OF_HEAP_REGION_GRAIN_BYTES:
1282     case INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED:
1283     case VERIFY_OOPS:
1284     case VERIFY_OOP_BITS:
1285     case VERIFY_OOP_MASK:
1286     case VERIFY_OOP_COUNT_ADDRESS:
1287       break;
1288     default:
1289       JVMCI_ERROR("invalid mark id: %d%s", id, stream->context());
1290       break;
1291   }
1292 }