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