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