Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/hotspot/share/opto/graphKit.cpp
64440 views
1
/*
2
* Copyright (c) 2001, 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
25
#include "precompiled.hpp"
26
#include "ci/ciUtilities.hpp"
27
#include "classfile/javaClasses.hpp"
28
#include "ci/ciNativeEntryPoint.hpp"
29
#include "ci/ciObjArray.hpp"
30
#include "asm/register.hpp"
31
#include "compiler/compileLog.hpp"
32
#include "gc/shared/barrierSet.hpp"
33
#include "gc/shared/c2/barrierSetC2.hpp"
34
#include "interpreter/interpreter.hpp"
35
#include "memory/resourceArea.hpp"
36
#include "opto/addnode.hpp"
37
#include "opto/castnode.hpp"
38
#include "opto/convertnode.hpp"
39
#include "opto/graphKit.hpp"
40
#include "opto/idealKit.hpp"
41
#include "opto/intrinsicnode.hpp"
42
#include "opto/locknode.hpp"
43
#include "opto/machnode.hpp"
44
#include "opto/opaquenode.hpp"
45
#include "opto/parse.hpp"
46
#include "opto/rootnode.hpp"
47
#include "opto/runtime.hpp"
48
#include "opto/subtypenode.hpp"
49
#include "runtime/deoptimization.hpp"
50
#include "runtime/sharedRuntime.hpp"
51
#include "utilities/bitMap.inline.hpp"
52
#include "utilities/powerOfTwo.hpp"
53
#include "utilities/growableArray.hpp"
54
55
//----------------------------GraphKit-----------------------------------------
56
// Main utility constructor.
57
GraphKit::GraphKit(JVMState* jvms)
58
: Phase(Phase::Parser),
59
_env(C->env()),
60
_gvn(*C->initial_gvn()),
61
_barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
62
{
63
_exceptions = jvms->map()->next_exception();
64
if (_exceptions != NULL) jvms->map()->set_next_exception(NULL);
65
set_jvms(jvms);
66
}
67
68
// Private constructor for parser.
69
GraphKit::GraphKit()
70
: Phase(Phase::Parser),
71
_env(C->env()),
72
_gvn(*C->initial_gvn()),
73
_barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
74
{
75
_exceptions = NULL;
76
set_map(NULL);
77
debug_only(_sp = -99);
78
debug_only(set_bci(-99));
79
}
80
81
82
83
//---------------------------clean_stack---------------------------------------
84
// Clear away rubbish from the stack area of the JVM state.
85
// This destroys any arguments that may be waiting on the stack.
86
void GraphKit::clean_stack(int from_sp) {
87
SafePointNode* map = this->map();
88
JVMState* jvms = this->jvms();
89
int stk_size = jvms->stk_size();
90
int stkoff = jvms->stkoff();
91
Node* top = this->top();
92
for (int i = from_sp; i < stk_size; i++) {
93
if (map->in(stkoff + i) != top) {
94
map->set_req(stkoff + i, top);
95
}
96
}
97
}
98
99
100
//--------------------------------sync_jvms-----------------------------------
101
// Make sure our current jvms agrees with our parse state.
102
JVMState* GraphKit::sync_jvms() const {
103
JVMState* jvms = this->jvms();
104
jvms->set_bci(bci()); // Record the new bci in the JVMState
105
jvms->set_sp(sp()); // Record the new sp in the JVMState
106
assert(jvms_in_sync(), "jvms is now in sync");
107
return jvms;
108
}
109
110
//--------------------------------sync_jvms_for_reexecute---------------------
111
// Make sure our current jvms agrees with our parse state. This version
112
// uses the reexecute_sp for reexecuting bytecodes.
113
JVMState* GraphKit::sync_jvms_for_reexecute() {
114
JVMState* jvms = this->jvms();
115
jvms->set_bci(bci()); // Record the new bci in the JVMState
116
jvms->set_sp(reexecute_sp()); // Record the new sp in the JVMState
117
return jvms;
118
}
119
120
#ifdef ASSERT
121
bool GraphKit::jvms_in_sync() const {
122
Parse* parse = is_Parse();
123
if (parse == NULL) {
124
if (bci() != jvms()->bci()) return false;
125
if (sp() != (int)jvms()->sp()) return false;
126
return true;
127
}
128
if (jvms()->method() != parse->method()) return false;
129
if (jvms()->bci() != parse->bci()) return false;
130
int jvms_sp = jvms()->sp();
131
if (jvms_sp != parse->sp()) return false;
132
int jvms_depth = jvms()->depth();
133
if (jvms_depth != parse->depth()) return false;
134
return true;
135
}
136
137
// Local helper checks for special internal merge points
138
// used to accumulate and merge exception states.
139
// They are marked by the region's in(0) edge being the map itself.
140
// Such merge points must never "escape" into the parser at large,
141
// until they have been handed to gvn.transform.
142
static bool is_hidden_merge(Node* reg) {
143
if (reg == NULL) return false;
144
if (reg->is_Phi()) {
145
reg = reg->in(0);
146
if (reg == NULL) return false;
147
}
148
return reg->is_Region() && reg->in(0) != NULL && reg->in(0)->is_Root();
149
}
150
151
void GraphKit::verify_map() const {
152
if (map() == NULL) return; // null map is OK
153
assert(map()->req() <= jvms()->endoff(), "no extra garbage on map");
154
assert(!map()->has_exceptions(), "call add_exception_states_from 1st");
155
assert(!is_hidden_merge(control()), "call use_exception_state, not set_map");
156
}
157
158
void GraphKit::verify_exception_state(SafePointNode* ex_map) {
159
assert(ex_map->next_exception() == NULL, "not already part of a chain");
160
assert(has_saved_ex_oop(ex_map), "every exception state has an ex_oop");
161
}
162
#endif
163
164
//---------------------------stop_and_kill_map---------------------------------
165
// Set _map to NULL, signalling a stop to further bytecode execution.
166
// First smash the current map's control to a constant, to mark it dead.
167
void GraphKit::stop_and_kill_map() {
168
SafePointNode* dead_map = stop();
169
if (dead_map != NULL) {
170
dead_map->disconnect_inputs(C); // Mark the map as killed.
171
assert(dead_map->is_killed(), "must be so marked");
172
}
173
}
174
175
176
//--------------------------------stopped--------------------------------------
177
// Tell if _map is NULL, or control is top.
178
bool GraphKit::stopped() {
179
if (map() == NULL) return true;
180
else if (control() == top()) return true;
181
else return false;
182
}
183
184
185
//-----------------------------has_ex_handler----------------------------------
186
// Tell if this method or any caller method has exception handlers.
187
bool GraphKit::has_ex_handler() {
188
for (JVMState* jvmsp = jvms(); jvmsp != NULL; jvmsp = jvmsp->caller()) {
189
if (jvmsp->has_method() && jvmsp->method()->has_exception_handlers()) {
190
return true;
191
}
192
}
193
return false;
194
}
195
196
//------------------------------save_ex_oop------------------------------------
197
// Save an exception without blowing stack contents or other JVM state.
198
void GraphKit::set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop) {
199
assert(!has_saved_ex_oop(ex_map), "clear ex-oop before setting again");
200
ex_map->add_req(ex_oop);
201
debug_only(verify_exception_state(ex_map));
202
}
203
204
inline static Node* common_saved_ex_oop(SafePointNode* ex_map, bool clear_it) {
205
assert(GraphKit::has_saved_ex_oop(ex_map), "ex_oop must be there");
206
Node* ex_oop = ex_map->in(ex_map->req()-1);
207
if (clear_it) ex_map->del_req(ex_map->req()-1);
208
return ex_oop;
209
}
210
211
//-----------------------------saved_ex_oop------------------------------------
212
// Recover a saved exception from its map.
213
Node* GraphKit::saved_ex_oop(SafePointNode* ex_map) {
214
return common_saved_ex_oop(ex_map, false);
215
}
216
217
//--------------------------clear_saved_ex_oop---------------------------------
218
// Erase a previously saved exception from its map.
219
Node* GraphKit::clear_saved_ex_oop(SafePointNode* ex_map) {
220
return common_saved_ex_oop(ex_map, true);
221
}
222
223
#ifdef ASSERT
224
//---------------------------has_saved_ex_oop----------------------------------
225
// Erase a previously saved exception from its map.
226
bool GraphKit::has_saved_ex_oop(SafePointNode* ex_map) {
227
return ex_map->req() == ex_map->jvms()->endoff()+1;
228
}
229
#endif
230
231
//-------------------------make_exception_state--------------------------------
232
// Turn the current JVM state into an exception state, appending the ex_oop.
233
SafePointNode* GraphKit::make_exception_state(Node* ex_oop) {
234
sync_jvms();
235
SafePointNode* ex_map = stop(); // do not manipulate this map any more
236
set_saved_ex_oop(ex_map, ex_oop);
237
return ex_map;
238
}
239
240
241
//--------------------------add_exception_state--------------------------------
242
// Add an exception to my list of exceptions.
243
void GraphKit::add_exception_state(SafePointNode* ex_map) {
244
if (ex_map == NULL || ex_map->control() == top()) {
245
return;
246
}
247
#ifdef ASSERT
248
verify_exception_state(ex_map);
249
if (has_exceptions()) {
250
assert(ex_map->jvms()->same_calls_as(_exceptions->jvms()), "all collected exceptions must come from the same place");
251
}
252
#endif
253
254
// If there is already an exception of exactly this type, merge with it.
255
// In particular, null-checks and other low-level exceptions common up here.
256
Node* ex_oop = saved_ex_oop(ex_map);
257
const Type* ex_type = _gvn.type(ex_oop);
258
if (ex_oop == top()) {
259
// No action needed.
260
return;
261
}
262
assert(ex_type->isa_instptr(), "exception must be an instance");
263
for (SafePointNode* e2 = _exceptions; e2 != NULL; e2 = e2->next_exception()) {
264
const Type* ex_type2 = _gvn.type(saved_ex_oop(e2));
265
// We check sp also because call bytecodes can generate exceptions
266
// both before and after arguments are popped!
267
if (ex_type2 == ex_type
268
&& e2->_jvms->sp() == ex_map->_jvms->sp()) {
269
combine_exception_states(ex_map, e2);
270
return;
271
}
272
}
273
274
// No pre-existing exception of the same type. Chain it on the list.
275
push_exception_state(ex_map);
276
}
277
278
//-----------------------add_exception_states_from-----------------------------
279
void GraphKit::add_exception_states_from(JVMState* jvms) {
280
SafePointNode* ex_map = jvms->map()->next_exception();
281
if (ex_map != NULL) {
282
jvms->map()->set_next_exception(NULL);
283
for (SafePointNode* next_map; ex_map != NULL; ex_map = next_map) {
284
next_map = ex_map->next_exception();
285
ex_map->set_next_exception(NULL);
286
add_exception_state(ex_map);
287
}
288
}
289
}
290
291
//-----------------------transfer_exceptions_into_jvms-------------------------
292
JVMState* GraphKit::transfer_exceptions_into_jvms() {
293
if (map() == NULL) {
294
// We need a JVMS to carry the exceptions, but the map has gone away.
295
// Create a scratch JVMS, cloned from any of the exception states...
296
if (has_exceptions()) {
297
_map = _exceptions;
298
_map = clone_map();
299
_map->set_next_exception(NULL);
300
clear_saved_ex_oop(_map);
301
debug_only(verify_map());
302
} else {
303
// ...or created from scratch
304
JVMState* jvms = new (C) JVMState(_method, NULL);
305
jvms->set_bci(_bci);
306
jvms->set_sp(_sp);
307
jvms->set_map(new SafePointNode(TypeFunc::Parms, jvms));
308
set_jvms(jvms);
309
for (uint i = 0; i < map()->req(); i++) map()->init_req(i, top());
310
set_all_memory(top());
311
while (map()->req() < jvms->endoff()) map()->add_req(top());
312
}
313
// (This is a kludge, in case you didn't notice.)
314
set_control(top());
315
}
316
JVMState* jvms = sync_jvms();
317
assert(!jvms->map()->has_exceptions(), "no exceptions on this map yet");
318
jvms->map()->set_next_exception(_exceptions);
319
_exceptions = NULL; // done with this set of exceptions
320
return jvms;
321
}
322
323
static inline void add_n_reqs(Node* dstphi, Node* srcphi) {
324
assert(is_hidden_merge(dstphi), "must be a special merge node");
325
assert(is_hidden_merge(srcphi), "must be a special merge node");
326
uint limit = srcphi->req();
327
for (uint i = PhiNode::Input; i < limit; i++) {
328
dstphi->add_req(srcphi->in(i));
329
}
330
}
331
static inline void add_one_req(Node* dstphi, Node* src) {
332
assert(is_hidden_merge(dstphi), "must be a special merge node");
333
assert(!is_hidden_merge(src), "must not be a special merge node");
334
dstphi->add_req(src);
335
}
336
337
//-----------------------combine_exception_states------------------------------
338
// This helper function combines exception states by building phis on a
339
// specially marked state-merging region. These regions and phis are
340
// untransformed, and can build up gradually. The region is marked by
341
// having a control input of its exception map, rather than NULL. Such
342
// regions do not appear except in this function, and in use_exception_state.
343
void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {
344
if (failing()) return; // dying anyway...
345
JVMState* ex_jvms = ex_map->_jvms;
346
assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");
347
assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");
348
assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");
349
assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");
350
assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");
351
assert(ex_map->req() == phi_map->req(), "matching maps");
352
uint tos = ex_jvms->stkoff() + ex_jvms->sp();
353
Node* hidden_merge_mark = root();
354
Node* region = phi_map->control();
355
MergeMemNode* phi_mem = phi_map->merged_memory();
356
MergeMemNode* ex_mem = ex_map->merged_memory();
357
if (region->in(0) != hidden_merge_mark) {
358
// The control input is not (yet) a specially-marked region in phi_map.
359
// Make it so, and build some phis.
360
region = new RegionNode(2);
361
_gvn.set_type(region, Type::CONTROL);
362
region->set_req(0, hidden_merge_mark); // marks an internal ex-state
363
region->init_req(1, phi_map->control());
364
phi_map->set_control(region);
365
Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);
366
record_for_igvn(io_phi);
367
_gvn.set_type(io_phi, Type::ABIO);
368
phi_map->set_i_o(io_phi);
369
for (MergeMemStream mms(phi_mem); mms.next_non_empty(); ) {
370
Node* m = mms.memory();
371
Node* m_phi = PhiNode::make(region, m, Type::MEMORY, mms.adr_type(C));
372
record_for_igvn(m_phi);
373
_gvn.set_type(m_phi, Type::MEMORY);
374
mms.set_memory(m_phi);
375
}
376
}
377
378
// Either or both of phi_map and ex_map might already be converted into phis.
379
Node* ex_control = ex_map->control();
380
// if there is special marking on ex_map also, we add multiple edges from src
381
bool add_multiple = (ex_control->in(0) == hidden_merge_mark);
382
// how wide was the destination phi_map, originally?
383
uint orig_width = region->req();
384
385
if (add_multiple) {
386
add_n_reqs(region, ex_control);
387
add_n_reqs(phi_map->i_o(), ex_map->i_o());
388
} else {
389
// ex_map has no merges, so we just add single edges everywhere
390
add_one_req(region, ex_control);
391
add_one_req(phi_map->i_o(), ex_map->i_o());
392
}
393
for (MergeMemStream mms(phi_mem, ex_mem); mms.next_non_empty2(); ) {
394
if (mms.is_empty()) {
395
// get a copy of the base memory, and patch some inputs into it
396
const TypePtr* adr_type = mms.adr_type(C);
397
Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
398
assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
399
mms.set_memory(phi);
400
// Prepare to append interesting stuff onto the newly sliced phi:
401
while (phi->req() > orig_width) phi->del_req(phi->req()-1);
402
}
403
// Append stuff from ex_map:
404
if (add_multiple) {
405
add_n_reqs(mms.memory(), mms.memory2());
406
} else {
407
add_one_req(mms.memory(), mms.memory2());
408
}
409
}
410
uint limit = ex_map->req();
411
for (uint i = TypeFunc::Parms; i < limit; i++) {
412
// Skip everything in the JVMS after tos. (The ex_oop follows.)
413
if (i == tos) i = ex_jvms->monoff();
414
Node* src = ex_map->in(i);
415
Node* dst = phi_map->in(i);
416
if (src != dst) {
417
PhiNode* phi;
418
if (dst->in(0) != region) {
419
dst = phi = PhiNode::make(region, dst, _gvn.type(dst));
420
record_for_igvn(phi);
421
_gvn.set_type(phi, phi->type());
422
phi_map->set_req(i, dst);
423
// Prepare to append interesting stuff onto the new phi:
424
while (dst->req() > orig_width) dst->del_req(dst->req()-1);
425
} else {
426
assert(dst->is_Phi(), "nobody else uses a hidden region");
427
phi = dst->as_Phi();
428
}
429
if (add_multiple && src->in(0) == ex_control) {
430
// Both are phis.
431
add_n_reqs(dst, src);
432
} else {
433
while (dst->req() < region->req()) add_one_req(dst, src);
434
}
435
const Type* srctype = _gvn.type(src);
436
if (phi->type() != srctype) {
437
const Type* dsttype = phi->type()->meet_speculative(srctype);
438
if (phi->type() != dsttype) {
439
phi->set_type(dsttype);
440
_gvn.set_type(phi, dsttype);
441
}
442
}
443
}
444
}
445
phi_map->merge_replaced_nodes_with(ex_map);
446
}
447
448
//--------------------------use_exception_state--------------------------------
449
Node* GraphKit::use_exception_state(SafePointNode* phi_map) {
450
if (failing()) { stop(); return top(); }
451
Node* region = phi_map->control();
452
Node* hidden_merge_mark = root();
453
assert(phi_map->jvms()->map() == phi_map, "sanity: 1-1 relation");
454
Node* ex_oop = clear_saved_ex_oop(phi_map);
455
if (region->in(0) == hidden_merge_mark) {
456
// Special marking for internal ex-states. Process the phis now.
457
region->set_req(0, region); // now it's an ordinary region
458
set_jvms(phi_map->jvms()); // ...so now we can use it as a map
459
// Note: Setting the jvms also sets the bci and sp.
460
set_control(_gvn.transform(region));
461
uint tos = jvms()->stkoff() + sp();
462
for (uint i = 1; i < tos; i++) {
463
Node* x = phi_map->in(i);
464
if (x->in(0) == region) {
465
assert(x->is_Phi(), "expected a special phi");
466
phi_map->set_req(i, _gvn.transform(x));
467
}
468
}
469
for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
470
Node* x = mms.memory();
471
if (x->in(0) == region) {
472
assert(x->is_Phi(), "nobody else uses a hidden region");
473
mms.set_memory(_gvn.transform(x));
474
}
475
}
476
if (ex_oop->in(0) == region) {
477
assert(ex_oop->is_Phi(), "expected a special phi");
478
ex_oop = _gvn.transform(ex_oop);
479
}
480
} else {
481
set_jvms(phi_map->jvms());
482
}
483
484
assert(!is_hidden_merge(phi_map->control()), "hidden ex. states cleared");
485
assert(!is_hidden_merge(phi_map->i_o()), "hidden ex. states cleared");
486
return ex_oop;
487
}
488
489
//---------------------------------java_bc-------------------------------------
490
Bytecodes::Code GraphKit::java_bc() const {
491
ciMethod* method = this->method();
492
int bci = this->bci();
493
if (method != NULL && bci != InvocationEntryBci)
494
return method->java_code_at_bci(bci);
495
else
496
return Bytecodes::_illegal;
497
}
498
499
void GraphKit::uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,
500
bool must_throw) {
501
// if the exception capability is set, then we will generate code
502
// to check the JavaThread.should_post_on_exceptions flag to see
503
// if we actually need to report exception events (for this
504
// thread). If we don't need to report exception events, we will
505
// take the normal fast path provided by add_exception_events. If
506
// exception event reporting is enabled for this thread, we will
507
// take the uncommon_trap in the BuildCutout below.
508
509
// first must access the should_post_on_exceptions_flag in this thread's JavaThread
510
Node* jthread = _gvn.transform(new ThreadLocalNode());
511
Node* adr = basic_plus_adr(top(), jthread, in_bytes(JavaThread::should_post_on_exceptions_flag_offset()));
512
Node* should_post_flag = make_load(control(), adr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, MemNode::unordered);
513
514
// Test the should_post_on_exceptions_flag vs. 0
515
Node* chk = _gvn.transform( new CmpINode(should_post_flag, intcon(0)) );
516
Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
517
518
// Branch to slow_path if should_post_on_exceptions_flag was true
519
{ BuildCutout unless(this, tst, PROB_MAX);
520
// Do not try anything fancy if we're notifying the VM on every throw.
521
// Cf. case Bytecodes::_athrow in parse2.cpp.
522
uncommon_trap(reason, Deoptimization::Action_none,
523
(ciKlass*)NULL, (char*)NULL, must_throw);
524
}
525
526
}
527
528
//------------------------------builtin_throw----------------------------------
529
void GraphKit::builtin_throw(Deoptimization::DeoptReason reason, Node* arg) {
530
bool must_throw = true;
531
532
// If this particular condition has not yet happened at this
533
// bytecode, then use the uncommon trap mechanism, and allow for
534
// a future recompilation if several traps occur here.
535
// If the throw is hot, try to use a more complicated inline mechanism
536
// which keeps execution inside the compiled code.
537
bool treat_throw_as_hot = false;
538
ciMethodData* md = method()->method_data();
539
540
if (ProfileTraps) {
541
if (too_many_traps(reason)) {
542
treat_throw_as_hot = true;
543
}
544
// (If there is no MDO at all, assume it is early in
545
// execution, and that any deopts are part of the
546
// startup transient, and don't need to be remembered.)
547
548
// Also, if there is a local exception handler, treat all throws
549
// as hot if there has been at least one in this method.
550
if (C->trap_count(reason) != 0
551
&& method()->method_data()->trap_count(reason) != 0
552
&& has_ex_handler()) {
553
treat_throw_as_hot = true;
554
}
555
}
556
557
// If this throw happens frequently, an uncommon trap might cause
558
// a performance pothole. If there is a local exception handler,
559
// and if this particular bytecode appears to be deoptimizing often,
560
// let us handle the throw inline, with a preconstructed instance.
561
// Note: If the deopt count has blown up, the uncommon trap
562
// runtime is going to flush this nmethod, not matter what.
563
if (treat_throw_as_hot
564
&& (!StackTraceInThrowable || OmitStackTraceInFastThrow)) {
565
// If the throw is local, we use a pre-existing instance and
566
// punt on the backtrace. This would lead to a missing backtrace
567
// (a repeat of 4292742) if the backtrace object is ever asked
568
// for its backtrace.
569
// Fixing this remaining case of 4292742 requires some flavor of
570
// escape analysis. Leave that for the future.
571
ciInstance* ex_obj = NULL;
572
switch (reason) {
573
case Deoptimization::Reason_null_check:
574
ex_obj = env()->NullPointerException_instance();
575
break;
576
case Deoptimization::Reason_div0_check:
577
ex_obj = env()->ArithmeticException_instance();
578
break;
579
case Deoptimization::Reason_range_check:
580
ex_obj = env()->ArrayIndexOutOfBoundsException_instance();
581
break;
582
case Deoptimization::Reason_class_check:
583
if (java_bc() == Bytecodes::_aastore) {
584
ex_obj = env()->ArrayStoreException_instance();
585
} else {
586
ex_obj = env()->ClassCastException_instance();
587
}
588
break;
589
default:
590
break;
591
}
592
if (failing()) { stop(); return; } // exception allocation might fail
593
if (ex_obj != NULL) {
594
if (env()->jvmti_can_post_on_exceptions()) {
595
// check if we must post exception events, take uncommon trap if so
596
uncommon_trap_if_should_post_on_exceptions(reason, must_throw);
597
// here if should_post_on_exceptions is false
598
// continue on with the normal codegen
599
}
600
601
// Cheat with a preallocated exception object.
602
if (C->log() != NULL)
603
C->log()->elem("hot_throw preallocated='1' reason='%s'",
604
Deoptimization::trap_reason_name(reason));
605
const TypeInstPtr* ex_con = TypeInstPtr::make(ex_obj);
606
Node* ex_node = _gvn.transform(ConNode::make(ex_con));
607
608
// Clear the detail message of the preallocated exception object.
609
// Weblogic sometimes mutates the detail message of exceptions
610
// using reflection.
611
int offset = java_lang_Throwable::get_detailMessage_offset();
612
const TypePtr* adr_typ = ex_con->add_offset(offset);
613
614
Node *adr = basic_plus_adr(ex_node, ex_node, offset);
615
const TypeOopPtr* val_type = TypeOopPtr::make_from_klass(env()->String_klass());
616
Node *store = access_store_at(ex_node, adr, adr_typ, null(), val_type, T_OBJECT, IN_HEAP);
617
618
if (!method()->has_exception_handlers()) {
619
// We don't need to preserve the stack if there's no handler as the entire frame is going to be popped anyway.
620
// This prevents issues with exception handling and late inlining.
621
set_sp(0);
622
clean_stack(0);
623
}
624
625
add_exception_state(make_exception_state(ex_node));
626
return;
627
}
628
}
629
630
// %%% Maybe add entry to OptoRuntime which directly throws the exc.?
631
// It won't be much cheaper than bailing to the interp., since we'll
632
// have to pass up all the debug-info, and the runtime will have to
633
// create the stack trace.
634
635
// Usual case: Bail to interpreter.
636
// Reserve the right to recompile if we haven't seen anything yet.
637
638
ciMethod* m = Deoptimization::reason_is_speculate(reason) ? C->method() : NULL;
639
Deoptimization::DeoptAction action = Deoptimization::Action_maybe_recompile;
640
if (treat_throw_as_hot
641
&& (method()->method_data()->trap_recompiled_at(bci(), m)
642
|| C->too_many_traps(reason))) {
643
// We cannot afford to take more traps here. Suffer in the interpreter.
644
if (C->log() != NULL)
645
C->log()->elem("hot_throw preallocated='0' reason='%s' mcount='%d'",
646
Deoptimization::trap_reason_name(reason),
647
C->trap_count(reason));
648
action = Deoptimization::Action_none;
649
}
650
651
// "must_throw" prunes the JVM state to include only the stack, if there
652
// are no local exception handlers. This should cut down on register
653
// allocation time and code size, by drastically reducing the number
654
// of in-edges on the call to the uncommon trap.
655
656
uncommon_trap(reason, action, (ciKlass*)NULL, (char*)NULL, must_throw);
657
}
658
659
660
//----------------------------PreserveJVMState---------------------------------
661
PreserveJVMState::PreserveJVMState(GraphKit* kit, bool clone_map) {
662
debug_only(kit->verify_map());
663
_kit = kit;
664
_map = kit->map(); // preserve the map
665
_sp = kit->sp();
666
kit->set_map(clone_map ? kit->clone_map() : NULL);
667
#ifdef ASSERT
668
_bci = kit->bci();
669
Parse* parser = kit->is_Parse();
670
int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();
671
_block = block;
672
#endif
673
}
674
PreserveJVMState::~PreserveJVMState() {
675
GraphKit* kit = _kit;
676
#ifdef ASSERT
677
assert(kit->bci() == _bci, "bci must not shift");
678
Parse* parser = kit->is_Parse();
679
int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();
680
assert(block == _block, "block must not shift");
681
#endif
682
kit->set_map(_map);
683
kit->set_sp(_sp);
684
}
685
686
687
//-----------------------------BuildCutout-------------------------------------
688
BuildCutout::BuildCutout(GraphKit* kit, Node* p, float prob, float cnt)
689
: PreserveJVMState(kit)
690
{
691
assert(p->is_Con() || p->is_Bool(), "test must be a bool");
692
SafePointNode* outer_map = _map; // preserved map is caller's
693
SafePointNode* inner_map = kit->map();
694
IfNode* iff = kit->create_and_map_if(outer_map->control(), p, prob, cnt);
695
outer_map->set_control(kit->gvn().transform( new IfTrueNode(iff) ));
696
inner_map->set_control(kit->gvn().transform( new IfFalseNode(iff) ));
697
}
698
BuildCutout::~BuildCutout() {
699
GraphKit* kit = _kit;
700
assert(kit->stopped(), "cutout code must stop, throw, return, etc.");
701
}
702
703
//---------------------------PreserveReexecuteState----------------------------
704
PreserveReexecuteState::PreserveReexecuteState(GraphKit* kit) {
705
assert(!kit->stopped(), "must call stopped() before");
706
_kit = kit;
707
_sp = kit->sp();
708
_reexecute = kit->jvms()->_reexecute;
709
}
710
PreserveReexecuteState::~PreserveReexecuteState() {
711
if (_kit->stopped()) return;
712
_kit->jvms()->_reexecute = _reexecute;
713
_kit->set_sp(_sp);
714
}
715
716
//------------------------------clone_map--------------------------------------
717
// Implementation of PreserveJVMState
718
//
719
// Only clone_map(...) here. If this function is only used in the
720
// PreserveJVMState class we may want to get rid of this extra
721
// function eventually and do it all there.
722
723
SafePointNode* GraphKit::clone_map() {
724
if (map() == NULL) return NULL;
725
726
// Clone the memory edge first
727
Node* mem = MergeMemNode::make(map()->memory());
728
gvn().set_type_bottom(mem);
729
730
SafePointNode *clonemap = (SafePointNode*)map()->clone();
731
JVMState* jvms = this->jvms();
732
JVMState* clonejvms = jvms->clone_shallow(C);
733
clonemap->set_memory(mem);
734
clonemap->set_jvms(clonejvms);
735
clonejvms->set_map(clonemap);
736
record_for_igvn(clonemap);
737
gvn().set_type_bottom(clonemap);
738
return clonemap;
739
}
740
741
742
//-----------------------------set_map_clone-----------------------------------
743
void GraphKit::set_map_clone(SafePointNode* m) {
744
_map = m;
745
_map = clone_map();
746
_map->set_next_exception(NULL);
747
debug_only(verify_map());
748
}
749
750
751
//----------------------------kill_dead_locals---------------------------------
752
// Detect any locals which are known to be dead, and force them to top.
753
void GraphKit::kill_dead_locals() {
754
// Consult the liveness information for the locals. If any
755
// of them are unused, then they can be replaced by top(). This
756
// should help register allocation time and cut down on the size
757
// of the deoptimization information.
758
759
// This call is made from many of the bytecode handling
760
// subroutines called from the Big Switch in do_one_bytecode.
761
// Every bytecode which might include a slow path is responsible
762
// for killing its dead locals. The more consistent we
763
// are about killing deads, the fewer useless phis will be
764
// constructed for them at various merge points.
765
766
// bci can be -1 (InvocationEntryBci). We return the entry
767
// liveness for the method.
768
769
if (method() == NULL || method()->code_size() == 0) {
770
// We are building a graph for a call to a native method.
771
// All locals are live.
772
return;
773
}
774
775
ResourceMark rm;
776
777
// Consult the liveness information for the locals. If any
778
// of them are unused, then they can be replaced by top(). This
779
// should help register allocation time and cut down on the size
780
// of the deoptimization information.
781
MethodLivenessResult live_locals = method()->liveness_at_bci(bci());
782
783
int len = (int)live_locals.size();
784
assert(len <= jvms()->loc_size(), "too many live locals");
785
for (int local = 0; local < len; local++) {
786
if (!live_locals.at(local)) {
787
set_local(local, top());
788
}
789
}
790
}
791
792
#ifdef ASSERT
793
//-------------------------dead_locals_are_killed------------------------------
794
// Return true if all dead locals are set to top in the map.
795
// Used to assert "clean" debug info at various points.
796
bool GraphKit::dead_locals_are_killed() {
797
if (method() == NULL || method()->code_size() == 0) {
798
// No locals need to be dead, so all is as it should be.
799
return true;
800
}
801
802
// Make sure somebody called kill_dead_locals upstream.
803
ResourceMark rm;
804
for (JVMState* jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {
805
if (jvms->loc_size() == 0) continue; // no locals to consult
806
SafePointNode* map = jvms->map();
807
ciMethod* method = jvms->method();
808
int bci = jvms->bci();
809
if (jvms == this->jvms()) {
810
bci = this->bci(); // it might not yet be synched
811
}
812
MethodLivenessResult live_locals = method->liveness_at_bci(bci);
813
int len = (int)live_locals.size();
814
if (!live_locals.is_valid() || len == 0)
815
// This method is trivial, or is poisoned by a breakpoint.
816
return true;
817
assert(len == jvms->loc_size(), "live map consistent with locals map");
818
for (int local = 0; local < len; local++) {
819
if (!live_locals.at(local) && map->local(jvms, local) != top()) {
820
if (PrintMiscellaneous && (Verbose || WizardMode)) {
821
tty->print_cr("Zombie local %d: ", local);
822
jvms->dump();
823
}
824
return false;
825
}
826
}
827
}
828
return true;
829
}
830
831
#endif //ASSERT
832
833
// Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
834
static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
835
ciMethod* cur_method = jvms->method();
836
int cur_bci = jvms->bci();
837
if (cur_method != NULL && cur_bci != InvocationEntryBci) {
838
Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
839
return Interpreter::bytecode_should_reexecute(code) ||
840
(is_anewarray && code == Bytecodes::_multianewarray);
841
// Reexecute _multianewarray bytecode which was replaced with
842
// sequence of [a]newarray. See Parse::do_multianewarray().
843
//
844
// Note: interpreter should not have it set since this optimization
845
// is limited by dimensions and guarded by flag so in some cases
846
// multianewarray() runtime calls will be generated and
847
// the bytecode should not be reexecutes (stack will not be reset).
848
} else {
849
return false;
850
}
851
}
852
853
// Helper function for adding JVMState and debug information to node
854
void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
855
// Add the safepoint edges to the call (or other safepoint).
856
857
// Make sure dead locals are set to top. This
858
// should help register allocation time and cut down on the size
859
// of the deoptimization information.
860
assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
861
862
// Walk the inline list to fill in the correct set of JVMState's
863
// Also fill in the associated edges for each JVMState.
864
865
// If the bytecode needs to be reexecuted we need to put
866
// the arguments back on the stack.
867
const bool should_reexecute = jvms()->should_reexecute();
868
JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();
869
870
// NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to
871
// undefined if the bci is different. This is normal for Parse but it
872
// should not happen for LibraryCallKit because only one bci is processed.
873
assert(!is_LibraryCallKit() || (jvms()->should_reexecute() == should_reexecute),
874
"in LibraryCallKit the reexecute bit should not change");
875
876
// If we are guaranteed to throw, we can prune everything but the
877
// input to the current bytecode.
878
bool can_prune_locals = false;
879
uint stack_slots_not_pruned = 0;
880
int inputs = 0, depth = 0;
881
if (must_throw) {
882
assert(method() == youngest_jvms->method(), "sanity");
883
if (compute_stack_effects(inputs, depth)) {
884
can_prune_locals = true;
885
stack_slots_not_pruned = inputs;
886
}
887
}
888
889
if (env()->should_retain_local_variables()) {
890
// At any safepoint, this method can get breakpointed, which would
891
// then require an immediate deoptimization.
892
can_prune_locals = false; // do not prune locals
893
stack_slots_not_pruned = 0;
894
}
895
896
// do not scribble on the input jvms
897
JVMState* out_jvms = youngest_jvms->clone_deep(C);
898
call->set_jvms(out_jvms); // Start jvms list for call node
899
900
// For a known set of bytecodes, the interpreter should reexecute them if
901
// deoptimization happens. We set the reexecute state for them here
902
if (out_jvms->is_reexecute_undefined() && //don't change if already specified
903
should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {
904
#ifdef ASSERT
905
int inputs = 0, not_used; // initialized by GraphKit::compute_stack_effects()
906
assert(method() == youngest_jvms->method(), "sanity");
907
assert(compute_stack_effects(inputs, not_used), "unknown bytecode: %s", Bytecodes::name(java_bc()));
908
assert(out_jvms->sp() >= (uint)inputs, "not enough operands for reexecution");
909
#endif // ASSERT
910
out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed
911
}
912
913
// Presize the call:
914
DEBUG_ONLY(uint non_debug_edges = call->req());
915
call->add_req_batch(top(), youngest_jvms->debug_depth());
916
assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");
917
918
// Set up edges so that the call looks like this:
919
// Call [state:] ctl io mem fptr retadr
920
// [parms:] parm0 ... parmN
921
// [root:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
922
// [...mid:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]
923
// [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
924
// Note that caller debug info precedes callee debug info.
925
926
// Fill pointer walks backwards from "young:" to "root:" in the diagram above:
927
uint debug_ptr = call->req();
928
929
// Loop over the map input edges associated with jvms, add them
930
// to the call node, & reset all offsets to match call node array.
931
for (JVMState* in_jvms = youngest_jvms; in_jvms != NULL; ) {
932
uint debug_end = debug_ptr;
933
uint debug_start = debug_ptr - in_jvms->debug_size();
934
debug_ptr = debug_start; // back up the ptr
935
936
uint p = debug_start; // walks forward in [debug_start, debug_end)
937
uint j, k, l;
938
SafePointNode* in_map = in_jvms->map();
939
out_jvms->set_map(call);
940
941
if (can_prune_locals) {
942
assert(in_jvms->method() == out_jvms->method(), "sanity");
943
// If the current throw can reach an exception handler in this JVMS,
944
// then we must keep everything live that can reach that handler.
945
// As a quick and dirty approximation, we look for any handlers at all.
946
if (in_jvms->method()->has_exception_handlers()) {
947
can_prune_locals = false;
948
}
949
}
950
951
// Add the Locals
952
k = in_jvms->locoff();
953
l = in_jvms->loc_size();
954
out_jvms->set_locoff(p);
955
if (!can_prune_locals) {
956
for (j = 0; j < l; j++)
957
call->set_req(p++, in_map->in(k+j));
958
} else {
959
p += l; // already set to top above by add_req_batch
960
}
961
962
// Add the Expression Stack
963
k = in_jvms->stkoff();
964
l = in_jvms->sp();
965
out_jvms->set_stkoff(p);
966
if (!can_prune_locals) {
967
for (j = 0; j < l; j++)
968
call->set_req(p++, in_map->in(k+j));
969
} else if (can_prune_locals && stack_slots_not_pruned != 0) {
970
// Divide stack into {S0,...,S1}, where S0 is set to top.
971
uint s1 = stack_slots_not_pruned;
972
stack_slots_not_pruned = 0; // for next iteration
973
if (s1 > l) s1 = l;
974
uint s0 = l - s1;
975
p += s0; // skip the tops preinstalled by add_req_batch
976
for (j = s0; j < l; j++)
977
call->set_req(p++, in_map->in(k+j));
978
} else {
979
p += l; // already set to top above by add_req_batch
980
}
981
982
// Add the Monitors
983
k = in_jvms->monoff();
984
l = in_jvms->mon_size();
985
out_jvms->set_monoff(p);
986
for (j = 0; j < l; j++)
987
call->set_req(p++, in_map->in(k+j));
988
989
// Copy any scalar object fields.
990
k = in_jvms->scloff();
991
l = in_jvms->scl_size();
992
out_jvms->set_scloff(p);
993
for (j = 0; j < l; j++)
994
call->set_req(p++, in_map->in(k+j));
995
996
// Finish the new jvms.
997
out_jvms->set_endoff(p);
998
999
assert(out_jvms->endoff() == debug_end, "fill ptr must match");
1000
assert(out_jvms->depth() == in_jvms->depth(), "depth must match");
1001
assert(out_jvms->loc_size() == in_jvms->loc_size(), "size must match");
1002
assert(out_jvms->mon_size() == in_jvms->mon_size(), "size must match");
1003
assert(out_jvms->scl_size() == in_jvms->scl_size(), "size must match");
1004
assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");
1005
1006
// Update the two tail pointers in parallel.
1007
out_jvms = out_jvms->caller();
1008
in_jvms = in_jvms->caller();
1009
}
1010
1011
assert(debug_ptr == non_debug_edges, "debug info must fit exactly");
1012
1013
// Test the correctness of JVMState::debug_xxx accessors:
1014
assert(call->jvms()->debug_start() == non_debug_edges, "");
1015
assert(call->jvms()->debug_end() == call->req(), "");
1016
assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");
1017
}
1018
1019
bool GraphKit::compute_stack_effects(int& inputs, int& depth) {
1020
Bytecodes::Code code = java_bc();
1021
if (code == Bytecodes::_wide) {
1022
code = method()->java_code_at_bci(bci() + 1);
1023
}
1024
1025
BasicType rtype = T_ILLEGAL;
1026
int rsize = 0;
1027
1028
if (code != Bytecodes::_illegal) {
1029
depth = Bytecodes::depth(code); // checkcast=0, athrow=-1
1030
rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V
1031
if (rtype < T_CONFLICT)
1032
rsize = type2size[rtype];
1033
}
1034
1035
switch (code) {
1036
case Bytecodes::_illegal:
1037
return false;
1038
1039
case Bytecodes::_ldc:
1040
case Bytecodes::_ldc_w:
1041
case Bytecodes::_ldc2_w:
1042
inputs = 0;
1043
break;
1044
1045
case Bytecodes::_dup: inputs = 1; break;
1046
case Bytecodes::_dup_x1: inputs = 2; break;
1047
case Bytecodes::_dup_x2: inputs = 3; break;
1048
case Bytecodes::_dup2: inputs = 2; break;
1049
case Bytecodes::_dup2_x1: inputs = 3; break;
1050
case Bytecodes::_dup2_x2: inputs = 4; break;
1051
case Bytecodes::_swap: inputs = 2; break;
1052
case Bytecodes::_arraylength: inputs = 1; break;
1053
1054
case Bytecodes::_getstatic:
1055
case Bytecodes::_putstatic:
1056
case Bytecodes::_getfield:
1057
case Bytecodes::_putfield:
1058
{
1059
bool ignored_will_link;
1060
ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);
1061
int size = field->type()->size();
1062
bool is_get = (depth >= 0), is_static = (depth & 1);
1063
inputs = (is_static ? 0 : 1);
1064
if (is_get) {
1065
depth = size - inputs;
1066
} else {
1067
inputs += size; // putxxx pops the value from the stack
1068
depth = - inputs;
1069
}
1070
}
1071
break;
1072
1073
case Bytecodes::_invokevirtual:
1074
case Bytecodes::_invokespecial:
1075
case Bytecodes::_invokestatic:
1076
case Bytecodes::_invokedynamic:
1077
case Bytecodes::_invokeinterface:
1078
{
1079
bool ignored_will_link;
1080
ciSignature* declared_signature = NULL;
1081
ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1082
assert(declared_signature != NULL, "cannot be null");
1083
inputs = declared_signature->arg_size_for_bc(code);
1084
int size = declared_signature->return_type()->size();
1085
depth = size - inputs;
1086
}
1087
break;
1088
1089
case Bytecodes::_multianewarray:
1090
{
1091
ciBytecodeStream iter(method());
1092
iter.reset_to_bci(bci());
1093
iter.next();
1094
inputs = iter.get_dimensions();
1095
assert(rsize == 1, "");
1096
depth = rsize - inputs;
1097
}
1098
break;
1099
1100
case Bytecodes::_ireturn:
1101
case Bytecodes::_lreturn:
1102
case Bytecodes::_freturn:
1103
case Bytecodes::_dreturn:
1104
case Bytecodes::_areturn:
1105
assert(rsize == -depth, "");
1106
inputs = rsize;
1107
break;
1108
1109
case Bytecodes::_jsr:
1110
case Bytecodes::_jsr_w:
1111
inputs = 0;
1112
depth = 1; // S.B. depth=1, not zero
1113
break;
1114
1115
default:
1116
// bytecode produces a typed result
1117
inputs = rsize - depth;
1118
assert(inputs >= 0, "");
1119
break;
1120
}
1121
1122
#ifdef ASSERT
1123
// spot check
1124
int outputs = depth + inputs;
1125
assert(outputs >= 0, "sanity");
1126
switch (code) {
1127
case Bytecodes::_checkcast: assert(inputs == 1 && outputs == 1, ""); break;
1128
case Bytecodes::_athrow: assert(inputs == 1 && outputs == 0, ""); break;
1129
case Bytecodes::_aload_0: assert(inputs == 0 && outputs == 1, ""); break;
1130
case Bytecodes::_return: assert(inputs == 0 && outputs == 0, ""); break;
1131
case Bytecodes::_drem: assert(inputs == 4 && outputs == 2, ""); break;
1132
default: break;
1133
}
1134
#endif //ASSERT
1135
1136
return true;
1137
}
1138
1139
1140
1141
//------------------------------basic_plus_adr---------------------------------
1142
Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) {
1143
// short-circuit a common case
1144
if (offset == intcon(0)) return ptr;
1145
return _gvn.transform( new AddPNode(base, ptr, offset) );
1146
}
1147
1148
Node* GraphKit::ConvI2L(Node* offset) {
1149
// short-circuit a common case
1150
jint offset_con = find_int_con(offset, Type::OffsetBot);
1151
if (offset_con != Type::OffsetBot) {
1152
return longcon((jlong) offset_con);
1153
}
1154
return _gvn.transform( new ConvI2LNode(offset));
1155
}
1156
1157
Node* GraphKit::ConvI2UL(Node* offset) {
1158
juint offset_con = (juint) find_int_con(offset, Type::OffsetBot);
1159
if (offset_con != (juint) Type::OffsetBot) {
1160
return longcon((julong) offset_con);
1161
}
1162
Node* conv = _gvn.transform( new ConvI2LNode(offset));
1163
Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1164
return _gvn.transform( new AndLNode(conv, mask) );
1165
}
1166
1167
Node* GraphKit::ConvL2I(Node* offset) {
1168
// short-circuit a common case
1169
jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1170
if (offset_con != (jlong)Type::OffsetBot) {
1171
return intcon((int) offset_con);
1172
}
1173
return _gvn.transform( new ConvL2INode(offset));
1174
}
1175
1176
//-------------------------load_object_klass-----------------------------------
1177
Node* GraphKit::load_object_klass(Node* obj) {
1178
// Special-case a fresh allocation to avoid building nodes:
1179
Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1180
if (akls != NULL) return akls;
1181
Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1182
return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));
1183
}
1184
1185
//-------------------------load_array_length-----------------------------------
1186
Node* GraphKit::load_array_length(Node* array) {
1187
// Special-case a fresh allocation to avoid building nodes:
1188
AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1189
Node *alen;
1190
if (alloc == NULL) {
1191
Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1192
alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1193
} else {
1194
alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1195
}
1196
return alen;
1197
}
1198
1199
Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1200
const TypeOopPtr* oop_type,
1201
bool replace_length_in_map) {
1202
Node* length = alloc->Ideal_length();
1203
if (replace_length_in_map == false || map()->find_edge(length) >= 0) {
1204
Node* ccast = alloc->make_ideal_length(oop_type, &_gvn);
1205
if (ccast != length) {
1206
// do not transfrom ccast here, it might convert to top node for
1207
// negative array length and break assumptions in parsing stage.
1208
_gvn.set_type_bottom(ccast);
1209
record_for_igvn(ccast);
1210
if (replace_length_in_map) {
1211
replace_in_map(length, ccast);
1212
}
1213
return ccast;
1214
}
1215
}
1216
return length;
1217
}
1218
1219
//------------------------------do_null_check----------------------------------
1220
// Helper function to do a NULL pointer check. Returned value is
1221
// the incoming address with NULL casted away. You are allowed to use the
1222
// not-null value only if you are control dependent on the test.
1223
#ifndef PRODUCT
1224
extern int explicit_null_checks_inserted,
1225
explicit_null_checks_elided;
1226
#endif
1227
Node* GraphKit::null_check_common(Node* value, BasicType type,
1228
// optional arguments for variations:
1229
bool assert_null,
1230
Node* *null_control,
1231
bool speculative) {
1232
assert(!assert_null || null_control == NULL, "not both at once");
1233
if (stopped()) return top();
1234
NOT_PRODUCT(explicit_null_checks_inserted++);
1235
1236
// Construct NULL check
1237
Node *chk = NULL;
1238
switch(type) {
1239
case T_LONG : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1240
case T_INT : chk = new CmpINode(value, _gvn.intcon(0)); break;
1241
case T_ARRAY : // fall through
1242
type = T_OBJECT; // simplify further tests
1243
case T_OBJECT : {
1244
const Type *t = _gvn.type( value );
1245
1246
const TypeOopPtr* tp = t->isa_oopptr();
1247
if (tp != NULL && tp->klass() != NULL && !tp->klass()->is_loaded()
1248
// Only for do_null_check, not any of its siblings:
1249
&& !assert_null && null_control == NULL) {
1250
// Usually, any field access or invocation on an unloaded oop type
1251
// will simply fail to link, since the statically linked class is
1252
// likely also to be unloaded. However, in -Xcomp mode, sometimes
1253
// the static class is loaded but the sharper oop type is not.
1254
// Rather than checking for this obscure case in lots of places,
1255
// we simply observe that a null check on an unloaded class
1256
// will always be followed by a nonsense operation, so we
1257
// can just issue the uncommon trap here.
1258
// Our access to the unloaded class will only be correct
1259
// after it has been loaded and initialized, which requires
1260
// a trip through the interpreter.
1261
#ifndef PRODUCT
1262
if (WizardMode) { tty->print("Null check of unloaded "); tp->klass()->print(); tty->cr(); }
1263
#endif
1264
uncommon_trap(Deoptimization::Reason_unloaded,
1265
Deoptimization::Action_reinterpret,
1266
tp->klass(), "!loaded");
1267
return top();
1268
}
1269
1270
if (assert_null) {
1271
// See if the type is contained in NULL_PTR.
1272
// If so, then the value is already null.
1273
if (t->higher_equal(TypePtr::NULL_PTR)) {
1274
NOT_PRODUCT(explicit_null_checks_elided++);
1275
return value; // Elided null assert quickly!
1276
}
1277
} else {
1278
// See if mixing in the NULL pointer changes type.
1279
// If so, then the NULL pointer was not allowed in the original
1280
// type. In other words, "value" was not-null.
1281
if (t->meet(TypePtr::NULL_PTR) != t->remove_speculative()) {
1282
// same as: if (!TypePtr::NULL_PTR->higher_equal(t)) ...
1283
NOT_PRODUCT(explicit_null_checks_elided++);
1284
return value; // Elided null check quickly!
1285
}
1286
}
1287
chk = new CmpPNode( value, null() );
1288
break;
1289
}
1290
1291
default:
1292
fatal("unexpected type: %s", type2name(type));
1293
}
1294
assert(chk != NULL, "sanity check");
1295
chk = _gvn.transform(chk);
1296
1297
BoolTest::mask btest = assert_null ? BoolTest::eq : BoolTest::ne;
1298
BoolNode *btst = new BoolNode( chk, btest);
1299
Node *tst = _gvn.transform( btst );
1300
1301
//-----------
1302
// if peephole optimizations occurred, a prior test existed.
1303
// If a prior test existed, maybe it dominates as we can avoid this test.
1304
if (tst != btst && type == T_OBJECT) {
1305
// At this point we want to scan up the CFG to see if we can
1306
// find an identical test (and so avoid this test altogether).
1307
Node *cfg = control();
1308
int depth = 0;
1309
while( depth < 16 ) { // Limit search depth for speed
1310
if( cfg->Opcode() == Op_IfTrue &&
1311
cfg->in(0)->in(1) == tst ) {
1312
// Found prior test. Use "cast_not_null" to construct an identical
1313
// CastPP (and hence hash to) as already exists for the prior test.
1314
// Return that casted value.
1315
if (assert_null) {
1316
replace_in_map(value, null());
1317
return null(); // do not issue the redundant test
1318
}
1319
Node *oldcontrol = control();
1320
set_control(cfg);
1321
Node *res = cast_not_null(value);
1322
set_control(oldcontrol);
1323
NOT_PRODUCT(explicit_null_checks_elided++);
1324
return res;
1325
}
1326
cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1327
if (cfg == NULL) break; // Quit at region nodes
1328
depth++;
1329
}
1330
}
1331
1332
//-----------
1333
// Branch to failure if null
1334
float ok_prob = PROB_MAX; // a priori estimate: nulls never happen
1335
Deoptimization::DeoptReason reason;
1336
if (assert_null) {
1337
reason = Deoptimization::reason_null_assert(speculative);
1338
} else if (type == T_OBJECT) {
1339
reason = Deoptimization::reason_null_check(speculative);
1340
} else {
1341
reason = Deoptimization::Reason_div0_check;
1342
}
1343
// %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1344
// ciMethodData::has_trap_at will return a conservative -1 if any
1345
// must-be-null assertion has failed. This could cause performance
1346
// problems for a method after its first do_null_assert failure.
1347
// Consider using 'Reason_class_check' instead?
1348
1349
// To cause an implicit null check, we set the not-null probability
1350
// to the maximum (PROB_MAX). For an explicit check the probability
1351
// is set to a smaller value.
1352
if (null_control != NULL || too_many_traps(reason)) {
1353
// probability is less likely
1354
ok_prob = PROB_LIKELY_MAG(3);
1355
} else if (!assert_null &&
1356
(ImplicitNullCheckThreshold > 0) &&
1357
method() != NULL &&
1358
(method()->method_data()->trap_count(reason)
1359
>= (uint)ImplicitNullCheckThreshold)) {
1360
ok_prob = PROB_LIKELY_MAG(3);
1361
}
1362
1363
if (null_control != NULL) {
1364
IfNode* iff = create_and_map_if(control(), tst, ok_prob, COUNT_UNKNOWN);
1365
Node* null_true = _gvn.transform( new IfFalseNode(iff));
1366
set_control( _gvn.transform( new IfTrueNode(iff)));
1367
#ifndef PRODUCT
1368
if (null_true == top()) {
1369
explicit_null_checks_elided++;
1370
}
1371
#endif
1372
(*null_control) = null_true;
1373
} else {
1374
BuildCutout unless(this, tst, ok_prob);
1375
// Check for optimizer eliding test at parse time
1376
if (stopped()) {
1377
// Failure not possible; do not bother making uncommon trap.
1378
NOT_PRODUCT(explicit_null_checks_elided++);
1379
} else if (assert_null) {
1380
uncommon_trap(reason,
1381
Deoptimization::Action_make_not_entrant,
1382
NULL, "assert_null");
1383
} else {
1384
replace_in_map(value, zerocon(type));
1385
builtin_throw(reason);
1386
}
1387
}
1388
1389
// Must throw exception, fall-thru not possible?
1390
if (stopped()) {
1391
return top(); // No result
1392
}
1393
1394
if (assert_null) {
1395
// Cast obj to null on this path.
1396
replace_in_map(value, zerocon(type));
1397
return zerocon(type);
1398
}
1399
1400
// Cast obj to not-null on this path, if there is no null_control.
1401
// (If there is a null_control, a non-null value may come back to haunt us.)
1402
if (type == T_OBJECT) {
1403
Node* cast = cast_not_null(value, false);
1404
if (null_control == NULL || (*null_control) == top())
1405
replace_in_map(value, cast);
1406
value = cast;
1407
}
1408
1409
return value;
1410
}
1411
1412
1413
//------------------------------cast_not_null----------------------------------
1414
// Cast obj to not-null on this path
1415
Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1416
const Type *t = _gvn.type(obj);
1417
const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1418
// Object is already not-null?
1419
if( t == t_not_null ) return obj;
1420
1421
Node *cast = new CastPPNode(obj,t_not_null);
1422
cast->init_req(0, control());
1423
cast = _gvn.transform( cast );
1424
1425
// Scan for instances of 'obj' in the current JVM mapping.
1426
// These instances are known to be not-null after the test.
1427
if (do_replace_in_map)
1428
replace_in_map(obj, cast);
1429
1430
return cast; // Return casted value
1431
}
1432
1433
// Sometimes in intrinsics, we implicitly know an object is not null
1434
// (there's no actual null check) so we can cast it to not null. In
1435
// the course of optimizations, the input to the cast can become null.
1436
// In that case that data path will die and we need the control path
1437
// to become dead as well to keep the graph consistent. So we have to
1438
// add a check for null for which one branch can't be taken. It uses
1439
// an Opaque4 node that will cause the check to be removed after loop
1440
// opts so the test goes away and the compiled code doesn't execute a
1441
// useless check.
1442
Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {
1443
if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {
1444
return value;
1445
}
1446
Node* chk = _gvn.transform(new CmpPNode(value, null()));
1447
Node *tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
1448
Node* opaq = _gvn.transform(new Opaque4Node(C, tst, intcon(1)));
1449
IfNode *iff = new IfNode(control(), opaq, PROB_MAX, COUNT_UNKNOWN);
1450
_gvn.set_type(iff, iff->Value(&_gvn));
1451
Node *if_f = _gvn.transform(new IfFalseNode(iff));
1452
Node *frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
1453
Node* halt = _gvn.transform(new HaltNode(if_f, frame, "unexpected null in intrinsic"));
1454
C->root()->add_req(halt);
1455
Node *if_t = _gvn.transform(new IfTrueNode(iff));
1456
set_control(if_t);
1457
return cast_not_null(value, do_replace_in_map);
1458
}
1459
1460
1461
//--------------------------replace_in_map-------------------------------------
1462
void GraphKit::replace_in_map(Node* old, Node* neww) {
1463
if (old == neww) {
1464
return;
1465
}
1466
1467
map()->replace_edge(old, neww);
1468
1469
// Note: This operation potentially replaces any edge
1470
// on the map. This includes locals, stack, and monitors
1471
// of the current (innermost) JVM state.
1472
1473
// don't let inconsistent types from profiling escape this
1474
// method
1475
1476
const Type* told = _gvn.type(old);
1477
const Type* tnew = _gvn.type(neww);
1478
1479
if (!tnew->higher_equal(told)) {
1480
return;
1481
}
1482
1483
map()->record_replaced_node(old, neww);
1484
}
1485
1486
1487
//=============================================================================
1488
//--------------------------------memory---------------------------------------
1489
Node* GraphKit::memory(uint alias_idx) {
1490
MergeMemNode* mem = merged_memory();
1491
Node* p = mem->memory_at(alias_idx);
1492
assert(p != mem->empty_memory(), "empty");
1493
_gvn.set_type(p, Type::MEMORY); // must be mapped
1494
return p;
1495
}
1496
1497
//-----------------------------reset_memory------------------------------------
1498
Node* GraphKit::reset_memory() {
1499
Node* mem = map()->memory();
1500
// do not use this node for any more parsing!
1501
debug_only( map()->set_memory((Node*)NULL) );
1502
return _gvn.transform( mem );
1503
}
1504
1505
//------------------------------set_all_memory---------------------------------
1506
void GraphKit::set_all_memory(Node* newmem) {
1507
Node* mergemem = MergeMemNode::make(newmem);
1508
gvn().set_type_bottom(mergemem);
1509
map()->set_memory(mergemem);
1510
}
1511
1512
//------------------------------set_all_memory_call----------------------------
1513
void GraphKit::set_all_memory_call(Node* call, bool separate_io_proj) {
1514
Node* newmem = _gvn.transform( new ProjNode(call, TypeFunc::Memory, separate_io_proj) );
1515
set_all_memory(newmem);
1516
}
1517
1518
//=============================================================================
1519
//
1520
// parser factory methods for MemNodes
1521
//
1522
// These are layered on top of the factory methods in LoadNode and StoreNode,
1523
// and integrate with the parser's memory state and _gvn engine.
1524
//
1525
1526
// factory methods in "int adr_idx"
1527
Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1528
int adr_idx,
1529
MemNode::MemOrd mo,
1530
LoadNode::ControlDependency control_dependency,
1531
bool require_atomic_access,
1532
bool unaligned,
1533
bool mismatched,
1534
bool unsafe,
1535
uint8_t barrier_data) {
1536
assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1537
const TypePtr* adr_type = NULL; // debug-mode-only argument
1538
debug_only(adr_type = C->get_adr_type(adr_idx));
1539
Node* mem = memory(adr_idx);
1540
Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1541
ld = _gvn.transform(ld);
1542
if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1543
// Improve graph before escape analysis and boxing elimination.
1544
record_for_igvn(ld);
1545
}
1546
return ld;
1547
}
1548
1549
Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1550
int adr_idx,
1551
MemNode::MemOrd mo,
1552
bool require_atomic_access,
1553
bool unaligned,
1554
bool mismatched,
1555
bool unsafe) {
1556
assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1557
const TypePtr* adr_type = NULL;
1558
debug_only(adr_type = C->get_adr_type(adr_idx));
1559
Node *mem = memory(adr_idx);
1560
Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1561
if (unaligned) {
1562
st->as_Store()->set_unaligned_access();
1563
}
1564
if (mismatched) {
1565
st->as_Store()->set_mismatched_access();
1566
}
1567
if (unsafe) {
1568
st->as_Store()->set_unsafe_access();
1569
}
1570
st = _gvn.transform(st);
1571
set_memory(st, adr_idx);
1572
// Back-to-back stores can only remove intermediate store with DU info
1573
// so push on worklist for optimizer.
1574
if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1575
record_for_igvn(st);
1576
1577
return st;
1578
}
1579
1580
Node* GraphKit::access_store_at(Node* obj,
1581
Node* adr,
1582
const TypePtr* adr_type,
1583
Node* val,
1584
const Type* val_type,
1585
BasicType bt,
1586
DecoratorSet decorators) {
1587
// Transformation of a value which could be NULL pointer (CastPP #NULL)
1588
// could be delayed during Parse (for example, in adjust_map_after_if()).
1589
// Execute transformation here to avoid barrier generation in such case.
1590
if (_gvn.type(val) == TypePtr::NULL_PTR) {
1591
val = _gvn.makecon(TypePtr::NULL_PTR);
1592
}
1593
1594
if (stopped()) {
1595
return top(); // Dead path ?
1596
}
1597
1598
assert(val != NULL, "not dead path");
1599
1600
C2AccessValuePtr addr(adr, adr_type);
1601
C2AccessValue value(val, val_type);
1602
C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1603
if (access.is_raw()) {
1604
return _barrier_set->BarrierSetC2::store_at(access, value);
1605
} else {
1606
return _barrier_set->store_at(access, value);
1607
}
1608
}
1609
1610
Node* GraphKit::access_load_at(Node* obj, // containing obj
1611
Node* adr, // actual adress to store val at
1612
const TypePtr* adr_type,
1613
const Type* val_type,
1614
BasicType bt,
1615
DecoratorSet decorators) {
1616
if (stopped()) {
1617
return top(); // Dead path ?
1618
}
1619
1620
C2AccessValuePtr addr(adr, adr_type);
1621
C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr);
1622
if (access.is_raw()) {
1623
return _barrier_set->BarrierSetC2::load_at(access, val_type);
1624
} else {
1625
return _barrier_set->load_at(access, val_type);
1626
}
1627
}
1628
1629
Node* GraphKit::access_load(Node* adr, // actual adress to load val at
1630
const Type* val_type,
1631
BasicType bt,
1632
DecoratorSet decorators) {
1633
if (stopped()) {
1634
return top(); // Dead path ?
1635
}
1636
1637
C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1638
C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1639
if (access.is_raw()) {
1640
return _barrier_set->BarrierSetC2::load_at(access, val_type);
1641
} else {
1642
return _barrier_set->load_at(access, val_type);
1643
}
1644
}
1645
1646
Node* GraphKit::access_atomic_cmpxchg_val_at(Node* obj,
1647
Node* adr,
1648
const TypePtr* adr_type,
1649
int alias_idx,
1650
Node* expected_val,
1651
Node* new_val,
1652
const Type* value_type,
1653
BasicType bt,
1654
DecoratorSet decorators) {
1655
C2AccessValuePtr addr(adr, adr_type);
1656
C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1657
bt, obj, addr, alias_idx);
1658
if (access.is_raw()) {
1659
return _barrier_set->BarrierSetC2::atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1660
} else {
1661
return _barrier_set->atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1662
}
1663
}
1664
1665
Node* GraphKit::access_atomic_cmpxchg_bool_at(Node* obj,
1666
Node* adr,
1667
const TypePtr* adr_type,
1668
int alias_idx,
1669
Node* expected_val,
1670
Node* new_val,
1671
const Type* value_type,
1672
BasicType bt,
1673
DecoratorSet decorators) {
1674
C2AccessValuePtr addr(adr, adr_type);
1675
C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1676
bt, obj, addr, alias_idx);
1677
if (access.is_raw()) {
1678
return _barrier_set->BarrierSetC2::atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1679
} else {
1680
return _barrier_set->atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1681
}
1682
}
1683
1684
Node* GraphKit::access_atomic_xchg_at(Node* obj,
1685
Node* adr,
1686
const TypePtr* adr_type,
1687
int alias_idx,
1688
Node* new_val,
1689
const Type* value_type,
1690
BasicType bt,
1691
DecoratorSet decorators) {
1692
C2AccessValuePtr addr(adr, adr_type);
1693
C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1694
bt, obj, addr, alias_idx);
1695
if (access.is_raw()) {
1696
return _barrier_set->BarrierSetC2::atomic_xchg_at(access, new_val, value_type);
1697
} else {
1698
return _barrier_set->atomic_xchg_at(access, new_val, value_type);
1699
}
1700
}
1701
1702
Node* GraphKit::access_atomic_add_at(Node* obj,
1703
Node* adr,
1704
const TypePtr* adr_type,
1705
int alias_idx,
1706
Node* new_val,
1707
const Type* value_type,
1708
BasicType bt,
1709
DecoratorSet decorators) {
1710
C2AccessValuePtr addr(adr, adr_type);
1711
C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1712
if (access.is_raw()) {
1713
return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1714
} else {
1715
return _barrier_set->atomic_add_at(access, new_val, value_type);
1716
}
1717
}
1718
1719
void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1720
return _barrier_set->clone(this, src, dst, size, is_array);
1721
}
1722
1723
//-------------------------array_element_address-------------------------
1724
Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1725
const TypeInt* sizetype, Node* ctrl) {
1726
uint shift = exact_log2(type2aelembytes(elembt));
1727
uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1728
1729
// short-circuit a common case (saves lots of confusing waste motion)
1730
jint idx_con = find_int_con(idx, -1);
1731
if (idx_con >= 0) {
1732
intptr_t offset = header + ((intptr_t)idx_con << shift);
1733
return basic_plus_adr(ary, offset);
1734
}
1735
1736
// must be correct type for alignment purposes
1737
Node* base = basic_plus_adr(ary, header);
1738
idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1739
Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1740
return basic_plus_adr(ary, base, scale);
1741
}
1742
1743
//-------------------------load_array_element-------------------------
1744
Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1745
const Type* elemtype = arytype->elem();
1746
BasicType elembt = elemtype->array_element_basic_type();
1747
Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1748
if (elembt == T_NARROWOOP) {
1749
elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1750
}
1751
Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1752
IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1753
return ld;
1754
}
1755
1756
//-------------------------set_arguments_for_java_call-------------------------
1757
// Arguments (pre-popped from the stack) are taken from the JVMS.
1758
void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1759
// Add the call arguments:
1760
uint nargs = call->method()->arg_size();
1761
for (uint i = 0; i < nargs; i++) {
1762
Node* arg = argument(i);
1763
call->init_req(i + TypeFunc::Parms, arg);
1764
}
1765
}
1766
1767
//---------------------------set_edges_for_java_call---------------------------
1768
// Connect a newly created call into the current JVMS.
1769
// A return value node (if any) is returned from set_edges_for_java_call.
1770
void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1771
1772
// Add the predefined inputs:
1773
call->init_req( TypeFunc::Control, control() );
1774
call->init_req( TypeFunc::I_O , i_o() );
1775
call->init_req( TypeFunc::Memory , reset_memory() );
1776
call->init_req( TypeFunc::FramePtr, frameptr() );
1777
call->init_req( TypeFunc::ReturnAdr, top() );
1778
1779
add_safepoint_edges(call, must_throw);
1780
1781
Node* xcall = _gvn.transform(call);
1782
1783
if (xcall == top()) {
1784
set_control(top());
1785
return;
1786
}
1787
assert(xcall == call, "call identity is stable");
1788
1789
// Re-use the current map to produce the result.
1790
1791
set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1792
set_i_o( _gvn.transform(new ProjNode(call, TypeFunc::I_O , separate_io_proj)));
1793
set_all_memory_call(xcall, separate_io_proj);
1794
1795
//return xcall; // no need, caller already has it
1796
}
1797
1798
Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1799
if (stopped()) return top(); // maybe the call folded up?
1800
1801
// Capture the return value, if any.
1802
Node* ret;
1803
if (call->method() == NULL ||
1804
call->method()->return_type()->basic_type() == T_VOID)
1805
ret = top();
1806
else ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1807
1808
// Note: Since any out-of-line call can produce an exception,
1809
// we always insert an I_O projection from the call into the result.
1810
1811
make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1812
1813
if (separate_io_proj) {
1814
// The caller requested separate projections be used by the fall
1815
// through and exceptional paths, so replace the projections for
1816
// the fall through path.
1817
set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1818
set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1819
}
1820
return ret;
1821
}
1822
1823
//--------------------set_predefined_input_for_runtime_call--------------------
1824
// Reading and setting the memory state is way conservative here.
1825
// The real problem is that I am not doing real Type analysis on memory,
1826
// so I cannot distinguish card mark stores from other stores. Across a GC
1827
// point the Store Barrier and the card mark memory has to agree. I cannot
1828
// have a card mark store and its barrier split across the GC point from
1829
// either above or below. Here I get that to happen by reading ALL of memory.
1830
// A better answer would be to separate out card marks from other memory.
1831
// For now, return the input memory state, so that it can be reused
1832
// after the call, if this call has restricted memory effects.
1833
Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1834
// Set fixed predefined input arguments
1835
Node* memory = reset_memory();
1836
Node* m = narrow_mem == NULL ? memory : narrow_mem;
1837
call->init_req( TypeFunc::Control, control() );
1838
call->init_req( TypeFunc::I_O, top() ); // does no i/o
1839
call->init_req( TypeFunc::Memory, m ); // may gc ptrs
1840
call->init_req( TypeFunc::FramePtr, frameptr() );
1841
call->init_req( TypeFunc::ReturnAdr, top() );
1842
return memory;
1843
}
1844
1845
//-------------------set_predefined_output_for_runtime_call--------------------
1846
// Set control and memory (not i_o) from the call.
1847
// If keep_mem is not NULL, use it for the output state,
1848
// except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM.
1849
// If hook_mem is NULL, this call produces no memory effects at all.
1850
// If hook_mem is a Java-visible memory slice (such as arraycopy operands),
1851
// then only that memory slice is taken from the call.
1852
// In the last case, we must put an appropriate memory barrier before
1853
// the call, so as to create the correct anti-dependencies on loads
1854
// preceding the call.
1855
void GraphKit::set_predefined_output_for_runtime_call(Node* call,
1856
Node* keep_mem,
1857
const TypePtr* hook_mem) {
1858
// no i/o
1859
set_control(_gvn.transform( new ProjNode(call,TypeFunc::Control) ));
1860
if (keep_mem) {
1861
// First clone the existing memory state
1862
set_all_memory(keep_mem);
1863
if (hook_mem != NULL) {
1864
// Make memory for the call
1865
Node* mem = _gvn.transform( new ProjNode(call, TypeFunc::Memory) );
1866
// Set the RawPtr memory state only. This covers all the heap top/GC stuff
1867
// We also use hook_mem to extract specific effects from arraycopy stubs.
1868
set_memory(mem, hook_mem);
1869
}
1870
// ...else the call has NO memory effects.
1871
1872
// Make sure the call advertises its memory effects precisely.
1873
// This lets us build accurate anti-dependences in gcm.cpp.
1874
assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem),
1875
"call node must be constructed correctly");
1876
} else {
1877
assert(hook_mem == NULL, "");
1878
// This is not a "slow path" call; all memory comes from the call.
1879
set_all_memory_call(call);
1880
}
1881
}
1882
1883
// Keep track of MergeMems feeding into other MergeMems
1884
static void add_mergemem_users_to_worklist(Unique_Node_List& wl, Node* mem) {
1885
if (!mem->is_MergeMem()) {
1886
return;
1887
}
1888
for (SimpleDUIterator i(mem); i.has_next(); i.next()) {
1889
Node* use = i.get();
1890
if (use->is_MergeMem()) {
1891
wl.push(use);
1892
}
1893
}
1894
}
1895
1896
// Replace the call with the current state of the kit.
1897
void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1898
JVMState* ejvms = NULL;
1899
if (has_exceptions()) {
1900
ejvms = transfer_exceptions_into_jvms();
1901
}
1902
1903
ReplacedNodes replaced_nodes = map()->replaced_nodes();
1904
ReplacedNodes replaced_nodes_exception;
1905
Node* ex_ctl = top();
1906
1907
SafePointNode* final_state = stop();
1908
1909
// Find all the needed outputs of this call
1910
CallProjections callprojs;
1911
call->extract_projections(&callprojs, true);
1912
1913
Unique_Node_List wl;
1914
Node* init_mem = call->in(TypeFunc::Memory);
1915
Node* final_mem = final_state->in(TypeFunc::Memory);
1916
Node* final_ctl = final_state->in(TypeFunc::Control);
1917
Node* final_io = final_state->in(TypeFunc::I_O);
1918
1919
// Replace all the old call edges with the edges from the inlining result
1920
if (callprojs.fallthrough_catchproj != NULL) {
1921
C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1922
}
1923
if (callprojs.fallthrough_memproj != NULL) {
1924
if (final_mem->is_MergeMem()) {
1925
// Parser's exits MergeMem was not transformed but may be optimized
1926
final_mem = _gvn.transform(final_mem);
1927
}
1928
C->gvn_replace_by(callprojs.fallthrough_memproj, final_mem);
1929
add_mergemem_users_to_worklist(wl, final_mem);
1930
}
1931
if (callprojs.fallthrough_ioproj != NULL) {
1932
C->gvn_replace_by(callprojs.fallthrough_ioproj, final_io);
1933
}
1934
1935
// Replace the result with the new result if it exists and is used
1936
if (callprojs.resproj != NULL && result != NULL) {
1937
C->gvn_replace_by(callprojs.resproj, result);
1938
}
1939
1940
if (ejvms == NULL) {
1941
// No exception edges to simply kill off those paths
1942
if (callprojs.catchall_catchproj != NULL) {
1943
C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
1944
}
1945
if (callprojs.catchall_memproj != NULL) {
1946
C->gvn_replace_by(callprojs.catchall_memproj, C->top());
1947
}
1948
if (callprojs.catchall_ioproj != NULL) {
1949
C->gvn_replace_by(callprojs.catchall_ioproj, C->top());
1950
}
1951
// Replace the old exception object with top
1952
if (callprojs.exobj != NULL) {
1953
C->gvn_replace_by(callprojs.exobj, C->top());
1954
}
1955
} else {
1956
GraphKit ekit(ejvms);
1957
1958
// Load my combined exception state into the kit, with all phis transformed:
1959
SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
1960
replaced_nodes_exception = ex_map->replaced_nodes();
1961
1962
Node* ex_oop = ekit.use_exception_state(ex_map);
1963
1964
if (callprojs.catchall_catchproj != NULL) {
1965
C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
1966
ex_ctl = ekit.control();
1967
}
1968
if (callprojs.catchall_memproj != NULL) {
1969
Node* ex_mem = ekit.reset_memory();
1970
C->gvn_replace_by(callprojs.catchall_memproj, ex_mem);
1971
add_mergemem_users_to_worklist(wl, ex_mem);
1972
}
1973
if (callprojs.catchall_ioproj != NULL) {
1974
C->gvn_replace_by(callprojs.catchall_ioproj, ekit.i_o());
1975
}
1976
1977
// Replace the old exception object with the newly created one
1978
if (callprojs.exobj != NULL) {
1979
C->gvn_replace_by(callprojs.exobj, ex_oop);
1980
}
1981
}
1982
1983
// Disconnect the call from the graph
1984
call->disconnect_inputs(C);
1985
C->gvn_replace_by(call, C->top());
1986
1987
// Clean up any MergeMems that feed other MergeMems since the
1988
// optimizer doesn't like that.
1989
while (wl.size() > 0) {
1990
_gvn.transform(wl.pop());
1991
}
1992
1993
if (callprojs.fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
1994
replaced_nodes.apply(C, final_ctl);
1995
}
1996
if (!ex_ctl->is_top() && do_replaced_nodes) {
1997
replaced_nodes_exception.apply(C, ex_ctl);
1998
}
1999
}
2000
2001
2002
//------------------------------increment_counter------------------------------
2003
// for statistics: increment a VM counter by 1
2004
2005
void GraphKit::increment_counter(address counter_addr) {
2006
Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2007
increment_counter(adr1);
2008
}
2009
2010
void GraphKit::increment_counter(Node* counter_addr) {
2011
int adr_type = Compile::AliasIdxRaw;
2012
Node* ctrl = control();
2013
Node* cnt = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);
2014
Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1)));
2015
store_to_memory(ctrl, counter_addr, incr, T_LONG, adr_type, MemNode::unordered);
2016
}
2017
2018
2019
//------------------------------uncommon_trap----------------------------------
2020
// Bail out to the interpreter in mid-method. Implemented by calling the
2021
// uncommon_trap blob. This helper function inserts a runtime call with the
2022
// right debug info.
2023
void GraphKit::uncommon_trap(int trap_request,
2024
ciKlass* klass, const char* comment,
2025
bool must_throw,
2026
bool keep_exact_action) {
2027
if (failing()) stop();
2028
if (stopped()) return; // trap reachable?
2029
2030
// Note: If ProfileTraps is true, and if a deopt. actually
2031
// occurs here, the runtime will make sure an MDO exists. There is
2032
// no need to call method()->ensure_method_data() at this point.
2033
2034
// Set the stack pointer to the right value for reexecution:
2035
set_sp(reexecute_sp());
2036
2037
#ifdef ASSERT
2038
if (!must_throw) {
2039
// Make sure the stack has at least enough depth to execute
2040
// the current bytecode.
2041
int inputs, ignored_depth;
2042
if (compute_stack_effects(inputs, ignored_depth)) {
2043
assert(sp() >= inputs, "must have enough JVMS stack to execute %s: sp=%d, inputs=%d",
2044
Bytecodes::name(java_bc()), sp(), inputs);
2045
}
2046
}
2047
#endif
2048
2049
Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
2050
Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
2051
2052
switch (action) {
2053
case Deoptimization::Action_maybe_recompile:
2054
case Deoptimization::Action_reinterpret:
2055
// Temporary fix for 6529811 to allow virtual calls to be sure they
2056
// get the chance to go from mono->bi->mega
2057
if (!keep_exact_action &&
2058
Deoptimization::trap_request_index(trap_request) < 0 &&
2059
too_many_recompiles(reason)) {
2060
// This BCI is causing too many recompilations.
2061
if (C->log() != NULL) {
2062
C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'",
2063
Deoptimization::trap_reason_name(reason),
2064
Deoptimization::trap_action_name(action));
2065
}
2066
action = Deoptimization::Action_none;
2067
trap_request = Deoptimization::make_trap_request(reason, action);
2068
} else {
2069
C->set_trap_can_recompile(true);
2070
}
2071
break;
2072
case Deoptimization::Action_make_not_entrant:
2073
C->set_trap_can_recompile(true);
2074
break;
2075
case Deoptimization::Action_none:
2076
case Deoptimization::Action_make_not_compilable:
2077
break;
2078
default:
2079
#ifdef ASSERT
2080
fatal("unknown action %d: %s", action, Deoptimization::trap_action_name(action));
2081
#endif
2082
break;
2083
}
2084
2085
if (TraceOptoParse) {
2086
char buf[100];
2087
tty->print_cr("Uncommon trap %s at bci:%d",
2088
Deoptimization::format_trap_request(buf, sizeof(buf),
2089
trap_request), bci());
2090
}
2091
2092
CompileLog* log = C->log();
2093
if (log != NULL) {
2094
int kid = (klass == NULL)? -1: log->identify(klass);
2095
log->begin_elem("uncommon_trap bci='%d'", bci());
2096
char buf[100];
2097
log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
2098
trap_request));
2099
if (kid >= 0) log->print(" klass='%d'", kid);
2100
if (comment != NULL) log->print(" comment='%s'", comment);
2101
log->end_elem();
2102
}
2103
2104
// Make sure any guarding test views this path as very unlikely
2105
Node *i0 = control()->in(0);
2106
if (i0 != NULL && i0->is_If()) { // Found a guarding if test?
2107
IfNode *iff = i0->as_If();
2108
float f = iff->_prob; // Get prob
2109
if (control()->Opcode() == Op_IfTrue) {
2110
if (f > PROB_UNLIKELY_MAG(4))
2111
iff->_prob = PROB_MIN;
2112
} else {
2113
if (f < PROB_LIKELY_MAG(4))
2114
iff->_prob = PROB_MAX;
2115
}
2116
}
2117
2118
// Clear out dead values from the debug info.
2119
kill_dead_locals();
2120
2121
// Now insert the uncommon trap subroutine call
2122
address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2123
const TypePtr* no_memory_effects = NULL;
2124
// Pass the index of the class to be loaded
2125
Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON |
2126
(must_throw ? RC_MUST_THROW : 0),
2127
OptoRuntime::uncommon_trap_Type(),
2128
call_addr, "uncommon_trap", no_memory_effects,
2129
intcon(trap_request));
2130
assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request,
2131
"must extract request correctly from the graph");
2132
assert(trap_request != 0, "zero value reserved by uncommon_trap_request");
2133
2134
call->set_req(TypeFunc::ReturnAdr, returnadr());
2135
// The debug info is the only real input to this call.
2136
2137
// Halt-and-catch fire here. The above call should never return!
2138
HaltNode* halt = new HaltNode(control(), frameptr(), "uncommon trap returned which should never happen"
2139
PRODUCT_ONLY(COMMA /*reachable*/false));
2140
_gvn.set_type_bottom(halt);
2141
root()->add_req(halt);
2142
2143
stop_and_kill_map();
2144
}
2145
2146
2147
//--------------------------just_allocated_object------------------------------
2148
// Report the object that was just allocated.
2149
// It must be the case that there are no intervening safepoints.
2150
// We use this to determine if an object is so "fresh" that
2151
// it does not require card marks.
2152
Node* GraphKit::just_allocated_object(Node* current_control) {
2153
Node* ctrl = current_control;
2154
// Object::<init> is invoked after allocation, most of invoke nodes
2155
// will be reduced, but a region node is kept in parse time, we check
2156
// the pattern and skip the region node if it degraded to a copy.
2157
if (ctrl != NULL && ctrl->is_Region() && ctrl->req() == 2 &&
2158
ctrl->as_Region()->is_copy()) {
2159
ctrl = ctrl->as_Region()->is_copy();
2160
}
2161
if (C->recent_alloc_ctl() == ctrl) {
2162
return C->recent_alloc_obj();
2163
}
2164
return NULL;
2165
}
2166
2167
2168
/**
2169
* Record profiling data exact_kls for Node n with the type system so
2170
* that it can propagate it (speculation)
2171
*
2172
* @param n node that the type applies to
2173
* @param exact_kls type from profiling
2174
* @param maybe_null did profiling see null?
2175
*
2176
* @return node with improved type
2177
*/
2178
Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2179
const Type* current_type = _gvn.type(n);
2180
assert(UseTypeSpeculation, "type speculation must be on");
2181
2182
const TypePtr* speculative = current_type->speculative();
2183
2184
// Should the klass from the profile be recorded in the speculative type?
2185
if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2186
const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);
2187
const TypeOopPtr* xtype = tklass->as_instance_type();
2188
assert(xtype->klass_is_exact(), "Should be exact");
2189
// Any reason to believe n is not null (from this profiling or a previous one)?
2190
assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2191
const TypePtr* ptr = (ptr_kind == ProfileMaybeNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2192
// record the new speculative type's depth
2193
speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2194
speculative = speculative->with_inline_depth(jvms()->depth());
2195
} else if (current_type->would_improve_ptr(ptr_kind)) {
2196
// Profiling report that null was never seen so we can change the
2197
// speculative type to non null ptr.
2198
if (ptr_kind == ProfileAlwaysNull) {
2199
speculative = TypePtr::NULL_PTR;
2200
} else {
2201
assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2202
const TypePtr* ptr = TypePtr::NOTNULL;
2203
if (speculative != NULL) {
2204
speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2205
} else {
2206
speculative = ptr;
2207
}
2208
}
2209
}
2210
2211
if (speculative != current_type->speculative()) {
2212
// Build a type with a speculative type (what we think we know
2213
// about the type but will need a guard when we use it)
2214
const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2215
// We're changing the type, we need a new CheckCast node to carry
2216
// the new type. The new type depends on the control: what
2217
// profiling tells us is only valid from here as far as we can
2218
// tell.
2219
Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2220
cast = _gvn.transform(cast);
2221
replace_in_map(n, cast);
2222
n = cast;
2223
}
2224
2225
return n;
2226
}
2227
2228
/**
2229
* Record profiling data from receiver profiling at an invoke with the
2230
* type system so that it can propagate it (speculation)
2231
*
2232
* @param n receiver node
2233
*
2234
* @return node with improved type
2235
*/
2236
Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2237
if (!UseTypeSpeculation) {
2238
return n;
2239
}
2240
ciKlass* exact_kls = profile_has_unique_klass();
2241
ProfilePtrKind ptr_kind = ProfileMaybeNull;
2242
if ((java_bc() == Bytecodes::_checkcast ||
2243
java_bc() == Bytecodes::_instanceof ||
2244
java_bc() == Bytecodes::_aastore) &&
2245
method()->method_data()->is_mature()) {
2246
ciProfileData* data = method()->method_data()->bci_to_data(bci());
2247
if (data != NULL) {
2248
if (!data->as_BitData()->null_seen()) {
2249
ptr_kind = ProfileNeverNull;
2250
} else {
2251
assert(data->is_ReceiverTypeData(), "bad profile data type");
2252
ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2253
uint i = 0;
2254
for (; i < call->row_limit(); i++) {
2255
ciKlass* receiver = call->receiver(i);
2256
if (receiver != NULL) {
2257
break;
2258
}
2259
}
2260
ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2261
}
2262
}
2263
}
2264
return record_profile_for_speculation(n, exact_kls, ptr_kind);
2265
}
2266
2267
/**
2268
* Record profiling data from argument profiling at an invoke with the
2269
* type system so that it can propagate it (speculation)
2270
*
2271
* @param dest_method target method for the call
2272
* @param bc what invoke bytecode is this?
2273
*/
2274
void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2275
if (!UseTypeSpeculation) {
2276
return;
2277
}
2278
const TypeFunc* tf = TypeFunc::make(dest_method);
2279
int nargs = tf->domain()->cnt() - TypeFunc::Parms;
2280
int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2281
for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2282
const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2283
if (is_reference_type(targ->basic_type())) {
2284
ProfilePtrKind ptr_kind = ProfileMaybeNull;
2285
ciKlass* better_type = NULL;
2286
if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2287
record_profile_for_speculation(argument(j), better_type, ptr_kind);
2288
}
2289
i++;
2290
}
2291
}
2292
}
2293
2294
/**
2295
* Record profiling data from parameter profiling at an invoke with
2296
* the type system so that it can propagate it (speculation)
2297
*/
2298
void GraphKit::record_profiled_parameters_for_speculation() {
2299
if (!UseTypeSpeculation) {
2300
return;
2301
}
2302
for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2303
if (_gvn.type(local(i))->isa_oopptr()) {
2304
ProfilePtrKind ptr_kind = ProfileMaybeNull;
2305
ciKlass* better_type = NULL;
2306
if (method()->parameter_profiled_type(j, better_type, ptr_kind)) {
2307
record_profile_for_speculation(local(i), better_type, ptr_kind);
2308
}
2309
j++;
2310
}
2311
}
2312
}
2313
2314
/**
2315
* Record profiling data from return value profiling at an invoke with
2316
* the type system so that it can propagate it (speculation)
2317
*/
2318
void GraphKit::record_profiled_return_for_speculation() {
2319
if (!UseTypeSpeculation) {
2320
return;
2321
}
2322
ProfilePtrKind ptr_kind = ProfileMaybeNull;
2323
ciKlass* better_type = NULL;
2324
if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2325
// If profiling reports a single type for the return value,
2326
// feed it to the type system so it can propagate it as a
2327
// speculative type
2328
record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2329
}
2330
}
2331
2332
void GraphKit::round_double_arguments(ciMethod* dest_method) {
2333
if (Matcher::strict_fp_requires_explicit_rounding) {
2334
// (Note: TypeFunc::make has a cache that makes this fast.)
2335
const TypeFunc* tf = TypeFunc::make(dest_method);
2336
int nargs = tf->domain()->cnt() - TypeFunc::Parms;
2337
for (int j = 0; j < nargs; j++) {
2338
const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2339
if (targ->basic_type() == T_DOUBLE) {
2340
// If any parameters are doubles, they must be rounded before
2341
// the call, dstore_rounding does gvn.transform
2342
Node *arg = argument(j);
2343
arg = dstore_rounding(arg);
2344
set_argument(j, arg);
2345
}
2346
}
2347
}
2348
}
2349
2350
// rounding for strict float precision conformance
2351
Node* GraphKit::precision_rounding(Node* n) {
2352
if (Matcher::strict_fp_requires_explicit_rounding) {
2353
#ifdef IA32
2354
if (UseSSE == 0) {
2355
return _gvn.transform(new RoundFloatNode(0, n));
2356
}
2357
#else
2358
Unimplemented();
2359
#endif // IA32
2360
}
2361
return n;
2362
}
2363
2364
// rounding for strict double precision conformance
2365
Node* GraphKit::dprecision_rounding(Node *n) {
2366
if (Matcher::strict_fp_requires_explicit_rounding) {
2367
#ifdef IA32
2368
if (UseSSE < 2) {
2369
return _gvn.transform(new RoundDoubleNode(0, n));
2370
}
2371
#else
2372
Unimplemented();
2373
#endif // IA32
2374
}
2375
return n;
2376
}
2377
2378
// rounding for non-strict double stores
2379
Node* GraphKit::dstore_rounding(Node* n) {
2380
if (Matcher::strict_fp_requires_explicit_rounding) {
2381
#ifdef IA32
2382
if (UseSSE < 2) {
2383
return _gvn.transform(new RoundDoubleNode(0, n));
2384
}
2385
#else
2386
Unimplemented();
2387
#endif // IA32
2388
}
2389
return n;
2390
}
2391
2392
//=============================================================================
2393
// Generate a fast path/slow path idiom. Graph looks like:
2394
// [foo] indicates that 'foo' is a parameter
2395
//
2396
// [in] NULL
2397
// \ /
2398
// CmpP
2399
// Bool ne
2400
// If
2401
// / \
2402
// True False-<2>
2403
// / |
2404
// / cast_not_null
2405
// Load | | ^
2406
// [fast_test] | |
2407
// gvn to opt_test | |
2408
// / \ | <1>
2409
// True False |
2410
// | \\ |
2411
// [slow_call] \[fast_result]
2412
// Ctl Val \ \
2413
// | \ \
2414
// Catch <1> \ \
2415
// / \ ^ \ \
2416
// Ex No_Ex | \ \
2417
// | \ \ | \ <2> \
2418
// ... \ [slow_res] | | \ [null_result]
2419
// \ \--+--+--- | |
2420
// \ | / \ | /
2421
// --------Region Phi
2422
//
2423
//=============================================================================
2424
// Code is structured as a series of driver functions all called 'do_XXX' that
2425
// call a set of helper functions. Helper functions first, then drivers.
2426
2427
//------------------------------null_check_oop---------------------------------
2428
// Null check oop. Set null-path control into Region in slot 3.
2429
// Make a cast-not-nullness use the other not-null control. Return cast.
2430
Node* GraphKit::null_check_oop(Node* value, Node* *null_control,
2431
bool never_see_null,
2432
bool safe_for_replace,
2433
bool speculative) {
2434
// Initial NULL check taken path
2435
(*null_control) = top();
2436
Node* cast = null_check_common(value, T_OBJECT, false, null_control, speculative);
2437
2438
// Generate uncommon_trap:
2439
if (never_see_null && (*null_control) != top()) {
2440
// If we see an unexpected null at a check-cast we record it and force a
2441
// recompile; the offending check-cast will be compiled to handle NULLs.
2442
// If we see more than one offending BCI, then all checkcasts in the
2443
// method will be compiled to handle NULLs.
2444
PreserveJVMState pjvms(this);
2445
set_control(*null_control);
2446
replace_in_map(value, null());
2447
Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculative);
2448
uncommon_trap(reason,
2449
Deoptimization::Action_make_not_entrant);
2450
(*null_control) = top(); // NULL path is dead
2451
}
2452
if ((*null_control) == top() && safe_for_replace) {
2453
replace_in_map(value, cast);
2454
}
2455
2456
// Cast away null-ness on the result
2457
return cast;
2458
}
2459
2460
//------------------------------opt_iff----------------------------------------
2461
// Optimize the fast-check IfNode. Set the fast-path region slot 2.
2462
// Return slow-path control.
2463
Node* GraphKit::opt_iff(Node* region, Node* iff) {
2464
IfNode *opt_iff = _gvn.transform(iff)->as_If();
2465
2466
// Fast path taken; set region slot 2
2467
Node *fast_taken = _gvn.transform( new IfFalseNode(opt_iff) );
2468
region->init_req(2,fast_taken); // Capture fast-control
2469
2470
// Fast path not-taken, i.e. slow path
2471
Node *slow_taken = _gvn.transform( new IfTrueNode(opt_iff) );
2472
return slow_taken;
2473
}
2474
2475
//-----------------------------make_runtime_call-------------------------------
2476
Node* GraphKit::make_runtime_call(int flags,
2477
const TypeFunc* call_type, address call_addr,
2478
const char* call_name,
2479
const TypePtr* adr_type,
2480
// The following parms are all optional.
2481
// The first NULL ends the list.
2482
Node* parm0, Node* parm1,
2483
Node* parm2, Node* parm3,
2484
Node* parm4, Node* parm5,
2485
Node* parm6, Node* parm7) {
2486
assert(call_addr != NULL, "must not call NULL targets");
2487
2488
// Slow-path call
2489
bool is_leaf = !(flags & RC_NO_LEAF);
2490
bool has_io = (!is_leaf && !(flags & RC_NO_IO));
2491
if (call_name == NULL) {
2492
assert(!is_leaf, "must supply name for leaf");
2493
call_name = OptoRuntime::stub_name(call_addr);
2494
}
2495
CallNode* call;
2496
if (!is_leaf) {
2497
call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2498
} else if (flags & RC_NO_FP) {
2499
call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2500
} else if (flags & RC_VECTOR){
2501
uint num_bits = call_type->range()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2502
call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2503
} else {
2504
call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2505
}
2506
2507
// The following is similar to set_edges_for_java_call,
2508
// except that the memory effects of the call are restricted to AliasIdxRaw.
2509
2510
// Slow path call has no side-effects, uses few values
2511
bool wide_in = !(flags & RC_NARROW_MEM);
2512
bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2513
2514
Node* prev_mem = NULL;
2515
if (wide_in) {
2516
prev_mem = set_predefined_input_for_runtime_call(call);
2517
} else {
2518
assert(!wide_out, "narrow in => narrow out");
2519
Node* narrow_mem = memory(adr_type);
2520
prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2521
}
2522
2523
// Hook each parm in order. Stop looking at the first NULL.
2524
if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);
2525
if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);
2526
if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);
2527
if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);
2528
if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);
2529
if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);
2530
if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);
2531
if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);
2532
/* close each nested if ===> */ } } } } } } } }
2533
assert(call->in(call->req()-1) != NULL, "must initialize all parms");
2534
2535
if (!is_leaf) {
2536
// Non-leaves can block and take safepoints:
2537
add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));
2538
}
2539
// Non-leaves can throw exceptions:
2540
if (has_io) {
2541
call->set_req(TypeFunc::I_O, i_o());
2542
}
2543
2544
if (flags & RC_UNCOMMON) {
2545
// Set the count to a tiny probability. Cf. Estimate_Block_Frequency.
2546
// (An "if" probability corresponds roughly to an unconditional count.
2547
// Sort of.)
2548
call->set_cnt(PROB_UNLIKELY_MAG(4));
2549
}
2550
2551
Node* c = _gvn.transform(call);
2552
assert(c == call, "cannot disappear");
2553
2554
if (wide_out) {
2555
// Slow path call has full side-effects.
2556
set_predefined_output_for_runtime_call(call);
2557
} else {
2558
// Slow path call has few side-effects, and/or sets few values.
2559
set_predefined_output_for_runtime_call(call, prev_mem, adr_type);
2560
}
2561
2562
if (has_io) {
2563
set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2564
}
2565
return call;
2566
2567
}
2568
2569
// i2b
2570
Node* GraphKit::sign_extend_byte(Node* in) {
2571
Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2572
return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2573
}
2574
2575
// i2s
2576
Node* GraphKit::sign_extend_short(Node* in) {
2577
Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2578
return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2579
}
2580
2581
//-----------------------------make_native_call-------------------------------
2582
Node* GraphKit::make_native_call(address call_addr, const TypeFunc* call_type, uint nargs, ciNativeEntryPoint* nep) {
2583
// Select just the actual call args to pass on
2584
// [MethodHandle fallback, long addr, HALF addr, ... args , NativeEntryPoint nep]
2585
// | |
2586
// V V
2587
// [ ... args ]
2588
uint n_filtered_args = nargs - 4; // -fallback, -addr (2), -nep;
2589
ResourceMark rm;
2590
Node** argument_nodes = NEW_RESOURCE_ARRAY(Node*, n_filtered_args);
2591
const Type** arg_types = TypeTuple::fields(n_filtered_args);
2592
GrowableArray<VMReg> arg_regs(C->comp_arena(), n_filtered_args, n_filtered_args, VMRegImpl::Bad());
2593
2594
VMReg* argRegs = nep->argMoves();
2595
{
2596
for (uint vm_arg_pos = 0, java_arg_read_pos = 0;
2597
vm_arg_pos < n_filtered_args; vm_arg_pos++) {
2598
uint vm_unfiltered_arg_pos = vm_arg_pos + 3; // +3 to skip fallback handle argument and addr (2 since long)
2599
Node* node = argument(vm_unfiltered_arg_pos);
2600
const Type* type = call_type->domain()->field_at(TypeFunc::Parms + vm_unfiltered_arg_pos);
2601
VMReg reg = type == Type::HALF
2602
? VMRegImpl::Bad()
2603
: argRegs[java_arg_read_pos++];
2604
2605
argument_nodes[vm_arg_pos] = node;
2606
arg_types[TypeFunc::Parms + vm_arg_pos] = type;
2607
arg_regs.at_put(vm_arg_pos, reg);
2608
}
2609
}
2610
2611
uint n_returns = call_type->range()->cnt() - TypeFunc::Parms;
2612
GrowableArray<VMReg> ret_regs(C->comp_arena(), n_returns, n_returns, VMRegImpl::Bad());
2613
const Type** ret_types = TypeTuple::fields(n_returns);
2614
2615
VMReg* retRegs = nep->returnMoves();
2616
{
2617
for (uint vm_ret_pos = 0, java_ret_read_pos = 0;
2618
vm_ret_pos < n_returns; vm_ret_pos++) { // 0 or 1
2619
const Type* type = call_type->range()->field_at(TypeFunc::Parms + vm_ret_pos);
2620
VMReg reg = type == Type::HALF
2621
? VMRegImpl::Bad()
2622
: retRegs[java_ret_read_pos++];
2623
2624
ret_regs.at_put(vm_ret_pos, reg);
2625
ret_types[TypeFunc::Parms + vm_ret_pos] = type;
2626
}
2627
}
2628
2629
const TypeFunc* new_call_type = TypeFunc::make(
2630
TypeTuple::make(TypeFunc::Parms + n_filtered_args, arg_types),
2631
TypeTuple::make(TypeFunc::Parms + n_returns, ret_types)
2632
);
2633
2634
if (nep->need_transition()) {
2635
RuntimeStub* invoker = SharedRuntime::make_native_invoker(call_addr,
2636
nep->shadow_space(),
2637
arg_regs, ret_regs);
2638
if (invoker == NULL) {
2639
C->record_failure("native invoker not implemented on this platform");
2640
return NULL;
2641
}
2642
C->add_native_invoker(invoker);
2643
call_addr = invoker->code_begin();
2644
}
2645
assert(call_addr != NULL, "sanity");
2646
2647
CallNativeNode* call = new CallNativeNode(new_call_type, call_addr, nep->name(), TypePtr::BOTTOM,
2648
arg_regs,
2649
ret_regs,
2650
nep->shadow_space(),
2651
nep->need_transition());
2652
2653
if (call->_need_transition) {
2654
add_safepoint_edges(call);
2655
}
2656
2657
set_predefined_input_for_runtime_call(call);
2658
2659
for (uint i = 0; i < n_filtered_args; i++) {
2660
call->init_req(i + TypeFunc::Parms, argument_nodes[i]);
2661
}
2662
2663
Node* c = gvn().transform(call);
2664
assert(c == call, "cannot disappear");
2665
2666
set_predefined_output_for_runtime_call(call);
2667
2668
Node* ret;
2669
if (method() == NULL || method()->return_type()->basic_type() == T_VOID) {
2670
ret = top();
2671
} else {
2672
ret = gvn().transform(new ProjNode(call, TypeFunc::Parms));
2673
// Unpack native results if needed
2674
// Need this method type since it's unerased
2675
switch (nep->method_type()->rtype()->basic_type()) {
2676
case T_CHAR:
2677
ret = _gvn.transform(new AndINode(ret, _gvn.intcon(0xFFFF)));
2678
break;
2679
case T_BYTE:
2680
ret = sign_extend_byte(ret);
2681
break;
2682
case T_SHORT:
2683
ret = sign_extend_short(ret);
2684
break;
2685
default: // do nothing
2686
break;
2687
}
2688
}
2689
2690
push_node(method()->return_type()->basic_type(), ret);
2691
2692
return call;
2693
}
2694
2695
//------------------------------merge_memory-----------------------------------
2696
// Merge memory from one path into the current memory state.
2697
void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2698
for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2699
Node* old_slice = mms.force_memory();
2700
Node* new_slice = mms.memory2();
2701
if (old_slice != new_slice) {
2702
PhiNode* phi;
2703
if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2704
if (mms.is_empty()) {
2705
// clone base memory Phi's inputs for this memory slice
2706
assert(old_slice == mms.base_memory(), "sanity");
2707
phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2708
_gvn.set_type(phi, Type::MEMORY);
2709
for (uint i = 1; i < phi->req(); i++) {
2710
phi->init_req(i, old_slice->in(i));
2711
}
2712
} else {
2713
phi = old_slice->as_Phi(); // Phi was generated already
2714
}
2715
} else {
2716
phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C));
2717
_gvn.set_type(phi, Type::MEMORY);
2718
}
2719
phi->set_req(new_path, new_slice);
2720
mms.set_memory(phi);
2721
}
2722
}
2723
}
2724
2725
//------------------------------make_slow_call_ex------------------------------
2726
// Make the exception handler hookups for the slow call
2727
void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) {
2728
if (stopped()) return;
2729
2730
// Make a catch node with just two handlers: fall-through and catch-all
2731
Node* i_o = _gvn.transform( new ProjNode(call, TypeFunc::I_O, separate_io_proj) );
2732
Node* catc = _gvn.transform( new CatchNode(control(), i_o, 2) );
2733
Node* norm = new CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci);
2734
_gvn.set_type_bottom(norm);
2735
C->record_for_igvn(norm);
2736
Node* excp = _gvn.transform( new CatchProjNode(catc, CatchProjNode::catch_all_index, CatchProjNode::no_handler_bci) );
2737
2738
{ PreserveJVMState pjvms(this);
2739
set_control(excp);
2740
set_i_o(i_o);
2741
2742
if (excp != top()) {
2743
if (deoptimize) {
2744
// Deoptimize if an exception is caught. Don't construct exception state in this case.
2745
uncommon_trap(Deoptimization::Reason_unhandled,
2746
Deoptimization::Action_none);
2747
} else {
2748
// Create an exception state also.
2749
// Use an exact type if the caller has a specific exception.
2750
const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull);
2751
Node* ex_oop = new CreateExNode(ex_type, control(), i_o);
2752
add_exception_state(make_exception_state(_gvn.transform(ex_oop)));
2753
}
2754
}
2755
}
2756
2757
// Get the no-exception control from the CatchNode.
2758
set_control(norm);
2759
}
2760
2761
static IfNode* gen_subtype_check_compare(Node* ctrl, Node* in1, Node* in2, BoolTest::mask test, float p, PhaseGVN& gvn, BasicType bt) {
2762
Node* cmp = NULL;
2763
switch(bt) {
2764
case T_INT: cmp = new CmpINode(in1, in2); break;
2765
case T_ADDRESS: cmp = new CmpPNode(in1, in2); break;
2766
default: fatal("unexpected comparison type %s", type2name(bt));
2767
}
2768
gvn.transform(cmp);
2769
Node* bol = gvn.transform(new BoolNode(cmp, test));
2770
IfNode* iff = new IfNode(ctrl, bol, p, COUNT_UNKNOWN);
2771
gvn.transform(iff);
2772
if (!bol->is_Con()) gvn.record_for_igvn(iff);
2773
return iff;
2774
}
2775
2776
//-------------------------------gen_subtype_check-----------------------------
2777
// Generate a subtyping check. Takes as input the subtype and supertype.
2778
// Returns 2 values: sets the default control() to the true path and returns
2779
// the false path. Only reads invariant memory; sets no (visible) memory.
2780
// The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding
2781
// but that's not exposed to the optimizer. This call also doesn't take in an
2782
// Object; if you wish to check an Object you need to load the Object's class
2783
// prior to coming here.
2784
Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, Node* mem, PhaseGVN& gvn) {
2785
Compile* C = gvn.C;
2786
if ((*ctrl)->is_top()) {
2787
return C->top();
2788
}
2789
2790
// Fast check for identical types, perhaps identical constants.
2791
// The types can even be identical non-constants, in cases
2792
// involving Array.newInstance, Object.clone, etc.
2793
if (subklass == superklass)
2794
return C->top(); // false path is dead; no test needed.
2795
2796
if (gvn.type(superklass)->singleton()) {
2797
ciKlass* superk = gvn.type(superklass)->is_klassptr()->klass();
2798
ciKlass* subk = gvn.type(subklass)->is_klassptr()->klass();
2799
2800
// In the common case of an exact superklass, try to fold up the
2801
// test before generating code. You may ask, why not just generate
2802
// the code and then let it fold up? The answer is that the generated
2803
// code will necessarily include null checks, which do not always
2804
// completely fold away. If they are also needless, then they turn
2805
// into a performance loss. Example:
2806
// Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;
2807
// Here, the type of 'fa' is often exact, so the store check
2808
// of fa[1]=x will fold up, without testing the nullness of x.
2809
switch (C->static_subtype_check(superk, subk)) {
2810
case Compile::SSC_always_false:
2811
{
2812
Node* always_fail = *ctrl;
2813
*ctrl = gvn.C->top();
2814
return always_fail;
2815
}
2816
case Compile::SSC_always_true:
2817
return C->top();
2818
case Compile::SSC_easy_test:
2819
{
2820
// Just do a direct pointer compare and be done.
2821
IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);
2822
*ctrl = gvn.transform(new IfTrueNode(iff));
2823
return gvn.transform(new IfFalseNode(iff));
2824
}
2825
case Compile::SSC_full_test:
2826
break;
2827
default:
2828
ShouldNotReachHere();
2829
}
2830
}
2831
2832
// %%% Possible further optimization: Even if the superklass is not exact,
2833
// if the subklass is the unique subtype of the superklass, the check
2834
// will always succeed. We could leave a dependency behind to ensure this.
2835
2836
// First load the super-klass's check-offset
2837
Node *p1 = gvn.transform(new AddPNode(superklass, superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset()))));
2838
Node* m = C->immutable_memory();
2839
Node *chk_off = gvn.transform(new LoadINode(NULL, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));
2840
int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());
2841
bool might_be_cache = (gvn.find_int_con(chk_off, cacheoff_con) == cacheoff_con);
2842
2843
// Load from the sub-klass's super-class display list, or a 1-word cache of
2844
// the secondary superclass list, or a failing value with a sentinel offset
2845
// if the super-klass is an interface or exceptionally deep in the Java
2846
// hierarchy and we have to scan the secondary superclass list the hard way.
2847
// Worst-case type is a little odd: NULL is allowed as a result (usually
2848
// klass loads can never produce a NULL).
2849
Node *chk_off_X = chk_off;
2850
#ifdef _LP64
2851
chk_off_X = gvn.transform(new ConvI2LNode(chk_off_X));
2852
#endif
2853
Node *p2 = gvn.transform(new AddPNode(subklass,subklass,chk_off_X));
2854
// For some types like interfaces the following loadKlass is from a 1-word
2855
// cache which is mutable so can't use immutable memory. Other
2856
// types load from the super-class display table which is immutable.
2857
Node *kmem = C->immutable_memory();
2858
// secondary_super_cache is not immutable but can be treated as such because:
2859
// - no ideal node writes to it in a way that could cause an
2860
// incorrect/missed optimization of the following Load.
2861
// - it's a cache so, worse case, not reading the latest value
2862
// wouldn't cause incorrect execution
2863
if (might_be_cache && mem != NULL) {
2864
kmem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(C->get_alias_index(gvn.type(p2)->is_ptr())) : mem;
2865
}
2866
Node *nkls = gvn.transform(LoadKlassNode::make(gvn, NULL, kmem, p2, gvn.type(p2)->is_ptr(), TypeKlassPtr::OBJECT_OR_NULL));
2867
2868
// Compile speed common case: ARE a subtype and we canNOT fail
2869
if( superklass == nkls )
2870
return C->top(); // false path is dead; no test needed.
2871
2872
// See if we get an immediate positive hit. Happens roughly 83% of the
2873
// time. Test to see if the value loaded just previously from the subklass
2874
// is exactly the superklass.
2875
IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);
2876
Node *iftrue1 = gvn.transform( new IfTrueNode (iff1));
2877
*ctrl = gvn.transform(new IfFalseNode(iff1));
2878
2879
// Compile speed common case: Check for being deterministic right now. If
2880
// chk_off is a constant and not equal to cacheoff then we are NOT a
2881
// subklass. In this case we need exactly the 1 test above and we can
2882
// return those results immediately.
2883
if (!might_be_cache) {
2884
Node* not_subtype_ctrl = *ctrl;
2885
*ctrl = iftrue1; // We need exactly the 1 test above
2886
return not_subtype_ctrl;
2887
}
2888
2889
// Gather the various success & failures here
2890
RegionNode *r_ok_subtype = new RegionNode(4);
2891
gvn.record_for_igvn(r_ok_subtype);
2892
RegionNode *r_not_subtype = new RegionNode(3);
2893
gvn.record_for_igvn(r_not_subtype);
2894
2895
r_ok_subtype->init_req(1, iftrue1);
2896
2897
// Check for immediate negative hit. Happens roughly 11% of the time (which
2898
// is roughly 63% of the remaining cases). Test to see if the loaded
2899
// check-offset points into the subklass display list or the 1-element
2900
// cache. If it points to the display (and NOT the cache) and the display
2901
// missed then it's not a subtype.
2902
Node *cacheoff = gvn.intcon(cacheoff_con);
2903
IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);
2904
r_not_subtype->init_req(1, gvn.transform(new IfTrueNode (iff2)));
2905
*ctrl = gvn.transform(new IfFalseNode(iff2));
2906
2907
// Check for self. Very rare to get here, but it is taken 1/3 the time.
2908
// No performance impact (too rare) but allows sharing of secondary arrays
2909
// which has some footprint reduction.
2910
IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);
2911
r_ok_subtype->init_req(2, gvn.transform(new IfTrueNode(iff3)));
2912
*ctrl = gvn.transform(new IfFalseNode(iff3));
2913
2914
// -- Roads not taken here: --
2915
// We could also have chosen to perform the self-check at the beginning
2916
// of this code sequence, as the assembler does. This would not pay off
2917
// the same way, since the optimizer, unlike the assembler, can perform
2918
// static type analysis to fold away many successful self-checks.
2919
// Non-foldable self checks work better here in second position, because
2920
// the initial primary superclass check subsumes a self-check for most
2921
// types. An exception would be a secondary type like array-of-interface,
2922
// which does not appear in its own primary supertype display.
2923
// Finally, we could have chosen to move the self-check into the
2924
// PartialSubtypeCheckNode, and from there out-of-line in a platform
2925
// dependent manner. But it is worthwhile to have the check here,
2926
// where it can be perhaps be optimized. The cost in code space is
2927
// small (register compare, branch).
2928
2929
// Now do a linear scan of the secondary super-klass array. Again, no real
2930
// performance impact (too rare) but it's gotta be done.
2931
// Since the code is rarely used, there is no penalty for moving it
2932
// out of line, and it can only improve I-cache density.
2933
// The decision to inline or out-of-line this final check is platform
2934
// dependent, and is found in the AD file definition of PartialSubtypeCheck.
2935
Node* psc = gvn.transform(
2936
new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2937
2938
IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2939
r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2940
r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2941
2942
// Return false path; set default control to true path.
2943
*ctrl = gvn.transform(r_ok_subtype);
2944
return gvn.transform(r_not_subtype);
2945
}
2946
2947
Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2948
bool expand_subtype_check = C->post_loop_opts_phase() || // macro node expansion is over
2949
ExpandSubTypeCheckAtParseTime; // forced expansion
2950
if (expand_subtype_check) {
2951
MergeMemNode* mem = merged_memory();
2952
Node* ctrl = control();
2953
Node* subklass = obj_or_subklass;
2954
if (!_gvn.type(obj_or_subklass)->isa_klassptr()) {
2955
subklass = load_object_klass(obj_or_subklass);
2956
}
2957
2958
Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2959
set_control(ctrl);
2960
return n;
2961
}
2962
2963
Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2964
Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2965
IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2966
set_control(_gvn.transform(new IfTrueNode(iff)));
2967
return _gvn.transform(new IfFalseNode(iff));
2968
}
2969
2970
// Profile-driven exact type check:
2971
Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2972
float prob,
2973
Node* *casted_receiver) {
2974
assert(!klass->is_interface(), "no exact type check on interfaces");
2975
2976
const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2977
Node* recv_klass = load_object_klass(receiver);
2978
Node* want_klass = makecon(tklass);
2979
Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
2980
Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
2981
IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2982
set_control( _gvn.transform(new IfTrueNode (iff)));
2983
Node* fail = _gvn.transform(new IfFalseNode(iff));
2984
2985
if (!stopped()) {
2986
const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2987
const TypeOopPtr* recvx_type = tklass->as_instance_type();
2988
assert(recvx_type->klass_is_exact(), "");
2989
2990
if (!receiver_type->higher_equal(recvx_type)) { // ignore redundant casts
2991
// Subsume downstream occurrences of receiver with a cast to
2992
// recv_xtype, since now we know what the type will be.
2993
Node* cast = new CheckCastPPNode(control(), receiver, recvx_type);
2994
(*casted_receiver) = _gvn.transform(cast);
2995
// (User must make the replace_in_map call.)
2996
}
2997
}
2998
2999
return fail;
3000
}
3001
3002
//------------------------------subtype_check_receiver-------------------------
3003
Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3004
Node** casted_receiver) {
3005
const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
3006
Node* want_klass = makecon(tklass);
3007
3008
Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3009
3010
// Ignore interface type information until interface types are properly tracked.
3011
if (!stopped() && !klass->is_interface()) {
3012
const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3013
const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3014
if (!receiver_type->higher_equal(recv_type)) { // ignore redundant casts
3015
Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
3016
(*casted_receiver) = _gvn.transform(cast);
3017
}
3018
}
3019
3020
return slow_ctl;
3021
}
3022
3023
//------------------------------seems_never_null-------------------------------
3024
// Use null_seen information if it is available from the profile.
3025
// If we see an unexpected null at a type check we record it and force a
3026
// recompile; the offending check will be recompiled to handle NULLs.
3027
// If we see several offending BCIs, then all checks in the
3028
// method will be recompiled.
3029
bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3030
speculating = !_gvn.type(obj)->speculative_maybe_null();
3031
Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3032
if (UncommonNullCast // Cutout for this technique
3033
&& obj != null() // And not the -Xcomp stupid case?
3034
&& !too_many_traps(reason)
3035
) {
3036
if (speculating) {
3037
return true;
3038
}
3039
if (data == NULL)
3040
// Edge case: no mature data. Be optimistic here.
3041
return true;
3042
// If the profile has not seen a null, assume it won't happen.
3043
assert(java_bc() == Bytecodes::_checkcast ||
3044
java_bc() == Bytecodes::_instanceof ||
3045
java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
3046
return !data->as_BitData()->null_seen();
3047
}
3048
speculating = false;
3049
return false;
3050
}
3051
3052
void GraphKit::guard_klass_being_initialized(Node* klass) {
3053
int init_state_off = in_bytes(InstanceKlass::init_state_offset());
3054
Node* adr = basic_plus_adr(top(), klass, init_state_off);
3055
Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3056
adr->bottom_type()->is_ptr(), TypeInt::BYTE,
3057
T_BYTE, MemNode::unordered);
3058
init_state = _gvn.transform(init_state);
3059
3060
Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
3061
3062
Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
3063
Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3064
3065
{ BuildCutout unless(this, tst, PROB_MAX);
3066
uncommon_trap(Deoptimization::Reason_initialized, Deoptimization::Action_reinterpret);
3067
}
3068
}
3069
3070
void GraphKit::guard_init_thread(Node* klass) {
3071
int init_thread_off = in_bytes(InstanceKlass::init_thread_offset());
3072
Node* adr = basic_plus_adr(top(), klass, init_thread_off);
3073
3074
Node* init_thread = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3075
adr->bottom_type()->is_ptr(), TypePtr::NOTNULL,
3076
T_ADDRESS, MemNode::unordered);
3077
init_thread = _gvn.transform(init_thread);
3078
3079
Node* cur_thread = _gvn.transform(new ThreadLocalNode());
3080
3081
Node* chk = _gvn.transform(new CmpPNode(cur_thread, init_thread));
3082
Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3083
3084
{ BuildCutout unless(this, tst, PROB_MAX);
3085
uncommon_trap(Deoptimization::Reason_uninitialized, Deoptimization::Action_none);
3086
}
3087
}
3088
3089
void GraphKit::clinit_barrier(ciInstanceKlass* ik, ciMethod* context) {
3090
if (ik->is_being_initialized()) {
3091
if (C->needs_clinit_barrier(ik, context)) {
3092
Node* klass = makecon(TypeKlassPtr::make(ik));
3093
guard_klass_being_initialized(klass);
3094
guard_init_thread(klass);
3095
insert_mem_bar(Op_MemBarCPUOrder);
3096
}
3097
} else if (ik->is_initialized()) {
3098
return; // no barrier needed
3099
} else {
3100
uncommon_trap(Deoptimization::Reason_uninitialized,
3101
Deoptimization::Action_reinterpret,
3102
NULL);
3103
}
3104
}
3105
3106
//------------------------maybe_cast_profiled_receiver-------------------------
3107
// If the profile has seen exactly one type, narrow to exactly that type.
3108
// Subsequent type checks will always fold up.
3109
Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3110
ciKlass* require_klass,
3111
ciKlass* spec_klass,
3112
bool safe_for_replace) {
3113
if (!UseTypeProfile || !TypeProfileCasts) return NULL;
3114
3115
Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
3116
3117
// Make sure we haven't already deoptimized from this tactic.
3118
if (too_many_traps_or_recompiles(reason))
3119
return NULL;
3120
3121
// (No, this isn't a call, but it's enough like a virtual call
3122
// to use the same ciMethod accessor to get the profile info...)
3123
// If we have a speculative type use it instead of profiling (which
3124
// may not help us)
3125
ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;
3126
if (exact_kls != NULL) {// no cast failures here
3127
if (require_klass == NULL ||
3128
C->static_subtype_check(require_klass, exact_kls) == Compile::SSC_always_true) {
3129
// If we narrow the type to match what the type profile sees or
3130
// the speculative type, we can then remove the rest of the
3131
// cast.
3132
// This is a win, even if the exact_kls is very specific,
3133
// because downstream operations, such as method calls,
3134
// will often benefit from the sharper type.
3135
Node* exact_obj = not_null_obj; // will get updated in place...
3136
Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,
3137
&exact_obj);
3138
{ PreserveJVMState pjvms(this);
3139
set_control(slow_ctl);
3140
uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3141
}
3142
if (safe_for_replace) {
3143
replace_in_map(not_null_obj, exact_obj);
3144
}
3145
return exact_obj;
3146
}
3147
// assert(ssc == Compile::SSC_always_true)... except maybe the profile lied to us.
3148
}
3149
3150
return NULL;
3151
}
3152
3153
/**
3154
* Cast obj to type and emit guard unless we had too many traps here
3155
* already
3156
*
3157
* @param obj node being casted
3158
* @param type type to cast the node to
3159
* @param not_null true if we know node cannot be null
3160
*/
3161
Node* GraphKit::maybe_cast_profiled_obj(Node* obj,
3162
ciKlass* type,
3163
bool not_null) {
3164
if (stopped()) {
3165
return obj;
3166
}
3167
3168
// type == NULL if profiling tells us this object is always null
3169
if (type != NULL) {
3170
Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check;
3171
Deoptimization::DeoptReason null_reason = Deoptimization::Reason_speculate_null_check;
3172
3173
if (!too_many_traps_or_recompiles(null_reason) &&
3174
!too_many_traps_or_recompiles(class_reason)) {
3175
Node* not_null_obj = NULL;
3176
// not_null is true if we know the object is not null and
3177
// there's no need for a null check
3178
if (!not_null) {
3179
Node* null_ctl = top();
3180
not_null_obj = null_check_oop(obj, &null_ctl, true, true, true);
3181
assert(null_ctl->is_top(), "no null control here");
3182
} else {
3183
not_null_obj = obj;
3184
}
3185
3186
Node* exact_obj = not_null_obj;
3187
ciKlass* exact_kls = type;
3188
Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,
3189
&exact_obj);
3190
{
3191
PreserveJVMState pjvms(this);
3192
set_control(slow_ctl);
3193
uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile);
3194
}
3195
replace_in_map(not_null_obj, exact_obj);
3196
obj = exact_obj;
3197
}
3198
} else {
3199
if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3200
Node* exact_obj = null_assert(obj);
3201
replace_in_map(obj, exact_obj);
3202
obj = exact_obj;
3203
}
3204
}
3205
return obj;
3206
}
3207
3208
//-------------------------------gen_instanceof--------------------------------
3209
// Generate an instance-of idiom. Used by both the instance-of bytecode
3210
// and the reflective instance-of call.
3211
Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
3212
kill_dead_locals(); // Benefit all the uncommon traps
3213
assert( !stopped(), "dead parse path should be checked in callers" );
3214
assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
3215
"must check for not-null not-dead klass in callers");
3216
3217
// Make the merge point
3218
enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
3219
RegionNode* region = new RegionNode(PATH_LIMIT);
3220
Node* phi = new PhiNode(region, TypeInt::BOOL);
3221
C->set_has_split_ifs(true); // Has chance for split-if optimization
3222
3223
ciProfileData* data = NULL;
3224
if (java_bc() == Bytecodes::_instanceof) { // Only for the bytecode
3225
data = method()->method_data()->bci_to_data(bci());
3226
}
3227
bool speculative_not_null = false;
3228
bool never_see_null = (ProfileDynamicTypes // aggressive use of profile
3229
&& seems_never_null(obj, data, speculative_not_null));
3230
3231
// Null check; get casted pointer; set region slot 3
3232
Node* null_ctl = top();
3233
Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3234
3235
// If not_null_obj is dead, only null-path is taken
3236
if (stopped()) { // Doing instance-of on a NULL?
3237
set_control(null_ctl);
3238
return intcon(0);
3239
}
3240
region->init_req(_null_path, null_ctl);
3241
phi ->init_req(_null_path, intcon(0)); // Set null path value
3242
if (null_ctl == top()) {
3243
// Do this eagerly, so that pattern matches like is_diamond_phi
3244
// will work even during parsing.
3245
assert(_null_path == PATH_LIMIT-1, "delete last");
3246
region->del_req(_null_path);
3247
phi ->del_req(_null_path);
3248
}
3249
3250
// Do we know the type check always succeed?
3251
bool known_statically = false;
3252
if (_gvn.type(superklass)->singleton()) {
3253
ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();
3254
ciKlass* subk = _gvn.type(obj)->is_oopptr()->klass();
3255
if (subk != NULL && subk->is_loaded()) {
3256
int static_res = C->static_subtype_check(superk, subk);
3257
known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3258
}
3259
}
3260
3261
if (!known_statically) {
3262
const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3263
// We may not have profiling here or it may not help us. If we
3264
// have a speculative type use it to perform an exact cast.
3265
ciKlass* spec_obj_type = obj_type->speculative_type();
3266
if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3267
Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3268
if (stopped()) { // Profile disagrees with this path.
3269
set_control(null_ctl); // Null is the only remaining possibility.
3270
return intcon(0);
3271
}
3272
if (cast_obj != NULL) {
3273
not_null_obj = cast_obj;
3274
}
3275
}
3276
}
3277
3278
// Generate the subtype check
3279
Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3280
3281
// Plug in the success path to the general merge in slot 1.
3282
region->init_req(_obj_path, control());
3283
phi ->init_req(_obj_path, intcon(1));
3284
3285
// Plug in the failing path to the general merge in slot 2.
3286
region->init_req(_fail_path, not_subtype_ctrl);
3287
phi ->init_req(_fail_path, intcon(0));
3288
3289
// Return final merged results
3290
set_control( _gvn.transform(region) );
3291
record_for_igvn(region);
3292
3293
// If we know the type check always succeeds then we don't use the
3294
// profiling data at this bytecode. Don't lose it, feed it to the
3295
// type system as a speculative type.
3296
if (safe_for_replace) {
3297
Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3298
replace_in_map(obj, casted_obj);
3299
}
3300
3301
return _gvn.transform(phi);
3302
}
3303
3304
//-------------------------------gen_checkcast---------------------------------
3305
// Generate a checkcast idiom. Used by both the checkcast bytecode and the
3306
// array store bytecode. Stack must be as-if BEFORE doing the bytecode so the
3307
// uncommon-trap paths work. Adjust stack after this call.
3308
// If failure_control is supplied and not null, it is filled in with
3309
// the control edge for the cast failure. Otherwise, an appropriate
3310
// uncommon trap or exception is thrown.
3311
Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
3312
Node* *failure_control) {
3313
kill_dead_locals(); // Benefit all the uncommon traps
3314
const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();
3315
const Type *toop = TypeOopPtr::make_from_klass(tk->klass());
3316
3317
// Fast cutout: Check the case that the cast is vacuously true.
3318
// This detects the common cases where the test will short-circuit
3319
// away completely. We do this before we perform the null check,
3320
// because if the test is going to turn into zero code, we don't
3321
// want a residual null check left around. (Causes a slowdown,
3322
// for example, in some objArray manipulations, such as a[i]=a[j].)
3323
if (tk->singleton()) {
3324
const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3325
if (objtp != NULL && objtp->klass() != NULL) {
3326
switch (C->static_subtype_check(tk->klass(), objtp->klass())) {
3327
case Compile::SSC_always_true:
3328
// If we know the type check always succeed then we don't use
3329
// the profiling data at this bytecode. Don't lose it, feed it
3330
// to the type system as a speculative type.
3331
return record_profiled_receiver_for_speculation(obj);
3332
case Compile::SSC_always_false:
3333
// It needs a null check because a null will *pass* the cast check.
3334
// A non-null value will always produce an exception.
3335
if (!objtp->maybe_null()) {
3336
builtin_throw(Deoptimization::Reason_class_check, makecon(TypeKlassPtr::make(objtp->klass())));
3337
return top();
3338
} else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3339
return null_assert(obj);
3340
}
3341
break; // Fall through to full check
3342
}
3343
}
3344
}
3345
3346
ciProfileData* data = NULL;
3347
bool safe_for_replace = false;
3348
if (failure_control == NULL) { // use MDO in regular case only
3349
assert(java_bc() == Bytecodes::_aastore ||
3350
java_bc() == Bytecodes::_checkcast,
3351
"interpreter profiles type checks only for these BCs");
3352
data = method()->method_data()->bci_to_data(bci());
3353
safe_for_replace = true;
3354
}
3355
3356
// Make the merge point
3357
enum { _obj_path = 1, _null_path, PATH_LIMIT };
3358
RegionNode* region = new RegionNode(PATH_LIMIT);
3359
Node* phi = new PhiNode(region, toop);
3360
C->set_has_split_ifs(true); // Has chance for split-if optimization
3361
3362
// Use null-cast information if it is available
3363
bool speculative_not_null = false;
3364
bool never_see_null = ((failure_control == NULL) // regular case only
3365
&& seems_never_null(obj, data, speculative_not_null));
3366
3367
// Null check; get casted pointer; set region slot 3
3368
Node* null_ctl = top();
3369
Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3370
3371
// If not_null_obj is dead, only null-path is taken
3372
if (stopped()) { // Doing instance-of on a NULL?
3373
set_control(null_ctl);
3374
return null();
3375
}
3376
region->init_req(_null_path, null_ctl);
3377
phi ->init_req(_null_path, null()); // Set null path value
3378
if (null_ctl == top()) {
3379
// Do this eagerly, so that pattern matches like is_diamond_phi
3380
// will work even during parsing.
3381
assert(_null_path == PATH_LIMIT-1, "delete last");
3382
region->del_req(_null_path);
3383
phi ->del_req(_null_path);
3384
}
3385
3386
Node* cast_obj = NULL;
3387
if (tk->klass_is_exact()) {
3388
// The following optimization tries to statically cast the speculative type of the object
3389
// (for example obtained during profiling) to the type of the superklass and then do a
3390
// dynamic check that the type of the object is what we expect. To work correctly
3391
// for checkcast and aastore the type of superklass should be exact.
3392
const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3393
// We may not have profiling here or it may not help us. If we have
3394
// a speculative type use it to perform an exact cast.
3395
ciKlass* spec_obj_type = obj_type->speculative_type();
3396
if (spec_obj_type != NULL || data != NULL) {
3397
cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);
3398
if (cast_obj != NULL) {
3399
if (failure_control != NULL) // failure is now impossible
3400
(*failure_control) = top();
3401
// adjust the type of the phi to the exact klass:
3402
phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3403
}
3404
}
3405
}
3406
3407
if (cast_obj == NULL) {
3408
// Generate the subtype check
3409
Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass );
3410
3411
// Plug in success path into the merge
3412
cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3413
// Failure path ends in uncommon trap (or may be dead - failure impossible)
3414
if (failure_control == NULL) {
3415
if (not_subtype_ctrl != top()) { // If failure is possible
3416
PreserveJVMState pjvms(this);
3417
set_control(not_subtype_ctrl);
3418
builtin_throw(Deoptimization::Reason_class_check, load_object_klass(not_null_obj));
3419
}
3420
} else {
3421
(*failure_control) = not_subtype_ctrl;
3422
}
3423
}
3424
3425
region->init_req(_obj_path, control());
3426
phi ->init_req(_obj_path, cast_obj);
3427
3428
// A merge of NULL or Casted-NotNull obj
3429
Node* res = _gvn.transform(phi);
3430
3431
// Note I do NOT always 'replace_in_map(obj,result)' here.
3432
// if( tk->klass()->can_be_primary_super() )
3433
// This means that if I successfully store an Object into an array-of-String
3434
// I 'forget' that the Object is really now known to be a String. I have to
3435
// do this because we don't have true union types for interfaces - if I store
3436
// a Baz into an array-of-Interface and then tell the optimizer it's an
3437
// Interface, I forget that it's also a Baz and cannot do Baz-like field
3438
// references to it. FIX THIS WHEN UNION TYPES APPEAR!
3439
// replace_in_map( obj, res );
3440
3441
// Return final merged results
3442
set_control( _gvn.transform(region) );
3443
record_for_igvn(region);
3444
3445
return record_profiled_receiver_for_speculation(res);
3446
}
3447
3448
//------------------------------next_monitor-----------------------------------
3449
// What number should be given to the next monitor?
3450
int GraphKit::next_monitor() {
3451
int current = jvms()->monitor_depth()* C->sync_stack_slots();
3452
int next = current + C->sync_stack_slots();
3453
// Keep the toplevel high water mark current:
3454
if (C->fixed_slots() < next) C->set_fixed_slots(next);
3455
return current;
3456
}
3457
3458
//------------------------------insert_mem_bar---------------------------------
3459
// Memory barrier to avoid floating things around
3460
// The membar serves as a pinch point between both control and all memory slices.
3461
Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3462
MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3463
mb->init_req(TypeFunc::Control, control());
3464
mb->init_req(TypeFunc::Memory, reset_memory());
3465
Node* membar = _gvn.transform(mb);
3466
set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3467
set_all_memory_call(membar);
3468
return membar;
3469
}
3470
3471
//-------------------------insert_mem_bar_volatile----------------------------
3472
// Memory barrier to avoid floating things around
3473
// The membar serves as a pinch point between both control and memory(alias_idx).
3474
// If you want to make a pinch point on all memory slices, do not use this
3475
// function (even with AliasIdxBot); use insert_mem_bar() instead.
3476
Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) {
3477
// When Parse::do_put_xxx updates a volatile field, it appends a series
3478
// of MemBarVolatile nodes, one for *each* volatile field alias category.
3479
// The first membar is on the same memory slice as the field store opcode.
3480
// This forces the membar to follow the store. (Bug 6500685 broke this.)
3481
// All the other membars (for other volatile slices, including AliasIdxBot,
3482
// which stands for all unknown volatile slices) are control-dependent
3483
// on the first membar. This prevents later volatile loads or stores
3484
// from sliding up past the just-emitted store.
3485
3486
MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent);
3487
mb->set_req(TypeFunc::Control,control());
3488
if (alias_idx == Compile::AliasIdxBot) {
3489
mb->set_req(TypeFunc::Memory, merged_memory()->base_memory());
3490
} else {
3491
assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller");
3492
mb->set_req(TypeFunc::Memory, memory(alias_idx));
3493
}
3494
Node* membar = _gvn.transform(mb);
3495
set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3496
if (alias_idx == Compile::AliasIdxBot) {
3497
merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3498
} else {
3499
set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3500
}
3501
return membar;
3502
}
3503
3504
//------------------------------shared_lock------------------------------------
3505
// Emit locking code.
3506
FastLockNode* GraphKit::shared_lock(Node* obj) {
3507
// bci is either a monitorenter bc or InvocationEntryBci
3508
// %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3509
assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3510
3511
if( !GenerateSynchronizationCode )
3512
return NULL; // Not locking things?
3513
if (stopped()) // Dead monitor?
3514
return NULL;
3515
3516
assert(dead_locals_are_killed(), "should kill locals before sync. point");
3517
3518
// Box the stack location
3519
Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3520
Node* mem = reset_memory();
3521
3522
FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3523
if (UseBiasedLocking && PrintPreciseBiasedLockingStatistics) {
3524
// Create the counters for this fast lock.
3525
flock->create_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3526
}
3527
3528
// Create the rtm counters for this fast lock if needed.
3529
flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3530
3531
// Add monitor to debug info for the slow path. If we block inside the
3532
// slow path and de-opt, we need the monitor hanging around
3533
map()->push_monitor( flock );
3534
3535
const TypeFunc *tf = LockNode::lock_type();
3536
LockNode *lock = new LockNode(C, tf);
3537
3538
lock->init_req( TypeFunc::Control, control() );
3539
lock->init_req( TypeFunc::Memory , mem );
3540
lock->init_req( TypeFunc::I_O , top() ) ; // does no i/o
3541
lock->init_req( TypeFunc::FramePtr, frameptr() );
3542
lock->init_req( TypeFunc::ReturnAdr, top() );
3543
3544
lock->init_req(TypeFunc::Parms + 0, obj);
3545
lock->init_req(TypeFunc::Parms + 1, box);
3546
lock->init_req(TypeFunc::Parms + 2, flock);
3547
add_safepoint_edges(lock);
3548
3549
lock = _gvn.transform( lock )->as_Lock();
3550
3551
// lock has no side-effects, sets few values
3552
set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM);
3553
3554
insert_mem_bar(Op_MemBarAcquireLock);
3555
3556
// Add this to the worklist so that the lock can be eliminated
3557
record_for_igvn(lock);
3558
3559
#ifndef PRODUCT
3560
if (PrintLockStatistics) {
3561
// Update the counter for this lock. Don't bother using an atomic
3562
// operation since we don't require absolute accuracy.
3563
lock->create_lock_counter(map()->jvms());
3564
increment_counter(lock->counter()->addr());
3565
}
3566
#endif
3567
3568
return flock;
3569
}
3570
3571
3572
//------------------------------shared_unlock----------------------------------
3573
// Emit unlocking code.
3574
void GraphKit::shared_unlock(Node* box, Node* obj) {
3575
// bci is either a monitorenter bc or InvocationEntryBci
3576
// %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3577
assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3578
3579
if( !GenerateSynchronizationCode )
3580
return;
3581
if (stopped()) { // Dead monitor?
3582
map()->pop_monitor(); // Kill monitor from debug info
3583
return;
3584
}
3585
3586
// Memory barrier to avoid floating things down past the locked region
3587
insert_mem_bar(Op_MemBarReleaseLock);
3588
3589
const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3590
UnlockNode *unlock = new UnlockNode(C, tf);
3591
#ifdef ASSERT
3592
unlock->set_dbg_jvms(sync_jvms());
3593
#endif
3594
uint raw_idx = Compile::AliasIdxRaw;
3595
unlock->init_req( TypeFunc::Control, control() );
3596
unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3597
unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o
3598
unlock->init_req( TypeFunc::FramePtr, frameptr() );
3599
unlock->init_req( TypeFunc::ReturnAdr, top() );
3600
3601
unlock->init_req(TypeFunc::Parms + 0, obj);
3602
unlock->init_req(TypeFunc::Parms + 1, box);
3603
unlock = _gvn.transform(unlock)->as_Unlock();
3604
3605
Node* mem = reset_memory();
3606
3607
// unlock has no side-effects, sets few values
3608
set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3609
3610
// Kill monitor from debug info
3611
map()->pop_monitor( );
3612
}
3613
3614
//-------------------------------get_layout_helper-----------------------------
3615
// If the given klass is a constant or known to be an array,
3616
// fetch the constant layout helper value into constant_value
3617
// and return (Node*)NULL. Otherwise, load the non-constant
3618
// layout helper value, and return the node which represents it.
3619
// This two-faced routine is useful because allocation sites
3620
// almost always feature constant types.
3621
Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3622
const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3623
if (!StressReflectiveCode && inst_klass != NULL) {
3624
ciKlass* klass = inst_klass->klass();
3625
bool xklass = inst_klass->klass_is_exact();
3626
if (xklass || klass->is_array_klass()) {
3627
jint lhelper = klass->layout_helper();
3628
if (lhelper != Klass::_lh_neutral_value) {
3629
constant_value = lhelper;
3630
return (Node*) NULL;
3631
}
3632
}
3633
}
3634
constant_value = Klass::_lh_neutral_value; // put in a known value
3635
Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3636
return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3637
}
3638
3639
// We just put in an allocate/initialize with a big raw-memory effect.
3640
// Hook selected additional alias categories on the initialization.
3641
static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3642
MergeMemNode* init_in_merge,
3643
Node* init_out_raw) {
3644
DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3645
assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3646
3647
Node* prevmem = kit.memory(alias_idx);
3648
init_in_merge->set_memory_at(alias_idx, prevmem);
3649
kit.set_memory(init_out_raw, alias_idx);
3650
}
3651
3652
//---------------------------set_output_for_allocation-------------------------
3653
Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3654
const TypeOopPtr* oop_type,
3655
bool deoptimize_on_exception) {
3656
int rawidx = Compile::AliasIdxRaw;
3657
alloc->set_req( TypeFunc::FramePtr, frameptr() );
3658
add_safepoint_edges(alloc);
3659
Node* allocx = _gvn.transform(alloc);
3660
set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3661
// create memory projection for i_o
3662
set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3663
make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3664
3665
// create a memory projection as for the normal control path
3666
Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3667
set_memory(malloc, rawidx);
3668
3669
// a normal slow-call doesn't change i_o, but an allocation does
3670
// we create a separate i_o projection for the normal control path
3671
set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3672
Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3673
3674
// put in an initialization barrier
3675
InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3676
rawoop)->as_Initialize();
3677
assert(alloc->initialization() == init, "2-way macro link must work");
3678
assert(init ->allocation() == alloc, "2-way macro link must work");
3679
{
3680
// Extract memory strands which may participate in the new object's
3681
// initialization, and source them from the new InitializeNode.
3682
// This will allow us to observe initializations when they occur,
3683
// and link them properly (as a group) to the InitializeNode.
3684
assert(init->in(InitializeNode::Memory) == malloc, "");
3685
MergeMemNode* minit_in = MergeMemNode::make(malloc);
3686
init->set_req(InitializeNode::Memory, minit_in);
3687
record_for_igvn(minit_in); // fold it up later, if possible
3688
Node* minit_out = memory(rawidx);
3689
assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3690
// Add an edge in the MergeMem for the header fields so an access
3691
// to one of those has correct memory state
3692
set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3693
set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3694
if (oop_type->isa_aryptr()) {
3695
const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3696
int elemidx = C->get_alias_index(telemref);
3697
hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3698
} else if (oop_type->isa_instptr()) {
3699
ciInstanceKlass* ik = oop_type->klass()->as_instance_klass();
3700
for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3701
ciField* field = ik->nonstatic_field_at(i);
3702
if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3703
continue; // do not bother to track really large numbers of fields
3704
// Find (or create) the alias category for this field:
3705
int fieldidx = C->alias_type(field)->index();
3706
hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3707
}
3708
}
3709
}
3710
3711
// Cast raw oop to the real thing...
3712
Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3713
javaoop = _gvn.transform(javaoop);
3714
C->set_recent_alloc(control(), javaoop);
3715
assert(just_allocated_object(control()) == javaoop, "just allocated");
3716
3717
#ifdef ASSERT
3718
{ // Verify that the AllocateNode::Ideal_allocation recognizers work:
3719
assert(AllocateNode::Ideal_allocation(rawoop, &_gvn) == alloc,
3720
"Ideal_allocation works");
3721
assert(AllocateNode::Ideal_allocation(javaoop, &_gvn) == alloc,
3722
"Ideal_allocation works");
3723
if (alloc->is_AllocateArray()) {
3724
assert(AllocateArrayNode::Ideal_array_allocation(rawoop, &_gvn) == alloc->as_AllocateArray(),
3725
"Ideal_allocation works");
3726
assert(AllocateArrayNode::Ideal_array_allocation(javaoop, &_gvn) == alloc->as_AllocateArray(),
3727
"Ideal_allocation works");
3728
} else {
3729
assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3730
}
3731
}
3732
#endif //ASSERT
3733
3734
return javaoop;
3735
}
3736
3737
//---------------------------new_instance--------------------------------------
3738
// This routine takes a klass_node which may be constant (for a static type)
3739
// or may be non-constant (for reflective code). It will work equally well
3740
// for either, and the graph will fold nicely if the optimizer later reduces
3741
// the type to a constant.
3742
// The optional arguments are for specialized use by intrinsics:
3743
// - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3744
// - If 'return_size_val', report the the total object size to the caller.
3745
// - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3746
Node* GraphKit::new_instance(Node* klass_node,
3747
Node* extra_slow_test,
3748
Node* *return_size_val,
3749
bool deoptimize_on_exception) {
3750
// Compute size in doublewords
3751
// The size is always an integral number of doublewords, represented
3752
// as a positive bytewise size stored in the klass's layout_helper.
3753
// The layout_helper also encodes (in a low bit) the need for a slow path.
3754
jint layout_con = Klass::_lh_neutral_value;
3755
Node* layout_val = get_layout_helper(klass_node, layout_con);
3756
int layout_is_con = (layout_val == NULL);
3757
3758
if (extra_slow_test == NULL) extra_slow_test = intcon(0);
3759
// Generate the initial go-slow test. It's either ALWAYS (return a
3760
// Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
3761
// case) a computed value derived from the layout_helper.
3762
Node* initial_slow_test = NULL;
3763
if (layout_is_con) {
3764
assert(!StressReflectiveCode, "stress mode does not use these paths");
3765
bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3766
initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3767
} else { // reflective case
3768
// This reflective path is used by Unsafe.allocateInstance.
3769
// (It may be stress-tested by specifying StressReflectiveCode.)
3770
// Basically, we want to get into the VM is there's an illegal argument.
3771
Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3772
initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3773
if (extra_slow_test != intcon(0)) {
3774
initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3775
}
3776
// (Macro-expander will further convert this to a Bool, if necessary.)
3777
}
3778
3779
// Find the size in bytes. This is easy; it's the layout_helper.
3780
// The size value must be valid even if the slow path is taken.
3781
Node* size = NULL;
3782
if (layout_is_con) {
3783
size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con));
3784
} else { // reflective case
3785
// This reflective path is used by clone and Unsafe.allocateInstance.
3786
size = ConvI2X(layout_val);
3787
3788
// Clear the low bits to extract layout_helper_size_in_bytes:
3789
assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3790
Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3791
size = _gvn.transform( new AndXNode(size, mask) );
3792
}
3793
if (return_size_val != NULL) {
3794
(*return_size_val) = size;
3795
}
3796
3797
// This is a precise notnull oop of the klass.
3798
// (Actually, it need not be precise if this is a reflective allocation.)
3799
// It's what we cast the result to.
3800
const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3801
if (!tklass) tklass = TypeKlassPtr::OBJECT;
3802
const TypeOopPtr* oop_type = tklass->as_instance_type();
3803
3804
// Now generate allocation code
3805
3806
// The entire memory state is needed for slow path of the allocation
3807
// since GC and deoptimization can happened.
3808
Node *mem = reset_memory();
3809
set_all_memory(mem); // Create new memory state
3810
3811
AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3812
control(), mem, i_o(),
3813
size, klass_node,
3814
initial_slow_test);
3815
3816
return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3817
}
3818
3819
//-------------------------------new_array-------------------------------------
3820
// helper for both newarray and anewarray
3821
// The 'length' parameter is (obviously) the length of the array.
3822
// See comments on new_instance for the meaning of the other arguments.
3823
Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable)
3824
Node* length, // number of array elements
3825
int nargs, // number of arguments to push back for uncommon trap
3826
Node* *return_size_val,
3827
bool deoptimize_on_exception) {
3828
jint layout_con = Klass::_lh_neutral_value;
3829
Node* layout_val = get_layout_helper(klass_node, layout_con);
3830
int layout_is_con = (layout_val == NULL);
3831
3832
if (!layout_is_con && !StressReflectiveCode &&
3833
!too_many_traps(Deoptimization::Reason_class_check)) {
3834
// This is a reflective array creation site.
3835
// Optimistically assume that it is a subtype of Object[],
3836
// so that we can fold up all the address arithmetic.
3837
layout_con = Klass::array_layout_helper(T_OBJECT);
3838
Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3839
Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3840
{ BuildCutout unless(this, bol_lh, PROB_MAX);
3841
inc_sp(nargs);
3842
uncommon_trap(Deoptimization::Reason_class_check,
3843
Deoptimization::Action_maybe_recompile);
3844
}
3845
layout_val = NULL;
3846
layout_is_con = true;
3847
}
3848
3849
// Generate the initial go-slow test. Make sure we do not overflow
3850
// if length is huge (near 2Gig) or negative! We do not need
3851
// exact double-words here, just a close approximation of needed
3852
// double-words. We can't add any offset or rounding bits, lest we
3853
// take a size -1 of bytes and make it positive. Use an unsigned
3854
// compare, so negative sizes look hugely positive.
3855
int fast_size_limit = FastAllocateSizeLimit;
3856
if (layout_is_con) {
3857
assert(!StressReflectiveCode, "stress mode does not use these paths");
3858
// Increase the size limit if we have exact knowledge of array type.
3859
int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3860
fast_size_limit <<= (LogBytesPerLong - log2_esize);
3861
}
3862
3863
Node* initial_slow_cmp = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3864
Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3865
3866
// --- Size Computation ---
3867
// array_size = round_to_heap(array_header + (length << elem_shift));
3868
// where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
3869
// and align_to(x, y) == ((x + y-1) & ~(y-1))
3870
// The rounding mask is strength-reduced, if possible.
3871
int round_mask = MinObjAlignmentInBytes - 1;
3872
Node* header_size = NULL;
3873
int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3874
// (T_BYTE has the weakest alignment and size restrictions...)
3875
if (layout_is_con) {
3876
int hsize = Klass::layout_helper_header_size(layout_con);
3877
int eshift = Klass::layout_helper_log2_element_size(layout_con);
3878
BasicType etype = Klass::layout_helper_element_type(layout_con);
3879
if ((round_mask & ~right_n_bits(eshift)) == 0)
3880
round_mask = 0; // strength-reduce it if it goes away completely
3881
assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3882
assert(header_size_min <= hsize, "generic minimum is smallest");
3883
header_size_min = hsize;
3884
header_size = intcon(hsize + round_mask);
3885
} else {
3886
Node* hss = intcon(Klass::_lh_header_size_shift);
3887
Node* hsm = intcon(Klass::_lh_header_size_mask);
3888
Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
3889
hsize = _gvn.transform( new AndINode(hsize, hsm) );
3890
Node* mask = intcon(round_mask);
3891
header_size = _gvn.transform( new AddINode(hsize, mask) );
3892
}
3893
3894
Node* elem_shift = NULL;
3895
if (layout_is_con) {
3896
int eshift = Klass::layout_helper_log2_element_size(layout_con);
3897
if (eshift != 0)
3898
elem_shift = intcon(eshift);
3899
} else {
3900
// There is no need to mask or shift this value.
3901
// The semantics of LShiftINode include an implicit mask to 0x1F.
3902
assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
3903
elem_shift = layout_val;
3904
}
3905
3906
// Transition to native address size for all offset calculations:
3907
Node* lengthx = ConvI2X(length);
3908
Node* headerx = ConvI2X(header_size);
3909
#ifdef _LP64
3910
{ const TypeInt* tilen = _gvn.find_int_type(length);
3911
if (tilen != NULL && tilen->_lo < 0) {
3912
// Add a manual constraint to a positive range. Cf. array_element_address.
3913
jint size_max = fast_size_limit;
3914
if (size_max > tilen->_hi) size_max = tilen->_hi;
3915
const TypeInt* tlcon = TypeInt::make(0, size_max, Type::WidenMin);
3916
3917
// Only do a narrow I2L conversion if the range check passed.
3918
IfNode* iff = new IfNode(control(), initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
3919
_gvn.transform(iff);
3920
RegionNode* region = new RegionNode(3);
3921
_gvn.set_type(region, Type::CONTROL);
3922
lengthx = new PhiNode(region, TypeLong::LONG);
3923
_gvn.set_type(lengthx, TypeLong::LONG);
3924
3925
// Range check passed. Use ConvI2L node with narrow type.
3926
Node* passed = IfFalse(iff);
3927
region->init_req(1, passed);
3928
// Make I2L conversion control dependent to prevent it from
3929
// floating above the range check during loop optimizations.
3930
lengthx->init_req(1, C->constrained_convI2L(&_gvn, length, tlcon, passed));
3931
3932
// Range check failed. Use ConvI2L with wide type because length may be invalid.
3933
region->init_req(2, IfTrue(iff));
3934
lengthx->init_req(2, ConvI2X(length));
3935
3936
set_control(region);
3937
record_for_igvn(region);
3938
record_for_igvn(lengthx);
3939
}
3940
}
3941
#endif
3942
3943
// Combine header size (plus rounding) and body size. Then round down.
3944
// This computation cannot overflow, because it is used only in two
3945
// places, one where the length is sharply limited, and the other
3946
// after a successful allocation.
3947
Node* abody = lengthx;
3948
if (elem_shift != NULL)
3949
abody = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
3950
Node* size = _gvn.transform( new AddXNode(headerx, abody) );
3951
if (round_mask != 0) {
3952
Node* mask = MakeConX(~round_mask);
3953
size = _gvn.transform( new AndXNode(size, mask) );
3954
}
3955
// else if round_mask == 0, the size computation is self-rounding
3956
3957
if (return_size_val != NULL) {
3958
// This is the size
3959
(*return_size_val) = size;
3960
}
3961
3962
// Now generate allocation code
3963
3964
// The entire memory state is needed for slow path of the allocation
3965
// since GC and deoptimization can happened.
3966
Node *mem = reset_memory();
3967
set_all_memory(mem); // Create new memory state
3968
3969
if (initial_slow_test->is_Bool()) {
3970
// Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3971
initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3972
}
3973
3974
const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();
3975
Node* valid_length_test = _gvn.intcon(1);
3976
if (ary_type->klass()->is_array_klass()) {
3977
BasicType bt = ary_type->klass()->as_array_klass()->element_type()->basic_type();
3978
jint max = TypeAryPtr::max_array_length(bt);
3979
Node* valid_length_cmp = _gvn.transform(new CmpUNode(length, intcon(max)));
3980
valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
3981
}
3982
3983
// Create the AllocateArrayNode and its result projections
3984
AllocateArrayNode* alloc
3985
= new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3986
control(), mem, i_o(),
3987
size, klass_node,
3988
initial_slow_test,
3989
length, valid_length_test);
3990
3991
// Cast to correct type. Note that the klass_node may be constant or not,
3992
// and in the latter case the actual array type will be inexact also.
3993
// (This happens via a non-constant argument to inline_native_newArray.)
3994
// In any case, the value of klass_node provides the desired array type.
3995
const TypeInt* length_type = _gvn.find_int_type(length);
3996
if (ary_type->isa_aryptr() && length_type != NULL) {
3997
// Try to get a better type than POS for the size
3998
ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3999
}
4000
4001
Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
4002
4003
array_ideal_length(alloc, ary_type, true);
4004
return javaoop;
4005
}
4006
4007
// The following "Ideal_foo" functions are placed here because they recognize
4008
// the graph shapes created by the functions immediately above.
4009
4010
//---------------------------Ideal_allocation----------------------------------
4011
// Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.
4012
AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {
4013
if (ptr == NULL) { // reduce dumb test in callers
4014
return NULL;
4015
}
4016
4017
BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4018
ptr = bs->step_over_gc_barrier(ptr);
4019
4020
if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast
4021
ptr = ptr->in(1);
4022
if (ptr == NULL) return NULL;
4023
}
4024
// Return NULL for allocations with several casts:
4025
// j.l.reflect.Array.newInstance(jobject, jint)
4026
// Object.clone()
4027
// to keep more precise type from last cast.
4028
if (ptr->is_Proj()) {
4029
Node* allo = ptr->in(0);
4030
if (allo != NULL && allo->is_Allocate()) {
4031
return allo->as_Allocate();
4032
}
4033
}
4034
// Report failure to match.
4035
return NULL;
4036
}
4037
4038
// Fancy version which also strips off an offset (and reports it to caller).
4039
AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase,
4040
intptr_t& offset) {
4041
Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset);
4042
if (base == NULL) return NULL;
4043
return Ideal_allocation(base, phase);
4044
}
4045
4046
// Trace Initialize <- Proj[Parm] <- Allocate
4047
AllocateNode* InitializeNode::allocation() {
4048
Node* rawoop = in(InitializeNode::RawAddress);
4049
if (rawoop->is_Proj()) {
4050
Node* alloc = rawoop->in(0);
4051
if (alloc->is_Allocate()) {
4052
return alloc->as_Allocate();
4053
}
4054
}
4055
return NULL;
4056
}
4057
4058
// Trace Allocate -> Proj[Parm] -> Initialize
4059
InitializeNode* AllocateNode::initialization() {
4060
ProjNode* rawoop = proj_out_or_null(AllocateNode::RawAddress);
4061
if (rawoop == NULL) return NULL;
4062
for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {
4063
Node* init = rawoop->fast_out(i);
4064
if (init->is_Initialize()) {
4065
assert(init->as_Initialize()->allocation() == this, "2-way link");
4066
return init->as_Initialize();
4067
}
4068
}
4069
return NULL;
4070
}
4071
4072
//----------------------------- loop predicates ---------------------------
4073
4074
//------------------------------add_predicate_impl----------------------------
4075
void GraphKit::add_empty_predicate_impl(Deoptimization::DeoptReason reason, int nargs) {
4076
// Too many traps seen?
4077
if (too_many_traps(reason)) {
4078
#ifdef ASSERT
4079
if (TraceLoopPredicate) {
4080
int tc = C->trap_count(reason);
4081
tty->print("too many traps=%s tcount=%d in ",
4082
Deoptimization::trap_reason_name(reason), tc);
4083
method()->print(); // which method has too many predicate traps
4084
tty->cr();
4085
}
4086
#endif
4087
// We cannot afford to take more traps here,
4088
// do not generate predicate.
4089
return;
4090
}
4091
4092
Node *cont = _gvn.intcon(1);
4093
Node* opq = _gvn.transform(new Opaque1Node(C, cont));
4094
Node *bol = _gvn.transform(new Conv2BNode(opq));
4095
IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
4096
Node* iffalse = _gvn.transform(new IfFalseNode(iff));
4097
C->add_predicate_opaq(opq);
4098
{
4099
PreserveJVMState pjvms(this);
4100
set_control(iffalse);
4101
inc_sp(nargs);
4102
uncommon_trap(reason, Deoptimization::Action_maybe_recompile);
4103
}
4104
Node* iftrue = _gvn.transform(new IfTrueNode(iff));
4105
set_control(iftrue);
4106
}
4107
4108
//------------------------------add_predicate---------------------------------
4109
void GraphKit::add_empty_predicates(int nargs) {
4110
// These loop predicates remain empty. All concrete loop predicates are inserted above the corresponding
4111
// empty loop predicate later by 'PhaseIdealLoop::create_new_if_for_predicate'. All concrete loop predicates of
4112
// a specific kind (normal, profile or limit check) share the same uncommon trap as the empty loop predicate.
4113
if (UseLoopPredicate) {
4114
add_empty_predicate_impl(Deoptimization::Reason_predicate, nargs);
4115
}
4116
if (UseProfiledLoopPredicate) {
4117
add_empty_predicate_impl(Deoptimization::Reason_profile_predicate, nargs);
4118
}
4119
// loop's limit check predicate should be near the loop.
4120
add_empty_predicate_impl(Deoptimization::Reason_loop_limit_check, nargs);
4121
}
4122
4123
void GraphKit::sync_kit(IdealKit& ideal) {
4124
set_all_memory(ideal.merged_memory());
4125
set_i_o(ideal.i_o());
4126
set_control(ideal.ctrl());
4127
}
4128
4129
void GraphKit::final_sync(IdealKit& ideal) {
4130
// Final sync IdealKit and graphKit.
4131
sync_kit(ideal);
4132
}
4133
4134
Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4135
Node* len = load_array_length(load_String_value(str, set_ctrl));
4136
Node* coder = load_String_coder(str, set_ctrl);
4137
// Divide length by 2 if coder is UTF16
4138
return _gvn.transform(new RShiftINode(len, coder));
4139
}
4140
4141
Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4142
int value_offset = java_lang_String::value_offset();
4143
const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4144
false, NULL, 0);
4145
const TypePtr* value_field_type = string_type->add_offset(value_offset);
4146
const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4147
TypeAry::make(TypeInt::BYTE, TypeInt::POS),
4148
ciTypeArrayKlass::make(T_BYTE), true, 0);
4149
Node* p = basic_plus_adr(str, str, value_offset);
4150
Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4151
IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4152
return load;
4153
}
4154
4155
Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4156
if (!CompactStrings) {
4157
return intcon(java_lang_String::CODER_UTF16);
4158
}
4159
int coder_offset = java_lang_String::coder_offset();
4160
const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4161
false, NULL, 0);
4162
const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4163
4164
Node* p = basic_plus_adr(str, str, coder_offset);
4165
Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4166
IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4167
return load;
4168
}
4169
4170
void GraphKit::store_String_value(Node* str, Node* value) {
4171
int value_offset = java_lang_String::value_offset();
4172
const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4173
false, NULL, 0);
4174
const TypePtr* value_field_type = string_type->add_offset(value_offset);
4175
4176
access_store_at(str, basic_plus_adr(str, value_offset), value_field_type,
4177
value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4178
}
4179
4180
void GraphKit::store_String_coder(Node* str, Node* value) {
4181
int coder_offset = java_lang_String::coder_offset();
4182
const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4183
false, NULL, 0);
4184
const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4185
4186
access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4187
value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4188
}
4189
4190
// Capture src and dst memory state with a MergeMemNode
4191
Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4192
if (src_type == dst_type) {
4193
// Types are equal, we don't need a MergeMemNode
4194
return memory(src_type);
4195
}
4196
MergeMemNode* merge = MergeMemNode::make(map()->memory());
4197
record_for_igvn(merge); // fold it up later, if possible
4198
int src_idx = C->get_alias_index(src_type);
4199
int dst_idx = C->get_alias_index(dst_type);
4200
merge->set_memory_at(src_idx, memory(src_idx));
4201
merge->set_memory_at(dst_idx, memory(dst_idx));
4202
return merge;
4203
}
4204
4205
Node* GraphKit::compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count) {
4206
assert(Matcher::match_rule_supported(Op_StrCompressedCopy), "Intrinsic not supported");
4207
assert(src_type == TypeAryPtr::BYTES || src_type == TypeAryPtr::CHARS, "invalid source type");
4208
// If input and output memory types differ, capture both states to preserve
4209
// the dependency between preceding and subsequent loads/stores.
4210
// For example, the following program:
4211
// StoreB
4212
// compress_string
4213
// LoadB
4214
// has this memory graph (use->def):
4215
// LoadB -> compress_string -> CharMem
4216
// ... -> StoreB -> ByteMem
4217
// The intrinsic hides the dependency between LoadB and StoreB, causing
4218
// the load to read from memory not containing the result of the StoreB.
4219
// The correct memory graph should look like this:
4220
// LoadB -> compress_string -> MergeMem(CharMem, StoreB(ByteMem))
4221
Node* mem = capture_memory(src_type, TypeAryPtr::BYTES);
4222
StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, src, dst, count);
4223
Node* res_mem = _gvn.transform(new SCMemProjNode(_gvn.transform(str)));
4224
set_memory(res_mem, TypeAryPtr::BYTES);
4225
return str;
4226
}
4227
4228
void GraphKit::inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count) {
4229
assert(Matcher::match_rule_supported(Op_StrInflatedCopy), "Intrinsic not supported");
4230
assert(dst_type == TypeAryPtr::BYTES || dst_type == TypeAryPtr::CHARS, "invalid dest type");
4231
// Capture src and dst memory (see comment in 'compress_string').
4232
Node* mem = capture_memory(TypeAryPtr::BYTES, dst_type);
4233
StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, src, dst, count);
4234
set_memory(_gvn.transform(str), dst_type);
4235
}
4236
4237
void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* count) {
4238
/**
4239
* int i_char = start;
4240
* for (int i_byte = 0; i_byte < count; i_byte++) {
4241
* dst[i_char++] = (char)(src[i_byte] & 0xff);
4242
* }
4243
*/
4244
add_empty_predicates();
4245
C->set_has_loops(true);
4246
4247
RegionNode* head = new RegionNode(3);
4248
head->init_req(1, control());
4249
gvn().set_type(head, Type::CONTROL);
4250
record_for_igvn(head);
4251
4252
Node* i_byte = new PhiNode(head, TypeInt::INT);
4253
i_byte->init_req(1, intcon(0));
4254
gvn().set_type(i_byte, TypeInt::INT);
4255
record_for_igvn(i_byte);
4256
4257
Node* i_char = new PhiNode(head, TypeInt::INT);
4258
i_char->init_req(1, start);
4259
gvn().set_type(i_char, TypeInt::INT);
4260
record_for_igvn(i_char);
4261
4262
Node* mem = PhiNode::make(head, memory(TypeAryPtr::BYTES), Type::MEMORY, TypeAryPtr::BYTES);
4263
gvn().set_type(mem, Type::MEMORY);
4264
record_for_igvn(mem);
4265
set_control(head);
4266
set_memory(mem, TypeAryPtr::BYTES);
4267
Node* ch = load_array_element(src, i_byte, TypeAryPtr::BYTES, /* set_ctrl */ true);
4268
Node* st = store_to_memory(control(), array_element_address(dst, i_char, T_BYTE),
4269
AndI(ch, intcon(0xff)), T_CHAR, TypeAryPtr::BYTES, MemNode::unordered,
4270
false, false, true /* mismatched */);
4271
4272
IfNode* iff = create_and_map_if(head, Bool(CmpI(i_byte, count), BoolTest::lt), PROB_FAIR, COUNT_UNKNOWN);
4273
head->init_req(2, IfTrue(iff));
4274
mem->init_req(2, st);
4275
i_byte->init_req(2, AddI(i_byte, intcon(1)));
4276
i_char->init_req(2, AddI(i_char, intcon(2)));
4277
4278
set_control(IfFalse(iff));
4279
set_memory(st, TypeAryPtr::BYTES);
4280
}
4281
4282
Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4283
if (!field->is_constant()) {
4284
return NULL; // Field not marked as constant.
4285
}
4286
ciInstance* holder = NULL;
4287
if (!field->is_static()) {
4288
ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4289
if (const_oop != NULL && const_oop->is_instance()) {
4290
holder = const_oop->as_instance();
4291
}
4292
}
4293
const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4294
/*is_unsigned_load=*/false);
4295
if (con_type != NULL) {
4296
return makecon(con_type);
4297
}
4298
return NULL;
4299
}
4300
4301