1 /*
   2  * Copyright (c) 2011, 2018, 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 "asm/register.hpp"
  26 #include "classfile/vmSymbols.hpp"
  27 #include "code/compiledIC.hpp"
  28 #include "code/vmreg.inline.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/disassembler.hpp"
  31 #include "jvmci/jvmciEnv.hpp"
  32 #include "jvmci/jvmciCompiler.hpp"
  33 #include "jvmci/jvmciCodeInstaller.hpp"
  34 #include "jvmci/jvmciJavaClasses.hpp"
  35 #include "jvmci/jvmciCompilerToVM.hpp"
  36 #include "jvmci/jvmciRuntime.hpp"
  37 #include "memory/allocation.inline.hpp"
  38 #include "oops/arrayOop.inline.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "oops/objArrayOop.inline.hpp"
  41 #include "oops/typeArrayOop.inline.hpp"
  42 #include "runtime/interfaceSupport.inline.hpp"
  43 #include "runtime/javaCalls.hpp"
  44 #include "runtime/jniHandles.inline.hpp"
  45 #include "runtime/safepointMechanism.inline.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "utilities/align.hpp"
  48 
  49 // frequently used constants
  50 // Allocate them with new so they are never destroyed (otherwise, a
  51 // forced exit could destroy these objects while they are still in
  52 // use).
  53 ConstantOopWriteValue* CodeInstaller::_oop_null_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantOopWriteValue(NULL);
  54 ConstantIntValue*      CodeInstaller::_int_m1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(-1);
  55 ConstantIntValue*      CodeInstaller::_int_0_scope_value =  new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue((jint)0);
  56 ConstantIntValue*      CodeInstaller::_int_1_scope_value =  new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(1);
  57 ConstantIntValue*      CodeInstaller::_int_2_scope_value =  new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(2);
  58 LocationValue*         CodeInstaller::_illegal_value = new (ResourceObj::C_HEAP, mtCompiler) LocationValue(Location());
  59 
  60 Method* getMethodFromHotSpotMethod(oop hotspot_method) {
  61   assert(hotspot_method != NULL && hotspot_method->is_a(HotSpotResolvedJavaMethodImpl::klass()), "sanity");
  62   return CompilerToVM::asMethod(hotspot_method);
  63 }
  64 
  65 VMReg getVMRegFromLocation(Handle location, int total_frame_size, TRAPS) {
  66   if (location.is_null()) {
  67     THROW_NULL(vmSymbols::java_lang_NullPointerException());
  68   }
  69 
  70   Handle reg(THREAD, code_Location::reg(location));
  71   jint offset = code_Location::offset(location);
  72 
  73   if (reg.not_null()) {
  74     // register
  75     jint number = code_Register::number(reg);
  76     VMReg vmReg = CodeInstaller::get_hotspot_reg(number, CHECK_NULL);
  77     if (offset % 4 == 0) {
  78       return vmReg->next(offset / 4);
  79     } else {
  80       JVMCI_ERROR_NULL("unaligned subregister offset %d in oop map", offset);
  81     }
  82   } else {
  83     // stack slot
  84     if (offset % 4 == 0) {
  85       VMReg vmReg = VMRegImpl::stack2reg(offset / 4);
  86       if (!OopMapValue::legal_vm_reg_name(vmReg)) {
  87         // This restriction only applies to VMRegs that are used in OopMap but
  88         // since that's the only use of VMRegs it's simplest to put this test
  89         // here.  This test should also be equivalent legal_vm_reg_name but JVMCI
  90         // clients can use max_oop_map_stack_stack_offset to detect this problem
  91         // directly.  The asserts just ensure that the tests are in agreement.
  92         assert(offset > CompilerToVM::Data::max_oop_map_stack_offset(), "illegal VMReg");
  93         JVMCI_ERROR_NULL("stack offset %d is too large to be encoded in OopMap (max %d)",
  94                          offset, CompilerToVM::Data::max_oop_map_stack_offset());
  95       }
  96       assert(OopMapValue::legal_vm_reg_name(vmReg), "illegal VMReg");
  97       return vmReg;
  98     } else {
  99       JVMCI_ERROR_NULL("unaligned stack offset %d in oop map", offset);
 100     }
 101   }
 102 }
 103 
 104 objArrayOop CodeInstaller::sites() {
 105   return (objArrayOop) JNIHandles::resolve(_sites_handle);
 106 }
 107 
 108 arrayOop CodeInstaller::code() {
 109   return (arrayOop) JNIHandles::resolve(_code_handle);
 110 }
 111 
 112 arrayOop CodeInstaller::data_section() {
 113   return (arrayOop) JNIHandles::resolve(_data_section_handle);
 114 }
 115 
 116 objArrayOop CodeInstaller::data_section_patches() {
 117   return (objArrayOop) JNIHandles::resolve(_data_section_patches_handle);
 118 }
 119 
 120 #ifndef PRODUCT
 121 objArrayOop CodeInstaller::comments() {
 122   return (objArrayOop) JNIHandles::resolve(_comments_handle);
 123 }
 124 #endif
 125 
 126 oop CodeInstaller::word_kind() {
 127   return JNIHandles::resolve(_word_kind_handle);
 128 }
 129 
 130 // creates a HotSpot oop map out of the byte arrays provided by DebugInfo
 131 OopMap* CodeInstaller::create_oop_map(Handle debug_info, TRAPS) {
 132   Handle reference_map(THREAD, DebugInfo::referenceMap(debug_info));
 133   if (reference_map.is_null()) {
 134     THROW_NULL(vmSymbols::java_lang_NullPointerException());
 135   }
 136   if (!reference_map->is_a(HotSpotReferenceMap::klass())) {
 137     JVMCI_ERROR_NULL("unknown reference map: %s", reference_map->klass()->signature_name());
 138   }
 139   if (!_has_wide_vector && SharedRuntime::is_wide_vector(HotSpotReferenceMap::maxRegisterSize(reference_map))) {
 140     if (SharedRuntime::polling_page_vectors_safepoint_handler_blob() == NULL) {
 141       JVMCI_ERROR_NULL("JVMCI is producing code using vectors larger than the runtime supports");
 142     }
 143     _has_wide_vector = true;
 144   }
 145   OopMap* map = new OopMap(_total_frame_size, _parameter_count);
 146   objArrayHandle objects(THREAD, HotSpotReferenceMap::objects(reference_map));
 147   objArrayHandle derivedBase(THREAD, HotSpotReferenceMap::derivedBase(reference_map));
 148   typeArrayHandle sizeInBytes(THREAD, HotSpotReferenceMap::sizeInBytes(reference_map));
 149   if (objects.is_null() || derivedBase.is_null() || sizeInBytes.is_null()) {
 150     THROW_NULL(vmSymbols::java_lang_NullPointerException());
 151   }
 152   if (objects->length() != derivedBase->length() || objects->length() != sizeInBytes->length()) {
 153     JVMCI_ERROR_NULL("arrays in reference map have different sizes: %d %d %d", objects->length(), derivedBase->length(), sizeInBytes->length());
 154   }
 155   for (int i = 0; i < objects->length(); i++) {
 156     Handle location(THREAD, objects->obj_at(i));
 157     Handle baseLocation(THREAD, derivedBase->obj_at(i));
 158     int bytes = sizeInBytes->int_at(i);
 159 
 160     VMReg vmReg = getVMRegFromLocation(location, _total_frame_size, CHECK_NULL);
 161     if (baseLocation.not_null()) {
 162       // derived oop
 163 #ifdef _LP64
 164       if (bytes == 8) {
 165 #else
 166       if (bytes == 4) {
 167 #endif
 168         VMReg baseReg = getVMRegFromLocation(baseLocation, _total_frame_size, CHECK_NULL);
 169         map->set_derived_oop(vmReg, baseReg);
 170       } else {
 171         JVMCI_ERROR_NULL("invalid derived oop size in ReferenceMap: %d", bytes);
 172       }
 173 #ifdef _LP64
 174     } else if (bytes == 8) {
 175       // wide oop
 176       map->set_oop(vmReg);
 177     } else if (bytes == 4) {
 178       // narrow oop
 179       map->set_narrowoop(vmReg);
 180 #else
 181     } else if (bytes == 4) {
 182       map->set_oop(vmReg);
 183 #endif
 184     } else {
 185       JVMCI_ERROR_NULL("invalid oop size in ReferenceMap: %d", bytes);
 186     }
 187   }
 188 
 189   Handle callee_save_info(THREAD, (oop) DebugInfo::calleeSaveInfo(debug_info));
 190   if (callee_save_info.not_null()) {
 191     objArrayHandle registers(THREAD, RegisterSaveLayout::registers(callee_save_info));
 192     typeArrayHandle slots(THREAD, RegisterSaveLayout::slots(callee_save_info));
 193     for (jint i = 0; i < slots->length(); i++) {
 194       Handle jvmci_reg (THREAD, registers->obj_at(i));
 195       jint jvmci_reg_number = code_Register::number(jvmci_reg);
 196       VMReg hotspot_reg = CodeInstaller::get_hotspot_reg(jvmci_reg_number, CHECK_NULL);
 197       // HotSpot stack slots are 4 bytes
 198       jint jvmci_slot = slots->int_at(i);
 199       jint hotspot_slot = jvmci_slot * VMRegImpl::slots_per_word;
 200       VMReg hotspot_slot_as_reg = VMRegImpl::stack2reg(hotspot_slot);
 201       map->set_callee_saved(hotspot_slot_as_reg, hotspot_reg);
 202 #ifdef _LP64
 203       // (copied from generate_oop_map() in c1_Runtime1_x86.cpp)
 204       VMReg hotspot_slot_hi_as_reg = VMRegImpl::stack2reg(hotspot_slot + 1);
 205       map->set_callee_saved(hotspot_slot_hi_as_reg, hotspot_reg->next());
 206 #endif
 207     }
 208   }
 209   return map;
 210 }
 211 
 212 AOTOopRecorder::AOTOopRecorder(Arena* arena, bool deduplicate) : OopRecorder(arena, deduplicate) {
 213   _meta_refs = new GrowableArray<jobject>();
 214 }
 215 
 216 int AOTOopRecorder::nr_meta_refs() const {
 217   return _meta_refs->length();
 218 }
 219 
 220 jobject AOTOopRecorder::meta_element(int pos) const {
 221   return _meta_refs->at(pos);
 222 }
 223 
 224 int AOTOopRecorder::find_index(Metadata* h) {
 225   JavaThread* THREAD = JavaThread::current();
 226   int oldCount = metadata_count();
 227   int index =  this->OopRecorder::find_index(h);
 228   int newCount = metadata_count();
 229 
 230   if (oldCount == newCount) {
 231     // found a match
 232     return index;
 233   }
 234 
 235   vmassert(index + 1 == newCount, "must be last");
 236 
 237   JVMCIKlassHandle klass(THREAD);
 238   oop result = NULL;
 239   guarantee(h != NULL,
 240             "If DebugInformationRecorder::describe_scope passes NULL oldCount == newCount must hold.");
 241   if (h->is_klass()) {
 242     klass = (Klass*) h;
 243     result = CompilerToVM::get_jvmci_type(klass, CATCH);
 244   } else if (h->is_method()) {
 245     Method* method = (Method*) h;
 246     methodHandle mh(method);
 247     result = CompilerToVM::get_jvmci_method(method, CATCH);
 248   }
 249   jobject ref = JNIHandles::make_local(THREAD, result);
 250   record_meta_ref(ref, index);
 251 
 252   return index;
 253 }
 254 
 255 int AOTOopRecorder::find_index(jobject h) {
 256   if (h == NULL) {
 257     return 0;
 258   }
 259   oop javaMirror = JNIHandles::resolve(h);
 260   Klass* klass = java_lang_Class::as_Klass(javaMirror);
 261   return find_index(klass);
 262 }
 263 
 264 void AOTOopRecorder::record_meta_ref(jobject o, int index) {
 265   assert(index > 0, "must be 1..n");
 266   index -= 1; // reduce by one to convert to array index
 267 
 268   assert(index == _meta_refs->length(), "must be last");
 269   _meta_refs->append(o);
 270 }
 271 
 272 void* CodeInstaller::record_metadata_reference(CodeSection* section, address dest, Handle constant, TRAPS) {
 273   /*
 274    * This method needs to return a raw (untyped) pointer, since the value of a pointer to the base
 275    * class is in general not equal to the pointer of the subclass. When patching metaspace pointers,
 276    * the compiler expects a direct pointer to the subclass (Klass* or Method*), not a pointer to the
 277    * base class (Metadata* or MetaspaceObj*).
 278    */
 279   oop obj = HotSpotMetaspaceConstantImpl::metaspaceObject(constant);
 280   if (obj->is_a(HotSpotResolvedObjectTypeImpl::klass())) {
 281     Klass* klass = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(obj));
 282     assert(!HotSpotMetaspaceConstantImpl::compressed(constant), "unexpected compressed klass pointer %s @ " INTPTR_FORMAT, klass->name()->as_C_string(), p2i(klass));
 283     int index = _oop_recorder->find_index(klass);
 284     section->relocate(dest, metadata_Relocation::spec(index));
 285     TRACE_jvmci_3("metadata[%d of %d] = %s", index, _oop_recorder->metadata_count(), klass->name()->as_C_string());
 286     return klass;
 287   } else if (obj->is_a(HotSpotResolvedJavaMethodImpl::klass())) {
 288     Method* method = (Method*) (address) HotSpotResolvedJavaMethodImpl::metaspaceMethod(obj);
 289     assert(!HotSpotMetaspaceConstantImpl::compressed(constant), "unexpected compressed method pointer %s @ " INTPTR_FORMAT, method->name()->as_C_string(), p2i(method));
 290     int index = _oop_recorder->find_index(method);
 291     section->relocate(dest, metadata_Relocation::spec(index));
 292     TRACE_jvmci_3("metadata[%d of %d] = %s", index, _oop_recorder->metadata_count(), method->name()->as_C_string());
 293     return method;
 294   } else {
 295     JVMCI_ERROR_NULL("unexpected metadata reference for constant of type %s", obj->klass()->signature_name());
 296   }
 297 }
 298 
 299 #ifdef _LP64
 300 narrowKlass CodeInstaller::record_narrow_metadata_reference(CodeSection* section, address dest, Handle constant, TRAPS) {
 301   oop obj = HotSpotMetaspaceConstantImpl::metaspaceObject(constant);
 302   assert(HotSpotMetaspaceConstantImpl::compressed(constant), "unexpected uncompressed pointer");
 303 
 304   if (!obj->is_a(HotSpotResolvedObjectTypeImpl::klass())) {
 305     JVMCI_ERROR_0("unexpected compressed pointer of type %s", obj->klass()->signature_name());
 306   }
 307 
 308   Klass* klass = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(obj));
 309   int index = _oop_recorder->find_index(klass);
 310   section->relocate(dest, metadata_Relocation::spec(index));
 311   TRACE_jvmci_3("narrowKlass[%d of %d] = %s", index, _oop_recorder->metadata_count(), klass->name()->as_C_string());
 312   return Klass::encode_klass(klass);
 313 }
 314 #endif
 315 
 316 Location::Type CodeInstaller::get_oop_type(Thread* thread, Handle value) {
 317   Handle valueKind(thread, Value::valueKind(value));
 318   Handle platformKind(thread, ValueKind::platformKind(valueKind));
 319 
 320   if (platformKind == word_kind()) {
 321     return Location::oop;
 322   } else {
 323     return Location::narrowoop;
 324   }
 325 }
 326 
 327 ScopeValue* CodeInstaller::get_scope_value(Handle value, BasicType type, GrowableArray<ScopeValue*>* objects, ScopeValue* &second, TRAPS) {
 328   second = NULL;
 329   if (value.is_null()) {
 330     THROW_NULL(vmSymbols::java_lang_NullPointerException());
 331   } else if (value == Value::ILLEGAL()) {
 332     if (type != T_ILLEGAL) {
 333       JVMCI_ERROR_NULL("unexpected illegal value, expected %s", basictype_to_str(type));
 334     }
 335     return _illegal_value;
 336   } else if (value->is_a(RegisterValue::klass())) {
 337     Handle reg(THREAD, RegisterValue::reg(value));
 338     jint number = code_Register::number(reg);
 339     VMReg hotspotRegister = get_hotspot_reg(number, CHECK_NULL);
 340     if (is_general_purpose_reg(hotspotRegister)) {
 341       Location::Type locationType;
 342       if (type == T_OBJECT) {
 343         locationType = get_oop_type(THREAD, value);
 344       } else if (type == T_LONG) {
 345         locationType = Location::lng;
 346       } else if (type == T_INT || type == T_FLOAT || type == T_SHORT || type == T_CHAR || type == T_BYTE || type == T_BOOLEAN) {
 347         locationType = Location::int_in_long;
 348       } else {
 349         JVMCI_ERROR_NULL("unexpected type %s in cpu register", basictype_to_str(type));
 350       }
 351       ScopeValue* value = new LocationValue(Location::new_reg_loc(locationType, hotspotRegister));
 352       if (type == T_LONG) {
 353         second = value;
 354       }
 355       return value;
 356     } else {
 357       Location::Type locationType;
 358       if (type == T_FLOAT) {
 359         // this seems weird, but the same value is used in c1_LinearScan
 360         locationType = Location::normal;
 361       } else if (type == T_DOUBLE) {
 362         locationType = Location::dbl;
 363       } else {
 364         JVMCI_ERROR_NULL("unexpected type %s in floating point register", basictype_to_str(type));
 365       }
 366       ScopeValue* value = new LocationValue(Location::new_reg_loc(locationType, hotspotRegister));
 367       if (type == T_DOUBLE) {
 368         second = value;
 369       }
 370       return value;
 371     }
 372   } else if (value->is_a(StackSlot::klass())) {
 373     jint offset = StackSlot::offset(value);
 374     if (StackSlot::addFrameSize(value)) {
 375       offset += _total_frame_size;
 376     }
 377 
 378     Location::Type locationType;
 379     if (type == T_OBJECT) {
 380       locationType = get_oop_type(THREAD, value);
 381     } else if (type == T_LONG) {
 382       locationType = Location::lng;
 383     } else if (type == T_DOUBLE) {
 384       locationType = Location::dbl;
 385     } else if (type == T_INT || type == T_FLOAT || type == T_SHORT || type == T_CHAR || type == T_BYTE || type == T_BOOLEAN) {
 386       locationType = Location::normal;
 387     } else {
 388       JVMCI_ERROR_NULL("unexpected type %s in stack slot", basictype_to_str(type));
 389     }
 390     ScopeValue* value = new LocationValue(Location::new_stk_loc(locationType, offset));
 391     if (type == T_DOUBLE || type == T_LONG) {
 392       second = value;
 393     }
 394     return value;
 395   } else if (value->is_a(JavaConstant::klass())) {
 396     if (value->is_a(PrimitiveConstant::klass())) {
 397       if (value->is_a(RawConstant::klass())) {
 398         jlong prim = PrimitiveConstant::primitive(value);
 399         return new ConstantLongValue(prim);
 400       } else {
 401         Handle primitive_constant_kind(THREAD, PrimitiveConstant::kind(value));
 402         BasicType constantType = JVMCIRuntime::kindToBasicType(primitive_constant_kind, CHECK_NULL);
 403         if (type != constantType) {
 404           JVMCI_ERROR_NULL("primitive constant type doesn't match, expected %s but got %s", basictype_to_str(type), basictype_to_str(constantType));
 405         }
 406         if (type == T_INT || type == T_FLOAT) {
 407           jint prim = (jint)PrimitiveConstant::primitive(value);
 408           switch (prim) {
 409             case -1: return _int_m1_scope_value;
 410             case  0: return _int_0_scope_value;
 411             case  1: return _int_1_scope_value;
 412             case  2: return _int_2_scope_value;
 413             default: return new ConstantIntValue(prim);
 414           }
 415         } else if (type == T_LONG || type == T_DOUBLE) {
 416           jlong prim = PrimitiveConstant::primitive(value);
 417           second = _int_1_scope_value;
 418           return new ConstantLongValue(prim);
 419         } else {
 420           JVMCI_ERROR_NULL("unexpected primitive constant type %s", basictype_to_str(type));
 421         }
 422       }
 423     } else if (value->is_a(NullConstant::klass()) || value->is_a(HotSpotCompressedNullConstant::klass())) {
 424       if (type == T_OBJECT) {
 425         return _oop_null_scope_value;
 426       } else {
 427         JVMCI_ERROR_NULL("unexpected null constant, expected %s", basictype_to_str(type));
 428       }
 429     } else if (value->is_a(HotSpotObjectConstantImpl::klass())) {
 430       if (type == T_OBJECT) {
 431         oop obj = HotSpotObjectConstantImpl::object(value);
 432         if (obj == NULL) {
 433           JVMCI_ERROR_NULL("null value must be in NullConstant");
 434         }
 435         return new ConstantOopWriteValue(JNIHandles::make_local(obj));
 436       } else {
 437         JVMCI_ERROR_NULL("unexpected object constant, expected %s", basictype_to_str(type));
 438       }
 439     }
 440   } else if (value->is_a(VirtualObject::klass())) {
 441     if (type == T_OBJECT) {
 442       int id = VirtualObject::id(value);
 443       if (0 <= id && id < objects->length()) {
 444         ScopeValue* object = objects->at(id);
 445         if (object != NULL) {
 446           return object;
 447         }
 448       }
 449       JVMCI_ERROR_NULL("unknown virtual object id %d", id);
 450     } else {
 451       JVMCI_ERROR_NULL("unexpected virtual object, expected %s", basictype_to_str(type));
 452     }
 453   }
 454 
 455   JVMCI_ERROR_NULL("unexpected value in scope: %s", value->klass()->signature_name())
 456 }
 457 
 458 void CodeInstaller::record_object_value(ObjectValue* sv, Handle value, GrowableArray<ScopeValue*>* objects, TRAPS) {
 459   // Might want a HandleMark here.
 460   Handle type(THREAD, VirtualObject::type(value));
 461   int id = VirtualObject::id(value);
 462   oop javaMirror = HotSpotResolvedObjectTypeImpl::javaClass(type);
 463   Klass* klass = java_lang_Class::as_Klass(javaMirror);
 464   bool isLongArray = klass == Universe::longArrayKlassObj();
 465 
 466   objArrayHandle values(THREAD, VirtualObject::values(value));
 467   objArrayHandle slotKinds(THREAD, VirtualObject::slotKinds(value));
 468   for (jint i = 0; i < values->length(); i++) {
 469     HandleMark hm(THREAD);
 470     ScopeValue* cur_second = NULL;
 471     Handle object(THREAD, values->obj_at(i));
 472     Handle slot_kind (THREAD, slotKinds->obj_at(i));
 473     BasicType type = JVMCIRuntime::kindToBasicType(slot_kind, CHECK);
 474     ScopeValue* value = get_scope_value(object, type, objects, cur_second, CHECK);
 475 
 476     if (isLongArray && cur_second == NULL) {
 477       // we're trying to put ints into a long array... this isn't really valid, but it's used for some optimizations.
 478       // add an int 0 constant
 479       cur_second = _int_0_scope_value;
 480     }
 481 
 482     if (cur_second != NULL) {
 483       sv->field_values()->append(cur_second);
 484     }
 485     assert(value != NULL, "missing value");
 486     sv->field_values()->append(value);
 487   }
 488 }
 489 
 490 MonitorValue* CodeInstaller::get_monitor_value(Handle value, GrowableArray<ScopeValue*>* objects, TRAPS) {
 491   if (value.is_null()) {
 492     THROW_NULL(vmSymbols::java_lang_NullPointerException());
 493   }
 494   if (!value->is_a(StackLockValue::klass())) {
 495     JVMCI_ERROR_NULL("Monitors must be of type StackLockValue, got %s", value->klass()->signature_name());
 496   }
 497 
 498   ScopeValue* second = NULL;
 499   Handle stack_lock_owner(THREAD, StackLockValue::owner(value));
 500   ScopeValue* owner_value = get_scope_value(stack_lock_owner, T_OBJECT, objects, second, CHECK_NULL);
 501   assert(second == NULL, "monitor cannot occupy two stack slots");
 502 
 503   Handle stack_lock_slot(THREAD, StackLockValue::slot(value));
 504   ScopeValue* lock_data_value = get_scope_value(stack_lock_slot, T_LONG, objects, second, CHECK_NULL);
 505   assert(second == lock_data_value, "monitor is LONG value that occupies two stack slots");
 506   assert(lock_data_value->is_location(), "invalid monitor location");
 507   Location lock_data_loc = ((LocationValue*)lock_data_value)->location();
 508 
 509   bool eliminated = false;
 510   if (StackLockValue::eliminated(value)) {
 511     eliminated = true;
 512   }
 513 
 514   return new MonitorValue(owner_value, lock_data_loc, eliminated);
 515 }
 516 
 517 void CodeInstaller::initialize_dependencies(oop compiled_code, OopRecorder* recorder, TRAPS) {
 518   JavaThread* thread = JavaThread::current();
 519   assert(THREAD == thread, "");
 520   CompilerThread* compilerThread = thread->is_Compiler_thread() ? thread->as_CompilerThread() : NULL;
 521   _oop_recorder = recorder;
 522   _dependencies = new Dependencies(&_arena, _oop_recorder, compilerThread != NULL ? compilerThread->log() : NULL);
 523   objArrayHandle assumptions(THREAD, HotSpotCompiledCode::assumptions(compiled_code));
 524   if (!assumptions.is_null()) {
 525     int length = assumptions->length();
 526     for (int i = 0; i < length; ++i) {
 527       Handle assumption(THREAD, assumptions->obj_at(i));
 528       if (!assumption.is_null()) {
 529         if (assumption->klass() == Assumptions_NoFinalizableSubclass::klass()) {
 530           assumption_NoFinalizableSubclass(THREAD, assumption);
 531         } else if (assumption->klass() == Assumptions_ConcreteSubtype::klass()) {
 532           assumption_ConcreteSubtype(THREAD, assumption);
 533         } else if (assumption->klass() == Assumptions_LeafType::klass()) {
 534           assumption_LeafType(THREAD, assumption);
 535         } else if (assumption->klass() == Assumptions_ConcreteMethod::klass()) {
 536           assumption_ConcreteMethod(THREAD, assumption);
 537         } else if (assumption->klass() == Assumptions_CallSiteTargetValue::klass()) {
 538           assumption_CallSiteTargetValue(THREAD, assumption);
 539         } else {
 540           JVMCI_ERROR("unexpected Assumption subclass %s", assumption->klass()->signature_name());
 541         }
 542       }
 543     }
 544   }
 545   if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
 546     objArrayHandle methods(THREAD, HotSpotCompiledCode::methods(compiled_code));
 547     if (!methods.is_null()) {
 548       int length = methods->length();
 549       for (int i = 0; i < length; ++i) {
 550         Handle method_handle(THREAD, methods->obj_at(i));
 551         methodHandle method = getMethodFromHotSpotMethod(method_handle());
 552         _dependencies->assert_evol_method(method());
 553       }
 554     }
 555   }
 556 }
 557 
 558 RelocBuffer::~RelocBuffer() {
 559   if (_buffer != NULL) {
 560     FREE_C_HEAP_ARRAY(char, _buffer);
 561   }
 562 }
 563 
 564 address RelocBuffer::begin() const {
 565   if (_buffer != NULL) {
 566     return (address) _buffer;
 567   }
 568   return (address) _static_buffer;
 569 }
 570 
 571 void RelocBuffer::set_size(size_t bytes) {
 572   assert(bytes <= _size, "can't grow in size!");
 573   _size = bytes;
 574 }
 575 
 576 void RelocBuffer::ensure_size(size_t bytes) {
 577   assert(_buffer == NULL, "can only be used once");
 578   assert(_size == 0, "can only be used once");
 579   if (bytes >= RelocBuffer::stack_size) {
 580     _buffer = NEW_C_HEAP_ARRAY(char, bytes, mtInternal);
 581   }
 582   _size = bytes;
 583 }
 584 
 585 JVMCIEnv::CodeInstallResult CodeInstaller::gather_metadata(Handle target, Handle compiled_code, CodeMetadata& metadata, TRAPS) {
 586   CodeBuffer buffer("JVMCI Compiler CodeBuffer for Metadata");
 587   jobject compiled_code_obj = JNIHandles::make_local(compiled_code());
 588   AOTOopRecorder* recorder = new AOTOopRecorder(&_arena, true);
 589   initialize_dependencies(JNIHandles::resolve(compiled_code_obj), recorder, CHECK_OK);
 590 
 591   metadata.set_oop_recorder(recorder);
 592 
 593   // Get instructions and constants CodeSections early because we need it.
 594   _instructions = buffer.insts();
 595   _constants = buffer.consts();
 596 #if INCLUDE_AOT
 597   buffer.set_immutable_PIC(_immutable_pic_compilation);
 598 #endif
 599 
 600   initialize_fields(target(), JNIHandles::resolve(compiled_code_obj), CHECK_OK);
 601   JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, false, CHECK_OK);
 602   if (result != JVMCIEnv::ok) {
 603     return result;
 604   }
 605 
 606   _debug_recorder->pcs_size(); // create the sentinel record
 607 
 608   assert(_debug_recorder->pcs_length() >= 2, "must be at least 2");
 609 
 610   metadata.set_pc_desc(_debug_recorder->pcs(), _debug_recorder->pcs_length());
 611   metadata.set_scopes(_debug_recorder->stream()->buffer(), _debug_recorder->data_size());
 612   metadata.set_exception_table(&_exception_handler_table);
 613 
 614   RelocBuffer* reloc_buffer = metadata.get_reloc_buffer();
 615 
 616   reloc_buffer->ensure_size(buffer.total_relocation_size());
 617   size_t size = (size_t) buffer.copy_relocations_to(reloc_buffer->begin(), (CodeBuffer::csize_t) reloc_buffer->size(), true);
 618   reloc_buffer->set_size(size);
 619   return JVMCIEnv::ok;
 620 }
 621 
 622 // constructor used to create a method
 623 JVMCIEnv::CodeInstallResult CodeInstaller::install(JVMCICompiler* compiler, Handle target, Handle compiled_code, CodeBlob*& cb, Handle installed_code, Handle speculation_log, TRAPS) {
 624   CodeBuffer buffer("JVMCI Compiler CodeBuffer");
 625   jobject compiled_code_obj = JNIHandles::make_local(compiled_code());
 626   OopRecorder* recorder = new OopRecorder(&_arena, true);
 627   initialize_dependencies(JNIHandles::resolve(compiled_code_obj), recorder, CHECK_OK);
 628 
 629   // Get instructions and constants CodeSections early because we need it.
 630   _instructions = buffer.insts();
 631   _constants = buffer.consts();
 632 #if INCLUDE_AOT
 633   buffer.set_immutable_PIC(_immutable_pic_compilation);
 634 #endif
 635 
 636   initialize_fields(target(), JNIHandles::resolve(compiled_code_obj), CHECK_OK);
 637   JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, true, CHECK_OK);
 638   if (result != JVMCIEnv::ok) {
 639     return result;
 640   }
 641 
 642   int stack_slots = _total_frame_size / HeapWordSize; // conversion to words
 643 
 644   if (!compiled_code->is_a(HotSpotCompiledNmethod::klass())) {
 645     oop stubName = HotSpotCompiledCode::name(compiled_code_obj);
 646     if (stubName == NULL) {
 647       JVMCI_ERROR_OK("stub should have a name");
 648     }
 649     char* name = strdup(java_lang_String::as_utf8_string(stubName));
 650     cb = RuntimeStub::new_runtime_stub(name,
 651                                        &buffer,
 652                                        CodeOffsets::frame_never_safe,
 653                                        stack_slots,
 654                                        _debug_recorder->_oopmaps,
 655                                        false);
 656     result = JVMCIEnv::ok;
 657   } else {
 658     nmethod* nm = NULL;
 659     methodHandle method = getMethodFromHotSpotMethod(HotSpotCompiledNmethod::method(compiled_code));
 660     jint entry_bci = HotSpotCompiledNmethod::entryBCI(compiled_code);
 661     jint id = HotSpotCompiledNmethod::id(compiled_code);
 662     bool has_unsafe_access = HotSpotCompiledNmethod::hasUnsafeAccess(compiled_code) == JNI_TRUE;
 663     JVMCIEnv* env = (JVMCIEnv*) (address) HotSpotCompiledNmethod::jvmciEnv(compiled_code);
 664     if (id == -1) {
 665       // Make sure a valid compile_id is associated with every compile
 666       id = CompileBroker::assign_compile_id_unlocked(Thread::current(), method, entry_bci);
 667     }
 668     result = JVMCIEnv::register_method(method, nm, entry_bci, &_offsets, _orig_pc_offset, &buffer,
 669                                        stack_slots, _debug_recorder->_oopmaps, &_exception_handler_table,
 670                                        compiler, _debug_recorder, _dependencies, env, id,
 671                                        has_unsafe_access, _has_wide_vector, installed_code, compiled_code, speculation_log);
 672     cb = nm->as_codeblob_or_null();
 673     if (nm != NULL && env == NULL) {
 674       DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, compiler);
 675       bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;
 676       if (!printnmethods && (PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers)) {
 677         nm->print_nmethod(printnmethods);
 678       }
 679       DirectivesStack::release(directive);
 680     }
 681   }
 682 
 683   if (cb != NULL) {
 684     // Make sure the pre-calculated constants section size was correct.
 685     guarantee((cb->code_begin() - cb->content_begin()) >= _constants_size, "%d < %d", (int)(cb->code_begin() - cb->content_begin()), _constants_size);
 686   }
 687   return result;
 688 }
 689 
 690 void CodeInstaller::initialize_fields(oop target, oop compiled_code, TRAPS) {
 691   if (compiled_code->is_a(HotSpotCompiledNmethod::klass())) {
 692     Handle hotspotJavaMethod(THREAD, HotSpotCompiledNmethod::method(compiled_code));
 693     methodHandle method = getMethodFromHotSpotMethod(hotspotJavaMethod());
 694     _parameter_count = method->size_of_parameters();
 695     TRACE_jvmci_2("installing code for %s", method->name_and_sig_as_C_string());
 696   } else {
 697     // Must be a HotSpotCompiledRuntimeStub.
 698     // Only used in OopMap constructor for non-product builds
 699     _parameter_count = 0;
 700   }
 701   _sites_handle = JNIHandles::make_local(HotSpotCompiledCode::sites(compiled_code));
 702 
 703   _code_handle = JNIHandles::make_local(HotSpotCompiledCode::targetCode(compiled_code));
 704   _code_size = HotSpotCompiledCode::targetCodeSize(compiled_code);
 705   _total_frame_size = HotSpotCompiledCode::totalFrameSize(compiled_code);
 706 
 707   oop deoptRescueSlot = HotSpotCompiledCode::deoptRescueSlot(compiled_code);
 708   if (deoptRescueSlot == NULL) {
 709     _orig_pc_offset = -1;
 710   } else {
 711     _orig_pc_offset = StackSlot::offset(deoptRescueSlot);
 712     if (StackSlot::addFrameSize(deoptRescueSlot)) {
 713       _orig_pc_offset += _total_frame_size;
 714     }
 715     if (_orig_pc_offset < 0) {
 716       JVMCI_ERROR("invalid deopt rescue slot: %d", _orig_pc_offset);
 717     }
 718   }
 719 
 720   // Pre-calculate the constants section size.  This is required for PC-relative addressing.
 721   _data_section_handle = JNIHandles::make_local(HotSpotCompiledCode::dataSection(compiled_code));
 722   if ((_constants->alignment() % HotSpotCompiledCode::dataSectionAlignment(compiled_code)) != 0) {
 723     JVMCI_ERROR("invalid data section alignment: %d", HotSpotCompiledCode::dataSectionAlignment(compiled_code));
 724   }
 725   _constants_size = data_section()->length();
 726 
 727   _data_section_patches_handle = JNIHandles::make_local(HotSpotCompiledCode::dataSectionPatches(compiled_code));
 728 
 729 #ifndef PRODUCT
 730   _comments_handle = JNIHandles::make_local(HotSpotCompiledCode::comments(compiled_code));
 731 #endif
 732 
 733   _next_call_type = INVOKE_INVALID;
 734 
 735   _has_wide_vector = false;
 736 
 737   oop arch = TargetDescription::arch(target);
 738   _word_kind_handle = JNIHandles::make_local(Architecture::wordKind(arch));
 739 }
 740 
 741 int CodeInstaller::estimate_stubs_size(TRAPS) {
 742   // Estimate the number of static and aot call stubs that might be emitted.
 743   int static_call_stubs = 0;
 744   int aot_call_stubs = 0;
 745   int trampoline_stubs = 0;
 746   objArrayOop sites = this->sites();
 747   for (int i = 0; i < sites->length(); i++) {
 748     oop site = sites->obj_at(i);
 749     if (site != NULL) {
 750       if (site->is_a(site_Mark::klass())) {
 751         oop id_obj = site_Mark::id(site);
 752         if (id_obj != NULL) {
 753           if (!java_lang_boxing_object::is_instance(id_obj, T_INT)) {
 754             JVMCI_ERROR_0("expected Integer id, got %s", id_obj->klass()->signature_name());
 755           }
 756           jint id = id_obj->int_field(java_lang_boxing_object::value_offset_in_bytes(T_INT));
 757           switch (id) {
 758           case INVOKEINTERFACE:
 759           case INVOKEVIRTUAL:
 760             trampoline_stubs++;
 761             break;
 762           case INVOKESTATIC:
 763           case INVOKESPECIAL:
 764             static_call_stubs++;
 765             trampoline_stubs++;
 766             break;
 767           default:
 768             break;
 769           }
 770         }
 771       }
 772       if (UseAOT && site->is_a(site_Call::klass())) {
 773         oop target = site_Call::target(site);
 774         InstanceKlass* target_klass = InstanceKlass::cast(target->klass());
 775         if (!target_klass->is_subclass_of(SystemDictionary::HotSpotForeignCallTarget_klass())) {
 776           // Add far aot trampolines.
 777           aot_call_stubs++;
 778         }
 779       }
 780     }
 781   }
 782   int size = static_call_stubs * CompiledStaticCall::to_interp_stub_size();
 783   size += trampoline_stubs * CompiledStaticCall::to_trampoline_stub_size();
 784 #if INCLUDE_AOT
 785   size += aot_call_stubs * CompiledStaticCall::to_aot_stub_size();
 786 #endif
 787   return size;
 788 }
 789 
 790 // perform data and call relocation on the CodeBuffer
 791 JVMCIEnv::CodeInstallResult CodeInstaller::initialize_buffer(CodeBuffer& buffer, bool check_size, TRAPS) {
 792   HandleMark hm;
 793   objArrayHandle sites(THREAD, this->sites());
 794   int locs_buffer_size = sites->length() * (relocInfo::length_limit + sizeof(relocInfo));
 795 
 796   // Allocate enough space in the stub section for the static call
 797   // stubs.  Stubs have extra relocs but they are managed by the stub
 798   // section itself so they don't need to be accounted for in the
 799   // locs_buffer above.
 800   int stubs_size = estimate_stubs_size(CHECK_OK);
 801   int total_size = align_up(_code_size, buffer.insts()->alignment()) + align_up(_constants_size, buffer.consts()->alignment()) + align_up(stubs_size, buffer.stubs()->alignment());
 802 
 803   if (check_size && total_size > JVMCINMethodSizeLimit) {
 804     return JVMCIEnv::code_too_large;
 805   }
 806 
 807   buffer.initialize(total_size, locs_buffer_size);
 808   if (buffer.blob() == NULL) {
 809     return JVMCIEnv::cache_full;
 810   }
 811   buffer.initialize_stubs_size(stubs_size);
 812   buffer.initialize_consts_size(_constants_size);
 813 
 814   _debug_recorder = new DebugInformationRecorder(_oop_recorder);
 815   _debug_recorder->set_oopmaps(new OopMapSet());
 816 
 817   buffer.initialize_oop_recorder(_oop_recorder);
 818 
 819   // copy the constant data into the newly created CodeBuffer
 820   address end_data = _constants->start() + _constants_size;
 821   memcpy(_constants->start(), data_section()->base(T_BYTE), _constants_size);
 822   _constants->set_end(end_data);
 823 
 824   // copy the code into the newly created CodeBuffer
 825   address end_pc = _instructions->start() + _code_size;
 826   guarantee(_instructions->allocates2(end_pc), "initialize should have reserved enough space for all the code");
 827   memcpy(_instructions->start(), code()->base(T_BYTE), _code_size);
 828   _instructions->set_end(end_pc);
 829 
 830   for (int i = 0; i < data_section_patches()->length(); i++) {
 831     HandleMark hm(THREAD);
 832     Handle patch(THREAD, data_section_patches()->obj_at(i));
 833     if (patch.is_null()) {
 834       THROW_(vmSymbols::java_lang_NullPointerException(), JVMCIEnv::ok);
 835     }
 836     Handle reference(THREAD, site_DataPatch::reference(patch));
 837     if (reference.is_null()) {
 838       THROW_(vmSymbols::java_lang_NullPointerException(), JVMCIEnv::ok);
 839     }
 840     if (!reference->is_a(site_ConstantReference::klass())) {
 841       JVMCI_ERROR_OK("invalid patch in data section: %s", reference->klass()->signature_name());
 842     }
 843     Handle constant(THREAD, site_ConstantReference::constant(reference));
 844     if (constant.is_null()) {
 845       THROW_(vmSymbols::java_lang_NullPointerException(), JVMCIEnv::ok);
 846     }
 847     address dest = _constants->start() + site_Site::pcOffset(patch);
 848     if (constant->is_a(HotSpotMetaspaceConstantImpl::klass())) {
 849       if (HotSpotMetaspaceConstantImpl::compressed(constant)) {
 850 #ifdef _LP64
 851         *((narrowKlass*) dest) = record_narrow_metadata_reference(_constants, dest, constant, CHECK_OK);
 852 #else
 853         JVMCI_ERROR_OK("unexpected compressed Klass* in 32-bit mode");
 854 #endif
 855       } else {
 856         *((void**) dest) = record_metadata_reference(_constants, dest, constant, CHECK_OK);
 857       }
 858     } else if (constant->is_a(HotSpotObjectConstantImpl::klass())) {
 859       Handle obj(THREAD, HotSpotObjectConstantImpl::object(constant));
 860       jobject value = JNIHandles::make_local(obj());
 861       int oop_index = _oop_recorder->find_index(value);
 862 
 863       if (HotSpotObjectConstantImpl::compressed(constant)) {
 864 #ifdef _LP64
 865         _constants->relocate(dest, oop_Relocation::spec(oop_index), relocInfo::narrow_oop_in_const);
 866 #else
 867         JVMCI_ERROR_OK("unexpected compressed oop in 32-bit mode");
 868 #endif
 869       } else {
 870         _constants->relocate(dest, oop_Relocation::spec(oop_index));
 871       }
 872     } else {
 873       JVMCI_ERROR_OK("invalid constant in data section: %s", constant->klass()->signature_name());
 874     }
 875   }
 876   jint last_pc_offset = -1;
 877   for (int i = 0; i < sites->length(); i++) {
 878     HandleMark hm(THREAD);
 879     Handle site(THREAD, sites->obj_at(i));
 880     if (site.is_null()) {
 881       THROW_(vmSymbols::java_lang_NullPointerException(), JVMCIEnv::ok);
 882     }
 883 
 884     jint pc_offset = site_Site::pcOffset(site);
 885 
 886     if (site->is_a(site_Call::klass())) {
 887       TRACE_jvmci_4("call at %i", pc_offset);
 888       site_Call(buffer, pc_offset, site, CHECK_OK);
 889     } else if (site->is_a(site_Infopoint::klass())) {
 890       // three reasons for infopoints denote actual safepoints
 891       oop reason = site_Infopoint::reason(site);
 892       if (site_InfopointReason::SAFEPOINT() == reason || site_InfopointReason::CALL() == reason || site_InfopointReason::IMPLICIT_EXCEPTION() == reason) {
 893         TRACE_jvmci_4("safepoint at %i", pc_offset);
 894         site_Safepoint(buffer, pc_offset, site, CHECK_OK);
 895         if (_orig_pc_offset < 0) {
 896           JVMCI_ERROR_OK("method contains safepoint, but has no deopt rescue slot");
 897         }
 898       } else {
 899         TRACE_jvmci_4("infopoint at %i", pc_offset);
 900         site_Infopoint(buffer, pc_offset, site, CHECK_OK);
 901       }
 902     } else if (site->is_a(site_DataPatch::klass())) {
 903       TRACE_jvmci_4("datapatch at %i", pc_offset);
 904       site_DataPatch(buffer, pc_offset, site, CHECK_OK);
 905     } else if (site->is_a(site_Mark::klass())) {
 906       TRACE_jvmci_4("mark at %i", pc_offset);
 907       site_Mark(buffer, pc_offset, site, CHECK_OK);
 908     } else if (site->is_a(site_ExceptionHandler::klass())) {
 909       TRACE_jvmci_4("exceptionhandler at %i", pc_offset);
 910       site_ExceptionHandler(pc_offset, site);
 911     } else {
 912       JVMCI_ERROR_OK("unexpected site subclass: %s", site->klass()->signature_name());
 913     }
 914     last_pc_offset = pc_offset;
 915 
 916     JavaThread* thread = JavaThread::current();
 917     if (SafepointMechanism::poll(thread)) {
 918       // this is a hacky way to force a safepoint check but nothing else was jumping out at me.
 919       ThreadToNativeFromVM ttnfv(thread);
 920     }
 921   }
 922 
 923 #ifndef PRODUCT
 924   if (comments() != NULL) {
 925     for (int i = 0; i < comments()->length(); i++) {
 926       oop comment = comments()->obj_at(i);
 927       assert(comment->is_a(HotSpotCompiledCode_Comment::klass()), "cce");
 928       jint offset = HotSpotCompiledCode_Comment::pcOffset(comment);
 929       char* text = java_lang_String::as_utf8_string(HotSpotCompiledCode_Comment::text(comment));
 930       buffer.block_comment(offset, text);
 931     }
 932   }
 933 #endif
 934   return JVMCIEnv::ok;
 935 }
 936 
 937 void CodeInstaller::assumption_NoFinalizableSubclass(Thread* thread, Handle assumption) {
 938   Handle receiverType_handle (thread, Assumptions_NoFinalizableSubclass::receiverType(assumption()));
 939   Klass* receiverType = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(receiverType_handle));
 940   _dependencies->assert_has_no_finalizable_subclasses(receiverType);
 941 }
 942 
 943 void CodeInstaller::assumption_ConcreteSubtype(Thread* thread, Handle assumption) {
 944   Handle context_handle (thread, Assumptions_ConcreteSubtype::context(assumption()));
 945   Handle subtype_handle (thread, Assumptions_ConcreteSubtype::subtype(assumption()));
 946   Klass* context = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(context_handle));
 947   Klass* subtype = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(subtype_handle));
 948 
 949   assert(context->is_abstract(), "");
 950   _dependencies->assert_abstract_with_unique_concrete_subtype(context, subtype);
 951 }
 952 
 953 void CodeInstaller::assumption_LeafType(Thread* thread, Handle assumption) {
 954   Handle context_handle (thread, Assumptions_LeafType::context(assumption()));
 955   Klass* context = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(context_handle));
 956 
 957   _dependencies->assert_leaf_type(context);
 958 }
 959 
 960 void CodeInstaller::assumption_ConcreteMethod(Thread* thread, Handle assumption) {
 961   Handle impl_handle (thread, Assumptions_ConcreteMethod::impl(assumption()));
 962   Handle context_handle (thread, Assumptions_ConcreteMethod::context(assumption()));
 963 
 964   methodHandle impl = getMethodFromHotSpotMethod(impl_handle());
 965   Klass* context = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(context_handle));
 966 
 967   _dependencies->assert_unique_concrete_method(context, impl());
 968 }
 969 
 970 void CodeInstaller::assumption_CallSiteTargetValue(Thread* thread, Handle assumption) {
 971   Handle callSite(thread, HotSpotObjectConstantImpl::object(Assumptions_CallSiteTargetValue::callSite(assumption())));
 972   Handle methodHandle(thread, HotSpotObjectConstantImpl::object(Assumptions_CallSiteTargetValue::methodHandle(assumption())));
 973 
 974   _dependencies->assert_call_site_target_value(callSite(), methodHandle());
 975 }
 976 
 977 void CodeInstaller::site_ExceptionHandler(jint pc_offset, Handle exc) {
 978   jint handler_offset = site_ExceptionHandler::handlerPos(exc);
 979 
 980   // Subtable header
 981   _exception_handler_table.add_entry(HandlerTableEntry(1, pc_offset, 0));
 982 
 983   // Subtable entry
 984   _exception_handler_table.add_entry(HandlerTableEntry(-1, handler_offset, 0));
 985 }
 986 
 987 // If deoptimization happens, the interpreter should reexecute these bytecodes.
 988 // This function mainly helps the compilers to set up the reexecute bit.
 989 static bool bytecode_should_reexecute(Bytecodes::Code code) {
 990   switch (code) {
 991     case Bytecodes::_invokedynamic:
 992     case Bytecodes::_invokevirtual:
 993     case Bytecodes::_invokeinterface:
 994     case Bytecodes::_invokespecial:
 995     case Bytecodes::_invokestatic:
 996       return false;
 997     default:
 998       return true;
 999     }
1000   return true;
1001 }
1002 
1003 GrowableArray<ScopeValue*>* CodeInstaller::record_virtual_objects(Handle debug_info, TRAPS) {
1004   objArrayHandle virtualObjects(THREAD, DebugInfo::virtualObjectMapping(debug_info));
1005   if (virtualObjects.is_null()) {
1006     return NULL;
1007   }
1008   GrowableArray<ScopeValue*>* objects = new GrowableArray<ScopeValue*>(virtualObjects->length(), virtualObjects->length(), NULL);
1009   // Create the unique ObjectValues
1010   for (int i = 0; i < virtualObjects->length(); i++) {
1011     HandleMark hm(THREAD);
1012     Handle value(THREAD, virtualObjects->obj_at(i));
1013     int id = VirtualObject::id(value);
1014     Handle type(THREAD, VirtualObject::type(value));
1015     oop javaMirror = HotSpotResolvedObjectTypeImpl::javaClass(type);
1016     ObjectValue* sv = new ObjectValue(id, new ConstantOopWriteValue(JNIHandles::make_local(Thread::current(), javaMirror)));
1017     if (id < 0 || id >= objects->length()) {
1018       JVMCI_ERROR_NULL("virtual object id %d out of bounds", id);
1019     }
1020     if (objects->at(id) != NULL) {
1021       JVMCI_ERROR_NULL("duplicate virtual object id %d", id);
1022     }
1023     objects->at_put(id, sv);
1024   }
1025   // All the values which could be referenced by the VirtualObjects
1026   // exist, so now describe all the VirtualObjects themselves.
1027   for (int i = 0; i < virtualObjects->length(); i++) {
1028     HandleMark hm(THREAD);
1029     Handle value(THREAD, virtualObjects->obj_at(i));
1030     int id = VirtualObject::id(value);
1031     record_object_value(objects->at(id)->as_ObjectValue(), value, objects, CHECK_NULL);
1032   }
1033   _debug_recorder->dump_object_pool(objects);
1034   return objects;
1035 }
1036 
1037 void CodeInstaller::record_scope(jint pc_offset, Handle debug_info, ScopeMode scope_mode, bool return_oop, TRAPS) {
1038   Handle position(THREAD, DebugInfo::bytecodePosition(debug_info));
1039   if (position.is_null()) {
1040     // Stubs do not record scope info, just oop maps
1041     return;
1042   }
1043 
1044   GrowableArray<ScopeValue*>* objectMapping;
1045   if (scope_mode == CodeInstaller::FullFrame) {
1046     objectMapping = record_virtual_objects(debug_info, CHECK);
1047   } else {
1048     objectMapping = NULL;
1049   }
1050   record_scope(pc_offset, position, scope_mode, objectMapping, return_oop, CHECK);
1051 }
1052 
1053 int CodeInstaller::map_jvmci_bci(int bci) {
1054   if (bci < 0) {
1055     if (bci == BytecodeFrame::BEFORE_BCI()) {
1056       return BeforeBci;
1057     } else if (bci == BytecodeFrame::AFTER_BCI()) {
1058       return AfterBci;
1059     } else if (bci == BytecodeFrame::UNWIND_BCI()) {
1060       return UnwindBci;
1061     } else if (bci == BytecodeFrame::AFTER_EXCEPTION_BCI()) {
1062       return AfterExceptionBci;
1063     } else if (bci == BytecodeFrame::UNKNOWN_BCI()) {
1064       return UnknownBci;
1065     } else if (bci == BytecodeFrame::INVALID_FRAMESTATE_BCI()) {
1066       return InvalidFrameStateBci;
1067     }
1068     ShouldNotReachHere();
1069   }
1070   return bci;
1071 }
1072 
1073 void CodeInstaller::record_scope(jint pc_offset, Handle position, ScopeMode scope_mode, GrowableArray<ScopeValue*>* objects, bool return_oop, TRAPS) {
1074   Handle frame;
1075   if (scope_mode == CodeInstaller::FullFrame) {
1076     if (!position->is_a(BytecodeFrame::klass())) {
1077       JVMCI_ERROR("Full frame expected for debug info at %i", pc_offset);
1078     }
1079     frame = position;
1080   }
1081   Handle caller_frame (THREAD, BytecodePosition::caller(position));
1082   if (caller_frame.not_null()) {
1083     record_scope(pc_offset, caller_frame, scope_mode, objects, return_oop, CHECK);
1084   }
1085 
1086   Handle hotspot_method (THREAD, BytecodePosition::method(position));
1087   Method* method = getMethodFromHotSpotMethod(hotspot_method());
1088   jint bci = map_jvmci_bci(BytecodePosition::bci(position));
1089 
1090   TRACE_jvmci_2("Recording scope pc_offset=%d bci=%d method=%s", pc_offset, bci, method->name_and_sig_as_C_string());
1091 
1092   bool reexecute = false;
1093   if (frame.not_null()) {
1094     if (bci < 0) {
1095        reexecute = false;
1096     } else {
1097       Bytecodes::Code code = Bytecodes::java_code_at(method, method->bcp_from(bci));
1098       reexecute = bytecode_should_reexecute(code);
1099       if (frame.not_null()) {
1100         reexecute = (BytecodeFrame::duringCall(frame) == JNI_FALSE);
1101       }
1102     }
1103   }
1104 
1105   DebugToken* locals_token = NULL;
1106   DebugToken* expressions_token = NULL;
1107   DebugToken* monitors_token = NULL;
1108   bool throw_exception = false;
1109 
1110   if (frame.not_null()) {
1111     jint local_count = BytecodeFrame::numLocals(frame);
1112     jint expression_count = BytecodeFrame::numStack(frame);
1113     jint monitor_count = BytecodeFrame::numLocks(frame);
1114     objArrayHandle values(THREAD, BytecodeFrame::values(frame));
1115     objArrayHandle slotKinds(THREAD, BytecodeFrame::slotKinds(frame));
1116 
1117     if (values.is_null() || slotKinds.is_null()) {
1118       THROW(vmSymbols::java_lang_NullPointerException());
1119     }
1120     if (local_count + expression_count + monitor_count != values->length()) {
1121       JVMCI_ERROR("unexpected values length %d in scope (%d locals, %d expressions, %d monitors)", values->length(), local_count, expression_count, monitor_count);
1122     }
1123     if (local_count + expression_count != slotKinds->length()) {
1124       JVMCI_ERROR("unexpected slotKinds length %d in scope (%d locals, %d expressions)", slotKinds->length(), local_count, expression_count);
1125     }
1126 
1127     GrowableArray<ScopeValue*>* locals = local_count > 0 ? new GrowableArray<ScopeValue*> (local_count) : NULL;
1128     GrowableArray<ScopeValue*>* expressions = expression_count > 0 ? new GrowableArray<ScopeValue*> (expression_count) : NULL;
1129     GrowableArray<MonitorValue*>* monitors = monitor_count > 0 ? new GrowableArray<MonitorValue*> (monitor_count) : NULL;
1130 
1131     TRACE_jvmci_2("Scope at bci %d with %d values", bci, values->length());
1132     TRACE_jvmci_2("%d locals %d expressions, %d monitors", local_count, expression_count, monitor_count);
1133 
1134     for (jint i = 0; i < values->length(); i++) {
1135       HandleMark hm(THREAD);
1136       ScopeValue* second = NULL;
1137       Handle value(THREAD, values->obj_at(i));
1138       if (i < local_count) {
1139         BasicType type = JVMCIRuntime::kindToBasicType(Handle(THREAD, slotKinds->obj_at(i)), CHECK);
1140         ScopeValue* first = get_scope_value(value, type, objects, second, CHECK);
1141         if (second != NULL) {
1142           locals->append(second);
1143         }
1144         locals->append(first);
1145       } else if (i < local_count + expression_count) {
1146         BasicType type = JVMCIRuntime::kindToBasicType(Handle(THREAD, slotKinds->obj_at(i)), CHECK);
1147         ScopeValue* first = get_scope_value(value, type, objects, second, CHECK);
1148         if (second != NULL) {
1149           expressions->append(second);
1150         }
1151         expressions->append(first);
1152       } else {
1153         MonitorValue *monitor = get_monitor_value(value, objects, CHECK);
1154         monitors->append(monitor);
1155       }
1156       if (second != NULL) {
1157         i++;
1158         if (i >= values->length() || values->obj_at(i) != Value::ILLEGAL()) {
1159           JVMCI_ERROR("double-slot value not followed by Value.ILLEGAL");
1160         }
1161       }
1162     }
1163 
1164     locals_token = _debug_recorder->create_scope_values(locals);
1165     expressions_token = _debug_recorder->create_scope_values(expressions);
1166     monitors_token = _debug_recorder->create_monitor_values(monitors);
1167 
1168     throw_exception = BytecodeFrame::rethrowException(frame) == JNI_TRUE;
1169   }
1170 
1171   _debug_recorder->describe_scope(pc_offset, method, NULL, bci, reexecute, throw_exception, false, return_oop, false,
1172                                   locals_token, expressions_token, monitors_token);
1173 }
1174 
1175 void CodeInstaller::site_Safepoint(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) {
1176   Handle debug_info (THREAD, site_Infopoint::debugInfo(site));
1177   if (debug_info.is_null()) {
1178     JVMCI_ERROR("debug info expected at safepoint at %i", pc_offset);
1179   }
1180 
1181   // address instruction = _instructions->start() + pc_offset;
1182   // jint next_pc_offset = Assembler::locate_next_instruction(instruction) - _instructions->start();
1183   OopMap *map = create_oop_map(debug_info, CHECK);
1184   _debug_recorder->add_safepoint(pc_offset, map);
1185   record_scope(pc_offset, debug_info, CodeInstaller::FullFrame, CHECK);
1186   _debug_recorder->end_safepoint(pc_offset);
1187 }
1188 
1189 void CodeInstaller::site_Infopoint(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) {
1190   Handle debug_info (THREAD, site_Infopoint::debugInfo(site));
1191   if (debug_info.is_null()) {
1192     JVMCI_ERROR("debug info expected at infopoint at %i", pc_offset);
1193   }
1194 
1195   // We'd like to check that pc_offset is greater than the
1196   // last pc recorded with _debug_recorder (raising an exception if not)
1197   // but DebugInformationRecorder doesn't have sufficient public API.
1198 
1199   _debug_recorder->add_non_safepoint(pc_offset);
1200   record_scope(pc_offset, debug_info, CodeInstaller::BytecodePosition, CHECK);
1201   _debug_recorder->end_non_safepoint(pc_offset);
1202 }
1203 
1204 void CodeInstaller::site_Call(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) {
1205   Handle target(THREAD, site_Call::target(site));
1206   InstanceKlass* target_klass = InstanceKlass::cast(target->klass());
1207 
1208   Handle hotspot_method; // JavaMethod
1209   Handle foreign_call;
1210 
1211   if (target_klass->is_subclass_of(SystemDictionary::HotSpotForeignCallTarget_klass())) {
1212     foreign_call = target;
1213   } else {
1214     hotspot_method = target;
1215   }
1216 
1217   Handle debug_info (THREAD, site_Call::debugInfo(site));
1218 
1219   assert(hotspot_method.not_null() ^ foreign_call.not_null(), "Call site needs exactly one type");
1220 
1221   NativeInstruction* inst = nativeInstruction_at(_instructions->start() + pc_offset);
1222   jint next_pc_offset = CodeInstaller::pd_next_offset(inst, pc_offset, hotspot_method, CHECK);
1223 
1224   if (debug_info.not_null()) {
1225     OopMap *map = create_oop_map(debug_info, CHECK);
1226     _debug_recorder->add_safepoint(next_pc_offset, map);
1227 
1228     bool return_oop = hotspot_method.not_null() && getMethodFromHotSpotMethod(hotspot_method())->may_return_oop();
1229 
1230     record_scope(next_pc_offset, debug_info, CodeInstaller::FullFrame, return_oop, CHECK);
1231   }
1232 
1233   if (foreign_call.not_null()) {
1234     jlong foreign_call_destination = HotSpotForeignCallTarget::address(foreign_call);
1235     if (_immutable_pic_compilation) {
1236       // Use fake short distance during PIC compilation.
1237       foreign_call_destination = (jlong)(_instructions->start() + pc_offset);
1238     }
1239     CodeInstaller::pd_relocate_ForeignCall(inst, foreign_call_destination, CHECK);
1240   } else { // method != NULL
1241     if (debug_info.is_null()) {
1242       JVMCI_ERROR("debug info expected at call at %i", pc_offset);
1243     }
1244 
1245     TRACE_jvmci_3("method call");
1246     CodeInstaller::pd_relocate_JavaMethod(buffer, hotspot_method, pc_offset, CHECK);
1247     if (_next_call_type == INVOKESTATIC || _next_call_type == INVOKESPECIAL) {
1248       // Need a static call stub for transitions from compiled to interpreted.
1249       CompiledStaticCall::emit_to_interp_stub(buffer, _instructions->start() + pc_offset);
1250     }
1251 #if INCLUDE_AOT
1252     // Trampoline to far aot code.
1253     CompiledStaticCall::emit_to_aot_stub(buffer, _instructions->start() + pc_offset);
1254 #endif
1255   }
1256 
1257   _next_call_type = INVOKE_INVALID;
1258 
1259   if (debug_info.not_null()) {
1260     _debug_recorder->end_safepoint(next_pc_offset);
1261   }
1262 }
1263 
1264 void CodeInstaller::site_DataPatch(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) {
1265   Handle reference(THREAD, site_DataPatch::reference(site));
1266   if (reference.is_null()) {
1267     THROW(vmSymbols::java_lang_NullPointerException());
1268   } else if (reference->is_a(site_ConstantReference::klass())) {
1269     Handle constant(THREAD, site_ConstantReference::constant(reference));
1270     if (constant.is_null()) {
1271       THROW(vmSymbols::java_lang_NullPointerException());
1272     } else if (constant->is_a(HotSpotObjectConstantImpl::klass())) {
1273       if (!_immutable_pic_compilation) {
1274         // Do not patch during PIC compilation.
1275         pd_patch_OopConstant(pc_offset, constant, CHECK);
1276       }
1277     } else if (constant->is_a(HotSpotMetaspaceConstantImpl::klass())) {
1278       if (!_immutable_pic_compilation) {
1279         pd_patch_MetaspaceConstant(pc_offset, constant, CHECK);
1280       }
1281     } else if (constant->is_a(HotSpotSentinelConstant::klass())) {
1282       if (!_immutable_pic_compilation) {
1283         JVMCI_ERROR("sentinel constant not supported for normal compiles: %s", constant->klass()->signature_name());
1284       }
1285     } else {
1286       JVMCI_ERROR("unknown constant type in data patch: %s", constant->klass()->signature_name());
1287     }
1288   } else if (reference->is_a(site_DataSectionReference::klass())) {
1289     int data_offset = site_DataSectionReference::offset(reference);
1290     if (0 <= data_offset && data_offset < _constants_size) {
1291       pd_patch_DataSectionReference(pc_offset, data_offset, CHECK);
1292     } else {
1293       JVMCI_ERROR("data offset 0x%X points outside data section (size 0x%X)", data_offset, _constants_size);
1294     }
1295   } else {
1296     JVMCI_ERROR("unknown data patch type: %s", reference->klass()->signature_name());
1297   }
1298 }
1299 
1300 void CodeInstaller::site_Mark(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) {
1301   Handle id_obj (THREAD, site_Mark::id(site));
1302 
1303   if (id_obj.not_null()) {
1304     if (!java_lang_boxing_object::is_instance(id_obj(), T_INT)) {
1305       JVMCI_ERROR("expected Integer id, got %s", id_obj->klass()->signature_name());
1306     }
1307     jint id = id_obj->int_field(java_lang_boxing_object::value_offset_in_bytes(T_INT));
1308 
1309     address pc = _instructions->start() + pc_offset;
1310 
1311     switch (id) {
1312       case UNVERIFIED_ENTRY:
1313         _offsets.set_value(CodeOffsets::Entry, pc_offset);
1314         break;
1315       case VERIFIED_ENTRY:
1316         _offsets.set_value(CodeOffsets::Verified_Entry, pc_offset);
1317         _offsets.set_value(CodeOffsets::Verified_Value_Entry, pc_offset);
1318         break;
1319       case OSR_ENTRY:
1320         _offsets.set_value(CodeOffsets::OSR_Entry, pc_offset);
1321         break;
1322       case EXCEPTION_HANDLER_ENTRY:
1323         _offsets.set_value(CodeOffsets::Exceptions, pc_offset);
1324         break;
1325       case DEOPT_HANDLER_ENTRY:
1326         _offsets.set_value(CodeOffsets::Deopt, pc_offset);
1327         break;
1328       case INVOKEVIRTUAL:
1329       case INVOKEINTERFACE:
1330       case INLINE_INVOKE:
1331       case INVOKESTATIC:
1332       case INVOKESPECIAL:
1333         _next_call_type = (MarkId) id;
1334         _invoke_mark_pc = pc;
1335         break;
1336       case POLL_NEAR:
1337       case POLL_FAR:
1338       case POLL_RETURN_NEAR:
1339       case POLL_RETURN_FAR:
1340         pd_relocate_poll(pc, id, CHECK);
1341         break;
1342       case CARD_TABLE_SHIFT:
1343       case CARD_TABLE_ADDRESS:
1344       case HEAP_TOP_ADDRESS:
1345       case HEAP_END_ADDRESS:
1346       case NARROW_KLASS_BASE_ADDRESS:
1347       case NARROW_OOP_BASE_ADDRESS:
1348       case CRC_TABLE_ADDRESS:
1349       case LOG_OF_HEAP_REGION_GRAIN_BYTES:
1350       case INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED:
1351         break;
1352       default:
1353         JVMCI_ERROR("invalid mark id: %d", id);
1354         break;
1355     }
1356   }
1357 }