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