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