Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/hotspot/share/jvmci/jvmciRuntime.cpp
40949 views
1
/*
2
* Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
#include "precompiled.hpp"
25
#include "classfile/javaClasses.inline.hpp"
26
#include "classfile/symbolTable.hpp"
27
#include "classfile/systemDictionary.hpp"
28
#include "classfile/vmClasses.hpp"
29
#include "compiler/compileBroker.hpp"
30
#include "gc/shared/collectedHeap.hpp"
31
#include "gc/shared/oopStorage.inline.hpp"
32
#include "jvmci/jniAccessMark.inline.hpp"
33
#include "jvmci/jvmciCompilerToVM.hpp"
34
#include "jvmci/jvmciRuntime.hpp"
35
#include "jvmci/metadataHandles.hpp"
36
#include "logging/log.hpp"
37
#include "memory/oopFactory.hpp"
38
#include "memory/universe.hpp"
39
#include "oops/constantPool.inline.hpp"
40
#include "oops/klass.inline.hpp"
41
#include "oops/method.inline.hpp"
42
#include "oops/objArrayKlass.hpp"
43
#include "oops/oop.inline.hpp"
44
#include "oops/typeArrayOop.inline.hpp"
45
#include "prims/jvmtiExport.hpp"
46
#include "prims/methodHandles.hpp"
47
#include "runtime/atomic.hpp"
48
#include "runtime/biasedLocking.hpp"
49
#include "runtime/deoptimization.hpp"
50
#include "runtime/fieldDescriptor.inline.hpp"
51
#include "runtime/frame.inline.hpp"
52
#include "runtime/java.hpp"
53
#include "runtime/jniHandles.inline.hpp"
54
#include "runtime/reflectionUtils.hpp"
55
#include "runtime/sharedRuntime.hpp"
56
#if INCLUDE_G1GC
57
#include "gc/g1/g1BarrierSetRuntime.hpp"
58
#endif // INCLUDE_G1GC
59
60
// Simple helper to see if the caller of a runtime stub which
61
// entered the VM has been deoptimized
62
63
static bool caller_is_deopted() {
64
JavaThread* thread = JavaThread::current();
65
RegisterMap reg_map(thread, false);
66
frame runtime_frame = thread->last_frame();
67
frame caller_frame = runtime_frame.sender(&reg_map);
68
assert(caller_frame.is_compiled_frame(), "must be compiled");
69
return caller_frame.is_deoptimized_frame();
70
}
71
72
// Stress deoptimization
73
static void deopt_caller() {
74
if ( !caller_is_deopted()) {
75
JavaThread* thread = JavaThread::current();
76
RegisterMap reg_map(thread, false);
77
frame runtime_frame = thread->last_frame();
78
frame caller_frame = runtime_frame.sender(&reg_map);
79
Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
80
assert(caller_is_deopted(), "Must be deoptimized");
81
}
82
}
83
84
// Manages a scope for a JVMCI runtime call that attempts a heap allocation.
85
// If there is a pending nonasync exception upon closing the scope and the runtime
86
// call is of the variety where allocation failure returns NULL without an
87
// exception, the following action is taken:
88
// 1. The pending nonasync exception is cleared
89
// 2. NULL is written to JavaThread::_vm_result
90
// 3. Checks that an OutOfMemoryError is Universe::out_of_memory_error_retry().
91
class RetryableAllocationMark: public StackObj {
92
private:
93
JavaThread* _thread;
94
public:
95
RetryableAllocationMark(JavaThread* thread, bool activate) {
96
if (activate) {
97
assert(!thread->in_retryable_allocation(), "retryable allocation scope is non-reentrant");
98
_thread = thread;
99
_thread->set_in_retryable_allocation(true);
100
} else {
101
_thread = NULL;
102
}
103
}
104
~RetryableAllocationMark() {
105
if (_thread != NULL) {
106
_thread->set_in_retryable_allocation(false);
107
JavaThread* THREAD = _thread; // For exception macros.
108
if (HAS_PENDING_EXCEPTION) {
109
oop ex = PENDING_EXCEPTION;
110
// Do not clear probable async exceptions.
111
CLEAR_PENDING_NONASYNC_EXCEPTION;
112
oop retry_oome = Universe::out_of_memory_error_retry();
113
if (ex->is_a(retry_oome->klass()) && retry_oome != ex) {
114
ResourceMark rm;
115
fatal("Unexpected exception in scope of retryable allocation: " INTPTR_FORMAT " of type %s", p2i(ex), ex->klass()->external_name());
116
}
117
_thread->set_vm_result(NULL);
118
}
119
}
120
}
121
};
122
123
JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_instance_common(JavaThread* current, Klass* klass, bool null_on_fail))
124
JRT_BLOCK;
125
assert(klass->is_klass(), "not a class");
126
Handle holder(current, klass->klass_holder()); // keep the klass alive
127
InstanceKlass* h = InstanceKlass::cast(klass);
128
{
129
RetryableAllocationMark ram(current, null_on_fail);
130
h->check_valid_for_instantiation(true, CHECK);
131
oop obj;
132
if (null_on_fail) {
133
if (!h->is_initialized()) {
134
// Cannot re-execute class initialization without side effects
135
// so return without attempting the initialization
136
return;
137
}
138
} else {
139
// make sure klass is initialized
140
h->initialize(CHECK);
141
}
142
// allocate instance and return via TLS
143
obj = h->allocate_instance(CHECK);
144
current->set_vm_result(obj);
145
}
146
JRT_BLOCK_END;
147
SharedRuntime::on_slowpath_allocation_exit(current);
148
JRT_END
149
150
JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_array_common(JavaThread* current, Klass* array_klass, jint length, bool null_on_fail))
151
JRT_BLOCK;
152
// Note: no handle for klass needed since they are not used
153
// anymore after new_objArray() and no GC can happen before.
154
// (This may have to change if this code changes!)
155
assert(array_klass->is_klass(), "not a class");
156
oop obj;
157
if (array_klass->is_typeArray_klass()) {
158
BasicType elt_type = TypeArrayKlass::cast(array_klass)->element_type();
159
RetryableAllocationMark ram(current, null_on_fail);
160
obj = oopFactory::new_typeArray(elt_type, length, CHECK);
161
} else {
162
Handle holder(current, array_klass->klass_holder()); // keep the klass alive
163
Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
164
RetryableAllocationMark ram(current, null_on_fail);
165
obj = oopFactory::new_objArray(elem_klass, length, CHECK);
166
}
167
current->set_vm_result(obj);
168
// This is pretty rare but this runtime patch is stressful to deoptimization
169
// if we deoptimize here so force a deopt to stress the path.
170
if (DeoptimizeALot) {
171
static int deopts = 0;
172
// Alternate between deoptimizing and raising an error (which will also cause a deopt)
173
if (deopts++ % 2 == 0) {
174
if (null_on_fail) {
175
return;
176
} else {
177
ResourceMark rm(current);
178
THROW(vmSymbols::java_lang_OutOfMemoryError());
179
}
180
} else {
181
deopt_caller();
182
}
183
}
184
JRT_BLOCK_END;
185
SharedRuntime::on_slowpath_allocation_exit(current);
186
JRT_END
187
188
JRT_ENTRY(void, JVMCIRuntime::new_multi_array_common(JavaThread* current, Klass* klass, int rank, jint* dims, bool null_on_fail))
189
assert(klass->is_klass(), "not a class");
190
assert(rank >= 1, "rank must be nonzero");
191
Handle holder(current, klass->klass_holder()); // keep the klass alive
192
RetryableAllocationMark ram(current, null_on_fail);
193
oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
194
current->set_vm_result(obj);
195
JRT_END
196
197
JRT_ENTRY(void, JVMCIRuntime::dynamic_new_array_common(JavaThread* current, oopDesc* element_mirror, jint length, bool null_on_fail))
198
RetryableAllocationMark ram(current, null_on_fail);
199
oop obj = Reflection::reflect_new_array(element_mirror, length, CHECK);
200
current->set_vm_result(obj);
201
JRT_END
202
203
JRT_ENTRY(void, JVMCIRuntime::dynamic_new_instance_common(JavaThread* current, oopDesc* type_mirror, bool null_on_fail))
204
InstanceKlass* klass = InstanceKlass::cast(java_lang_Class::as_Klass(type_mirror));
205
206
if (klass == NULL) {
207
ResourceMark rm(current);
208
THROW(vmSymbols::java_lang_InstantiationException());
209
}
210
RetryableAllocationMark ram(current, null_on_fail);
211
212
// Create new instance (the receiver)
213
klass->check_valid_for_instantiation(false, CHECK);
214
215
if (null_on_fail) {
216
if (!klass->is_initialized()) {
217
// Cannot re-execute class initialization without side effects
218
// so return without attempting the initialization
219
return;
220
}
221
} else {
222
// Make sure klass gets initialized
223
klass->initialize(CHECK);
224
}
225
226
oop obj = klass->allocate_instance(CHECK);
227
current->set_vm_result(obj);
228
JRT_END
229
230
extern void vm_exit(int code);
231
232
// Enter this method from compiled code handler below. This is where we transition
233
// to VM mode. This is done as a helper routine so that the method called directly
234
// from compiled code does not have to transition to VM. This allows the entry
235
// method to see if the nmethod that we have just looked up a handler for has
236
// been deoptimized while we were in the vm. This simplifies the assembly code
237
// cpu directories.
238
//
239
// We are entering here from exception stub (via the entry method below)
240
// If there is a compiled exception handler in this method, we will continue there;
241
// otherwise we will unwind the stack and continue at the caller of top frame method
242
// Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
243
// control the area where we can allow a safepoint. After we exit the safepoint area we can
244
// check to see if the handler we are going to return is now in a nmethod that has
245
// been deoptimized. If that is the case we return the deopt blob
246
// unpack_with_exception entry instead. This makes life for the exception blob easier
247
// because making that same check and diverting is painful from assembly language.
248
JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* current, oopDesc* ex, address pc, CompiledMethod*& cm))
249
// Reset method handle flag.
250
current->set_is_method_handle_return(false);
251
252
Handle exception(current, ex);
253
cm = CodeCache::find_compiled(pc);
254
assert(cm != NULL, "this is not a compiled method");
255
// Adjust the pc as needed/
256
if (cm->is_deopt_pc(pc)) {
257
RegisterMap map(current, false);
258
frame exception_frame = current->last_frame().sender(&map);
259
// if the frame isn't deopted then pc must not correspond to the caller of last_frame
260
assert(exception_frame.is_deoptimized_frame(), "must be deopted");
261
pc = exception_frame.pc();
262
}
263
assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
264
assert(oopDesc::is_oop(exception()), "just checking");
265
// Check that exception is a subclass of Throwable
266
assert(exception->is_a(vmClasses::Throwable_klass()),
267
"Exception not subclass of Throwable");
268
269
// debugging support
270
// tracing
271
if (log_is_enabled(Info, exceptions)) {
272
ResourceMark rm;
273
stringStream tempst;
274
assert(cm->method() != NULL, "Unexpected null method()");
275
tempst.print("JVMCI compiled method <%s>\n"
276
" at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
277
cm->method()->print_value_string(), p2i(pc), p2i(current));
278
Exceptions::log_exception(exception, tempst.as_string());
279
}
280
// for AbortVMOnException flag
281
Exceptions::debug_check_abort(exception);
282
283
// Check the stack guard pages and reenable them if necessary and there is
284
// enough space on the stack to do so. Use fast exceptions only if the guard
285
// pages are enabled.
286
bool guard_pages_enabled = current->stack_overflow_state()->reguard_stack_if_needed();
287
288
if (JvmtiExport::can_post_on_exceptions()) {
289
// To ensure correct notification of exception catches and throws
290
// we have to deoptimize here. If we attempted to notify the
291
// catches and throws during this exception lookup it's possible
292
// we could deoptimize on the way out of the VM and end back in
293
// the interpreter at the throw site. This would result in double
294
// notifications since the interpreter would also notify about
295
// these same catches and throws as it unwound the frame.
296
297
RegisterMap reg_map(current);
298
frame stub_frame = current->last_frame();
299
frame caller_frame = stub_frame.sender(&reg_map);
300
301
// We don't really want to deoptimize the nmethod itself since we
302
// can actually continue in the exception handler ourselves but I
303
// don't see an easy way to have the desired effect.
304
Deoptimization::deoptimize_frame(current, caller_frame.id(), Deoptimization::Reason_constraint);
305
assert(caller_is_deopted(), "Must be deoptimized");
306
307
return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
308
}
309
310
// ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
311
if (guard_pages_enabled) {
312
address fast_continuation = cm->handler_for_exception_and_pc(exception, pc);
313
if (fast_continuation != NULL) {
314
// Set flag if return address is a method handle call site.
315
current->set_is_method_handle_return(cm->is_method_handle_return(pc));
316
return fast_continuation;
317
}
318
}
319
320
// If the stack guard pages are enabled, check whether there is a handler in
321
// the current method. Otherwise (guard pages disabled), force an unwind and
322
// skip the exception cache update (i.e., just leave continuation==NULL).
323
address continuation = NULL;
324
if (guard_pages_enabled) {
325
326
// New exception handling mechanism can support inlined methods
327
// with exception handlers since the mappings are from PC to PC
328
329
// Clear out the exception oop and pc since looking up an
330
// exception handler can cause class loading, which might throw an
331
// exception and those fields are expected to be clear during
332
// normal bytecode execution.
333
current->clear_exception_oop_and_pc();
334
335
bool recursive_exception = false;
336
continuation = SharedRuntime::compute_compiled_exc_handler(cm, pc, exception, false, false, recursive_exception);
337
// If an exception was thrown during exception dispatch, the exception oop may have changed
338
current->set_exception_oop(exception());
339
current->set_exception_pc(pc);
340
341
// The exception cache is used only for non-implicit exceptions
342
// Update the exception cache only when another exception did
343
// occur during the computation of the compiled exception handler
344
// (e.g., when loading the class of the catch type).
345
// Checking for exception oop equality is not
346
// sufficient because some exceptions are pre-allocated and reused.
347
if (continuation != NULL && !recursive_exception && !SharedRuntime::deopt_blob()->contains(continuation)) {
348
cm->add_handler_for_exception_and_pc(exception, pc, continuation);
349
}
350
}
351
352
// Set flag if return address is a method handle call site.
353
current->set_is_method_handle_return(cm->is_method_handle_return(pc));
354
355
if (log_is_enabled(Info, exceptions)) {
356
ResourceMark rm;
357
log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
358
" for exception thrown at PC " PTR_FORMAT,
359
p2i(current), p2i(continuation), p2i(pc));
360
}
361
362
return continuation;
363
JRT_END
364
365
// Enter this method from compiled code only if there is a Java exception handler
366
// in the method handling the exception.
367
// We are entering here from exception stub. We don't do a normal VM transition here.
368
// We do it in a helper. This is so we can check to see if the nmethod we have just
369
// searched for an exception handler has been deoptimized in the meantime.
370
address JVMCIRuntime::exception_handler_for_pc(JavaThread* current) {
371
oop exception = current->exception_oop();
372
address pc = current->exception_pc();
373
// Still in Java mode
374
DEBUG_ONLY(NoHandleMark nhm);
375
CompiledMethod* cm = NULL;
376
address continuation = NULL;
377
{
378
// Enter VM mode by calling the helper
379
ResetNoHandleMark rnhm;
380
continuation = exception_handler_for_pc_helper(current, exception, pc, cm);
381
}
382
// Back in JAVA, use no oops DON'T safepoint
383
384
// Now check to see if the compiled method we were called from is now deoptimized.
385
// If so we must return to the deopt blob and deoptimize the nmethod
386
if (cm != NULL && caller_is_deopted()) {
387
continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
388
}
389
390
assert(continuation != NULL, "no handler found");
391
return continuation;
392
}
393
394
JRT_BLOCK_ENTRY(void, JVMCIRuntime::monitorenter(JavaThread* current, oopDesc* obj, BasicLock* lock))
395
SharedRuntime::monitor_enter_helper(obj, lock, current);
396
JRT_END
397
398
JRT_LEAF(void, JVMCIRuntime::monitorexit(JavaThread* current, oopDesc* obj, BasicLock* lock))
399
assert(current->last_Java_sp(), "last_Java_sp must be set");
400
assert(oopDesc::is_oop(obj), "invalid lock object pointer dected");
401
SharedRuntime::monitor_exit_helper(obj, lock, current);
402
JRT_END
403
404
// Object.notify() fast path, caller does slow path
405
JRT_LEAF(jboolean, JVMCIRuntime::object_notify(JavaThread* current, oopDesc* obj))
406
407
// Very few notify/notifyAll operations find any threads on the waitset, so
408
// the dominant fast-path is to simply return.
409
// Relatedly, it's critical that notify/notifyAll be fast in order to
410
// reduce lock hold times.
411
if (!SafepointSynchronize::is_synchronizing()) {
412
if (ObjectSynchronizer::quick_notify(obj, current, false)) {
413
return true;
414
}
415
}
416
return false; // caller must perform slow path
417
418
JRT_END
419
420
// Object.notifyAll() fast path, caller does slow path
421
JRT_LEAF(jboolean, JVMCIRuntime::object_notifyAll(JavaThread* current, oopDesc* obj))
422
423
if (!SafepointSynchronize::is_synchronizing() ) {
424
if (ObjectSynchronizer::quick_notify(obj, current, true)) {
425
return true;
426
}
427
}
428
return false; // caller must perform slow path
429
430
JRT_END
431
432
JRT_BLOCK_ENTRY(int, JVMCIRuntime::throw_and_post_jvmti_exception(JavaThread* current, const char* exception, const char* message))
433
JRT_BLOCK;
434
TempNewSymbol symbol = SymbolTable::new_symbol(exception);
435
SharedRuntime::throw_and_post_jvmti_exception(current, symbol, message);
436
JRT_BLOCK_END;
437
return caller_is_deopted();
438
JRT_END
439
440
JRT_BLOCK_ENTRY(int, JVMCIRuntime::throw_klass_external_name_exception(JavaThread* current, const char* exception, Klass* klass))
441
JRT_BLOCK;
442
ResourceMark rm(current);
443
TempNewSymbol symbol = SymbolTable::new_symbol(exception);
444
SharedRuntime::throw_and_post_jvmti_exception(current, symbol, klass->external_name());
445
JRT_BLOCK_END;
446
return caller_is_deopted();
447
JRT_END
448
449
JRT_BLOCK_ENTRY(int, JVMCIRuntime::throw_class_cast_exception(JavaThread* current, const char* exception, Klass* caster_klass, Klass* target_klass))
450
JRT_BLOCK;
451
ResourceMark rm(current);
452
const char* message = SharedRuntime::generate_class_cast_message(caster_klass, target_klass);
453
TempNewSymbol symbol = SymbolTable::new_symbol(exception);
454
SharedRuntime::throw_and_post_jvmti_exception(current, symbol, message);
455
JRT_BLOCK_END;
456
return caller_is_deopted();
457
JRT_END
458
459
class ArgumentPusher : public SignatureIterator {
460
protected:
461
JavaCallArguments* _jca;
462
jlong _argument;
463
bool _pushed;
464
465
jlong next_arg() {
466
guarantee(!_pushed, "one argument");
467
_pushed = true;
468
return _argument;
469
}
470
471
float next_float() {
472
guarantee(!_pushed, "one argument");
473
_pushed = true;
474
jvalue v;
475
v.i = (jint) _argument;
476
return v.f;
477
}
478
479
double next_double() {
480
guarantee(!_pushed, "one argument");
481
_pushed = true;
482
jvalue v;
483
v.j = _argument;
484
return v.d;
485
}
486
487
Handle next_object() {
488
guarantee(!_pushed, "one argument");
489
_pushed = true;
490
return Handle(Thread::current(), cast_to_oop(_argument));
491
}
492
493
public:
494
ArgumentPusher(Symbol* signature, JavaCallArguments* jca, jlong argument) : SignatureIterator(signature) {
495
this->_return_type = T_ILLEGAL;
496
_jca = jca;
497
_argument = argument;
498
_pushed = false;
499
do_parameters_on(this);
500
}
501
502
void do_type(BasicType type) {
503
switch (type) {
504
case T_OBJECT:
505
case T_ARRAY: _jca->push_oop(next_object()); break;
506
case T_BOOLEAN: _jca->push_int((jboolean) next_arg()); break;
507
case T_CHAR: _jca->push_int((jchar) next_arg()); break;
508
case T_SHORT: _jca->push_int((jint) next_arg()); break;
509
case T_BYTE: _jca->push_int((jbyte) next_arg()); break;
510
case T_INT: _jca->push_int((jint) next_arg()); break;
511
case T_LONG: _jca->push_long((jlong) next_arg()); break;
512
case T_FLOAT: _jca->push_float(next_float()); break;
513
case T_DOUBLE: _jca->push_double(next_double()); break;
514
default: fatal("Unexpected type %s", type2name(type));
515
}
516
}
517
};
518
519
520
JRT_ENTRY(jlong, JVMCIRuntime::invoke_static_method_one_arg(JavaThread* current, Method* method, jlong argument))
521
ResourceMark rm;
522
HandleMark hm(current);
523
524
methodHandle mh(current, method);
525
if (mh->size_of_parameters() > 1 && !mh->is_static()) {
526
THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Invoked method must be static and take at most one argument");
527
}
528
529
Symbol* signature = mh->signature();
530
JavaCallArguments jca(mh->size_of_parameters());
531
ArgumentPusher jap(signature, &jca, argument);
532
BasicType return_type = jap.return_type();
533
JavaValue result(return_type);
534
JavaCalls::call(&result, mh, &jca, CHECK_0);
535
536
if (return_type == T_VOID) {
537
return 0;
538
} else if (return_type == T_OBJECT || return_type == T_ARRAY) {
539
current->set_vm_result(result.get_oop());
540
return 0;
541
} else {
542
jvalue *value = (jvalue *) result.get_value_addr();
543
// Narrow the value down if required (Important on big endian machines)
544
switch (return_type) {
545
case T_BOOLEAN:
546
return (jboolean) value->i;
547
case T_BYTE:
548
return (jbyte) value->i;
549
case T_CHAR:
550
return (jchar) value->i;
551
case T_SHORT:
552
return (jshort) value->i;
553
case T_INT:
554
case T_FLOAT:
555
return value->i;
556
case T_LONG:
557
case T_DOUBLE:
558
return value->j;
559
default:
560
fatal("Unexpected type %s", type2name(return_type));
561
return 0;
562
}
563
}
564
JRT_END
565
566
JRT_LEAF(void, JVMCIRuntime::log_object(JavaThread* thread, oopDesc* obj, bool as_string, bool newline))
567
ttyLocker ttyl;
568
569
if (obj == NULL) {
570
tty->print("NULL");
571
} else if (oopDesc::is_oop_or_null(obj, true) && (!as_string || !java_lang_String::is_instance(obj))) {
572
if (oopDesc::is_oop_or_null(obj, true)) {
573
char buf[O_BUFLEN];
574
tty->print("%s@" INTPTR_FORMAT, obj->klass()->name()->as_C_string(buf, O_BUFLEN), p2i(obj));
575
} else {
576
tty->print(INTPTR_FORMAT, p2i(obj));
577
}
578
} else {
579
ResourceMark rm;
580
assert(obj != NULL && java_lang_String::is_instance(obj), "must be");
581
char *buf = java_lang_String::as_utf8_string(obj);
582
tty->print_raw(buf);
583
}
584
if (newline) {
585
tty->cr();
586
}
587
JRT_END
588
589
#if INCLUDE_G1GC
590
591
void JVMCIRuntime::write_barrier_pre(JavaThread* thread, oopDesc* obj) {
592
G1BarrierSetRuntime::write_ref_field_pre_entry(obj, thread);
593
}
594
595
void JVMCIRuntime::write_barrier_post(JavaThread* thread, volatile CardValue* card_addr) {
596
G1BarrierSetRuntime::write_ref_field_post_entry(card_addr, thread);
597
}
598
599
#endif // INCLUDE_G1GC
600
601
JRT_LEAF(jboolean, JVMCIRuntime::validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child))
602
bool ret = true;
603
if(!Universe::heap()->is_in(parent)) {
604
tty->print_cr("Parent Object " INTPTR_FORMAT " not in heap", p2i(parent));
605
parent->print();
606
ret=false;
607
}
608
if(!Universe::heap()->is_in(child)) {
609
tty->print_cr("Child Object " INTPTR_FORMAT " not in heap", p2i(child));
610
child->print();
611
ret=false;
612
}
613
return (jint)ret;
614
JRT_END
615
616
JRT_ENTRY(void, JVMCIRuntime::vm_error(JavaThread* current, jlong where, jlong format, jlong value))
617
ResourceMark rm(current);
618
const char *error_msg = where == 0L ? "<internal JVMCI error>" : (char*) (address) where;
619
char *detail_msg = NULL;
620
if (format != 0L) {
621
const char* buf = (char*) (address) format;
622
size_t detail_msg_length = strlen(buf) * 2;
623
detail_msg = (char *) NEW_RESOURCE_ARRAY(u_char, detail_msg_length);
624
jio_snprintf(detail_msg, detail_msg_length, buf, value);
625
}
626
report_vm_error(__FILE__, __LINE__, error_msg, "%s", detail_msg);
627
JRT_END
628
629
JRT_LEAF(oopDesc*, JVMCIRuntime::load_and_clear_exception(JavaThread* thread))
630
oop exception = thread->exception_oop();
631
assert(exception != NULL, "npe");
632
thread->set_exception_oop(NULL);
633
thread->set_exception_pc(0);
634
return exception;
635
JRT_END
636
637
PRAGMA_DIAG_PUSH
638
PRAGMA_FORMAT_NONLITERAL_IGNORED
639
JRT_LEAF(void, JVMCIRuntime::log_printf(JavaThread* thread, const char* format, jlong v1, jlong v2, jlong v3))
640
ResourceMark rm;
641
tty->print(format, v1, v2, v3);
642
JRT_END
643
PRAGMA_DIAG_POP
644
645
static void decipher(jlong v, bool ignoreZero) {
646
if (v != 0 || !ignoreZero) {
647
void* p = (void *)(address) v;
648
CodeBlob* cb = CodeCache::find_blob(p);
649
if (cb) {
650
if (cb->is_nmethod()) {
651
char buf[O_BUFLEN];
652
tty->print("%s [" INTPTR_FORMAT "+" JLONG_FORMAT "]", cb->as_nmethod_or_null()->method()->name_and_sig_as_C_string(buf, O_BUFLEN), p2i(cb->code_begin()), (jlong)((address)v - cb->code_begin()));
653
return;
654
}
655
cb->print_value_on(tty);
656
return;
657
}
658
if (Universe::heap()->is_in(p)) {
659
oop obj = cast_to_oop(p);
660
obj->print_value_on(tty);
661
return;
662
}
663
tty->print(INTPTR_FORMAT " [long: " JLONG_FORMAT ", double %lf, char %c]",p2i((void *)v), (jlong)v, (jdouble)v, (char)v);
664
}
665
}
666
667
PRAGMA_DIAG_PUSH
668
PRAGMA_FORMAT_NONLITERAL_IGNORED
669
JRT_LEAF(void, JVMCIRuntime::vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3))
670
ResourceMark rm;
671
const char *buf = (const char*) (address) format;
672
if (vmError) {
673
if (buf != NULL) {
674
fatal(buf, v1, v2, v3);
675
} else {
676
fatal("<anonymous error>");
677
}
678
} else if (buf != NULL) {
679
tty->print(buf, v1, v2, v3);
680
} else {
681
assert(v2 == 0, "v2 != 0");
682
assert(v3 == 0, "v3 != 0");
683
decipher(v1, false);
684
}
685
JRT_END
686
PRAGMA_DIAG_POP
687
688
JRT_LEAF(void, JVMCIRuntime::log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline))
689
union {
690
jlong l;
691
jdouble d;
692
jfloat f;
693
} uu;
694
uu.l = value;
695
switch (typeChar) {
696
case 'Z': tty->print(value == 0 ? "false" : "true"); break;
697
case 'B': tty->print("%d", (jbyte) value); break;
698
case 'C': tty->print("%c", (jchar) value); break;
699
case 'S': tty->print("%d", (jshort) value); break;
700
case 'I': tty->print("%d", (jint) value); break;
701
case 'F': tty->print("%f", uu.f); break;
702
case 'J': tty->print(JLONG_FORMAT, value); break;
703
case 'D': tty->print("%lf", uu.d); break;
704
default: assert(false, "unknown typeChar"); break;
705
}
706
if (newline) {
707
tty->cr();
708
}
709
JRT_END
710
711
JRT_ENTRY(jint, JVMCIRuntime::identity_hash_code(JavaThread* current, oopDesc* obj))
712
return (jint) obj->identity_hash();
713
JRT_END
714
715
JRT_ENTRY(jint, JVMCIRuntime::test_deoptimize_call_int(JavaThread* current, int value))
716
deopt_caller();
717
return (jint) value;
718
JRT_END
719
720
721
// private static JVMCIRuntime JVMCI.initializeRuntime()
722
JVM_ENTRY_NO_ENV(jobject, JVM_GetJVMCIRuntime(JNIEnv *env, jclass c))
723
JNI_JVMCIENV(thread, env);
724
if (!EnableJVMCI) {
725
JVMCI_THROW_MSG_NULL(InternalError, "JVMCI is not enabled");
726
}
727
JVMCIENV->runtime()->initialize_HotSpotJVMCIRuntime(JVMCI_CHECK_NULL);
728
JVMCIObject runtime = JVMCIENV->runtime()->get_HotSpotJVMCIRuntime(JVMCI_CHECK_NULL);
729
return JVMCIENV->get_jobject(runtime);
730
JVM_END
731
732
void JVMCIRuntime::call_getCompiler(TRAPS) {
733
THREAD_JVMCIENV(JavaThread::current());
734
JVMCIObject jvmciRuntime = JVMCIRuntime::get_HotSpotJVMCIRuntime(JVMCI_CHECK);
735
initialize(JVMCIENV);
736
JVMCIENV->call_HotSpotJVMCIRuntime_getCompiler(jvmciRuntime, JVMCI_CHECK);
737
}
738
739
void JVMCINMethodData::initialize(
740
int nmethod_mirror_index,
741
const char* name,
742
FailedSpeculation** failed_speculations)
743
{
744
_failed_speculations = failed_speculations;
745
_nmethod_mirror_index = nmethod_mirror_index;
746
if (name != NULL) {
747
_has_name = true;
748
char* dest = (char*) this->name();
749
strcpy(dest, name);
750
} else {
751
_has_name = false;
752
}
753
}
754
755
void JVMCINMethodData::add_failed_speculation(nmethod* nm, jlong speculation) {
756
jlong index = speculation >> JVMCINMethodData::SPECULATION_LENGTH_BITS;
757
guarantee(index >= 0 && index <= max_jint, "Encoded JVMCI speculation index is not a positive Java int: " INTPTR_FORMAT, index);
758
int length = speculation & JVMCINMethodData::SPECULATION_LENGTH_MASK;
759
if (index + length > (uint) nm->speculations_size()) {
760
fatal(INTPTR_FORMAT "[index: " JLONG_FORMAT ", length: %d out of bounds wrt encoded speculations of length %u", speculation, index, length, nm->speculations_size());
761
}
762
address data = nm->speculations_begin() + index;
763
FailedSpeculation::add_failed_speculation(nm, _failed_speculations, data, length);
764
}
765
766
oop JVMCINMethodData::get_nmethod_mirror(nmethod* nm, bool phantom_ref) {
767
if (_nmethod_mirror_index == -1) {
768
return NULL;
769
}
770
if (phantom_ref) {
771
return nm->oop_at_phantom(_nmethod_mirror_index);
772
} else {
773
return nm->oop_at(_nmethod_mirror_index);
774
}
775
}
776
777
void JVMCINMethodData::set_nmethod_mirror(nmethod* nm, oop new_mirror) {
778
assert(_nmethod_mirror_index != -1, "cannot set JVMCI mirror for nmethod");
779
oop* addr = nm->oop_addr_at(_nmethod_mirror_index);
780
assert(new_mirror != NULL, "use clear_nmethod_mirror to clear the mirror");
781
assert(*addr == NULL, "cannot overwrite non-null mirror");
782
783
*addr = new_mirror;
784
785
// Since we've patched some oops in the nmethod,
786
// (re)register it with the heap.
787
MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
788
Universe::heap()->register_nmethod(nm);
789
}
790
791
void JVMCINMethodData::clear_nmethod_mirror(nmethod* nm) {
792
if (_nmethod_mirror_index != -1) {
793
oop* addr = nm->oop_addr_at(_nmethod_mirror_index);
794
*addr = NULL;
795
}
796
}
797
798
void JVMCINMethodData::invalidate_nmethod_mirror(nmethod* nm) {
799
oop nmethod_mirror = get_nmethod_mirror(nm, /* phantom_ref */ false);
800
if (nmethod_mirror == NULL) {
801
return;
802
}
803
804
// Update the values in the mirror if it still refers to nm.
805
// We cannot use JVMCIObject to wrap the mirror as this is called
806
// during GC, forbidding the creation of JNIHandles.
807
JVMCIEnv* jvmciEnv = NULL;
808
nmethod* current = (nmethod*) HotSpotJVMCI::InstalledCode::address(jvmciEnv, nmethod_mirror);
809
if (nm == current) {
810
if (!nm->is_alive()) {
811
// Break the link from the mirror to nm such that
812
// future invocations via the mirror will result in
813
// an InvalidInstalledCodeException.
814
HotSpotJVMCI::InstalledCode::set_address(jvmciEnv, nmethod_mirror, 0);
815
HotSpotJVMCI::InstalledCode::set_entryPoint(jvmciEnv, nmethod_mirror, 0);
816
} else if (nm->is_not_entrant()) {
817
// Zero the entry point so any new invocation will fail but keep
818
// the address link around that so that existing activations can
819
// be deoptimized via the mirror (i.e. JVMCIEnv::invalidate_installed_code).
820
HotSpotJVMCI::InstalledCode::set_entryPoint(jvmciEnv, nmethod_mirror, 0);
821
}
822
}
823
824
if (_nmethod_mirror_index != -1 && nm->is_unloaded()) {
825
// Drop the reference to the nmethod mirror object but don't clear the actual oop reference. Otherwise
826
// it would appear that the nmethod didn't need to be unloaded in the first place.
827
_nmethod_mirror_index = -1;
828
}
829
}
830
831
JVMCIRuntime::JVMCIRuntime(int id) {
832
_init_state = uninitialized;
833
_shared_library_javavm = NULL;
834
_id = id;
835
_metadata_handles = new MetadataHandles();
836
JVMCI_event_1("created new JVMCI runtime %d (" PTR_FORMAT ")", id, p2i(this));
837
}
838
839
// Handles to objects in the Hotspot heap.
840
static OopStorage* object_handles() {
841
return Universe::vm_global();
842
}
843
844
jobject JVMCIRuntime::make_global(const Handle& obj) {
845
assert(!Universe::heap()->is_gc_active(), "can't extend the root set during GC");
846
assert(oopDesc::is_oop(obj()), "not an oop");
847
oop* ptr = object_handles()->allocate();
848
jobject res = NULL;
849
if (ptr != NULL) {
850
assert(*ptr == NULL, "invariant");
851
NativeAccess<>::oop_store(ptr, obj());
852
res = reinterpret_cast<jobject>(ptr);
853
} else {
854
vm_exit_out_of_memory(sizeof(oop), OOM_MALLOC_ERROR,
855
"Cannot create JVMCI oop handle");
856
}
857
MutexLocker ml(JVMCI_lock);
858
return res;
859
}
860
861
void JVMCIRuntime::destroy_global(jobject handle) {
862
// Assert before nulling out, for better debugging.
863
assert(is_global_handle(handle), "precondition");
864
oop* oop_ptr = reinterpret_cast<oop*>(handle);
865
NativeAccess<>::oop_store(oop_ptr, (oop)NULL);
866
object_handles()->release(oop_ptr);
867
MutexLocker ml(JVMCI_lock);
868
}
869
870
bool JVMCIRuntime::is_global_handle(jobject handle) {
871
const oop* ptr = reinterpret_cast<oop*>(handle);
872
return object_handles()->allocation_status(ptr) == OopStorage::ALLOCATED_ENTRY;
873
}
874
875
jmetadata JVMCIRuntime::allocate_handle(const methodHandle& handle) {
876
MutexLocker ml(JVMCI_lock);
877
return _metadata_handles->allocate_handle(handle);
878
}
879
880
jmetadata JVMCIRuntime::allocate_handle(const constantPoolHandle& handle) {
881
MutexLocker ml(JVMCI_lock);
882
return _metadata_handles->allocate_handle(handle);
883
}
884
885
void JVMCIRuntime::release_handle(jmetadata handle) {
886
MutexLocker ml(JVMCI_lock);
887
_metadata_handles->chain_free_list(handle);
888
}
889
890
// Function for redirecting shared library JavaVM output to tty
891
static void _log(const char* buf, size_t count) {
892
tty->write((char*) buf, count);
893
}
894
895
// Function for shared library JavaVM to flush tty
896
static void _flush_log() {
897
tty->flush();
898
}
899
900
// Function for shared library JavaVM to exit HotSpot on a fatal error
901
static void _fatal() {
902
fatal("Fatal error in JVMCI shared library");
903
}
904
905
JNIEnv* JVMCIRuntime::init_shared_library_javavm() {
906
JavaVM* javaVM = (JavaVM*) _shared_library_javavm;
907
if (javaVM == NULL) {
908
MutexLocker locker(JVMCI_lock);
909
// Check again under JVMCI_lock
910
javaVM = (JavaVM*) _shared_library_javavm;
911
if (javaVM != NULL) {
912
return NULL;
913
}
914
char* sl_path;
915
void* sl_handle = JVMCI::get_shared_library(sl_path, true);
916
917
jint (*JNI_CreateJavaVM)(JavaVM **pvm, void **penv, void *args);
918
typedef jint (*JNI_CreateJavaVM_t)(JavaVM **pvm, void **penv, void *args);
919
920
JNI_CreateJavaVM = CAST_TO_FN_PTR(JNI_CreateJavaVM_t, os::dll_lookup(sl_handle, "JNI_CreateJavaVM"));
921
if (JNI_CreateJavaVM == NULL) {
922
fatal("Unable to find JNI_CreateJavaVM in %s", sl_path);
923
}
924
925
ResourceMark rm;
926
JavaVMInitArgs vm_args;
927
vm_args.version = JNI_VERSION_1_2;
928
vm_args.ignoreUnrecognized = JNI_TRUE;
929
JavaVMOption options[4];
930
jlong javaVM_id = 0;
931
932
// Protocol: JVMCI shared library JavaVM should support a non-standard "_javavm_id"
933
// option whose extraInfo info field is a pointer to which a unique id for the
934
// JavaVM should be written.
935
options[0].optionString = (char*) "_javavm_id";
936
options[0].extraInfo = &javaVM_id;
937
938
options[1].optionString = (char*) "_log";
939
options[1].extraInfo = (void*) _log;
940
options[2].optionString = (char*) "_flush_log";
941
options[2].extraInfo = (void*) _flush_log;
942
options[3].optionString = (char*) "_fatal";
943
options[3].extraInfo = (void*) _fatal;
944
945
vm_args.version = JNI_VERSION_1_2;
946
vm_args.options = options;
947
vm_args.nOptions = sizeof(options) / sizeof(JavaVMOption);
948
949
JNIEnv* env = NULL;
950
int result = (*JNI_CreateJavaVM)(&javaVM, (void**) &env, &vm_args);
951
if (result == JNI_OK) {
952
guarantee(env != NULL, "missing env");
953
_shared_library_javavm = javaVM;
954
JVMCI_event_1("created JavaVM[%ld]@" PTR_FORMAT " for JVMCI runtime %d", javaVM_id, p2i(javaVM), _id);
955
return env;
956
} else {
957
fatal("JNI_CreateJavaVM failed with return value %d", result);
958
}
959
}
960
return NULL;
961
}
962
963
void JVMCIRuntime::init_JavaVM_info(jlongArray info, JVMCI_TRAPS) {
964
if (info != NULL) {
965
typeArrayOop info_oop = (typeArrayOop) JNIHandles::resolve(info);
966
if (info_oop->length() < 4) {
967
JVMCI_THROW_MSG(ArrayIndexOutOfBoundsException, err_msg("%d < 4", info_oop->length()));
968
}
969
JavaVM* javaVM = (JavaVM*) _shared_library_javavm;
970
info_oop->long_at_put(0, (jlong) (address) javaVM);
971
info_oop->long_at_put(1, (jlong) (address) javaVM->functions->reserved0);
972
info_oop->long_at_put(2, (jlong) (address) javaVM->functions->reserved1);
973
info_oop->long_at_put(3, (jlong) (address) javaVM->functions->reserved2);
974
}
975
}
976
977
#define JAVAVM_CALL_BLOCK \
978
guarantee(thread != NULL && _shared_library_javavm != NULL, "npe"); \
979
ThreadToNativeFromVM ttnfv(thread); \
980
JavaVM* javavm = (JavaVM*) _shared_library_javavm;
981
982
jint JVMCIRuntime::AttachCurrentThread(JavaThread* thread, void **penv, void *args) {
983
JAVAVM_CALL_BLOCK
984
return javavm->AttachCurrentThread(penv, args);
985
}
986
987
jint JVMCIRuntime::AttachCurrentThreadAsDaemon(JavaThread* thread, void **penv, void *args) {
988
JAVAVM_CALL_BLOCK
989
return javavm->AttachCurrentThreadAsDaemon(penv, args);
990
}
991
992
jint JVMCIRuntime::DetachCurrentThread(JavaThread* thread) {
993
JAVAVM_CALL_BLOCK
994
return javavm->DetachCurrentThread();
995
}
996
997
jint JVMCIRuntime::GetEnv(JavaThread* thread, void **penv, jint version) {
998
JAVAVM_CALL_BLOCK
999
return javavm->GetEnv(penv, version);
1000
}
1001
#undef JAVAVM_CALL_BLOCK \
1002
1003
void JVMCIRuntime::initialize_HotSpotJVMCIRuntime(JVMCI_TRAPS) {
1004
if (is_HotSpotJVMCIRuntime_initialized()) {
1005
if (JVMCIENV->is_hotspot() && UseJVMCINativeLibrary) {
1006
JVMCI_THROW_MSG(InternalError, "JVMCI has already been enabled in the JVMCI shared library");
1007
}
1008
}
1009
1010
initialize(JVMCIENV);
1011
1012
// This should only be called in the context of the JVMCI class being initialized
1013
JVMCIObject result = JVMCIENV->call_HotSpotJVMCIRuntime_runtime(JVMCI_CHECK);
1014
result = JVMCIENV->make_global(result);
1015
1016
OrderAccess::storestore(); // Ensure handle is fully constructed before publishing
1017
_HotSpotJVMCIRuntime_instance = result;
1018
1019
JVMCI::_is_initialized = true;
1020
}
1021
1022
void JVMCIRuntime::initialize(JVMCIEnv* JVMCIENV) {
1023
// Check first without JVMCI_lock
1024
if (_init_state == fully_initialized) {
1025
return;
1026
}
1027
1028
MutexLocker locker(JVMCI_lock);
1029
// Check again under JVMCI_lock
1030
if (_init_state == fully_initialized) {
1031
return;
1032
}
1033
1034
while (_init_state == being_initialized) {
1035
JVMCI_event_1("waiting for initialization of JVMCI runtime %d", _id);
1036
JVMCI_lock->wait();
1037
if (_init_state == fully_initialized) {
1038
JVMCI_event_1("done waiting for initialization of JVMCI runtime %d", _id);
1039
return;
1040
}
1041
}
1042
1043
JVMCI_event_1("initializing JVMCI runtime %d", _id);
1044
_init_state = being_initialized;
1045
1046
{
1047
MutexUnlocker unlock(JVMCI_lock);
1048
1049
JavaThread* THREAD = JavaThread::current(); // For exception macros.
1050
HandleMark hm(THREAD);
1051
ResourceMark rm(THREAD);
1052
if (JVMCIENV->is_hotspot()) {
1053
HotSpotJVMCI::compute_offsets(CHECK_EXIT);
1054
} else {
1055
JNIAccessMark jni(JVMCIENV);
1056
1057
JNIJVMCI::initialize_ids(jni.env());
1058
if (jni()->ExceptionCheck()) {
1059
jni()->ExceptionDescribe();
1060
fatal("JNI exception during init");
1061
}
1062
}
1063
1064
if (!JVMCIENV->is_hotspot()) {
1065
JNIAccessMark jni(JVMCIENV, THREAD);
1066
JNIJVMCI::register_natives(jni.env());
1067
}
1068
create_jvmci_primitive_type(T_BOOLEAN, JVMCI_CHECK_EXIT_((void)0));
1069
create_jvmci_primitive_type(T_BYTE, JVMCI_CHECK_EXIT_((void)0));
1070
create_jvmci_primitive_type(T_CHAR, JVMCI_CHECK_EXIT_((void)0));
1071
create_jvmci_primitive_type(T_SHORT, JVMCI_CHECK_EXIT_((void)0));
1072
create_jvmci_primitive_type(T_INT, JVMCI_CHECK_EXIT_((void)0));
1073
create_jvmci_primitive_type(T_LONG, JVMCI_CHECK_EXIT_((void)0));
1074
create_jvmci_primitive_type(T_FLOAT, JVMCI_CHECK_EXIT_((void)0));
1075
create_jvmci_primitive_type(T_DOUBLE, JVMCI_CHECK_EXIT_((void)0));
1076
create_jvmci_primitive_type(T_VOID, JVMCI_CHECK_EXIT_((void)0));
1077
1078
if (!JVMCIENV->is_hotspot()) {
1079
JVMCIENV->copy_saved_properties();
1080
}
1081
}
1082
1083
_init_state = fully_initialized;
1084
JVMCI_event_1("initialized JVMCI runtime %d", _id);
1085
JVMCI_lock->notify_all();
1086
}
1087
1088
JVMCIObject JVMCIRuntime::create_jvmci_primitive_type(BasicType type, JVMCI_TRAPS) {
1089
JavaThread* THREAD = JavaThread::current(); // For exception macros.
1090
// These primitive types are long lived and are created before the runtime is fully set up
1091
// so skip registering them for scanning.
1092
JVMCIObject mirror = JVMCIENV->get_object_constant(java_lang_Class::primitive_mirror(type), false, true);
1093
if (JVMCIENV->is_hotspot()) {
1094
JavaValue result(T_OBJECT);
1095
JavaCallArguments args;
1096
args.push_oop(Handle(THREAD, HotSpotJVMCI::resolve(mirror)));
1097
args.push_int(type2char(type));
1098
JavaCalls::call_static(&result, HotSpotJVMCI::HotSpotResolvedPrimitiveType::klass(), vmSymbols::fromMetaspace_name(), vmSymbols::primitive_fromMetaspace_signature(), &args, CHECK_(JVMCIObject()));
1099
1100
return JVMCIENV->wrap(JNIHandles::make_local(result.get_oop()));
1101
} else {
1102
JNIAccessMark jni(JVMCIENV);
1103
jobject result = jni()->CallStaticObjectMethod(JNIJVMCI::HotSpotResolvedPrimitiveType::clazz(),
1104
JNIJVMCI::HotSpotResolvedPrimitiveType_fromMetaspace_method(),
1105
mirror.as_jobject(), type2char(type));
1106
if (jni()->ExceptionCheck()) {
1107
return JVMCIObject();
1108
}
1109
return JVMCIENV->wrap(result);
1110
}
1111
}
1112
1113
void JVMCIRuntime::initialize_JVMCI(JVMCI_TRAPS) {
1114
if (!is_HotSpotJVMCIRuntime_initialized()) {
1115
initialize(JVMCI_CHECK);
1116
JVMCIENV->call_JVMCI_getRuntime(JVMCI_CHECK);
1117
}
1118
}
1119
1120
JVMCIObject JVMCIRuntime::get_HotSpotJVMCIRuntime(JVMCI_TRAPS) {
1121
initialize(JVMCIENV);
1122
initialize_JVMCI(JVMCI_CHECK_(JVMCIObject()));
1123
return _HotSpotJVMCIRuntime_instance;
1124
}
1125
1126
// private static void CompilerToVM.registerNatives()
1127
JVM_ENTRY_NO_ENV(void, JVM_RegisterJVMCINatives(JNIEnv *env, jclass c2vmClass))
1128
JNI_JVMCIENV(thread, env);
1129
1130
if (!EnableJVMCI) {
1131
JVMCI_THROW_MSG(InternalError, "JVMCI is not enabled");
1132
}
1133
1134
JVMCIENV->runtime()->initialize(JVMCIENV);
1135
1136
{
1137
ResourceMark rm(thread);
1138
HandleMark hm(thread);
1139
ThreadToNativeFromVM trans(thread);
1140
1141
// Ensure _non_oop_bits is initialized
1142
Universe::non_oop_word();
1143
1144
if (JNI_OK != env->RegisterNatives(c2vmClass, CompilerToVM::methods, CompilerToVM::methods_count())) {
1145
if (!env->ExceptionCheck()) {
1146
for (int i = 0; i < CompilerToVM::methods_count(); i++) {
1147
if (JNI_OK != env->RegisterNatives(c2vmClass, CompilerToVM::methods + i, 1)) {
1148
guarantee(false, "Error registering JNI method %s%s", CompilerToVM::methods[i].name, CompilerToVM::methods[i].signature);
1149
break;
1150
}
1151
}
1152
} else {
1153
env->ExceptionDescribe();
1154
}
1155
guarantee(false, "Failed registering CompilerToVM native methods");
1156
}
1157
}
1158
JVM_END
1159
1160
1161
void JVMCIRuntime::shutdown() {
1162
if (_HotSpotJVMCIRuntime_instance.is_non_null()) {
1163
JVMCI_event_1("shutting down HotSpotJVMCIRuntime for JVMCI runtime %d", _id);
1164
JVMCIEnv __stack_jvmci_env__(JavaThread::current(), _HotSpotJVMCIRuntime_instance.is_hotspot(), __FILE__, __LINE__);
1165
JVMCIEnv* JVMCIENV = &__stack_jvmci_env__;
1166
JVMCIENV->call_HotSpotJVMCIRuntime_shutdown(_HotSpotJVMCIRuntime_instance);
1167
JVMCI_event_1("shut down HotSpotJVMCIRuntime for JVMCI runtime %d", _id);
1168
}
1169
}
1170
1171
void JVMCIRuntime::bootstrap_finished(TRAPS) {
1172
if (_HotSpotJVMCIRuntime_instance.is_non_null()) {
1173
THREAD_JVMCIENV(JavaThread::current());
1174
JVMCIENV->call_HotSpotJVMCIRuntime_bootstrapFinished(_HotSpotJVMCIRuntime_instance, JVMCIENV);
1175
}
1176
}
1177
1178
void JVMCIRuntime::describe_pending_hotspot_exception(JavaThread* THREAD, bool clear) {
1179
if (HAS_PENDING_EXCEPTION) {
1180
Handle exception(THREAD, PENDING_EXCEPTION);
1181
const char* exception_file = THREAD->exception_file();
1182
int exception_line = THREAD->exception_line();
1183
CLEAR_PENDING_EXCEPTION;
1184
if (exception->is_a(vmClasses::ThreadDeath_klass())) {
1185
// Don't print anything if we are being killed.
1186
} else {
1187
java_lang_Throwable::print_stack_trace(exception, tty);
1188
1189
// Clear and ignore any exceptions raised during printing
1190
CLEAR_PENDING_EXCEPTION;
1191
}
1192
if (!clear) {
1193
THREAD->set_pending_exception(exception(), exception_file, exception_line);
1194
}
1195
}
1196
}
1197
1198
1199
void JVMCIRuntime::fatal_exception(JVMCIEnv* JVMCIENV, const char* message) {
1200
JavaThread* THREAD = JavaThread::current(); // For exception macros.
1201
1202
static volatile int report_error = 0;
1203
if (!report_error && Atomic::cmpxchg(&report_error, 0, 1) == 0) {
1204
// Only report an error once
1205
tty->print_raw_cr(message);
1206
if (JVMCIENV != NULL) {
1207
JVMCIENV->describe_pending_exception(true);
1208
} else {
1209
describe_pending_hotspot_exception(THREAD, true);
1210
}
1211
} else {
1212
// Allow error reporting thread to print the stack trace.
1213
THREAD->sleep(200);
1214
}
1215
fatal("Fatal exception in JVMCI: %s", message);
1216
}
1217
1218
// ------------------------------------------------------------------
1219
// Note: the logic of this method should mirror the logic of
1220
// constantPoolOopDesc::verify_constant_pool_resolve.
1221
bool JVMCIRuntime::check_klass_accessibility(Klass* accessing_klass, Klass* resolved_klass) {
1222
if (accessing_klass->is_objArray_klass()) {
1223
accessing_klass = ObjArrayKlass::cast(accessing_klass)->bottom_klass();
1224
}
1225
if (!accessing_klass->is_instance_klass()) {
1226
return true;
1227
}
1228
1229
if (resolved_klass->is_objArray_klass()) {
1230
// Find the element klass, if this is an array.
1231
resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass();
1232
}
1233
if (resolved_klass->is_instance_klass()) {
1234
Reflection::VerifyClassAccessResults result =
1235
Reflection::verify_class_access(accessing_klass, InstanceKlass::cast(resolved_klass), true);
1236
return result == Reflection::ACCESS_OK;
1237
}
1238
return true;
1239
}
1240
1241
// ------------------------------------------------------------------
1242
Klass* JVMCIRuntime::get_klass_by_name_impl(Klass*& accessing_klass,
1243
const constantPoolHandle& cpool,
1244
Symbol* sym,
1245
bool require_local) {
1246
JVMCI_EXCEPTION_CONTEXT;
1247
1248
// Now we need to check the SystemDictionary
1249
if (sym->char_at(0) == JVM_SIGNATURE_CLASS &&
1250
sym->char_at(sym->utf8_length()-1) == JVM_SIGNATURE_ENDCLASS) {
1251
// This is a name from a signature. Strip off the trimmings.
1252
// Call recursive to keep scope of strippedsym.
1253
TempNewSymbol strippedsym = SymbolTable::new_symbol(sym->as_utf8()+1,
1254
sym->utf8_length()-2);
1255
return get_klass_by_name_impl(accessing_klass, cpool, strippedsym, require_local);
1256
}
1257
1258
Handle loader;
1259
Handle domain;
1260
if (accessing_klass != NULL) {
1261
loader = Handle(THREAD, accessing_klass->class_loader());
1262
domain = Handle(THREAD, accessing_klass->protection_domain());
1263
}
1264
1265
Klass* found_klass;
1266
{
1267
ttyUnlocker ttyul; // release tty lock to avoid ordering problems
1268
MutexLocker ml(THREAD, Compile_lock);
1269
if (!require_local) {
1270
found_klass = SystemDictionary::find_constrained_instance_or_array_klass(THREAD, sym, loader);
1271
} else {
1272
found_klass = SystemDictionary::find_instance_or_array_klass(sym, loader, domain);
1273
}
1274
}
1275
1276
// If we fail to find an array klass, look again for its element type.
1277
// The element type may be available either locally or via constraints.
1278
// In either case, if we can find the element type in the system dictionary,
1279
// we must build an array type around it. The CI requires array klasses
1280
// to be loaded if their element klasses are loaded, except when memory
1281
// is exhausted.
1282
if (sym->char_at(0) == JVM_SIGNATURE_ARRAY &&
1283
(sym->char_at(1) == JVM_SIGNATURE_ARRAY || sym->char_at(1) == JVM_SIGNATURE_CLASS)) {
1284
// We have an unloaded array.
1285
// Build it on the fly if the element class exists.
1286
TempNewSymbol elem_sym = SymbolTable::new_symbol(sym->as_utf8()+1,
1287
sym->utf8_length()-1);
1288
1289
// Get element Klass recursively.
1290
Klass* elem_klass =
1291
get_klass_by_name_impl(accessing_klass,
1292
cpool,
1293
elem_sym,
1294
require_local);
1295
if (elem_klass != NULL) {
1296
// Now make an array for it
1297
return elem_klass->array_klass(THREAD);
1298
}
1299
}
1300
1301
if (found_klass == NULL && !cpool.is_null() && cpool->has_preresolution()) {
1302
// Look inside the constant pool for pre-resolved class entries.
1303
for (int i = cpool->length() - 1; i >= 1; i--) {
1304
if (cpool->tag_at(i).is_klass()) {
1305
Klass* kls = cpool->resolved_klass_at(i);
1306
if (kls->name() == sym) {
1307
return kls;
1308
}
1309
}
1310
}
1311
}
1312
1313
return found_klass;
1314
}
1315
1316
// ------------------------------------------------------------------
1317
Klass* JVMCIRuntime::get_klass_by_name(Klass* accessing_klass,
1318
Symbol* klass_name,
1319
bool require_local) {
1320
ResourceMark rm;
1321
constantPoolHandle cpool;
1322
return get_klass_by_name_impl(accessing_klass,
1323
cpool,
1324
klass_name,
1325
require_local);
1326
}
1327
1328
// ------------------------------------------------------------------
1329
// Implementation of get_klass_by_index.
1330
Klass* JVMCIRuntime::get_klass_by_index_impl(const constantPoolHandle& cpool,
1331
int index,
1332
bool& is_accessible,
1333
Klass* accessor) {
1334
JVMCI_EXCEPTION_CONTEXT;
1335
Klass* klass = ConstantPool::klass_at_if_loaded(cpool, index);
1336
Symbol* klass_name = NULL;
1337
if (klass == NULL) {
1338
klass_name = cpool->klass_name_at(index);
1339
}
1340
1341
if (klass == NULL) {
1342
// Not found in constant pool. Use the name to do the lookup.
1343
Klass* k = get_klass_by_name_impl(accessor,
1344
cpool,
1345
klass_name,
1346
false);
1347
// Calculate accessibility the hard way.
1348
if (k == NULL) {
1349
is_accessible = false;
1350
} else if (k->class_loader() != accessor->class_loader() &&
1351
get_klass_by_name_impl(accessor, cpool, k->name(), true) == NULL) {
1352
// Loaded only remotely. Not linked yet.
1353
is_accessible = false;
1354
} else {
1355
// Linked locally, and we must also check public/private, etc.
1356
is_accessible = check_klass_accessibility(accessor, k);
1357
}
1358
if (!is_accessible) {
1359
return NULL;
1360
}
1361
return k;
1362
}
1363
1364
// It is known to be accessible, since it was found in the constant pool.
1365
is_accessible = true;
1366
return klass;
1367
}
1368
1369
// ------------------------------------------------------------------
1370
// Get a klass from the constant pool.
1371
Klass* JVMCIRuntime::get_klass_by_index(const constantPoolHandle& cpool,
1372
int index,
1373
bool& is_accessible,
1374
Klass* accessor) {
1375
ResourceMark rm;
1376
Klass* result = get_klass_by_index_impl(cpool, index, is_accessible, accessor);
1377
return result;
1378
}
1379
1380
// ------------------------------------------------------------------
1381
// Implementation of get_field_by_index.
1382
//
1383
// Implementation note: the results of field lookups are cached
1384
// in the accessor klass.
1385
void JVMCIRuntime::get_field_by_index_impl(InstanceKlass* klass, fieldDescriptor& field_desc,
1386
int index) {
1387
JVMCI_EXCEPTION_CONTEXT;
1388
1389
assert(klass->is_linked(), "must be linked before using its constant-pool");
1390
1391
constantPoolHandle cpool(thread, klass->constants());
1392
1393
// Get the field's name, signature, and type.
1394
Symbol* name = cpool->name_ref_at(index);
1395
1396
int nt_index = cpool->name_and_type_ref_index_at(index);
1397
int sig_index = cpool->signature_ref_index_at(nt_index);
1398
Symbol* signature = cpool->symbol_at(sig_index);
1399
1400
// Get the field's declared holder.
1401
int holder_index = cpool->klass_ref_index_at(index);
1402
bool holder_is_accessible;
1403
Klass* declared_holder = get_klass_by_index(cpool, holder_index,
1404
holder_is_accessible,
1405
klass);
1406
1407
// The declared holder of this field may not have been loaded.
1408
// Bail out with partial field information.
1409
if (!holder_is_accessible) {
1410
return;
1411
}
1412
1413
1414
// Perform the field lookup.
1415
Klass* canonical_holder =
1416
InstanceKlass::cast(declared_holder)->find_field(name, signature, &field_desc);
1417
if (canonical_holder == NULL) {
1418
return;
1419
}
1420
1421
assert(canonical_holder == field_desc.field_holder(), "just checking");
1422
}
1423
1424
// ------------------------------------------------------------------
1425
// Get a field by index from a klass's constant pool.
1426
void JVMCIRuntime::get_field_by_index(InstanceKlass* accessor, fieldDescriptor& fd, int index) {
1427
ResourceMark rm;
1428
return get_field_by_index_impl(accessor, fd, index);
1429
}
1430
1431
// ------------------------------------------------------------------
1432
// Perform an appropriate method lookup based on accessor, holder,
1433
// name, signature, and bytecode.
1434
Method* JVMCIRuntime::lookup_method(InstanceKlass* accessor,
1435
Klass* holder,
1436
Symbol* name,
1437
Symbol* sig,
1438
Bytecodes::Code bc,
1439
constantTag tag) {
1440
// Accessibility checks are performed in JVMCIEnv::get_method_by_index_impl().
1441
assert(check_klass_accessibility(accessor, holder), "holder not accessible");
1442
1443
LinkInfo link_info(holder, name, sig, accessor,
1444
LinkInfo::AccessCheck::required,
1445
LinkInfo::LoaderConstraintCheck::required,
1446
tag);
1447
switch (bc) {
1448
case Bytecodes::_invokestatic:
1449
return LinkResolver::resolve_static_call_or_null(link_info);
1450
case Bytecodes::_invokespecial:
1451
return LinkResolver::resolve_special_call_or_null(link_info);
1452
case Bytecodes::_invokeinterface:
1453
return LinkResolver::linktime_resolve_interface_method_or_null(link_info);
1454
case Bytecodes::_invokevirtual:
1455
return LinkResolver::linktime_resolve_virtual_method_or_null(link_info);
1456
default:
1457
fatal("Unhandled bytecode: %s", Bytecodes::name(bc));
1458
return NULL; // silence compiler warnings
1459
}
1460
}
1461
1462
1463
// ------------------------------------------------------------------
1464
Method* JVMCIRuntime::get_method_by_index_impl(const constantPoolHandle& cpool,
1465
int index, Bytecodes::Code bc,
1466
InstanceKlass* accessor) {
1467
if (bc == Bytecodes::_invokedynamic) {
1468
ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index);
1469
bool is_resolved = !cpce->is_f1_null();
1470
if (is_resolved) {
1471
// Get the invoker Method* from the constant pool.
1472
// (The appendix argument, if any, will be noted in the method's signature.)
1473
Method* adapter = cpce->f1_as_method();
1474
return adapter;
1475
}
1476
1477
return NULL;
1478
}
1479
1480
int holder_index = cpool->klass_ref_index_at(index);
1481
bool holder_is_accessible;
1482
Klass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);
1483
1484
// Get the method's name and signature.
1485
Symbol* name_sym = cpool->name_ref_at(index);
1486
Symbol* sig_sym = cpool->signature_ref_at(index);
1487
1488
if (cpool->has_preresolution()
1489
|| ((holder == vmClasses::MethodHandle_klass() || holder == vmClasses::VarHandle_klass()) &&
1490
MethodHandles::is_signature_polymorphic_name(holder, name_sym))) {
1491
// Short-circuit lookups for JSR 292-related call sites.
1492
// That is, do not rely only on name-based lookups, because they may fail
1493
// if the names are not resolvable in the boot class loader (7056328).
1494
switch (bc) {
1495
case Bytecodes::_invokevirtual:
1496
case Bytecodes::_invokeinterface:
1497
case Bytecodes::_invokespecial:
1498
case Bytecodes::_invokestatic:
1499
{
1500
Method* m = ConstantPool::method_at_if_loaded(cpool, index);
1501
if (m != NULL) {
1502
return m;
1503
}
1504
}
1505
break;
1506
default:
1507
break;
1508
}
1509
}
1510
1511
if (holder_is_accessible) { // Our declared holder is loaded.
1512
constantTag tag = cpool->tag_ref_at(index);
1513
Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);
1514
if (m != NULL) {
1515
// We found the method.
1516
return m;
1517
}
1518
}
1519
1520
// Either the declared holder was not loaded, or the method could
1521
// not be found.
1522
1523
return NULL;
1524
}
1525
1526
// ------------------------------------------------------------------
1527
InstanceKlass* JVMCIRuntime::get_instance_klass_for_declared_method_holder(Klass* method_holder) {
1528
// For the case of <array>.clone(), the method holder can be an ArrayKlass*
1529
// instead of an InstanceKlass*. For that case simply pretend that the
1530
// declared holder is Object.clone since that's where the call will bottom out.
1531
if (method_holder->is_instance_klass()) {
1532
return InstanceKlass::cast(method_holder);
1533
} else if (method_holder->is_array_klass()) {
1534
return vmClasses::Object_klass();
1535
} else {
1536
ShouldNotReachHere();
1537
}
1538
return NULL;
1539
}
1540
1541
1542
// ------------------------------------------------------------------
1543
Method* JVMCIRuntime::get_method_by_index(const constantPoolHandle& cpool,
1544
int index, Bytecodes::Code bc,
1545
InstanceKlass* accessor) {
1546
ResourceMark rm;
1547
return get_method_by_index_impl(cpool, index, bc, accessor);
1548
}
1549
1550
// ------------------------------------------------------------------
1551
// Check for changes to the system dictionary during compilation
1552
// class loads, evolution, breakpoints
1553
JVMCI::CodeInstallResult JVMCIRuntime::validate_compile_task_dependencies(Dependencies* dependencies, JVMCICompileState* compile_state, char** failure_detail) {
1554
// If JVMTI capabilities were enabled during compile, the compilation is invalidated.
1555
if (compile_state != NULL && compile_state->jvmti_state_changed()) {
1556
*failure_detail = (char*) "Jvmti state change during compilation invalidated dependencies";
1557
return JVMCI::dependencies_failed;
1558
}
1559
1560
CompileTask* task = compile_state == NULL ? NULL : compile_state->task();
1561
Dependencies::DepType result = dependencies->validate_dependencies(task, failure_detail);
1562
if (result == Dependencies::end_marker) {
1563
return JVMCI::ok;
1564
}
1565
1566
return JVMCI::dependencies_failed;
1567
}
1568
1569
void JVMCIRuntime::compile_method(JVMCIEnv* JVMCIENV, JVMCICompiler* compiler, const methodHandle& method, int entry_bci) {
1570
JVMCI_EXCEPTION_CONTEXT
1571
1572
JVMCICompileState* compile_state = JVMCIENV->compile_state();
1573
1574
bool is_osr = entry_bci != InvocationEntryBci;
1575
if (compiler->is_bootstrapping() && is_osr) {
1576
// no OSR compilations during bootstrap - the compiler is just too slow at this point,
1577
// and we know that there are no endless loops
1578
compile_state->set_failure(true, "No OSR during bootstrap");
1579
return;
1580
}
1581
if (JVMCI::in_shutdown()) {
1582
compile_state->set_failure(false, "Avoiding compilation during shutdown");
1583
return;
1584
}
1585
1586
HandleMark hm(thread);
1587
JVMCIObject receiver = get_HotSpotJVMCIRuntime(JVMCIENV);
1588
if (JVMCIENV->has_pending_exception()) {
1589
fatal_exception(JVMCIENV, "Exception during HotSpotJVMCIRuntime initialization");
1590
}
1591
JVMCIObject jvmci_method = JVMCIENV->get_jvmci_method(method, JVMCIENV);
1592
if (JVMCIENV->has_pending_exception()) {
1593
JVMCIENV->describe_pending_exception(true);
1594
compile_state->set_failure(false, "exception getting JVMCI wrapper method");
1595
return;
1596
}
1597
1598
JVMCIObject result_object = JVMCIENV->call_HotSpotJVMCIRuntime_compileMethod(receiver, jvmci_method, entry_bci,
1599
(jlong) compile_state, compile_state->task()->compile_id());
1600
if (!JVMCIENV->has_pending_exception()) {
1601
if (result_object.is_non_null()) {
1602
JVMCIObject failure_message = JVMCIENV->get_HotSpotCompilationRequestResult_failureMessage(result_object);
1603
if (failure_message.is_non_null()) {
1604
// Copy failure reason into resource memory first ...
1605
const char* failure_reason = JVMCIENV->as_utf8_string(failure_message);
1606
// ... and then into the C heap.
1607
failure_reason = os::strdup(failure_reason, mtJVMCI);
1608
bool retryable = JVMCIENV->get_HotSpotCompilationRequestResult_retry(result_object) != 0;
1609
compile_state->set_failure(retryable, failure_reason, true);
1610
} else {
1611
if (compile_state->task()->code() == NULL) {
1612
compile_state->set_failure(true, "no nmethod produced");
1613
} else {
1614
compile_state->task()->set_num_inlined_bytecodes(JVMCIENV->get_HotSpotCompilationRequestResult_inlinedBytecodes(result_object));
1615
compiler->inc_methods_compiled();
1616
}
1617
}
1618
} else {
1619
assert(false, "JVMCICompiler.compileMethod should always return non-null");
1620
}
1621
} else {
1622
// An uncaught exception here implies failure during compiler initialization.
1623
// The only sensible thing to do here is to exit the VM.
1624
fatal_exception(JVMCIENV, "Exception during JVMCI compiler initialization");
1625
}
1626
if (compiler->is_bootstrapping()) {
1627
compiler->set_bootstrap_compilation_request_handled();
1628
}
1629
}
1630
1631
bool JVMCIRuntime::is_gc_supported(JVMCIEnv* JVMCIENV, CollectedHeap::Name name) {
1632
JVMCI_EXCEPTION_CONTEXT
1633
1634
JVMCIObject receiver = get_HotSpotJVMCIRuntime(JVMCIENV);
1635
if (JVMCIENV->has_pending_exception()) {
1636
fatal_exception(JVMCIENV, "Exception during HotSpotJVMCIRuntime initialization");
1637
}
1638
return JVMCIENV->call_HotSpotJVMCIRuntime_isGCSupported(receiver, (int) name);
1639
}
1640
1641
// ------------------------------------------------------------------
1642
JVMCI::CodeInstallResult JVMCIRuntime::register_method(JVMCIEnv* JVMCIENV,
1643
const methodHandle& method,
1644
nmethod*& nm,
1645
int entry_bci,
1646
CodeOffsets* offsets,
1647
int orig_pc_offset,
1648
CodeBuffer* code_buffer,
1649
int frame_words,
1650
OopMapSet* oop_map_set,
1651
ExceptionHandlerTable* handler_table,
1652
ImplicitExceptionTable* implicit_exception_table,
1653
AbstractCompiler* compiler,
1654
DebugInformationRecorder* debug_info,
1655
Dependencies* dependencies,
1656
int compile_id,
1657
bool has_unsafe_access,
1658
bool has_wide_vector,
1659
JVMCIObject compiled_code,
1660
JVMCIObject nmethod_mirror,
1661
FailedSpeculation** failed_speculations,
1662
char* speculations,
1663
int speculations_len) {
1664
JVMCI_EXCEPTION_CONTEXT;
1665
nm = NULL;
1666
int comp_level = CompLevel_full_optimization;
1667
char* failure_detail = NULL;
1668
1669
bool install_default = JVMCIENV->get_HotSpotNmethod_isDefault(nmethod_mirror) != 0;
1670
assert(JVMCIENV->isa_HotSpotNmethod(nmethod_mirror), "must be");
1671
JVMCIObject name = JVMCIENV->get_InstalledCode_name(nmethod_mirror);
1672
const char* nmethod_mirror_name = name.is_null() ? NULL : JVMCIENV->as_utf8_string(name);
1673
int nmethod_mirror_index;
1674
if (!install_default) {
1675
// Reserve or initialize mirror slot in the oops table.
1676
OopRecorder* oop_recorder = debug_info->oop_recorder();
1677
nmethod_mirror_index = oop_recorder->allocate_oop_index(nmethod_mirror.is_hotspot() ? nmethod_mirror.as_jobject() : NULL);
1678
} else {
1679
// A default HotSpotNmethod mirror is never tracked by the nmethod
1680
nmethod_mirror_index = -1;
1681
}
1682
1683
JVMCI::CodeInstallResult result(JVMCI::ok);
1684
1685
// We require method counters to store some method state (max compilation levels) required by the compilation policy.
1686
if (method->get_method_counters(THREAD) == NULL) {
1687
result = JVMCI::cache_full;
1688
failure_detail = (char*) "can't create method counters";
1689
}
1690
1691
if (result == JVMCI::ok) {
1692
// To prevent compile queue updates.
1693
MutexLocker locker(THREAD, MethodCompileQueue_lock);
1694
1695
// Prevent SystemDictionary::add_to_hierarchy from running
1696
// and invalidating our dependencies until we install this method.
1697
MutexLocker ml(Compile_lock);
1698
1699
// Encode the dependencies now, so we can check them right away.
1700
dependencies->encode_content_bytes();
1701
1702
// Record the dependencies for the current compile in the log
1703
if (LogCompilation) {
1704
for (Dependencies::DepStream deps(dependencies); deps.next(); ) {
1705
deps.log_dependency();
1706
}
1707
}
1708
1709
// Check for {class loads, evolution, breakpoints} during compilation
1710
result = validate_compile_task_dependencies(dependencies, JVMCIENV->compile_state(), &failure_detail);
1711
if (result != JVMCI::ok) {
1712
// While not a true deoptimization, it is a preemptive decompile.
1713
MethodData* mdp = method()->method_data();
1714
if (mdp != NULL) {
1715
mdp->inc_decompile_count();
1716
#ifdef ASSERT
1717
if (mdp->decompile_count() > (uint)PerMethodRecompilationCutoff) {
1718
ResourceMark m;
1719
tty->print_cr("WARN: endless recompilation of %s. Method was set to not compilable.", method()->name_and_sig_as_C_string());
1720
}
1721
#endif
1722
}
1723
1724
// All buffers in the CodeBuffer are allocated in the CodeCache.
1725
// If the code buffer is created on each compile attempt
1726
// as in C2, then it must be freed.
1727
//code_buffer->free_blob();
1728
} else {
1729
nm = nmethod::new_nmethod(method,
1730
compile_id,
1731
entry_bci,
1732
offsets,
1733
orig_pc_offset,
1734
debug_info, dependencies, code_buffer,
1735
frame_words, oop_map_set,
1736
handler_table, implicit_exception_table,
1737
compiler, comp_level, GrowableArrayView<RuntimeStub*>::EMPTY,
1738
speculations, speculations_len,
1739
nmethod_mirror_index, nmethod_mirror_name, failed_speculations);
1740
1741
1742
// Free codeBlobs
1743
if (nm == NULL) {
1744
// The CodeCache is full. Print out warning and disable compilation.
1745
{
1746
MutexUnlocker ml(Compile_lock);
1747
MutexUnlocker locker(MethodCompileQueue_lock);
1748
CompileBroker::handle_full_code_cache(CodeCache::get_code_blob_type(comp_level));
1749
}
1750
} else {
1751
nm->set_has_unsafe_access(has_unsafe_access);
1752
nm->set_has_wide_vectors(has_wide_vector);
1753
1754
// Record successful registration.
1755
// (Put nm into the task handle *before* publishing to the Java heap.)
1756
if (JVMCIENV->compile_state() != NULL) {
1757
JVMCIENV->compile_state()->task()->set_code(nm);
1758
}
1759
1760
JVMCINMethodData* data = nm->jvmci_nmethod_data();
1761
assert(data != NULL, "must be");
1762
if (install_default) {
1763
assert(!nmethod_mirror.is_hotspot() || data->get_nmethod_mirror(nm, /* phantom_ref */ false) == NULL, "must be");
1764
if (entry_bci == InvocationEntryBci) {
1765
// If there is an old version we're done with it
1766
CompiledMethod* old = method->code();
1767
if (TraceMethodReplacement && old != NULL) {
1768
ResourceMark rm;
1769
char *method_name = method->name_and_sig_as_C_string();
1770
tty->print_cr("Replacing method %s", method_name);
1771
}
1772
if (old != NULL ) {
1773
old->make_not_entrant();
1774
}
1775
1776
LogTarget(Info, nmethod, install) lt;
1777
if (lt.is_enabled()) {
1778
ResourceMark rm;
1779
char *method_name = method->name_and_sig_as_C_string();
1780
lt.print("Installing method (%d) %s [entry point: %p]",
1781
comp_level, method_name, nm->entry_point());
1782
}
1783
// Allow the code to be executed
1784
MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1785
if (nm->make_in_use()) {
1786
method->set_code(method, nm);
1787
}
1788
} else {
1789
LogTarget(Info, nmethod, install) lt;
1790
if (lt.is_enabled()) {
1791
ResourceMark rm;
1792
char *method_name = method->name_and_sig_as_C_string();
1793
lt.print("Installing osr method (%d) %s @ %d",
1794
comp_level, method_name, entry_bci);
1795
}
1796
MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1797
if (nm->make_in_use()) {
1798
InstanceKlass::cast(method->method_holder())->add_osr_nmethod(nm);
1799
}
1800
}
1801
} else {
1802
assert(!nmethod_mirror.is_hotspot() || data->get_nmethod_mirror(nm, /* phantom_ref */ false) == HotSpotJVMCI::resolve(nmethod_mirror), "must be");
1803
}
1804
}
1805
result = nm != NULL ? JVMCI::ok :JVMCI::cache_full;
1806
}
1807
}
1808
1809
// String creation must be done outside lock
1810
if (failure_detail != NULL) {
1811
// A failure to allocate the string is silently ignored.
1812
JVMCIObject message = JVMCIENV->create_string(failure_detail, JVMCIENV);
1813
JVMCIENV->set_HotSpotCompiledNmethod_installationFailureMessage(compiled_code, message);
1814
}
1815
1816
// JVMTI -- compiled method notification (must be done outside lock)
1817
if (nm != NULL) {
1818
nm->post_compiled_method_load_event();
1819
}
1820
1821
return result;
1822
}
1823
1824