Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-aarch32-jdk8u
Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/opto/compile.cpp
83404 views
1
/*
2
* Copyright (c) 1997, 2018, 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 "asm/macroAssembler.hpp"
27
#include "asm/macroAssembler.inline.hpp"
28
#include "ci/ciReplay.hpp"
29
#include "classfile/systemDictionary.hpp"
30
#include "code/exceptionHandlerTable.hpp"
31
#include "code/nmethod.hpp"
32
#include "compiler/compileLog.hpp"
33
#include "compiler/disassembler.hpp"
34
#include "compiler/oopMap.hpp"
35
#include "jfr/jfrEvents.hpp"
36
#include "opto/addnode.hpp"
37
#include "opto/block.hpp"
38
#include "opto/c2compiler.hpp"
39
#include "opto/callGenerator.hpp"
40
#include "opto/callnode.hpp"
41
#include "opto/cfgnode.hpp"
42
#include "opto/chaitin.hpp"
43
#include "opto/compile.hpp"
44
#include "opto/connode.hpp"
45
#include "opto/divnode.hpp"
46
#include "opto/escape.hpp"
47
#include "opto/idealGraphPrinter.hpp"
48
#include "opto/loopnode.hpp"
49
#include "opto/machnode.hpp"
50
#include "opto/macro.hpp"
51
#include "opto/matcher.hpp"
52
#include "opto/mathexactnode.hpp"
53
#include "opto/memnode.hpp"
54
#include "opto/mulnode.hpp"
55
#include "opto/node.hpp"
56
#include "opto/opcodes.hpp"
57
#include "opto/output.hpp"
58
#include "opto/parse.hpp"
59
#include "opto/phaseX.hpp"
60
#include "opto/rootnode.hpp"
61
#include "opto/runtime.hpp"
62
#include "opto/stringopts.hpp"
63
#include "opto/type.hpp"
64
#include "opto/vectornode.hpp"
65
#include "runtime/arguments.hpp"
66
#include "runtime/signature.hpp"
67
#include "runtime/stubRoutines.hpp"
68
#include "runtime/timer.hpp"
69
#include "utilities/copy.hpp"
70
#if defined AD_MD_HPP
71
# include AD_MD_HPP
72
#elif defined TARGET_ARCH_MODEL_x86_32
73
# include "adfiles/ad_x86_32.hpp"
74
#elif defined TARGET_ARCH_MODEL_x86_64
75
# include "adfiles/ad_x86_64.hpp"
76
#elif defined TARGET_ARCH_MODEL_aarch64
77
# include "adfiles/ad_aarch64.hpp"
78
#elif defined TARGET_ARCH_MODEL_sparc
79
# include "adfiles/ad_sparc.hpp"
80
#elif defined TARGET_ARCH_MODEL_zero
81
# include "adfiles/ad_zero.hpp"
82
#elif defined TARGET_ARCH_MODEL_ppc_64
83
# include "adfiles/ad_ppc_64.hpp"
84
#elif defined TARGET_ARCH_MODEL_aarch32
85
# include "adfiles/ad_aarch32.hpp"
86
#endif
87
88
// -------------------- Compile::mach_constant_base_node -----------------------
89
// Constant table base node singleton.
90
MachConstantBaseNode* Compile::mach_constant_base_node() {
91
if (_mach_constant_base_node == NULL) {
92
_mach_constant_base_node = new (C) MachConstantBaseNode();
93
_mach_constant_base_node->add_req(C->root());
94
}
95
return _mach_constant_base_node;
96
}
97
98
99
/// Support for intrinsics.
100
101
// Return the index at which m must be inserted (or already exists).
102
// The sort order is by the address of the ciMethod, with is_virtual as minor key.
103
int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual) {
104
#ifdef ASSERT
105
for (int i = 1; i < _intrinsics->length(); i++) {
106
CallGenerator* cg1 = _intrinsics->at(i-1);
107
CallGenerator* cg2 = _intrinsics->at(i);
108
assert(cg1->method() != cg2->method()
109
? cg1->method() < cg2->method()
110
: cg1->is_virtual() < cg2->is_virtual(),
111
"compiler intrinsics list must stay sorted");
112
}
113
#endif
114
// Binary search sorted list, in decreasing intervals [lo, hi].
115
int lo = 0, hi = _intrinsics->length()-1;
116
while (lo <= hi) {
117
int mid = (uint)(hi + lo) / 2;
118
ciMethod* mid_m = _intrinsics->at(mid)->method();
119
if (m < mid_m) {
120
hi = mid-1;
121
} else if (m > mid_m) {
122
lo = mid+1;
123
} else {
124
// look at minor sort key
125
bool mid_virt = _intrinsics->at(mid)->is_virtual();
126
if (is_virtual < mid_virt) {
127
hi = mid-1;
128
} else if (is_virtual > mid_virt) {
129
lo = mid+1;
130
} else {
131
return mid; // exact match
132
}
133
}
134
}
135
return lo; // inexact match
136
}
137
138
void Compile::register_intrinsic(CallGenerator* cg) {
139
if (_intrinsics == NULL) {
140
_intrinsics = new (comp_arena())GrowableArray<CallGenerator*>(comp_arena(), 60, 0, NULL);
141
}
142
// This code is stolen from ciObjectFactory::insert.
143
// Really, GrowableArray should have methods for
144
// insert_at, remove_at, and binary_search.
145
int len = _intrinsics->length();
146
int index = intrinsic_insertion_index(cg->method(), cg->is_virtual());
147
if (index == len) {
148
_intrinsics->append(cg);
149
} else {
150
#ifdef ASSERT
151
CallGenerator* oldcg = _intrinsics->at(index);
152
assert(oldcg->method() != cg->method() || oldcg->is_virtual() != cg->is_virtual(), "don't register twice");
153
#endif
154
_intrinsics->append(_intrinsics->at(len-1));
155
int pos;
156
for (pos = len-2; pos >= index; pos--) {
157
_intrinsics->at_put(pos+1,_intrinsics->at(pos));
158
}
159
_intrinsics->at_put(index, cg);
160
}
161
assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked");
162
}
163
164
CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) {
165
assert(m->is_loaded(), "don't try this on unloaded methods");
166
if (_intrinsics != NULL) {
167
int index = intrinsic_insertion_index(m, is_virtual);
168
if (index < _intrinsics->length()
169
&& _intrinsics->at(index)->method() == m
170
&& _intrinsics->at(index)->is_virtual() == is_virtual) {
171
return _intrinsics->at(index);
172
}
173
}
174
// Lazily create intrinsics for intrinsic IDs well-known in the runtime.
175
if (m->intrinsic_id() != vmIntrinsics::_none &&
176
m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) {
177
CallGenerator* cg = make_vm_intrinsic(m, is_virtual);
178
if (cg != NULL) {
179
// Save it for next time:
180
register_intrinsic(cg);
181
return cg;
182
} else {
183
gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled);
184
}
185
}
186
return NULL;
187
}
188
189
// Compile:: register_library_intrinsics and make_vm_intrinsic are defined
190
// in library_call.cpp.
191
192
193
#ifndef PRODUCT
194
// statistics gathering...
195
196
juint Compile::_intrinsic_hist_count[vmIntrinsics::ID_LIMIT] = {0};
197
jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::ID_LIMIT] = {0};
198
199
bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) {
200
assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob");
201
int oflags = _intrinsic_hist_flags[id];
202
assert(flags != 0, "what happened?");
203
if (is_virtual) {
204
flags |= _intrinsic_virtual;
205
}
206
bool changed = (flags != oflags);
207
if ((flags & _intrinsic_worked) != 0) {
208
juint count = (_intrinsic_hist_count[id] += 1);
209
if (count == 1) {
210
changed = true; // first time
211
}
212
// increment the overall count also:
213
_intrinsic_hist_count[vmIntrinsics::_none] += 1;
214
}
215
if (changed) {
216
if (((oflags ^ flags) & _intrinsic_virtual) != 0) {
217
// Something changed about the intrinsic's virtuality.
218
if ((flags & _intrinsic_virtual) != 0) {
219
// This is the first use of this intrinsic as a virtual call.
220
if (oflags != 0) {
221
// We already saw it as a non-virtual, so note both cases.
222
flags |= _intrinsic_both;
223
}
224
} else if ((oflags & _intrinsic_both) == 0) {
225
// This is the first use of this intrinsic as a non-virtual
226
flags |= _intrinsic_both;
227
}
228
}
229
_intrinsic_hist_flags[id] = (jubyte) (oflags | flags);
230
}
231
// update the overall flags also:
232
_intrinsic_hist_flags[vmIntrinsics::_none] |= (jubyte) flags;
233
return changed;
234
}
235
236
static char* format_flags(int flags, char* buf) {
237
buf[0] = 0;
238
if ((flags & Compile::_intrinsic_worked) != 0) strcat(buf, ",worked");
239
if ((flags & Compile::_intrinsic_failed) != 0) strcat(buf, ",failed");
240
if ((flags & Compile::_intrinsic_disabled) != 0) strcat(buf, ",disabled");
241
if ((flags & Compile::_intrinsic_virtual) != 0) strcat(buf, ",virtual");
242
if ((flags & Compile::_intrinsic_both) != 0) strcat(buf, ",nonvirtual");
243
if (buf[0] == 0) strcat(buf, ",");
244
assert(buf[0] == ',', "must be");
245
return &buf[1];
246
}
247
248
void Compile::print_intrinsic_statistics() {
249
char flagsbuf[100];
250
ttyLocker ttyl;
251
if (xtty != NULL) xtty->head("statistics type='intrinsic'");
252
tty->print_cr("Compiler intrinsic usage:");
253
juint total = _intrinsic_hist_count[vmIntrinsics::_none];
254
if (total == 0) total = 1; // avoid div0 in case of no successes
255
#define PRINT_STAT_LINE(name, c, f) \
256
tty->print_cr(" %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f);
257
for (int index = 1 + (int)vmIntrinsics::_none; index < (int)vmIntrinsics::ID_LIMIT; index++) {
258
vmIntrinsics::ID id = (vmIntrinsics::ID) index;
259
int flags = _intrinsic_hist_flags[id];
260
juint count = _intrinsic_hist_count[id];
261
if ((flags | count) != 0) {
262
PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf));
263
}
264
}
265
PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[vmIntrinsics::_none], flagsbuf));
266
if (xtty != NULL) xtty->tail("statistics");
267
}
268
269
void Compile::print_statistics() {
270
{ ttyLocker ttyl;
271
if (xtty != NULL) xtty->head("statistics type='opto'");
272
Parse::print_statistics();
273
PhaseCCP::print_statistics();
274
PhaseRegAlloc::print_statistics();
275
Scheduling::print_statistics();
276
PhasePeephole::print_statistics();
277
PhaseIdealLoop::print_statistics();
278
if (xtty != NULL) xtty->tail("statistics");
279
}
280
if (_intrinsic_hist_flags[vmIntrinsics::_none] != 0) {
281
// put this under its own <statistics> element.
282
print_intrinsic_statistics();
283
}
284
}
285
#endif //PRODUCT
286
287
// Support for bundling info
288
Bundle* Compile::node_bundling(const Node *n) {
289
assert(valid_bundle_info(n), "oob");
290
return &_node_bundling_base[n->_idx];
291
}
292
293
bool Compile::valid_bundle_info(const Node *n) {
294
return (_node_bundling_limit > n->_idx);
295
}
296
297
298
void Compile::gvn_replace_by(Node* n, Node* nn) {
299
for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) {
300
Node* use = n->last_out(i);
301
bool is_in_table = initial_gvn()->hash_delete(use);
302
uint uses_found = 0;
303
for (uint j = 0; j < use->len(); j++) {
304
if (use->in(j) == n) {
305
if (j < use->req())
306
use->set_req(j, nn);
307
else
308
use->set_prec(j, nn);
309
uses_found++;
310
}
311
}
312
if (is_in_table) {
313
// reinsert into table
314
initial_gvn()->hash_find_insert(use);
315
}
316
record_for_igvn(use);
317
i -= uses_found; // we deleted 1 or more copies of this edge
318
}
319
}
320
321
322
static inline bool not_a_node(const Node* n) {
323
if (n == NULL) return true;
324
if (((intptr_t)n & 1) != 0) return true; // uninitialized, etc.
325
if (*(address*)n == badAddress) return true; // kill by Node::destruct
326
return false;
327
}
328
329
// Identify all nodes that are reachable from below, useful.
330
// Use breadth-first pass that records state in a Unique_Node_List,
331
// recursive traversal is slower.
332
void Compile::identify_useful_nodes(Unique_Node_List &useful) {
333
int estimated_worklist_size = live_nodes();
334
useful.map( estimated_worklist_size, NULL ); // preallocate space
335
336
// Initialize worklist
337
if (root() != NULL) { useful.push(root()); }
338
// If 'top' is cached, declare it useful to preserve cached node
339
if( cached_top_node() ) { useful.push(cached_top_node()); }
340
341
// Push all useful nodes onto the list, breadthfirst
342
for( uint next = 0; next < useful.size(); ++next ) {
343
assert( next < unique(), "Unique useful nodes < total nodes");
344
Node *n = useful.at(next);
345
uint max = n->len();
346
for( uint i = 0; i < max; ++i ) {
347
Node *m = n->in(i);
348
if (not_a_node(m)) continue;
349
useful.push(m);
350
}
351
}
352
}
353
354
// Update dead_node_list with any missing dead nodes using useful
355
// list. Consider all non-useful nodes to be useless i.e., dead nodes.
356
void Compile::update_dead_node_list(Unique_Node_List &useful) {
357
uint max_idx = unique();
358
VectorSet& useful_node_set = useful.member_set();
359
360
for (uint node_idx = 0; node_idx < max_idx; node_idx++) {
361
// If node with index node_idx is not in useful set,
362
// mark it as dead in dead node list.
363
if (! useful_node_set.test(node_idx) ) {
364
record_dead_node(node_idx);
365
}
366
}
367
}
368
369
void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) {
370
int shift = 0;
371
for (int i = 0; i < inlines->length(); i++) {
372
CallGenerator* cg = inlines->at(i);
373
CallNode* call = cg->call_node();
374
if (shift > 0) {
375
inlines->at_put(i-shift, cg);
376
}
377
if (!useful.member(call)) {
378
shift++;
379
}
380
}
381
inlines->trunc_to(inlines->length()-shift);
382
}
383
384
// Disconnect all useless nodes by disconnecting those at the boundary.
385
void Compile::remove_useless_nodes(Unique_Node_List &useful) {
386
uint next = 0;
387
while (next < useful.size()) {
388
Node *n = useful.at(next++);
389
if (n->is_SafePoint()) {
390
// We're done with a parsing phase. Replaced nodes are not valid
391
// beyond that point.
392
n->as_SafePoint()->delete_replaced_nodes();
393
}
394
// Use raw traversal of out edges since this code removes out edges
395
int max = n->outcnt();
396
for (int j = 0; j < max; ++j) {
397
Node* child = n->raw_out(j);
398
if (! useful.member(child)) {
399
assert(!child->is_top() || child != top(),
400
"If top is cached in Compile object it is in useful list");
401
// Only need to remove this out-edge to the useless node
402
n->raw_del_out(j);
403
--j;
404
--max;
405
}
406
}
407
if (n->outcnt() == 1 && n->has_special_unique_user()) {
408
record_for_igvn(n->unique_out());
409
}
410
}
411
// Remove useless macro and predicate opaq nodes
412
for (int i = C->macro_count()-1; i >= 0; i--) {
413
Node* n = C->macro_node(i);
414
if (!useful.member(n)) {
415
remove_macro_node(n);
416
}
417
}
418
// Remove useless CastII nodes with range check dependency
419
for (int i = range_check_cast_count() - 1; i >= 0; i--) {
420
Node* cast = range_check_cast_node(i);
421
if (!useful.member(cast)) {
422
remove_range_check_cast(cast);
423
}
424
}
425
// Remove useless expensive node
426
for (int i = C->expensive_count()-1; i >= 0; i--) {
427
Node* n = C->expensive_node(i);
428
if (!useful.member(n)) {
429
remove_expensive_node(n);
430
}
431
}
432
// clean up the late inline lists
433
remove_useless_late_inlines(&_string_late_inlines, useful);
434
remove_useless_late_inlines(&_boxing_late_inlines, useful);
435
remove_useless_late_inlines(&_late_inlines, useful);
436
debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
437
}
438
439
//------------------------------frame_size_in_words-----------------------------
440
// frame_slots in units of words
441
int Compile::frame_size_in_words() const {
442
// shift is 0 in LP32 and 1 in LP64
443
const int shift = (LogBytesPerWord - LogBytesPerInt);
444
int words = _frame_slots >> shift;
445
assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" );
446
return words;
447
}
448
449
// To bang the stack of this compiled method we use the stack size
450
// that the interpreter would need in case of a deoptimization. This
451
// removes the need to bang the stack in the deoptimization blob which
452
// in turn simplifies stack overflow handling.
453
int Compile::bang_size_in_bytes() const {
454
return MAX2(_interpreter_frame_size, frame_size_in_bytes());
455
}
456
457
// ============================================================================
458
//------------------------------CompileWrapper---------------------------------
459
class CompileWrapper : public StackObj {
460
Compile *const _compile;
461
public:
462
CompileWrapper(Compile* compile);
463
464
~CompileWrapper();
465
};
466
467
CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) {
468
// the Compile* pointer is stored in the current ciEnv:
469
ciEnv* env = compile->env();
470
assert(env == ciEnv::current(), "must already be a ciEnv active");
471
assert(env->compiler_data() == NULL, "compile already active?");
472
env->set_compiler_data(compile);
473
assert(compile == Compile::current(), "sanity");
474
475
compile->set_type_dict(NULL);
476
compile->set_type_hwm(NULL);
477
compile->set_type_last_size(0);
478
compile->set_last_tf(NULL, NULL);
479
compile->set_indexSet_arena(NULL);
480
compile->set_indexSet_free_block_list(NULL);
481
compile->init_type_arena();
482
Type::Initialize(compile);
483
_compile->set_scratch_buffer_blob(NULL);
484
_compile->begin_method();
485
}
486
CompileWrapper::~CompileWrapper() {
487
_compile->end_method();
488
if (_compile->scratch_buffer_blob() != NULL)
489
BufferBlob::free(_compile->scratch_buffer_blob());
490
_compile->env()->set_compiler_data(NULL);
491
}
492
493
494
//----------------------------print_compile_messages---------------------------
495
void Compile::print_compile_messages() {
496
#ifndef PRODUCT
497
// Check if recompiling
498
if (_subsume_loads == false && PrintOpto) {
499
// Recompiling without allowing machine instructions to subsume loads
500
tty->print_cr("*********************************************************");
501
tty->print_cr("** Bailout: Recompile without subsuming loads **");
502
tty->print_cr("*********************************************************");
503
}
504
if (_do_escape_analysis != DoEscapeAnalysis && PrintOpto) {
505
// Recompiling without escape analysis
506
tty->print_cr("*********************************************************");
507
tty->print_cr("** Bailout: Recompile without escape analysis **");
508
tty->print_cr("*********************************************************");
509
}
510
if (_eliminate_boxing != EliminateAutoBox && PrintOpto) {
511
// Recompiling without boxing elimination
512
tty->print_cr("*********************************************************");
513
tty->print_cr("** Bailout: Recompile without boxing elimination **");
514
tty->print_cr("*********************************************************");
515
}
516
if (env()->break_at_compile()) {
517
// Open the debugger when compiling this method.
518
tty->print("### Breaking when compiling: ");
519
method()->print_short_name();
520
tty->cr();
521
BREAKPOINT;
522
}
523
524
if( PrintOpto ) {
525
if (is_osr_compilation()) {
526
tty->print("[OSR]%3d", _compile_id);
527
} else {
528
tty->print("%3d", _compile_id);
529
}
530
}
531
#endif
532
}
533
534
535
//-----------------------init_scratch_buffer_blob------------------------------
536
// Construct a temporary BufferBlob and cache it for this compile.
537
void Compile::init_scratch_buffer_blob(int const_size) {
538
// If there is already a scratch buffer blob allocated and the
539
// constant section is big enough, use it. Otherwise free the
540
// current and allocate a new one.
541
BufferBlob* blob = scratch_buffer_blob();
542
if ((blob != NULL) && (const_size <= _scratch_const_size)) {
543
// Use the current blob.
544
} else {
545
if (blob != NULL) {
546
BufferBlob::free(blob);
547
}
548
549
ResourceMark rm;
550
_scratch_const_size = const_size;
551
int size = (MAX_inst_size + MAX_stubs_size + _scratch_const_size);
552
blob = BufferBlob::create("Compile::scratch_buffer", size);
553
// Record the buffer blob for next time.
554
set_scratch_buffer_blob(blob);
555
// Have we run out of code space?
556
if (scratch_buffer_blob() == NULL) {
557
// Let CompilerBroker disable further compilations.
558
record_failure("Not enough space for scratch buffer in CodeCache");
559
return;
560
}
561
}
562
563
// Initialize the relocation buffers
564
relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size;
565
set_scratch_locs_memory(locs_buf);
566
}
567
568
569
//-----------------------scratch_emit_size-------------------------------------
570
// Helper function that computes size by emitting code
571
uint Compile::scratch_emit_size(const Node* n) {
572
// Start scratch_emit_size section.
573
set_in_scratch_emit_size(true);
574
575
// Emit into a trash buffer and count bytes emitted.
576
// This is a pretty expensive way to compute a size,
577
// but it works well enough if seldom used.
578
// All common fixed-size instructions are given a size
579
// method by the AD file.
580
// Note that the scratch buffer blob and locs memory are
581
// allocated at the beginning of the compile task, and
582
// may be shared by several calls to scratch_emit_size.
583
// The allocation of the scratch buffer blob is particularly
584
// expensive, since it has to grab the code cache lock.
585
BufferBlob* blob = this->scratch_buffer_blob();
586
assert(blob != NULL, "Initialize BufferBlob at start");
587
assert(blob->size() > MAX_inst_size, "sanity");
588
relocInfo* locs_buf = scratch_locs_memory();
589
address blob_begin = blob->content_begin();
590
address blob_end = (address)locs_buf;
591
assert(blob->content_contains(blob_end), "sanity");
592
CodeBuffer buf(blob_begin, blob_end - blob_begin);
593
buf.initialize_consts_size(_scratch_const_size);
594
buf.initialize_stubs_size(MAX_stubs_size);
595
assert(locs_buf != NULL, "sanity");
596
int lsize = MAX_locs_size / 3;
597
buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize);
598
buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize);
599
buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize);
600
601
// Do the emission.
602
603
Label fakeL; // Fake label for branch instructions.
604
Label* saveL = NULL;
605
uint save_bnum = 0;
606
bool is_branch = n->is_MachBranch();
607
if (is_branch) {
608
MacroAssembler masm(&buf);
609
masm.bind(fakeL);
610
n->as_MachBranch()->save_label(&saveL, &save_bnum);
611
n->as_MachBranch()->label_set(&fakeL, 0);
612
}
613
n->emit(buf, this->regalloc());
614
615
// Emitting into the scratch buffer should not fail
616
assert (!failing(), err_msg_res("Must not have pending failure. Reason is: %s", failure_reason()));
617
618
if (is_branch) // Restore label.
619
n->as_MachBranch()->label_set(saveL, save_bnum);
620
621
// End scratch_emit_size section.
622
set_in_scratch_emit_size(false);
623
624
return buf.insts_size();
625
}
626
627
628
// ============================================================================
629
//------------------------------Compile standard-------------------------------
630
debug_only( int Compile::_debug_idx = 100000; )
631
632
// Compile a method. entry_bci is -1 for normal compilations and indicates
633
// the continuation bci for on stack replacement.
634
635
636
Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr_bci,
637
bool subsume_loads, bool do_escape_analysis, bool eliminate_boxing )
638
: Phase(Compiler),
639
_env(ci_env),
640
_log(ci_env->log()),
641
_compile_id(ci_env->compile_id()),
642
_save_argument_registers(false),
643
_stub_name(NULL),
644
_stub_function(NULL),
645
_stub_entry_point(NULL),
646
_method(target),
647
_entry_bci(osr_bci),
648
_initial_gvn(NULL),
649
_for_igvn(NULL),
650
_warm_calls(NULL),
651
_subsume_loads(subsume_loads),
652
_do_escape_analysis(do_escape_analysis),
653
_eliminate_boxing(eliminate_boxing),
654
_failure_reason(NULL),
655
_code_buffer("Compile::Fill_buffer"),
656
_orig_pc_slot(0),
657
_orig_pc_slot_offset_in_bytes(0),
658
_has_method_handle_invokes(false),
659
_mach_constant_base_node(NULL),
660
_node_bundling_limit(0),
661
_node_bundling_base(NULL),
662
_java_calls(0),
663
_inner_loops(0),
664
_scratch_const_size(-1),
665
_in_scratch_emit_size(false),
666
_dead_node_list(comp_arena()),
667
_dead_node_count(0),
668
#ifndef PRODUCT
669
_trace_opto_output(TraceOptoOutput || method()->has_option("TraceOptoOutput")),
670
_in_dump_cnt(0),
671
_printer(IdealGraphPrinter::printer()),
672
#endif
673
_congraph(NULL),
674
_comp_arena(mtCompiler),
675
_node_arena(mtCompiler),
676
_old_arena(mtCompiler),
677
_Compile_types(mtCompiler),
678
_replay_inline_data(NULL),
679
_late_inlines(comp_arena(), 2, 0, NULL),
680
_string_late_inlines(comp_arena(), 2, 0, NULL),
681
_boxing_late_inlines(comp_arena(), 2, 0, NULL),
682
_late_inlines_pos(0),
683
_number_of_mh_late_inlines(0),
684
_inlining_progress(false),
685
_inlining_incrementally(false),
686
_print_inlining_list(NULL),
687
_print_inlining_idx(0),
688
_interpreter_frame_size(0),
689
_max_node_limit(MaxNodeLimit) {
690
C = this;
691
692
CompileWrapper cw(this);
693
#ifndef PRODUCT
694
if (TimeCompiler2) {
695
tty->print(" ");
696
target->holder()->name()->print();
697
tty->print(".");
698
target->print_short_name();
699
tty->print(" ");
700
}
701
TraceTime t1("Total compilation time", &_t_totalCompilation, TimeCompiler, TimeCompiler2);
702
TraceTime t2(NULL, &_t_methodCompilation, TimeCompiler, false);
703
bool print_opto_assembly = PrintOptoAssembly || _method->has_option("PrintOptoAssembly");
704
if (!print_opto_assembly) {
705
bool print_assembly = (PrintAssembly || _method->should_print_assembly());
706
if (print_assembly && !Disassembler::can_decode()) {
707
tty->print_cr("PrintAssembly request changed to PrintOptoAssembly");
708
print_opto_assembly = true;
709
}
710
}
711
set_print_assembly(print_opto_assembly);
712
set_parsed_irreducible_loop(false);
713
714
if (method()->has_option("ReplayInline")) {
715
_replay_inline_data = ciReplay::load_inline_data(method(), entry_bci(), ci_env->comp_level());
716
}
717
#endif
718
set_print_inlining(PrintInlining || method()->has_option("PrintInlining") NOT_PRODUCT( || PrintOptoInlining));
719
set_print_intrinsics(PrintIntrinsics || method()->has_option("PrintIntrinsics"));
720
set_has_irreducible_loop(true); // conservative until build_loop_tree() reset it
721
722
if (ProfileTraps RTM_OPT_ONLY( || UseRTMLocking )) {
723
// Make sure the method being compiled gets its own MDO,
724
// so we can at least track the decompile_count().
725
// Need MDO to record RTM code generation state.
726
method()->ensure_method_data();
727
}
728
729
Init(::AliasLevel);
730
731
732
print_compile_messages();
733
734
_ilt = InlineTree::build_inline_tree_root();
735
736
// Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
737
assert(num_alias_types() >= AliasIdxRaw, "");
738
739
#define MINIMUM_NODE_HASH 1023
740
// Node list that Iterative GVN will start with
741
Unique_Node_List for_igvn(comp_arena());
742
set_for_igvn(&for_igvn);
743
744
// GVN that will be run immediately on new nodes
745
uint estimated_size = method()->code_size()*4+64;
746
estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
747
PhaseGVN gvn(node_arena(), estimated_size);
748
set_initial_gvn(&gvn);
749
750
if (print_inlining() || print_intrinsics()) {
751
_print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer>(comp_arena(), 1, 1, PrintInliningBuffer());
752
}
753
{ // Scope for timing the parser
754
TracePhase t3("parse", &_t_parser, true);
755
756
// Put top into the hash table ASAP.
757
initial_gvn()->transform_no_reclaim(top());
758
759
// Set up tf(), start(), and find a CallGenerator.
760
CallGenerator* cg = NULL;
761
if (is_osr_compilation()) {
762
const TypeTuple *domain = StartOSRNode::osr_domain();
763
const TypeTuple *range = TypeTuple::make_range(method()->signature());
764
init_tf(TypeFunc::make(domain, range));
765
StartNode* s = new (this) StartOSRNode(root(), domain);
766
initial_gvn()->set_type_bottom(s);
767
init_start(s);
768
cg = CallGenerator::for_osr(method(), entry_bci());
769
} else {
770
// Normal case.
771
init_tf(TypeFunc::make(method()));
772
StartNode* s = new (this) StartNode(root(), tf()->domain());
773
initial_gvn()->set_type_bottom(s);
774
init_start(s);
775
if (method()->intrinsic_id() == vmIntrinsics::_Reference_get && UseG1GC) {
776
// With java.lang.ref.reference.get() we must go through the
777
// intrinsic when G1 is enabled - even when get() is the root
778
// method of the compile - so that, if necessary, the value in
779
// the referent field of the reference object gets recorded by
780
// the pre-barrier code.
781
// Specifically, if G1 is enabled, the value in the referent
782
// field is recorded by the G1 SATB pre barrier. This will
783
// result in the referent being marked live and the reference
784
// object removed from the list of discovered references during
785
// reference processing.
786
cg = find_intrinsic(method(), false);
787
}
788
if (cg == NULL) {
789
float past_uses = method()->interpreter_invocation_count();
790
float expected_uses = past_uses;
791
cg = CallGenerator::for_inline(method(), expected_uses);
792
}
793
}
794
if (failing()) return;
795
if (cg == NULL) {
796
record_method_not_compilable_all_tiers("cannot parse method");
797
return;
798
}
799
JVMState* jvms = build_start_state(start(), tf());
800
if ((jvms = cg->generate(jvms)) == NULL) {
801
if (!failure_reason_is(C2Compiler::retry_class_loading_during_parsing())) {
802
record_method_not_compilable("method parse failed");
803
}
804
return;
805
}
806
GraphKit kit(jvms);
807
808
if (!kit.stopped()) {
809
// Accept return values, and transfer control we know not where.
810
// This is done by a special, unique ReturnNode bound to root.
811
return_values(kit.jvms());
812
}
813
814
if (kit.has_exceptions()) {
815
// Any exceptions that escape from this call must be rethrown
816
// to whatever caller is dynamically above us on the stack.
817
// This is done by a special, unique RethrowNode bound to root.
818
rethrow_exceptions(kit.transfer_exceptions_into_jvms());
819
}
820
821
assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off");
822
823
if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) {
824
inline_string_calls(true);
825
}
826
827
if (failing()) return;
828
829
print_method(PHASE_BEFORE_REMOVEUSELESS, 3);
830
831
// Remove clutter produced by parsing.
832
if (!failing()) {
833
ResourceMark rm;
834
PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
835
}
836
}
837
838
// Note: Large methods are capped off in do_one_bytecode().
839
if (failing()) return;
840
841
// After parsing, node notes are no longer automagic.
842
// They must be propagated by register_new_node_with_optimizer(),
843
// clone(), or the like.
844
set_default_node_notes(NULL);
845
846
for (;;) {
847
int successes = Inline_Warm();
848
if (failing()) return;
849
if (successes == 0) break;
850
}
851
852
// Drain the list.
853
Finish_Warm();
854
#ifndef PRODUCT
855
if (_printer) {
856
_printer->print_inlining(this);
857
}
858
#endif
859
860
if (failing()) return;
861
NOT_PRODUCT( verify_graph_edges(); )
862
863
// Now optimize
864
Optimize();
865
if (failing()) return;
866
NOT_PRODUCT( verify_graph_edges(); )
867
868
#ifndef PRODUCT
869
if (PrintIdeal) {
870
ttyLocker ttyl; // keep the following output all in one block
871
// This output goes directly to the tty, not the compiler log.
872
// To enable tools to match it up with the compilation activity,
873
// be sure to tag this tty output with the compile ID.
874
if (xtty != NULL) {
875
xtty->head("ideal compile_id='%d'%s", compile_id(),
876
is_osr_compilation() ? " compile_kind='osr'" :
877
"");
878
}
879
root()->dump(9999);
880
if (xtty != NULL) {
881
xtty->tail("ideal");
882
}
883
}
884
#endif
885
886
NOT_PRODUCT( verify_barriers(); )
887
888
// Dump compilation data to replay it.
889
if (method()->has_option("DumpReplay")) {
890
env()->dump_replay_data(_compile_id);
891
}
892
if (method()->has_option("DumpInline") && (ilt() != NULL)) {
893
env()->dump_inline_data(_compile_id);
894
}
895
896
// Now that we know the size of all the monitors we can add a fixed slot
897
// for the original deopt pc.
898
899
_orig_pc_slot = fixed_slots();
900
int next_slot = _orig_pc_slot + (sizeof(address) / VMRegImpl::stack_slot_size);
901
set_fixed_slots(next_slot);
902
903
// Compute when to use implicit null checks. Used by matching trap based
904
// nodes and NullCheck optimization.
905
set_allowed_deopt_reasons();
906
907
// Now generate code
908
Code_Gen();
909
if (failing()) return;
910
911
// Check if we want to skip execution of all compiled code.
912
{
913
#ifndef PRODUCT
914
if (OptoNoExecute) {
915
record_method_not_compilable("+OptoNoExecute"); // Flag as failed
916
return;
917
}
918
TracePhase t2("install_code", &_t_registerMethod, TimeCompiler);
919
#endif
920
921
if (is_osr_compilation()) {
922
_code_offsets.set_value(CodeOffsets::Verified_Entry, 0);
923
_code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size);
924
} else {
925
_code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size);
926
_code_offsets.set_value(CodeOffsets::OSR_Entry, 0);
927
}
928
929
env()->register_method(_method, _entry_bci,
930
&_code_offsets,
931
_orig_pc_slot_offset_in_bytes,
932
code_buffer(),
933
frame_size_in_words(), _oop_map_set,
934
&_handler_table, &_inc_table,
935
compiler,
936
env()->comp_level(),
937
has_unsafe_access(),
938
SharedRuntime::is_wide_vector(max_vector_size()),
939
rtm_state()
940
);
941
942
if (log() != NULL) // Print code cache state into compiler log
943
log()->code_cache_state();
944
}
945
}
946
947
//------------------------------Compile----------------------------------------
948
// Compile a runtime stub
949
Compile::Compile( ciEnv* ci_env,
950
TypeFunc_generator generator,
951
address stub_function,
952
const char *stub_name,
953
int is_fancy_jump,
954
bool pass_tls,
955
bool save_arg_registers,
956
bool return_pc )
957
: Phase(Compiler),
958
_env(ci_env),
959
_log(ci_env->log()),
960
_compile_id(0),
961
_save_argument_registers(save_arg_registers),
962
_method(NULL),
963
_stub_name(stub_name),
964
_stub_function(stub_function),
965
_stub_entry_point(NULL),
966
_entry_bci(InvocationEntryBci),
967
_initial_gvn(NULL),
968
_for_igvn(NULL),
969
_warm_calls(NULL),
970
_orig_pc_slot(0),
971
_orig_pc_slot_offset_in_bytes(0),
972
_subsume_loads(true),
973
_do_escape_analysis(false),
974
_eliminate_boxing(false),
975
_failure_reason(NULL),
976
_code_buffer("Compile::Fill_buffer"),
977
_has_method_handle_invokes(false),
978
_mach_constant_base_node(NULL),
979
_node_bundling_limit(0),
980
_node_bundling_base(NULL),
981
_java_calls(0),
982
_inner_loops(0),
983
#ifndef PRODUCT
984
_trace_opto_output(TraceOptoOutput),
985
_in_dump_cnt(0),
986
_printer(NULL),
987
#endif
988
_comp_arena(mtCompiler),
989
_node_arena(mtCompiler),
990
_old_arena(mtCompiler),
991
_Compile_types(mtCompiler),
992
_dead_node_list(comp_arena()),
993
_dead_node_count(0),
994
_congraph(NULL),
995
_replay_inline_data(NULL),
996
_number_of_mh_late_inlines(0),
997
_inlining_progress(false),
998
_inlining_incrementally(false),
999
_print_inlining_list(NULL),
1000
_print_inlining_idx(0),
1001
_allowed_reasons(0),
1002
_interpreter_frame_size(0),
1003
_max_node_limit(MaxNodeLimit) {
1004
C = this;
1005
1006
#ifndef PRODUCT
1007
TraceTime t1(NULL, &_t_totalCompilation, TimeCompiler, false);
1008
TraceTime t2(NULL, &_t_stubCompilation, TimeCompiler, false);
1009
set_print_assembly(PrintFrameConverterAssembly);
1010
set_parsed_irreducible_loop(false);
1011
#endif
1012
set_has_irreducible_loop(false); // no loops
1013
1014
CompileWrapper cw(this);
1015
Init(/*AliasLevel=*/ 0);
1016
init_tf((*generator)());
1017
1018
{
1019
// The following is a dummy for the sake of GraphKit::gen_stub
1020
Unique_Node_List for_igvn(comp_arena());
1021
set_for_igvn(&for_igvn); // not used, but some GraphKit guys push on this
1022
PhaseGVN gvn(Thread::current()->resource_area(),255);
1023
set_initial_gvn(&gvn); // not significant, but GraphKit guys use it pervasively
1024
gvn.transform_no_reclaim(top());
1025
1026
GraphKit kit;
1027
kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc);
1028
}
1029
1030
NOT_PRODUCT( verify_graph_edges(); )
1031
Code_Gen();
1032
if (failing()) return;
1033
1034
1035
// Entry point will be accessed using compile->stub_entry_point();
1036
if (code_buffer() == NULL) {
1037
Matcher::soft_match_failure();
1038
} else {
1039
if (PrintAssembly && (WizardMode || Verbose))
1040
tty->print_cr("### Stub::%s", stub_name);
1041
1042
if (!failing()) {
1043
assert(_fixed_slots == 0, "no fixed slots used for runtime stubs");
1044
1045
// Make the NMethod
1046
// For now we mark the frame as never safe for profile stackwalking
1047
RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name,
1048
code_buffer(),
1049
CodeOffsets::frame_never_safe,
1050
// _code_offsets.value(CodeOffsets::Frame_Complete),
1051
frame_size_in_words(),
1052
_oop_map_set,
1053
save_arg_registers);
1054
assert(rs != NULL && rs->is_runtime_stub(), "sanity check");
1055
1056
_stub_entry_point = rs->entry_point();
1057
}
1058
}
1059
}
1060
1061
//------------------------------Init-------------------------------------------
1062
// Prepare for a single compilation
1063
void Compile::Init(int aliaslevel) {
1064
_unique = 0;
1065
_regalloc = NULL;
1066
1067
_tf = NULL; // filled in later
1068
_top = NULL; // cached later
1069
_matcher = NULL; // filled in later
1070
_cfg = NULL; // filled in later
1071
1072
set_24_bit_selection_and_mode(Use24BitFP, false);
1073
1074
_node_note_array = NULL;
1075
_default_node_notes = NULL;
1076
1077
_immutable_memory = NULL; // filled in at first inquiry
1078
1079
// Globally visible Nodes
1080
// First set TOP to NULL to give safe behavior during creation of RootNode
1081
set_cached_top_node(NULL);
1082
set_root(new (this) RootNode());
1083
// Now that you have a Root to point to, create the real TOP
1084
set_cached_top_node( new (this) ConNode(Type::TOP) );
1085
set_recent_alloc(NULL, NULL);
1086
1087
// Create Debug Information Recorder to record scopes, oopmaps, etc.
1088
env()->set_oop_recorder(new OopRecorder(env()->arena()));
1089
env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder()));
1090
env()->set_dependencies(new Dependencies(env()));
1091
1092
_fixed_slots = 0;
1093
set_has_split_ifs(false);
1094
set_has_loops(has_method() && method()->has_loops()); // first approximation
1095
set_has_stringbuilder(false);
1096
set_has_boxed_value(false);
1097
_trap_can_recompile = false; // no traps emitted yet
1098
_major_progress = true; // start out assuming good things will happen
1099
set_has_unsafe_access(false);
1100
set_max_vector_size(0);
1101
Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
1102
set_decompile_count(0);
1103
1104
set_do_freq_based_layout(BlockLayoutByFrequency || method_has_option("BlockLayoutByFrequency"));
1105
set_num_loop_opts(LoopOptsCount);
1106
set_do_inlining(Inline);
1107
set_max_inline_size(MaxInlineSize);
1108
set_freq_inline_size(FreqInlineSize);
1109
set_do_scheduling(OptoScheduling);
1110
set_do_count_invocations(false);
1111
set_do_method_data_update(false);
1112
set_rtm_state(NoRTM); // No RTM lock eliding by default
1113
method_has_option_value("MaxNodeLimit", _max_node_limit);
1114
#if INCLUDE_RTM_OPT
1115
if (UseRTMLocking && has_method() && (method()->method_data_or_null() != NULL)) {
1116
int rtm_state = method()->method_data()->rtm_state();
1117
if (method_has_option("NoRTMLockEliding") || ((rtm_state & NoRTM) != 0)) {
1118
// Don't generate RTM lock eliding code.
1119
set_rtm_state(NoRTM);
1120
} else if (method_has_option("UseRTMLockEliding") || ((rtm_state & UseRTM) != 0) || !UseRTMDeopt) {
1121
// Generate RTM lock eliding code without abort ratio calculation code.
1122
set_rtm_state(UseRTM);
1123
} else if (UseRTMDeopt) {
1124
// Generate RTM lock eliding code and include abort ratio calculation
1125
// code if UseRTMDeopt is on.
1126
set_rtm_state(ProfileRTM);
1127
}
1128
}
1129
#endif
1130
if (debug_info()->recording_non_safepoints()) {
1131
set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*>
1132
(comp_arena(), 8, 0, NULL));
1133
set_default_node_notes(Node_Notes::make(this));
1134
}
1135
1136
// // -- Initialize types before each compile --
1137
// // Update cached type information
1138
// if( _method && _method->constants() )
1139
// Type::update_loaded_types(_method, _method->constants());
1140
1141
// Init alias_type map.
1142
if (!_do_escape_analysis && aliaslevel == 3)
1143
aliaslevel = 2; // No unique types without escape analysis
1144
_AliasLevel = aliaslevel;
1145
const int grow_ats = 16;
1146
_max_alias_types = grow_ats;
1147
_alias_types = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats);
1148
AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, grow_ats);
1149
Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats);
1150
{
1151
for (int i = 0; i < grow_ats; i++) _alias_types[i] = &ats[i];
1152
}
1153
// Initialize the first few types.
1154
_alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL);
1155
_alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM);
1156
_alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM);
1157
_num_alias_types = AliasIdxRaw+1;
1158
// Zero out the alias type cache.
1159
Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache));
1160
// A NULL adr_type hits in the cache right away. Preload the right answer.
1161
probe_alias_cache(NULL)->_index = AliasIdxTop;
1162
1163
_intrinsics = NULL;
1164
_macro_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL);
1165
_predicate_opaqs = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL);
1166
_expensive_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL);
1167
_range_check_casts = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL);
1168
register_library_intrinsics();
1169
#ifdef ASSERT
1170
_type_verify_symmetry = true;
1171
#endif
1172
}
1173
1174
//---------------------------init_start----------------------------------------
1175
// Install the StartNode on this compile object.
1176
void Compile::init_start(StartNode* s) {
1177
if (failing())
1178
return; // already failing
1179
assert(s == start(), "");
1180
}
1181
1182
StartNode* Compile::start() const {
1183
assert(!failing(), "");
1184
for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
1185
Node* start = root()->fast_out(i);
1186
if( start->is_Start() )
1187
return start->as_Start();
1188
}
1189
fatal("Did not find Start node!");
1190
return NULL;
1191
}
1192
1193
//-------------------------------immutable_memory-------------------------------------
1194
// Access immutable memory
1195
Node* Compile::immutable_memory() {
1196
if (_immutable_memory != NULL) {
1197
return _immutable_memory;
1198
}
1199
StartNode* s = start();
1200
for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) {
1201
Node *p = s->fast_out(i);
1202
if (p != s && p->as_Proj()->_con == TypeFunc::Memory) {
1203
_immutable_memory = p;
1204
return _immutable_memory;
1205
}
1206
}
1207
ShouldNotReachHere();
1208
return NULL;
1209
}
1210
1211
//----------------------set_cached_top_node------------------------------------
1212
// Install the cached top node, and make sure Node::is_top works correctly.
1213
void Compile::set_cached_top_node(Node* tn) {
1214
if (tn != NULL) verify_top(tn);
1215
Node* old_top = _top;
1216
_top = tn;
1217
// Calling Node::setup_is_top allows the nodes the chance to adjust
1218
// their _out arrays.
1219
if (_top != NULL) _top->setup_is_top();
1220
if (old_top != NULL) old_top->setup_is_top();
1221
assert(_top == NULL || top()->is_top(), "");
1222
}
1223
1224
#ifdef ASSERT
1225
uint Compile::count_live_nodes_by_graph_walk() {
1226
Unique_Node_List useful(comp_arena());
1227
// Get useful node list by walking the graph.
1228
identify_useful_nodes(useful);
1229
return useful.size();
1230
}
1231
1232
void Compile::print_missing_nodes() {
1233
1234
// Return if CompileLog is NULL and PrintIdealNodeCount is false.
1235
if ((_log == NULL) && (! PrintIdealNodeCount)) {
1236
return;
1237
}
1238
1239
// This is an expensive function. It is executed only when the user
1240
// specifies VerifyIdealNodeCount option or otherwise knows the
1241
// additional work that needs to be done to identify reachable nodes
1242
// by walking the flow graph and find the missing ones using
1243
// _dead_node_list.
1244
1245
Unique_Node_List useful(comp_arena());
1246
// Get useful node list by walking the graph.
1247
identify_useful_nodes(useful);
1248
1249
uint l_nodes = C->live_nodes();
1250
uint l_nodes_by_walk = useful.size();
1251
1252
if (l_nodes != l_nodes_by_walk) {
1253
if (_log != NULL) {
1254
_log->begin_head("mismatched_nodes count='%d'", abs((int) (l_nodes - l_nodes_by_walk)));
1255
_log->stamp();
1256
_log->end_head();
1257
}
1258
VectorSet& useful_member_set = useful.member_set();
1259
int last_idx = l_nodes_by_walk;
1260
for (int i = 0; i < last_idx; i++) {
1261
if (useful_member_set.test(i)) {
1262
if (_dead_node_list.test(i)) {
1263
if (_log != NULL) {
1264
_log->elem("mismatched_node_info node_idx='%d' type='both live and dead'", i);
1265
}
1266
if (PrintIdealNodeCount) {
1267
// Print the log message to tty
1268
tty->print_cr("mismatched_node idx='%d' both live and dead'", i);
1269
useful.at(i)->dump();
1270
}
1271
}
1272
}
1273
else if (! _dead_node_list.test(i)) {
1274
if (_log != NULL) {
1275
_log->elem("mismatched_node_info node_idx='%d' type='neither live nor dead'", i);
1276
}
1277
if (PrintIdealNodeCount) {
1278
// Print the log message to tty
1279
tty->print_cr("mismatched_node idx='%d' type='neither live nor dead'", i);
1280
}
1281
}
1282
}
1283
if (_log != NULL) {
1284
_log->tail("mismatched_nodes");
1285
}
1286
}
1287
}
1288
#endif
1289
1290
#ifndef PRODUCT
1291
void Compile::verify_top(Node* tn) const {
1292
if (tn != NULL) {
1293
assert(tn->is_Con(), "top node must be a constant");
1294
assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type");
1295
assert(tn->in(0) != NULL, "must have live top node");
1296
}
1297
}
1298
#endif
1299
1300
1301
///-------------------Managing Per-Node Debug & Profile Info-------------------
1302
1303
void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) {
1304
guarantee(arr != NULL, "");
1305
int num_blocks = arr->length();
1306
if (grow_by < num_blocks) grow_by = num_blocks;
1307
int num_notes = grow_by * _node_notes_block_size;
1308
Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes);
1309
Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes));
1310
while (num_notes > 0) {
1311
arr->append(notes);
1312
notes += _node_notes_block_size;
1313
num_notes -= _node_notes_block_size;
1314
}
1315
assert(num_notes == 0, "exact multiple, please");
1316
}
1317
1318
bool Compile::copy_node_notes_to(Node* dest, Node* source) {
1319
if (source == NULL || dest == NULL) return false;
1320
1321
if (dest->is_Con())
1322
return false; // Do not push debug info onto constants.
1323
1324
#ifdef ASSERT
1325
// Leave a bread crumb trail pointing to the original node:
1326
if (dest != NULL && dest != source && dest->debug_orig() == NULL) {
1327
dest->set_debug_orig(source);
1328
}
1329
#endif
1330
1331
if (node_note_array() == NULL)
1332
return false; // Not collecting any notes now.
1333
1334
// This is a copy onto a pre-existing node, which may already have notes.
1335
// If both nodes have notes, do not overwrite any pre-existing notes.
1336
Node_Notes* source_notes = node_notes_at(source->_idx);
1337
if (source_notes == NULL || source_notes->is_clear()) return false;
1338
Node_Notes* dest_notes = node_notes_at(dest->_idx);
1339
if (dest_notes == NULL || dest_notes->is_clear()) {
1340
return set_node_notes_at(dest->_idx, source_notes);
1341
}
1342
1343
Node_Notes merged_notes = (*source_notes);
1344
// The order of operations here ensures that dest notes will win...
1345
merged_notes.update_from(dest_notes);
1346
return set_node_notes_at(dest->_idx, &merged_notes);
1347
}
1348
1349
1350
//--------------------------allow_range_check_smearing-------------------------
1351
// Gating condition for coalescing similar range checks.
1352
// Sometimes we try 'speculatively' replacing a series of a range checks by a
1353
// single covering check that is at least as strong as any of them.
1354
// If the optimization succeeds, the simplified (strengthened) range check
1355
// will always succeed. If it fails, we will deopt, and then give up
1356
// on the optimization.
1357
bool Compile::allow_range_check_smearing() const {
1358
// If this method has already thrown a range-check,
1359
// assume it was because we already tried range smearing
1360
// and it failed.
1361
uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1362
return !already_trapped;
1363
}
1364
1365
1366
//------------------------------flatten_alias_type-----------------------------
1367
const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1368
int offset = tj->offset();
1369
TypePtr::PTR ptr = tj->ptr();
1370
1371
// Known instance (scalarizable allocation) alias only with itself.
1372
bool is_known_inst = tj->isa_oopptr() != NULL &&
1373
tj->is_oopptr()->is_known_instance();
1374
1375
// Process weird unsafe references.
1376
if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1377
assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops");
1378
assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1379
tj = TypeOopPtr::BOTTOM;
1380
ptr = tj->ptr();
1381
offset = tj->offset();
1382
}
1383
1384
// Array pointers need some flattening
1385
const TypeAryPtr *ta = tj->isa_aryptr();
1386
if (ta && ta->is_stable()) {
1387
// Erase stability property for alias analysis.
1388
tj = ta = ta->cast_to_stable(false);
1389
}
1390
if( ta && is_known_inst ) {
1391
if ( offset != Type::OffsetBot &&
1392
offset > arrayOopDesc::length_offset_in_bytes() ) {
1393
offset = Type::OffsetBot; // Flatten constant access into array body only
1394
tj = ta = TypeAryPtr::make(ptr, ta->ary(), ta->klass(), true, offset, ta->instance_id());
1395
}
1396
} else if( ta && _AliasLevel >= 2 ) {
1397
// For arrays indexed by constant indices, we flatten the alias
1398
// space to include all of the array body. Only the header, klass
1399
// and array length can be accessed un-aliased.
1400
if( offset != Type::OffsetBot ) {
1401
if( ta->const_oop() ) { // MethodData* or Method*
1402
offset = Type::OffsetBot; // Flatten constant access into array body
1403
tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1404
} else if( offset == arrayOopDesc::length_offset_in_bytes() ) {
1405
// range is OK as-is.
1406
tj = ta = TypeAryPtr::RANGE;
1407
} else if( offset == oopDesc::klass_offset_in_bytes() ) {
1408
tj = TypeInstPtr::KLASS; // all klass loads look alike
1409
ta = TypeAryPtr::RANGE; // generic ignored junk
1410
ptr = TypePtr::BotPTR;
1411
} else if( offset == oopDesc::mark_offset_in_bytes() ) {
1412
tj = TypeInstPtr::MARK;
1413
ta = TypeAryPtr::RANGE; // generic ignored junk
1414
ptr = TypePtr::BotPTR;
1415
} else { // Random constant offset into array body
1416
offset = Type::OffsetBot; // Flatten constant access into array body
1417
tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,offset);
1418
}
1419
}
1420
// Arrays of fixed size alias with arrays of unknown size.
1421
if (ta->size() != TypeInt::POS) {
1422
const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS);
1423
tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset);
1424
}
1425
// Arrays of known objects become arrays of unknown objects.
1426
if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) {
1427
const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size());
1428
tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1429
}
1430
if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) {
1431
const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size());
1432
tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1433
}
1434
// Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1435
// cannot be distinguished by bytecode alone.
1436
if (ta->elem() == TypeInt::BOOL) {
1437
const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size());
1438
ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE);
1439
tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset);
1440
}
1441
// During the 2nd round of IterGVN, NotNull castings are removed.
1442
// Make sure the Bottom and NotNull variants alias the same.
1443
// Also, make sure exact and non-exact variants alias the same.
1444
if (ptr == TypePtr::NotNull || ta->klass_is_exact() || ta->speculative() != NULL) {
1445
tj = ta = TypeAryPtr::make(TypePtr::BotPTR,ta->ary(),ta->klass(),false,offset);
1446
}
1447
}
1448
1449
// Oop pointers need some flattening
1450
const TypeInstPtr *to = tj->isa_instptr();
1451
if( to && _AliasLevel >= 2 && to != TypeOopPtr::BOTTOM ) {
1452
ciInstanceKlass *k = to->klass()->as_instance_klass();
1453
if( ptr == TypePtr::Constant ) {
1454
if (to->klass() != ciEnv::current()->Class_klass() ||
1455
offset < k->size_helper() * wordSize) {
1456
// No constant oop pointers (such as Strings); they alias with
1457
// unknown strings.
1458
assert(!is_known_inst, "not scalarizable allocation");
1459
tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1460
}
1461
} else if( is_known_inst ) {
1462
tj = to; // Keep NotNull and klass_is_exact for instance type
1463
} else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1464
// During the 2nd round of IterGVN, NotNull castings are removed.
1465
// Make sure the Bottom and NotNull variants alias the same.
1466
// Also, make sure exact and non-exact variants alias the same.
1467
tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1468
}
1469
if (to->speculative() != NULL) {
1470
tj = to = TypeInstPtr::make(to->ptr(),to->klass(),to->klass_is_exact(),to->const_oop(),to->offset(), to->instance_id());
1471
}
1472
// Canonicalize the holder of this field
1473
if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1474
// First handle header references such as a LoadKlassNode, even if the
1475
// object's klass is unloaded at compile time (4965979).
1476
if (!is_known_inst) { // Do it only for non-instance types
1477
tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset);
1478
}
1479
} else if (offset < 0 || offset >= k->size_helper() * wordSize) {
1480
// Static fields are in the space above the normal instance
1481
// fields in the java.lang.Class instance.
1482
if (to->klass() != ciEnv::current()->Class_klass()) {
1483
to = NULL;
1484
tj = TypeOopPtr::BOTTOM;
1485
offset = tj->offset();
1486
}
1487
} else {
1488
ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset);
1489
if (!k->equals(canonical_holder) || tj->offset() != offset) {
1490
if( is_known_inst ) {
1491
tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id());
1492
} else {
1493
tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset);
1494
}
1495
}
1496
}
1497
}
1498
1499
// Klass pointers to object array klasses need some flattening
1500
const TypeKlassPtr *tk = tj->isa_klassptr();
1501
if( tk ) {
1502
// If we are referencing a field within a Klass, we need
1503
// to assume the worst case of an Object. Both exact and
1504
// inexact types must flatten to the same alias class so
1505
// use NotNull as the PTR.
1506
if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1507
1508
tj = tk = TypeKlassPtr::make(TypePtr::NotNull,
1509
TypeKlassPtr::OBJECT->klass(),
1510
offset);
1511
}
1512
1513
ciKlass* klass = tk->klass();
1514
if( klass->is_obj_array_klass() ) {
1515
ciKlass* k = TypeAryPtr::OOPS->klass();
1516
if( !k || !k->is_loaded() ) // Only fails for some -Xcomp runs
1517
k = TypeInstPtr::BOTTOM->klass();
1518
tj = tk = TypeKlassPtr::make( TypePtr::NotNull, k, offset );
1519
}
1520
1521
// Check for precise loads from the primary supertype array and force them
1522
// to the supertype cache alias index. Check for generic array loads from
1523
// the primary supertype array and also force them to the supertype cache
1524
// alias index. Since the same load can reach both, we need to merge
1525
// these 2 disparate memories into the same alias class. Since the
1526
// primary supertype array is read-only, there's no chance of confusion
1527
// where we bypass an array load and an array store.
1528
int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1529
if (offset == Type::OffsetBot ||
1530
(offset >= primary_supers_offset &&
1531
offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1532
offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1533
offset = in_bytes(Klass::secondary_super_cache_offset());
1534
tj = tk = TypeKlassPtr::make( TypePtr::NotNull, tk->klass(), offset );
1535
}
1536
}
1537
1538
// Flatten all Raw pointers together.
1539
if (tj->base() == Type::RawPtr)
1540
tj = TypeRawPtr::BOTTOM;
1541
1542
if (tj->base() == Type::AnyPtr)
1543
tj = TypePtr::BOTTOM; // An error, which the caller must check for.
1544
1545
// Flatten all to bottom for now
1546
switch( _AliasLevel ) {
1547
case 0:
1548
tj = TypePtr::BOTTOM;
1549
break;
1550
case 1: // Flatten to: oop, static, field or array
1551
switch (tj->base()) {
1552
//case Type::AryPtr: tj = TypeAryPtr::RANGE; break;
1553
case Type::RawPtr: tj = TypeRawPtr::BOTTOM; break;
1554
case Type::AryPtr: // do not distinguish arrays at all
1555
case Type::InstPtr: tj = TypeInstPtr::BOTTOM; break;
1556
case Type::KlassPtr: tj = TypeKlassPtr::OBJECT; break;
1557
case Type::AnyPtr: tj = TypePtr::BOTTOM; break; // caller checks it
1558
default: ShouldNotReachHere();
1559
}
1560
break;
1561
case 2: // No collapsing at level 2; keep all splits
1562
case 3: // No collapsing at level 3; keep all splits
1563
break;
1564
default:
1565
Unimplemented();
1566
}
1567
1568
offset = tj->offset();
1569
assert( offset != Type::OffsetTop, "Offset has fallen from constant" );
1570
1571
assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) ||
1572
(offset == Type::OffsetBot && tj->base() == Type::AryPtr) ||
1573
(offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) ||
1574
(offset == Type::OffsetBot && tj == TypePtr::BOTTOM) ||
1575
(offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1576
(offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1577
(offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr) ,
1578
"For oops, klasses, raw offset must be constant; for arrays the offset is never known" );
1579
assert( tj->ptr() != TypePtr::TopPTR &&
1580
tj->ptr() != TypePtr::AnyNull &&
1581
tj->ptr() != TypePtr::Null, "No imprecise addresses" );
1582
// assert( tj->ptr() != TypePtr::Constant ||
1583
// tj->base() == Type::RawPtr ||
1584
// tj->base() == Type::KlassPtr, "No constant oop addresses" );
1585
1586
return tj;
1587
}
1588
1589
void Compile::AliasType::Init(int i, const TypePtr* at) {
1590
_index = i;
1591
_adr_type = at;
1592
_field = NULL;
1593
_element = NULL;
1594
_is_rewritable = true; // default
1595
const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL;
1596
if (atoop != NULL && atoop->is_known_instance()) {
1597
const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot);
1598
_general_index = Compile::current()->get_alias_index(gt);
1599
} else {
1600
_general_index = 0;
1601
}
1602
}
1603
1604
BasicType Compile::AliasType::basic_type() const {
1605
if (element() != NULL) {
1606
const Type* element = adr_type()->is_aryptr()->elem();
1607
return element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type();
1608
} if (field() != NULL) {
1609
return field()->layout_type();
1610
} else {
1611
return T_ILLEGAL; // unknown
1612
}
1613
}
1614
1615
//---------------------------------print_on------------------------------------
1616
#ifndef PRODUCT
1617
void Compile::AliasType::print_on(outputStream* st) {
1618
if (index() < 10)
1619
st->print("@ <%d> ", index());
1620
else st->print("@ <%d>", index());
1621
st->print(is_rewritable() ? " " : " RO");
1622
int offset = adr_type()->offset();
1623
if (offset == Type::OffsetBot)
1624
st->print(" +any");
1625
else st->print(" +%-3d", offset);
1626
st->print(" in ");
1627
adr_type()->dump_on(st);
1628
const TypeOopPtr* tjp = adr_type()->isa_oopptr();
1629
if (field() != NULL && tjp) {
1630
if (tjp->klass() != field()->holder() ||
1631
tjp->offset() != field()->offset_in_bytes()) {
1632
st->print(" != ");
1633
field()->print();
1634
st->print(" ***");
1635
}
1636
}
1637
}
1638
1639
void print_alias_types() {
1640
Compile* C = Compile::current();
1641
tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1);
1642
for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) {
1643
C->alias_type(idx)->print_on(tty);
1644
tty->cr();
1645
}
1646
}
1647
#endif
1648
1649
1650
//----------------------------probe_alias_cache--------------------------------
1651
Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) {
1652
intptr_t key = (intptr_t) adr_type;
1653
key ^= key >> logAliasCacheSize;
1654
return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1655
}
1656
1657
1658
//-----------------------------grow_alias_types--------------------------------
1659
void Compile::grow_alias_types() {
1660
const int old_ats = _max_alias_types; // how many before?
1661
const int new_ats = old_ats; // how many more?
1662
const int grow_ats = old_ats+new_ats; // how many now?
1663
_max_alias_types = grow_ats;
1664
_alias_types = REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats);
1665
AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1666
Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1667
for (int i = 0; i < new_ats; i++) _alias_types[old_ats+i] = &ats[i];
1668
}
1669
1670
1671
//--------------------------------find_alias_type------------------------------
1672
Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) {
1673
if (_AliasLevel == 0)
1674
return alias_type(AliasIdxBot);
1675
1676
AliasCacheEntry* ace = probe_alias_cache(adr_type);
1677
if (ace->_adr_type == adr_type) {
1678
return alias_type(ace->_index);
1679
}
1680
1681
// Handle special cases.
1682
if (adr_type == NULL) return alias_type(AliasIdxTop);
1683
if (adr_type == TypePtr::BOTTOM) return alias_type(AliasIdxBot);
1684
1685
// Do it the slow way.
1686
const TypePtr* flat = flatten_alias_type(adr_type);
1687
1688
#ifdef ASSERT
1689
{
1690
ResourceMark rm;
1691
assert(flat == flatten_alias_type(flat),
1692
err_msg("not idempotent: adr_type = %s; flat = %s => %s", Type::str(adr_type),
1693
Type::str(flat), Type::str(flatten_alias_type(flat))));
1694
assert(flat != TypePtr::BOTTOM,
1695
err_msg("cannot alias-analyze an untyped ptr: adr_type = %s", Type::str(adr_type)));
1696
if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1697
const TypeOopPtr* foop = flat->is_oopptr();
1698
// Scalarizable allocations have exact klass always.
1699
bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1700
const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr();
1701
assert(foop == flatten_alias_type(xoop),
1702
err_msg("exactness must not affect alias type: foop = %s; xoop = %s",
1703
Type::str(foop), Type::str(xoop)));
1704
}
1705
}
1706
#endif
1707
1708
int idx = AliasIdxTop;
1709
for (int i = 0; i < num_alias_types(); i++) {
1710
if (alias_type(i)->adr_type() == flat) {
1711
idx = i;
1712
break;
1713
}
1714
}
1715
1716
if (idx == AliasIdxTop) {
1717
if (no_create) return NULL;
1718
// Grow the array if necessary.
1719
if (_num_alias_types == _max_alias_types) grow_alias_types();
1720
// Add a new alias type.
1721
idx = _num_alias_types++;
1722
_alias_types[idx]->Init(idx, flat);
1723
if (flat == TypeInstPtr::KLASS) alias_type(idx)->set_rewritable(false);
1724
if (flat == TypeAryPtr::RANGE) alias_type(idx)->set_rewritable(false);
1725
if (flat->isa_instptr()) {
1726
if (flat->offset() == java_lang_Class::klass_offset_in_bytes()
1727
&& flat->is_instptr()->klass() == env()->Class_klass())
1728
alias_type(idx)->set_rewritable(false);
1729
}
1730
if (flat->isa_aryptr()) {
1731
#ifdef ASSERT
1732
const int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1733
// (T_BYTE has the weakest alignment and size restrictions...)
1734
assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1735
#endif
1736
if (flat->offset() == TypePtr::OffsetBot) {
1737
alias_type(idx)->set_element(flat->is_aryptr()->elem());
1738
}
1739
}
1740
if (flat->isa_klassptr()) {
1741
if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1742
alias_type(idx)->set_rewritable(false);
1743
if (flat->offset() == in_bytes(Klass::modifier_flags_offset()))
1744
alias_type(idx)->set_rewritable(false);
1745
if (flat->offset() == in_bytes(Klass::access_flags_offset()))
1746
alias_type(idx)->set_rewritable(false);
1747
if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1748
alias_type(idx)->set_rewritable(false);
1749
}
1750
// %%% (We would like to finalize JavaThread::threadObj_offset(),
1751
// but the base pointer type is not distinctive enough to identify
1752
// references into JavaThread.)
1753
1754
// Check for final fields.
1755
const TypeInstPtr* tinst = flat->isa_instptr();
1756
if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1757
ciField* field;
1758
if (tinst->const_oop() != NULL &&
1759
tinst->klass() == ciEnv::current()->Class_klass() &&
1760
tinst->offset() >= (tinst->klass()->as_instance_klass()->size_helper() * wordSize)) {
1761
// static field
1762
ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1763
field = k->get_field_by_offset(tinst->offset(), true);
1764
} else {
1765
ciInstanceKlass *k = tinst->klass()->as_instance_klass();
1766
field = k->get_field_by_offset(tinst->offset(), false);
1767
}
1768
assert(field == NULL ||
1769
original_field == NULL ||
1770
(field->holder() == original_field->holder() &&
1771
field->offset() == original_field->offset() &&
1772
field->is_static() == original_field->is_static()), "wrong field?");
1773
// Set field() and is_rewritable() attributes.
1774
if (field != NULL) alias_type(idx)->set_field(field);
1775
}
1776
}
1777
1778
// Fill the cache for next time.
1779
ace->_adr_type = adr_type;
1780
ace->_index = idx;
1781
assert(alias_type(adr_type) == alias_type(idx), "type must be installed");
1782
1783
// Might as well try to fill the cache for the flattened version, too.
1784
AliasCacheEntry* face = probe_alias_cache(flat);
1785
if (face->_adr_type == NULL) {
1786
face->_adr_type = flat;
1787
face->_index = idx;
1788
assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1789
}
1790
1791
return alias_type(idx);
1792
}
1793
1794
1795
Compile::AliasType* Compile::alias_type(ciField* field) {
1796
const TypeOopPtr* t;
1797
if (field->is_static())
1798
t = TypeInstPtr::make(field->holder()->java_mirror());
1799
else
1800
t = TypeOopPtr::make_from_klass_raw(field->holder());
1801
AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1802
assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1803
return atp;
1804
}
1805
1806
1807
//------------------------------have_alias_type--------------------------------
1808
bool Compile::have_alias_type(const TypePtr* adr_type) {
1809
AliasCacheEntry* ace = probe_alias_cache(adr_type);
1810
if (ace->_adr_type == adr_type) {
1811
return true;
1812
}
1813
1814
// Handle special cases.
1815
if (adr_type == NULL) return true;
1816
if (adr_type == TypePtr::BOTTOM) return true;
1817
1818
return find_alias_type(adr_type, true, NULL) != NULL;
1819
}
1820
1821
//-----------------------------must_alias--------------------------------------
1822
// True if all values of the given address type are in the given alias category.
1823
bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1824
if (alias_idx == AliasIdxBot) return true; // the universal category
1825
if (adr_type == NULL) return true; // NULL serves as TypePtr::TOP
1826
if (alias_idx == AliasIdxTop) return false; // the empty category
1827
if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1828
1829
// the only remaining possible overlap is identity
1830
int adr_idx = get_alias_index(adr_type);
1831
assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1832
assert(adr_idx == alias_idx ||
1833
(alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1834
&& adr_type != TypeOopPtr::BOTTOM),
1835
"should not be testing for overlap with an unsafe pointer");
1836
return adr_idx == alias_idx;
1837
}
1838
1839
//------------------------------can_alias--------------------------------------
1840
// True if any values of the given address type are in the given alias category.
1841
bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1842
if (alias_idx == AliasIdxTop) return false; // the empty category
1843
if (adr_type == NULL) return false; // NULL serves as TypePtr::TOP
1844
if (alias_idx == AliasIdxBot) return true; // the universal category
1845
if (adr_type->base() == Type::AnyPtr) return true; // TypePtr::BOTTOM or its twins
1846
1847
// the only remaining possible overlap is identity
1848
int adr_idx = get_alias_index(adr_type);
1849
assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1850
return adr_idx == alias_idx;
1851
}
1852
1853
1854
1855
//---------------------------pop_warm_call-------------------------------------
1856
WarmCallInfo* Compile::pop_warm_call() {
1857
WarmCallInfo* wci = _warm_calls;
1858
if (wci != NULL) _warm_calls = wci->remove_from(wci);
1859
return wci;
1860
}
1861
1862
//----------------------------Inline_Warm--------------------------------------
1863
int Compile::Inline_Warm() {
1864
// If there is room, try to inline some more warm call sites.
1865
// %%% Do a graph index compaction pass when we think we're out of space?
1866
if (!InlineWarmCalls) return 0;
1867
1868
int calls_made_hot = 0;
1869
int room_to_grow = NodeCountInliningCutoff - unique();
1870
int amount_to_grow = MIN2(room_to_grow, (int)NodeCountInliningStep);
1871
int amount_grown = 0;
1872
WarmCallInfo* call;
1873
while (amount_to_grow > 0 && (call = pop_warm_call()) != NULL) {
1874
int est_size = (int)call->size();
1875
if (est_size > (room_to_grow - amount_grown)) {
1876
// This one won't fit anyway. Get rid of it.
1877
call->make_cold();
1878
continue;
1879
}
1880
call->make_hot();
1881
calls_made_hot++;
1882
amount_grown += est_size;
1883
amount_to_grow -= est_size;
1884
}
1885
1886
if (calls_made_hot > 0) set_major_progress();
1887
return calls_made_hot;
1888
}
1889
1890
1891
//----------------------------Finish_Warm--------------------------------------
1892
void Compile::Finish_Warm() {
1893
if (!InlineWarmCalls) return;
1894
if (failing()) return;
1895
if (warm_calls() == NULL) return;
1896
1897
// Clean up loose ends, if we are out of space for inlining.
1898
WarmCallInfo* call;
1899
while ((call = pop_warm_call()) != NULL) {
1900
call->make_cold();
1901
}
1902
}
1903
1904
//---------------------cleanup_loop_predicates-----------------------
1905
// Remove the opaque nodes that protect the predicates so that all unused
1906
// checks and uncommon_traps will be eliminated from the ideal graph
1907
void Compile::cleanup_loop_predicates(PhaseIterGVN &igvn) {
1908
if (predicate_count()==0) return;
1909
for (int i = predicate_count(); i > 0; i--) {
1910
Node * n = predicate_opaque1_node(i-1);
1911
assert(n->Opcode() == Op_Opaque1, "must be");
1912
igvn.replace_node(n, n->in(1));
1913
}
1914
assert(predicate_count()==0, "should be clean!");
1915
}
1916
1917
void Compile::add_range_check_cast(Node* n) {
1918
assert(n->isa_CastII()->has_range_check(), "CastII should have range check dependency");
1919
assert(!_range_check_casts->contains(n), "duplicate entry in range check casts");
1920
_range_check_casts->append(n);
1921
}
1922
1923
// Remove all range check dependent CastIINodes.
1924
void Compile::remove_range_check_casts(PhaseIterGVN &igvn) {
1925
for (int i = range_check_cast_count(); i > 0; i--) {
1926
Node* cast = range_check_cast_node(i-1);
1927
assert(cast->isa_CastII()->has_range_check(), "CastII should have range check dependency");
1928
igvn.replace_node(cast, cast->in(1));
1929
}
1930
assert(range_check_cast_count() == 0, "should be empty");
1931
}
1932
1933
// StringOpts and late inlining of string methods
1934
void Compile::inline_string_calls(bool parse_time) {
1935
{
1936
// remove useless nodes to make the usage analysis simpler
1937
ResourceMark rm;
1938
PhaseRemoveUseless pru(initial_gvn(), for_igvn());
1939
}
1940
1941
{
1942
ResourceMark rm;
1943
print_method(PHASE_BEFORE_STRINGOPTS, 3);
1944
PhaseStringOpts pso(initial_gvn(), for_igvn());
1945
print_method(PHASE_AFTER_STRINGOPTS, 3);
1946
}
1947
1948
// now inline anything that we skipped the first time around
1949
if (!parse_time) {
1950
_late_inlines_pos = _late_inlines.length();
1951
}
1952
1953
while (_string_late_inlines.length() > 0) {
1954
CallGenerator* cg = _string_late_inlines.pop();
1955
cg->do_late_inline();
1956
if (failing()) return;
1957
}
1958
_string_late_inlines.trunc_to(0);
1959
}
1960
1961
// Late inlining of boxing methods
1962
void Compile::inline_boxing_calls(PhaseIterGVN& igvn) {
1963
if (_boxing_late_inlines.length() > 0) {
1964
assert(has_boxed_value(), "inconsistent");
1965
1966
PhaseGVN* gvn = initial_gvn();
1967
set_inlining_incrementally(true);
1968
1969
assert( igvn._worklist.size() == 0, "should be done with igvn" );
1970
for_igvn()->clear();
1971
gvn->replace_with(&igvn);
1972
1973
_late_inlines_pos = _late_inlines.length();
1974
1975
while (_boxing_late_inlines.length() > 0) {
1976
CallGenerator* cg = _boxing_late_inlines.pop();
1977
cg->do_late_inline();
1978
if (failing()) return;
1979
}
1980
_boxing_late_inlines.trunc_to(0);
1981
1982
{
1983
ResourceMark rm;
1984
PhaseRemoveUseless pru(gvn, for_igvn());
1985
}
1986
1987
igvn = PhaseIterGVN(gvn);
1988
igvn.optimize();
1989
1990
set_inlining_progress(false);
1991
set_inlining_incrementally(false);
1992
}
1993
}
1994
1995
void Compile::inline_incrementally_one(PhaseIterGVN& igvn) {
1996
assert(IncrementalInline, "incremental inlining should be on");
1997
PhaseGVN* gvn = initial_gvn();
1998
1999
set_inlining_progress(false);
2000
for_igvn()->clear();
2001
gvn->replace_with(&igvn);
2002
2003
int i = 0;
2004
2005
for (; i <_late_inlines.length() && !inlining_progress(); i++) {
2006
CallGenerator* cg = _late_inlines.at(i);
2007
_late_inlines_pos = i+1;
2008
cg->do_late_inline();
2009
if (failing()) return;
2010
}
2011
int j = 0;
2012
for (; i < _late_inlines.length(); i++, j++) {
2013
_late_inlines.at_put(j, _late_inlines.at(i));
2014
}
2015
_late_inlines.trunc_to(j);
2016
2017
{
2018
ResourceMark rm;
2019
PhaseRemoveUseless pru(gvn, for_igvn());
2020
}
2021
2022
igvn = PhaseIterGVN(gvn);
2023
}
2024
2025
// Perform incremental inlining until bound on number of live nodes is reached
2026
void Compile::inline_incrementally(PhaseIterGVN& igvn) {
2027
PhaseGVN* gvn = initial_gvn();
2028
2029
set_inlining_incrementally(true);
2030
set_inlining_progress(true);
2031
uint low_live_nodes = 0;
2032
2033
while(inlining_progress() && _late_inlines.length() > 0) {
2034
2035
if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2036
if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) {
2037
// PhaseIdealLoop is expensive so we only try it once we are
2038
// out of live nodes and we only try it again if the previous
2039
// helped got the number of nodes down significantly
2040
PhaseIdealLoop ideal_loop( igvn, false, true );
2041
if (failing()) return;
2042
low_live_nodes = live_nodes();
2043
_major_progress = true;
2044
}
2045
2046
if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2047
break;
2048
}
2049
}
2050
2051
inline_incrementally_one(igvn);
2052
2053
if (failing()) return;
2054
2055
igvn.optimize();
2056
2057
if (failing()) return;
2058
}
2059
2060
assert( igvn._worklist.size() == 0, "should be done with igvn" );
2061
2062
if (_string_late_inlines.length() > 0) {
2063
assert(has_stringbuilder(), "inconsistent");
2064
for_igvn()->clear();
2065
initial_gvn()->replace_with(&igvn);
2066
2067
inline_string_calls(false);
2068
2069
if (failing()) return;
2070
2071
{
2072
ResourceMark rm;
2073
PhaseRemoveUseless pru(initial_gvn(), for_igvn());
2074
}
2075
2076
igvn = PhaseIterGVN(gvn);
2077
2078
igvn.optimize();
2079
}
2080
2081
set_inlining_incrementally(false);
2082
}
2083
2084
2085
// Remove edges from "root" to each SafePoint at a backward branch.
2086
// They were inserted during parsing (see add_safepoint()) to make
2087
// infinite loops without calls or exceptions visible to root, i.e.,
2088
// useful.
2089
void Compile::remove_root_to_sfpts_edges() {
2090
Node *r = root();
2091
if (r != NULL) {
2092
for (uint i = r->req(); i < r->len(); ++i) {
2093
Node *n = r->in(i);
2094
if (n != NULL && n->is_SafePoint()) {
2095
r->rm_prec(i);
2096
--i;
2097
}
2098
}
2099
}
2100
}
2101
2102
//------------------------------Optimize---------------------------------------
2103
// Given a graph, optimize it.
2104
void Compile::Optimize() {
2105
TracePhase t1("optimizer", &_t_optimizer, true);
2106
2107
#ifndef PRODUCT
2108
if (env()->break_at_compile()) {
2109
BREAKPOINT;
2110
}
2111
2112
#endif
2113
2114
ResourceMark rm;
2115
int loop_opts_cnt;
2116
2117
NOT_PRODUCT( verify_graph_edges(); )
2118
2119
print_method(PHASE_AFTER_PARSING);
2120
2121
{
2122
// Iterative Global Value Numbering, including ideal transforms
2123
// Initialize IterGVN with types and values from parse-time GVN
2124
PhaseIterGVN igvn(initial_gvn());
2125
{
2126
NOT_PRODUCT( TracePhase t2("iterGVN", &_t_iterGVN, TimeCompiler); )
2127
igvn.optimize();
2128
}
2129
2130
print_method(PHASE_ITER_GVN1, 2);
2131
2132
if (failing()) return;
2133
2134
{
2135
NOT_PRODUCT( TracePhase t2("incrementalInline", &_t_incrInline, TimeCompiler); )
2136
inline_incrementally(igvn);
2137
}
2138
2139
print_method(PHASE_INCREMENTAL_INLINE, 2);
2140
2141
if (failing()) return;
2142
2143
if (eliminate_boxing()) {
2144
NOT_PRODUCT( TracePhase t2("incrementalInline", &_t_incrInline, TimeCompiler); )
2145
// Inline valueOf() methods now.
2146
inline_boxing_calls(igvn);
2147
2148
if (AlwaysIncrementalInline) {
2149
inline_incrementally(igvn);
2150
}
2151
2152
print_method(PHASE_INCREMENTAL_BOXING_INLINE, 2);
2153
2154
if (failing()) return;
2155
}
2156
2157
// Now that all inlining is over, cut edge from root to loop
2158
// safepoints
2159
remove_root_to_sfpts_edges();
2160
2161
// Remove the speculative part of types and clean up the graph from
2162
// the extra CastPP nodes whose only purpose is to carry them. Do
2163
// that early so that optimizations are not disrupted by the extra
2164
// CastPP nodes.
2165
remove_speculative_types(igvn);
2166
2167
// No more new expensive nodes will be added to the list from here
2168
// so keep only the actual candidates for optimizations.
2169
cleanup_expensive_nodes(igvn);
2170
2171
if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2172
NOT_PRODUCT(Compile::TracePhase t2("", &_t_renumberLive, TimeCompiler);)
2173
initial_gvn()->replace_with(&igvn);
2174
for_igvn()->clear();
2175
Unique_Node_List new_worklist(C->comp_arena());
2176
{
2177
ResourceMark rm;
2178
PhaseRenumberLive prl = PhaseRenumberLive(initial_gvn(), for_igvn(), &new_worklist);
2179
}
2180
set_for_igvn(&new_worklist);
2181
igvn = PhaseIterGVN(initial_gvn());
2182
igvn.optimize();
2183
}
2184
2185
// Perform escape analysis
2186
if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) {
2187
if (has_loops()) {
2188
// Cleanup graph (remove dead nodes).
2189
TracePhase t2("idealLoop", &_t_idealLoop, true);
2190
PhaseIdealLoop ideal_loop( igvn, false, true );
2191
if (major_progress()) print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2192
if (failing()) return;
2193
}
2194
ConnectionGraph::do_analysis(this, &igvn);
2195
2196
if (failing()) return;
2197
2198
// Optimize out fields loads from scalar replaceable allocations.
2199
igvn.optimize();
2200
print_method(PHASE_ITER_GVN_AFTER_EA, 2);
2201
2202
if (failing()) return;
2203
2204
if (congraph() != NULL && macro_count() > 0) {
2205
NOT_PRODUCT( TracePhase t2("macroEliminate", &_t_macroEliminate, TimeCompiler); )
2206
PhaseMacroExpand mexp(igvn);
2207
mexp.eliminate_macro_nodes();
2208
igvn.set_delay_transform(false);
2209
2210
igvn.optimize();
2211
print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2212
2213
if (failing()) return;
2214
}
2215
}
2216
2217
// Loop transforms on the ideal graph. Range Check Elimination,
2218
// peeling, unrolling, etc.
2219
2220
// Set loop opts counter
2221
loop_opts_cnt = num_loop_opts();
2222
if((loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
2223
{
2224
TracePhase t2("idealLoop", &_t_idealLoop, true);
2225
PhaseIdealLoop ideal_loop( igvn, true );
2226
loop_opts_cnt--;
2227
if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
2228
if (failing()) return;
2229
}
2230
// Loop opts pass if partial peeling occurred in previous pass
2231
if(PartialPeelLoop && major_progress() && (loop_opts_cnt > 0)) {
2232
TracePhase t3("idealLoop", &_t_idealLoop, true);
2233
PhaseIdealLoop ideal_loop( igvn, false );
2234
loop_opts_cnt--;
2235
if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
2236
if (failing()) return;
2237
}
2238
// Loop opts pass for loop-unrolling before CCP
2239
if(major_progress() && (loop_opts_cnt > 0)) {
2240
TracePhase t4("idealLoop", &_t_idealLoop, true);
2241
PhaseIdealLoop ideal_loop( igvn, false );
2242
loop_opts_cnt--;
2243
if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2);
2244
}
2245
if (!failing()) {
2246
// Verify that last round of loop opts produced a valid graph
2247
NOT_PRODUCT( TracePhase t2("idealLoopVerify", &_t_idealLoopVerify, TimeCompiler); )
2248
PhaseIdealLoop::verify(igvn);
2249
}
2250
}
2251
if (failing()) return;
2252
2253
// Conditional Constant Propagation;
2254
PhaseCCP ccp( &igvn );
2255
assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
2256
{
2257
TracePhase t2("ccp", &_t_ccp, true);
2258
ccp.do_transform();
2259
}
2260
print_method(PHASE_CPP1, 2);
2261
2262
assert( true, "Break here to ccp.dump_old2new_map()");
2263
2264
// Iterative Global Value Numbering, including ideal transforms
2265
{
2266
NOT_PRODUCT( TracePhase t2("iterGVN2", &_t_iterGVN2, TimeCompiler); )
2267
igvn = ccp;
2268
igvn.optimize();
2269
}
2270
2271
print_method(PHASE_ITER_GVN2, 2);
2272
2273
if (failing()) return;
2274
2275
// Loop transforms on the ideal graph. Range Check Elimination,
2276
// peeling, unrolling, etc.
2277
if(loop_opts_cnt > 0) {
2278
debug_only( int cnt = 0; );
2279
while(major_progress() && (loop_opts_cnt > 0)) {
2280
TracePhase t2("idealLoop", &_t_idealLoop, true);
2281
assert( cnt++ < 40, "infinite cycle in loop optimization" );
2282
PhaseIdealLoop ideal_loop( igvn, true);
2283
loop_opts_cnt--;
2284
if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2285
if (failing()) return;
2286
}
2287
}
2288
2289
{
2290
// Verify that all previous optimizations produced a valid graph
2291
// at least to this point, even if no loop optimizations were done.
2292
NOT_PRODUCT( TracePhase t2("idealLoopVerify", &_t_idealLoopVerify, TimeCompiler); )
2293
PhaseIdealLoop::verify(igvn);
2294
}
2295
2296
if (range_check_cast_count() > 0) {
2297
// No more loop optimizations. Remove all range check dependent CastIINodes.
2298
C->remove_range_check_casts(igvn);
2299
igvn.optimize();
2300
}
2301
2302
{
2303
NOT_PRODUCT( TracePhase t2("macroExpand", &_t_macroExpand, TimeCompiler); )
2304
PhaseMacroExpand mex(igvn);
2305
if (mex.expand_macro_nodes()) {
2306
assert(failing(), "must bail out w/ explicit message");
2307
return;
2308
}
2309
}
2310
2311
} // (End scope of igvn; run destructor if necessary for asserts.)
2312
2313
dump_inlining();
2314
// A method with only infinite loops has no edges entering loops from root
2315
{
2316
NOT_PRODUCT( TracePhase t2("graphReshape", &_t_graphReshaping, TimeCompiler); )
2317
if (final_graph_reshaping()) {
2318
assert(failing(), "must bail out w/ explicit message");
2319
return;
2320
}
2321
}
2322
2323
print_method(PHASE_OPTIMIZE_FINISHED, 2);
2324
}
2325
2326
2327
//------------------------------Code_Gen---------------------------------------
2328
// Given a graph, generate code for it
2329
void Compile::Code_Gen() {
2330
if (failing()) {
2331
return;
2332
}
2333
2334
// Perform instruction selection. You might think we could reclaim Matcher
2335
// memory PDQ, but actually the Matcher is used in generating spill code.
2336
// Internals of the Matcher (including some VectorSets) must remain live
2337
// for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
2338
// set a bit in reclaimed memory.
2339
2340
// In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2341
// nodes. Mapping is only valid at the root of each matched subtree.
2342
NOT_PRODUCT( verify_graph_edges(); )
2343
2344
Matcher matcher;
2345
_matcher = &matcher;
2346
{
2347
TracePhase t2("matcher", &_t_matcher, true);
2348
matcher.match();
2349
}
2350
// In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2351
// nodes. Mapping is only valid at the root of each matched subtree.
2352
NOT_PRODUCT( verify_graph_edges(); )
2353
2354
// If you have too many nodes, or if matching has failed, bail out
2355
check_node_count(0, "out of nodes matching instructions");
2356
if (failing()) {
2357
return;
2358
}
2359
2360
// Build a proper-looking CFG
2361
PhaseCFG cfg(node_arena(), root(), matcher);
2362
_cfg = &cfg;
2363
{
2364
NOT_PRODUCT( TracePhase t2("scheduler", &_t_scheduler, TimeCompiler); )
2365
bool success = cfg.do_global_code_motion();
2366
if (!success) {
2367
return;
2368
}
2369
2370
print_method(PHASE_GLOBAL_CODE_MOTION, 2);
2371
NOT_PRODUCT( verify_graph_edges(); )
2372
debug_only( cfg.verify(); )
2373
}
2374
2375
PhaseChaitin regalloc(unique(), cfg, matcher);
2376
_regalloc = &regalloc;
2377
{
2378
TracePhase t2("regalloc", &_t_registerAllocation, true);
2379
// Perform register allocation. After Chaitin, use-def chains are
2380
// no longer accurate (at spill code) and so must be ignored.
2381
// Node->LRG->reg mappings are still accurate.
2382
_regalloc->Register_Allocate();
2383
2384
// Bail out if the allocator builds too many nodes
2385
if (failing()) {
2386
return;
2387
}
2388
}
2389
2390
// Prior to register allocation we kept empty basic blocks in case the
2391
// the allocator needed a place to spill. After register allocation we
2392
// are not adding any new instructions. If any basic block is empty, we
2393
// can now safely remove it.
2394
{
2395
NOT_PRODUCT( TracePhase t2("blockOrdering", &_t_blockOrdering, TimeCompiler); )
2396
cfg.remove_empty_blocks();
2397
if (do_freq_based_layout()) {
2398
PhaseBlockLayout layout(cfg);
2399
} else {
2400
cfg.set_loop_alignment();
2401
}
2402
cfg.fixup_flow();
2403
}
2404
2405
// Apply peephole optimizations
2406
if( OptoPeephole ) {
2407
NOT_PRODUCT( TracePhase t2("peephole", &_t_peephole, TimeCompiler); )
2408
PhasePeephole peep( _regalloc, cfg);
2409
peep.do_transform();
2410
}
2411
2412
// Do late expand if CPU requires this.
2413
if (Matcher::require_postalloc_expand) {
2414
NOT_PRODUCT(TracePhase t2c("postalloc_expand", &_t_postalloc_expand, true));
2415
cfg.postalloc_expand(_regalloc);
2416
}
2417
2418
// Convert Nodes to instruction bits in a buffer
2419
{
2420
// %%%% workspace merge brought two timers together for one job
2421
TracePhase t2a("output", &_t_output, true);
2422
NOT_PRODUCT( TraceTime t2b(NULL, &_t_codeGeneration, TimeCompiler, false); )
2423
Output();
2424
}
2425
2426
print_method(PHASE_FINAL_CODE);
2427
2428
// He's dead, Jim.
2429
_cfg = (PhaseCFG*)((intptr_t)0xdeadbeef);
2430
_regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
2431
}
2432
2433
2434
//------------------------------dump_asm---------------------------------------
2435
// Dump formatted assembly
2436
#ifndef PRODUCT
2437
void Compile::dump_asm(int *pcs, uint pc_limit) {
2438
bool cut_short = false;
2439
tty->print_cr("#");
2440
tty->print("# "); _tf->dump(); tty->cr();
2441
tty->print_cr("#");
2442
2443
// For all blocks
2444
int pc = 0x0; // Program counter
2445
char starts_bundle = ' ';
2446
_regalloc->dump_frame();
2447
2448
Node *n = NULL;
2449
for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
2450
if (VMThread::should_terminate()) {
2451
cut_short = true;
2452
break;
2453
}
2454
Block* block = _cfg->get_block(i);
2455
if (block->is_connector() && !Verbose) {
2456
continue;
2457
}
2458
n = block->head();
2459
if (pcs && n->_idx < pc_limit) {
2460
tty->print("%3.3x ", pcs[n->_idx]);
2461
} else {
2462
tty->print(" ");
2463
}
2464
block->dump_head(_cfg);
2465
if (block->is_connector()) {
2466
tty->print_cr(" # Empty connector block");
2467
} else if (block->num_preds() == 2 && block->pred(1)->is_CatchProj() && block->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
2468
tty->print_cr(" # Block is sole successor of call");
2469
}
2470
2471
// For all instructions
2472
Node *delay = NULL;
2473
for (uint j = 0; j < block->number_of_nodes(); j++) {
2474
if (VMThread::should_terminate()) {
2475
cut_short = true;
2476
break;
2477
}
2478
n = block->get_node(j);
2479
if (valid_bundle_info(n)) {
2480
Bundle* bundle = node_bundling(n);
2481
if (bundle->used_in_unconditional_delay()) {
2482
delay = n;
2483
continue;
2484
}
2485
if (bundle->starts_bundle()) {
2486
starts_bundle = '+';
2487
}
2488
}
2489
2490
if (WizardMode) {
2491
n->dump();
2492
}
2493
2494
if( !n->is_Region() && // Dont print in the Assembly
2495
!n->is_Phi() && // a few noisely useless nodes
2496
!n->is_Proj() &&
2497
!n->is_MachTemp() &&
2498
!n->is_SafePointScalarObject() &&
2499
!n->is_Catch() && // Would be nice to print exception table targets
2500
!n->is_MergeMem() && // Not very interesting
2501
!n->is_top() && // Debug info table constants
2502
!(n->is_Con() && !n->is_Mach())// Debug info table constants
2503
) {
2504
if (pcs && n->_idx < pc_limit)
2505
tty->print("%3.3x", pcs[n->_idx]);
2506
else
2507
tty->print(" ");
2508
tty->print(" %c ", starts_bundle);
2509
starts_bundle = ' ';
2510
tty->print("\t");
2511
n->format(_regalloc, tty);
2512
tty->cr();
2513
}
2514
2515
// If we have an instruction with a delay slot, and have seen a delay,
2516
// then back up and print it
2517
if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
2518
assert(delay != NULL, "no unconditional delay instruction");
2519
if (WizardMode) delay->dump();
2520
2521
if (node_bundling(delay)->starts_bundle())
2522
starts_bundle = '+';
2523
if (pcs && n->_idx < pc_limit)
2524
tty->print("%3.3x", pcs[n->_idx]);
2525
else
2526
tty->print(" ");
2527
tty->print(" %c ", starts_bundle);
2528
starts_bundle = ' ';
2529
tty->print("\t");
2530
delay->format(_regalloc, tty);
2531
tty->cr();
2532
delay = NULL;
2533
}
2534
2535
// Dump the exception table as well
2536
if( n->is_Catch() && (Verbose || WizardMode) ) {
2537
// Print the exception table for this offset
2538
_handler_table.print_subtable_for(pc);
2539
}
2540
}
2541
2542
if (pcs && n->_idx < pc_limit)
2543
tty->print_cr("%3.3x", pcs[n->_idx]);
2544
else
2545
tty->cr();
2546
2547
assert(cut_short || delay == NULL, "no unconditional delay branch");
2548
2549
} // End of per-block dump
2550
tty->cr();
2551
2552
if (cut_short) tty->print_cr("*** disassembly is cut short ***");
2553
}
2554
#endif
2555
2556
//------------------------------Final_Reshape_Counts---------------------------
2557
// This class defines counters to help identify when a method
2558
// may/must be executed using hardware with only 24-bit precision.
2559
struct Final_Reshape_Counts : public StackObj {
2560
int _call_count; // count non-inlined 'common' calls
2561
int _float_count; // count float ops requiring 24-bit precision
2562
int _double_count; // count double ops requiring more precision
2563
int _java_call_count; // count non-inlined 'java' calls
2564
int _inner_loop_count; // count loops which need alignment
2565
VectorSet _visited; // Visitation flags
2566
Node_List _tests; // Set of IfNodes & PCTableNodes
2567
2568
Final_Reshape_Counts() :
2569
_call_count(0), _float_count(0), _double_count(0),
2570
_java_call_count(0), _inner_loop_count(0),
2571
_visited( Thread::current()->resource_area() ) { }
2572
2573
void inc_call_count () { _call_count ++; }
2574
void inc_float_count () { _float_count ++; }
2575
void inc_double_count() { _double_count++; }
2576
void inc_java_call_count() { _java_call_count++; }
2577
void inc_inner_loop_count() { _inner_loop_count++; }
2578
2579
int get_call_count () const { return _call_count ; }
2580
int get_float_count () const { return _float_count ; }
2581
int get_double_count() const { return _double_count; }
2582
int get_java_call_count() const { return _java_call_count; }
2583
int get_inner_loop_count() const { return _inner_loop_count; }
2584
};
2585
2586
#ifdef ASSERT
2587
static bool oop_offset_is_sane(const TypeInstPtr* tp) {
2588
ciInstanceKlass *k = tp->klass()->as_instance_klass();
2589
// Make sure the offset goes inside the instance layout.
2590
return k->contains_field_offset(tp->offset());
2591
// Note that OffsetBot and OffsetTop are very negative.
2592
}
2593
#endif
2594
2595
// Eliminate trivially redundant StoreCMs and accumulate their
2596
// precedence edges.
2597
void Compile::eliminate_redundant_card_marks(Node* n) {
2598
assert(n->Opcode() == Op_StoreCM, "expected StoreCM");
2599
if (n->in(MemNode::Address)->outcnt() > 1) {
2600
// There are multiple users of the same address so it might be
2601
// possible to eliminate some of the StoreCMs
2602
Node* mem = n->in(MemNode::Memory);
2603
Node* adr = n->in(MemNode::Address);
2604
Node* val = n->in(MemNode::ValueIn);
2605
Node* prev = n;
2606
bool done = false;
2607
// Walk the chain of StoreCMs eliminating ones that match. As
2608
// long as it's a chain of single users then the optimization is
2609
// safe. Eliminating partially redundant StoreCMs would require
2610
// cloning copies down the other paths.
2611
while (mem->Opcode() == Op_StoreCM && mem->outcnt() == 1 && !done) {
2612
if (adr == mem->in(MemNode::Address) &&
2613
val == mem->in(MemNode::ValueIn)) {
2614
// redundant StoreCM
2615
if (mem->req() > MemNode::OopStore) {
2616
// Hasn't been processed by this code yet.
2617
n->add_prec(mem->in(MemNode::OopStore));
2618
} else {
2619
// Already converted to precedence edge
2620
for (uint i = mem->req(); i < mem->len(); i++) {
2621
// Accumulate any precedence edges
2622
if (mem->in(i) != NULL) {
2623
n->add_prec(mem->in(i));
2624
}
2625
}
2626
// Everything above this point has been processed.
2627
done = true;
2628
}
2629
// Eliminate the previous StoreCM
2630
prev->set_req(MemNode::Memory, mem->in(MemNode::Memory));
2631
assert(mem->outcnt() == 0, "should be dead");
2632
mem->disconnect_inputs(NULL, this);
2633
} else {
2634
prev = mem;
2635
}
2636
mem = prev->in(MemNode::Memory);
2637
}
2638
}
2639
}
2640
2641
//------------------------------final_graph_reshaping_impl----------------------
2642
// Implement items 1-5 from final_graph_reshaping below.
2643
void Compile::final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &frc) {
2644
2645
if ( n->outcnt() == 0 ) return; // dead node
2646
uint nop = n->Opcode();
2647
2648
// Check for 2-input instruction with "last use" on right input.
2649
// Swap to left input. Implements item (2).
2650
if( n->req() == 3 && // two-input instruction
2651
n->in(1)->outcnt() > 1 && // left use is NOT a last use
2652
(!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
2653
n->in(2)->outcnt() == 1 &&// right use IS a last use
2654
!n->in(2)->is_Con() ) { // right use is not a constant
2655
// Check for commutative opcode
2656
switch( nop ) {
2657
case Op_AddI: case Op_AddF: case Op_AddD: case Op_AddL:
2658
case Op_MaxI: case Op_MinI:
2659
case Op_MulI: case Op_MulF: case Op_MulD: case Op_MulL:
2660
case Op_AndL: case Op_XorL: case Op_OrL:
2661
case Op_AndI: case Op_XorI: case Op_OrI: {
2662
// Move "last use" input to left by swapping inputs
2663
n->swap_edges(1, 2);
2664
break;
2665
}
2666
default:
2667
break;
2668
}
2669
}
2670
2671
#ifdef ASSERT
2672
if( n->is_Mem() ) {
2673
int alias_idx = get_alias_index(n->as_Mem()->adr_type());
2674
assert( n->in(0) != NULL || alias_idx != Compile::AliasIdxRaw ||
2675
// oop will be recorded in oop map if load crosses safepoint
2676
n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
2677
LoadNode::is_immutable_value(n->in(MemNode::Address))),
2678
"raw memory operations should have control edge");
2679
}
2680
if (n->is_MemBar()) {
2681
MemBarNode* mb = n->as_MemBar();
2682
if (mb->trailing_store() || mb->trailing_load_store()) {
2683
assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair");
2684
Node* mem = mb->in(MemBarNode::Precedent);
2685
assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) ||
2686
(mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op");
2687
} else if (mb->leading()) {
2688
assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair");
2689
}
2690
}
2691
#endif
2692
// Count FPU ops and common calls, implements item (3)
2693
switch( nop ) {
2694
// Count all float operations that may use FPU
2695
case Op_AddF:
2696
case Op_SubF:
2697
case Op_MulF:
2698
case Op_DivF:
2699
case Op_NegF:
2700
case Op_ModF:
2701
case Op_ConvI2F:
2702
case Op_ConF:
2703
case Op_CmpF:
2704
case Op_CmpF3:
2705
// case Op_ConvL2F: // longs are split into 32-bit halves
2706
frc.inc_float_count();
2707
break;
2708
2709
case Op_ConvF2D:
2710
case Op_ConvD2F:
2711
frc.inc_float_count();
2712
frc.inc_double_count();
2713
break;
2714
2715
// Count all double operations that may use FPU
2716
case Op_AddD:
2717
case Op_SubD:
2718
case Op_MulD:
2719
case Op_DivD:
2720
case Op_NegD:
2721
case Op_ModD:
2722
case Op_ConvI2D:
2723
case Op_ConvD2I:
2724
// case Op_ConvL2D: // handled by leaf call
2725
// case Op_ConvD2L: // handled by leaf call
2726
case Op_ConD:
2727
case Op_CmpD:
2728
case Op_CmpD3:
2729
frc.inc_double_count();
2730
break;
2731
case Op_Opaque1: // Remove Opaque Nodes before matching
2732
case Op_Opaque2: // Remove Opaque Nodes before matching
2733
case Op_Opaque3:
2734
n->subsume_by(n->in(1), this);
2735
break;
2736
case Op_CallStaticJava:
2737
case Op_CallJava:
2738
case Op_CallDynamicJava:
2739
frc.inc_java_call_count(); // Count java call site;
2740
case Op_CallRuntime:
2741
case Op_CallLeaf:
2742
case Op_CallLeafNoFP: {
2743
assert( n->is_Call(), "" );
2744
CallNode *call = n->as_Call();
2745
// Count call sites where the FP mode bit would have to be flipped.
2746
// Do not count uncommon runtime calls:
2747
// uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
2748
// _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
2749
if( !call->is_CallStaticJava() || !call->as_CallStaticJava()->_name ) {
2750
frc.inc_call_count(); // Count the call site
2751
} else { // See if uncommon argument is shared
2752
Node *n = call->in(TypeFunc::Parms);
2753
int nop = n->Opcode();
2754
// Clone shared simple arguments to uncommon calls, item (1).
2755
if( n->outcnt() > 1 &&
2756
!n->is_Proj() &&
2757
nop != Op_CreateEx &&
2758
nop != Op_CheckCastPP &&
2759
nop != Op_DecodeN &&
2760
nop != Op_DecodeNKlass &&
2761
!n->is_Mem() ) {
2762
Node *x = n->clone();
2763
call->set_req( TypeFunc::Parms, x );
2764
}
2765
}
2766
break;
2767
}
2768
2769
case Op_StoreD:
2770
case Op_LoadD:
2771
case Op_LoadD_unaligned:
2772
frc.inc_double_count();
2773
goto handle_mem;
2774
case Op_StoreF:
2775
case Op_LoadF:
2776
frc.inc_float_count();
2777
goto handle_mem;
2778
2779
case Op_StoreCM:
2780
{
2781
// Convert OopStore dependence into precedence edge
2782
Node* prec = n->in(MemNode::OopStore);
2783
n->del_req(MemNode::OopStore);
2784
n->add_prec(prec);
2785
eliminate_redundant_card_marks(n);
2786
}
2787
2788
// fall through
2789
2790
case Op_StoreB:
2791
case Op_StoreC:
2792
case Op_StorePConditional:
2793
case Op_StoreI:
2794
case Op_StoreL:
2795
case Op_StoreIConditional:
2796
case Op_StoreLConditional:
2797
case Op_CompareAndSwapI:
2798
case Op_CompareAndSwapL:
2799
case Op_CompareAndSwapP:
2800
case Op_CompareAndSwapN:
2801
case Op_GetAndAddI:
2802
case Op_GetAndAddL:
2803
case Op_GetAndSetI:
2804
case Op_GetAndSetL:
2805
case Op_GetAndSetP:
2806
case Op_GetAndSetN:
2807
case Op_StoreP:
2808
case Op_StoreN:
2809
case Op_StoreNKlass:
2810
case Op_LoadB:
2811
case Op_LoadUB:
2812
case Op_LoadUS:
2813
case Op_LoadI:
2814
case Op_LoadKlass:
2815
case Op_LoadNKlass:
2816
case Op_LoadL:
2817
case Op_LoadL_unaligned:
2818
case Op_LoadPLocked:
2819
case Op_LoadP:
2820
case Op_LoadN:
2821
case Op_LoadRange:
2822
case Op_LoadS: {
2823
handle_mem:
2824
#ifdef ASSERT
2825
if( VerifyOptoOopOffsets ) {
2826
assert( n->is_Mem(), "" );
2827
MemNode *mem = (MemNode*)n;
2828
// Check to see if address types have grounded out somehow.
2829
const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
2830
assert( !tp || oop_offset_is_sane(tp), "" );
2831
}
2832
#endif
2833
break;
2834
}
2835
2836
case Op_AddP: { // Assert sane base pointers
2837
Node *addp = n->in(AddPNode::Address);
2838
assert( !addp->is_AddP() ||
2839
addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
2840
addp->in(AddPNode::Base) == n->in(AddPNode::Base),
2841
"Base pointers must match" );
2842
#ifdef _LP64
2843
if ((UseCompressedOops || UseCompressedClassPointers) &&
2844
addp->Opcode() == Op_ConP &&
2845
addp == n->in(AddPNode::Base) &&
2846
n->in(AddPNode::Offset)->is_Con()) {
2847
// Use addressing with narrow klass to load with offset on x86.
2848
// On sparc loading 32-bits constant and decoding it have less
2849
// instructions (4) then load 64-bits constant (7).
2850
// Do this transformation here since IGVN will convert ConN back to ConP.
2851
const Type* t = addp->bottom_type();
2852
if (t->isa_oopptr() || t->isa_klassptr()) {
2853
Node* nn = NULL;
2854
2855
int op = t->isa_oopptr() ? Op_ConN : Op_ConNKlass;
2856
2857
// Look for existing ConN node of the same exact type.
2858
Node* r = root();
2859
uint cnt = r->outcnt();
2860
for (uint i = 0; i < cnt; i++) {
2861
Node* m = r->raw_out(i);
2862
if (m!= NULL && m->Opcode() == op &&
2863
m->bottom_type()->make_ptr() == t) {
2864
nn = m;
2865
break;
2866
}
2867
}
2868
if (nn != NULL) {
2869
// Decode a narrow oop to match address
2870
// [R12 + narrow_oop_reg<<3 + offset]
2871
if (t->isa_oopptr()) {
2872
nn = new (this) DecodeNNode(nn, t);
2873
} else {
2874
nn = new (this) DecodeNKlassNode(nn, t);
2875
}
2876
n->set_req(AddPNode::Base, nn);
2877
n->set_req(AddPNode::Address, nn);
2878
if (addp->outcnt() == 0) {
2879
addp->disconnect_inputs(NULL, this);
2880
}
2881
}
2882
}
2883
}
2884
#endif
2885
break;
2886
}
2887
2888
#ifdef _LP64
2889
case Op_CastPP:
2890
if (n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
2891
Node* in1 = n->in(1);
2892
const Type* t = n->bottom_type();
2893
Node* new_in1 = in1->clone();
2894
new_in1->as_DecodeN()->set_type(t);
2895
2896
if (!Matcher::narrow_oop_use_complex_address()) {
2897
//
2898
// x86, ARM and friends can handle 2 adds in addressing mode
2899
// and Matcher can fold a DecodeN node into address by using
2900
// a narrow oop directly and do implicit NULL check in address:
2901
//
2902
// [R12 + narrow_oop_reg<<3 + offset]
2903
// NullCheck narrow_oop_reg
2904
//
2905
// On other platforms (Sparc) we have to keep new DecodeN node and
2906
// use it to do implicit NULL check in address:
2907
//
2908
// decode_not_null narrow_oop_reg, base_reg
2909
// [base_reg + offset]
2910
// NullCheck base_reg
2911
//
2912
// Pin the new DecodeN node to non-null path on these platform (Sparc)
2913
// to keep the information to which NULL check the new DecodeN node
2914
// corresponds to use it as value in implicit_null_check().
2915
//
2916
new_in1->set_req(0, n->in(0));
2917
}
2918
2919
n->subsume_by(new_in1, this);
2920
if (in1->outcnt() == 0) {
2921
in1->disconnect_inputs(NULL, this);
2922
}
2923
}
2924
break;
2925
2926
case Op_CmpP:
2927
// Do this transformation here to preserve CmpPNode::sub() and
2928
// other TypePtr related Ideal optimizations (for example, ptr nullness).
2929
if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
2930
Node* in1 = n->in(1);
2931
Node* in2 = n->in(2);
2932
if (!in1->is_DecodeNarrowPtr()) {
2933
in2 = in1;
2934
in1 = n->in(2);
2935
}
2936
assert(in1->is_DecodeNarrowPtr(), "sanity");
2937
2938
Node* new_in2 = NULL;
2939
if (in2->is_DecodeNarrowPtr()) {
2940
assert(in2->Opcode() == in1->Opcode(), "must be same node type");
2941
new_in2 = in2->in(1);
2942
} else if (in2->Opcode() == Op_ConP) {
2943
const Type* t = in2->bottom_type();
2944
if (t == TypePtr::NULL_PTR) {
2945
assert(in1->is_DecodeN(), "compare klass to null?");
2946
// Don't convert CmpP null check into CmpN if compressed
2947
// oops implicit null check is not generated.
2948
// This will allow to generate normal oop implicit null check.
2949
if (Matcher::gen_narrow_oop_implicit_null_checks())
2950
new_in2 = ConNode::make(this, TypeNarrowOop::NULL_PTR);
2951
//
2952
// This transformation together with CastPP transformation above
2953
// will generated code for implicit NULL checks for compressed oops.
2954
//
2955
// The original code after Optimize()
2956
//
2957
// LoadN memory, narrow_oop_reg
2958
// decode narrow_oop_reg, base_reg
2959
// CmpP base_reg, NULL
2960
// CastPP base_reg // NotNull
2961
// Load [base_reg + offset], val_reg
2962
//
2963
// after these transformations will be
2964
//
2965
// LoadN memory, narrow_oop_reg
2966
// CmpN narrow_oop_reg, NULL
2967
// decode_not_null narrow_oop_reg, base_reg
2968
// Load [base_reg + offset], val_reg
2969
//
2970
// and the uncommon path (== NULL) will use narrow_oop_reg directly
2971
// since narrow oops can be used in debug info now (see the code in
2972
// final_graph_reshaping_walk()).
2973
//
2974
// At the end the code will be matched to
2975
// on x86:
2976
//
2977
// Load_narrow_oop memory, narrow_oop_reg
2978
// Load [R12 + narrow_oop_reg<<3 + offset], val_reg
2979
// NullCheck narrow_oop_reg
2980
//
2981
// and on sparc:
2982
//
2983
// Load_narrow_oop memory, narrow_oop_reg
2984
// decode_not_null narrow_oop_reg, base_reg
2985
// Load [base_reg + offset], val_reg
2986
// NullCheck base_reg
2987
//
2988
} else if (t->isa_oopptr()) {
2989
new_in2 = ConNode::make(this, t->make_narrowoop());
2990
} else if (t->isa_klassptr()) {
2991
new_in2 = ConNode::make(this, t->make_narrowklass());
2992
}
2993
}
2994
if (new_in2 != NULL) {
2995
Node* cmpN = new (this) CmpNNode(in1->in(1), new_in2);
2996
n->subsume_by(cmpN, this);
2997
if (in1->outcnt() == 0) {
2998
in1->disconnect_inputs(NULL, this);
2999
}
3000
if (in2->outcnt() == 0) {
3001
in2->disconnect_inputs(NULL, this);
3002
}
3003
}
3004
}
3005
break;
3006
3007
case Op_DecodeN:
3008
case Op_DecodeNKlass:
3009
assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
3010
// DecodeN could be pinned when it can't be fold into
3011
// an address expression, see the code for Op_CastPP above.
3012
assert(n->in(0) == NULL || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
3013
break;
3014
3015
case Op_EncodeP:
3016
case Op_EncodePKlass: {
3017
Node* in1 = n->in(1);
3018
if (in1->is_DecodeNarrowPtr()) {
3019
n->subsume_by(in1->in(1), this);
3020
} else if (in1->Opcode() == Op_ConP) {
3021
const Type* t = in1->bottom_type();
3022
if (t == TypePtr::NULL_PTR) {
3023
assert(t->isa_oopptr(), "null klass?");
3024
n->subsume_by(ConNode::make(this, TypeNarrowOop::NULL_PTR), this);
3025
} else if (t->isa_oopptr()) {
3026
n->subsume_by(ConNode::make(this, t->make_narrowoop()), this);
3027
} else if (t->isa_klassptr()) {
3028
n->subsume_by(ConNode::make(this, t->make_narrowklass()), this);
3029
}
3030
}
3031
if (in1->outcnt() == 0) {
3032
in1->disconnect_inputs(NULL, this);
3033
}
3034
break;
3035
}
3036
3037
case Op_Proj: {
3038
if (OptimizeStringConcat) {
3039
ProjNode* p = n->as_Proj();
3040
if (p->_is_io_use) {
3041
// Separate projections were used for the exception path which
3042
// are normally removed by a late inline. If it wasn't inlined
3043
// then they will hang around and should just be replaced with
3044
// the original one.
3045
Node* proj = NULL;
3046
// Replace with just one
3047
for (SimpleDUIterator i(p->in(0)); i.has_next(); i.next()) {
3048
Node *use = i.get();
3049
if (use->is_Proj() && p != use && use->as_Proj()->_con == p->_con) {
3050
proj = use;
3051
break;
3052
}
3053
}
3054
assert(proj != NULL || p->_con == TypeFunc::I_O, "io may be dropped at an infinite loop");
3055
if (proj != NULL) {
3056
p->subsume_by(proj, this);
3057
}
3058
}
3059
}
3060
break;
3061
}
3062
3063
case Op_Phi:
3064
if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
3065
// The EncodeP optimization may create Phi with the same edges
3066
// for all paths. It is not handled well by Register Allocator.
3067
Node* unique_in = n->in(1);
3068
assert(unique_in != NULL, "");
3069
uint cnt = n->req();
3070
for (uint i = 2; i < cnt; i++) {
3071
Node* m = n->in(i);
3072
assert(m != NULL, "");
3073
if (unique_in != m)
3074
unique_in = NULL;
3075
}
3076
if (unique_in != NULL) {
3077
n->subsume_by(unique_in, this);
3078
}
3079
}
3080
break;
3081
3082
#endif
3083
3084
#ifdef ASSERT
3085
case Op_CastII:
3086
// Verify that all range check dependent CastII nodes were removed.
3087
if (n->isa_CastII()->has_range_check()) {
3088
n->dump(3);
3089
assert(false, "Range check dependent CastII node was not removed");
3090
}
3091
break;
3092
#endif
3093
3094
case Op_ModI:
3095
if (UseDivMod) {
3096
// Check if a%b and a/b both exist
3097
Node* d = n->find_similar(Op_DivI);
3098
if (d) {
3099
// Replace them with a fused divmod if supported
3100
if (Matcher::has_match_rule(Op_DivModI)) {
3101
DivModINode* divmod = DivModINode::make(this, n);
3102
d->subsume_by(divmod->div_proj(), this);
3103
n->subsume_by(divmod->mod_proj(), this);
3104
} else {
3105
// replace a%b with a-((a/b)*b)
3106
Node* mult = new (this) MulINode(d, d->in(2));
3107
Node* sub = new (this) SubINode(d->in(1), mult);
3108
n->subsume_by(sub, this);
3109
}
3110
}
3111
}
3112
break;
3113
3114
case Op_ModL:
3115
if (UseDivMod) {
3116
// Check if a%b and a/b both exist
3117
Node* d = n->find_similar(Op_DivL);
3118
if (d) {
3119
// Replace them with a fused divmod if supported
3120
if (Matcher::has_match_rule(Op_DivModL)) {
3121
DivModLNode* divmod = DivModLNode::make(this, n);
3122
d->subsume_by(divmod->div_proj(), this);
3123
n->subsume_by(divmod->mod_proj(), this);
3124
} else {
3125
// replace a%b with a-((a/b)*b)
3126
Node* mult = new (this) MulLNode(d, d->in(2));
3127
Node* sub = new (this) SubLNode(d->in(1), mult);
3128
n->subsume_by(sub, this);
3129
}
3130
}
3131
}
3132
break;
3133
3134
case Op_LoadVector:
3135
case Op_StoreVector:
3136
break;
3137
3138
case Op_PackB:
3139
case Op_PackS:
3140
case Op_PackI:
3141
case Op_PackF:
3142
case Op_PackL:
3143
case Op_PackD:
3144
if (n->req()-1 > 2) {
3145
// Replace many operand PackNodes with a binary tree for matching
3146
PackNode* p = (PackNode*) n;
3147
Node* btp = p->binary_tree_pack(this, 1, n->req());
3148
n->subsume_by(btp, this);
3149
}
3150
break;
3151
case Op_Loop:
3152
case Op_CountedLoop:
3153
if (n->as_Loop()->is_inner_loop()) {
3154
frc.inc_inner_loop_count();
3155
}
3156
break;
3157
case Op_LShiftI:
3158
case Op_RShiftI:
3159
case Op_URShiftI:
3160
case Op_LShiftL:
3161
case Op_RShiftL:
3162
case Op_URShiftL:
3163
if (Matcher::need_masked_shift_count) {
3164
// The cpu's shift instructions don't restrict the count to the
3165
// lower 5/6 bits. We need to do the masking ourselves.
3166
Node* in2 = n->in(2);
3167
juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
3168
const TypeInt* t = in2->find_int_type();
3169
if (t != NULL && t->is_con()) {
3170
juint shift = t->get_con();
3171
if (shift > mask) { // Unsigned cmp
3172
n->set_req(2, ConNode::make(this, TypeInt::make(shift & mask)));
3173
}
3174
} else {
3175
if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
3176
Node* shift = new (this) AndINode(in2, ConNode::make(this, TypeInt::make(mask)));
3177
n->set_req(2, shift);
3178
}
3179
}
3180
if (in2->outcnt() == 0) { // Remove dead node
3181
in2->disconnect_inputs(NULL, this);
3182
}
3183
}
3184
break;
3185
case Op_MemBarStoreStore:
3186
case Op_MemBarRelease:
3187
// Break the link with AllocateNode: it is no longer useful and
3188
// confuses register allocation.
3189
if (n->req() > MemBarNode::Precedent) {
3190
n->set_req(MemBarNode::Precedent, top());
3191
}
3192
break;
3193
default:
3194
assert( !n->is_Call(), "" );
3195
assert( !n->is_Mem(), "" );
3196
assert( nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3197
break;
3198
}
3199
3200
// Collect CFG split points
3201
if (n->is_MultiBranch())
3202
frc._tests.push(n);
3203
}
3204
3205
//------------------------------final_graph_reshaping_walk---------------------
3206
// Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3207
// requires that the walk visits a node's inputs before visiting the node.
3208
void Compile::final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &frc ) {
3209
ResourceArea *area = Thread::current()->resource_area();
3210
Unique_Node_List sfpt(area);
3211
3212
frc._visited.set(root->_idx); // first, mark node as visited
3213
uint cnt = root->req();
3214
Node *n = root;
3215
uint i = 0;
3216
while (true) {
3217
if (i < cnt) {
3218
// Place all non-visited non-null inputs onto stack
3219
Node* m = n->in(i);
3220
++i;
3221
if (m != NULL && !frc._visited.test_set(m->_idx)) {
3222
if (m->is_SafePoint() && m->as_SafePoint()->jvms() != NULL) {
3223
// compute worst case interpreter size in case of a deoptimization
3224
update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
3225
3226
sfpt.push(m);
3227
}
3228
cnt = m->req();
3229
nstack.push(n, i); // put on stack parent and next input's index
3230
n = m;
3231
i = 0;
3232
}
3233
} else {
3234
// Now do post-visit work
3235
final_graph_reshaping_impl( n, frc );
3236
if (nstack.is_empty())
3237
break; // finished
3238
n = nstack.node(); // Get node from stack
3239
cnt = n->req();
3240
i = nstack.index();
3241
nstack.pop(); // Shift to the next node on stack
3242
}
3243
}
3244
3245
// Skip next transformation if compressed oops are not used.
3246
if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) ||
3247
(!UseCompressedOops && !UseCompressedClassPointers))
3248
return;
3249
3250
// Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
3251
// It could be done for an uncommon traps or any safepoints/calls
3252
// if the DecodeN/DecodeNKlass node is referenced only in a debug info.
3253
while (sfpt.size() > 0) {
3254
n = sfpt.pop();
3255
JVMState *jvms = n->as_SafePoint()->jvms();
3256
assert(jvms != NULL, "sanity");
3257
int start = jvms->debug_start();
3258
int end = n->req();
3259
bool is_uncommon = (n->is_CallStaticJava() &&
3260
n->as_CallStaticJava()->uncommon_trap_request() != 0);
3261
for (int j = start; j < end; j++) {
3262
Node* in = n->in(j);
3263
if (in->is_DecodeNarrowPtr()) {
3264
bool safe_to_skip = true;
3265
if (!is_uncommon ) {
3266
// Is it safe to skip?
3267
for (uint i = 0; i < in->outcnt(); i++) {
3268
Node* u = in->raw_out(i);
3269
if (!u->is_SafePoint() ||
3270
u->is_Call() && u->as_Call()->has_non_debug_use(n)) {
3271
safe_to_skip = false;
3272
}
3273
}
3274
}
3275
if (safe_to_skip) {
3276
n->set_req(j, in->in(1));
3277
}
3278
if (in->outcnt() == 0) {
3279
in->disconnect_inputs(NULL, this);
3280
}
3281
}
3282
}
3283
}
3284
}
3285
3286
//------------------------------final_graph_reshaping--------------------------
3287
// Final Graph Reshaping.
3288
//
3289
// (1) Clone simple inputs to uncommon calls, so they can be scheduled late
3290
// and not commoned up and forced early. Must come after regular
3291
// optimizations to avoid GVN undoing the cloning. Clone constant
3292
// inputs to Loop Phis; these will be split by the allocator anyways.
3293
// Remove Opaque nodes.
3294
// (2) Move last-uses by commutative operations to the left input to encourage
3295
// Intel update-in-place two-address operations and better register usage
3296
// on RISCs. Must come after regular optimizations to avoid GVN Ideal
3297
// calls canonicalizing them back.
3298
// (3) Count the number of double-precision FP ops, single-precision FP ops
3299
// and call sites. On Intel, we can get correct rounding either by
3300
// forcing singles to memory (requires extra stores and loads after each
3301
// FP bytecode) or we can set a rounding mode bit (requires setting and
3302
// clearing the mode bit around call sites). The mode bit is only used
3303
// if the relative frequency of single FP ops to calls is low enough.
3304
// This is a key transform for SPEC mpeg_audio.
3305
// (4) Detect infinite loops; blobs of code reachable from above but not
3306
// below. Several of the Code_Gen algorithms fail on such code shapes,
3307
// so we simply bail out. Happens a lot in ZKM.jar, but also happens
3308
// from time to time in other codes (such as -Xcomp finalizer loops, etc).
3309
// Detection is by looking for IfNodes where only 1 projection is
3310
// reachable from below or CatchNodes missing some targets.
3311
// (5) Assert for insane oop offsets in debug mode.
3312
3313
bool Compile::final_graph_reshaping() {
3314
// an infinite loop may have been eliminated by the optimizer,
3315
// in which case the graph will be empty.
3316
if (root()->req() == 1) {
3317
record_method_not_compilable("trivial infinite loop");
3318
return true;
3319
}
3320
3321
// Expensive nodes have their control input set to prevent the GVN
3322
// from freely commoning them. There's no GVN beyond this point so
3323
// no need to keep the control input. We want the expensive nodes to
3324
// be freely moved to the least frequent code path by gcm.
3325
assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
3326
for (int i = 0; i < expensive_count(); i++) {
3327
_expensive_nodes->at(i)->set_req(0, NULL);
3328
}
3329
3330
Final_Reshape_Counts frc;
3331
3332
// Visit everybody reachable!
3333
// Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
3334
Node_Stack nstack(live_nodes() >> 1);
3335
final_graph_reshaping_walk(nstack, root(), frc);
3336
3337
// Check for unreachable (from below) code (i.e., infinite loops).
3338
for( uint i = 0; i < frc._tests.size(); i++ ) {
3339
MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
3340
// Get number of CFG targets.
3341
// Note that PCTables include exception targets after calls.
3342
uint required_outcnt = n->required_outcnt();
3343
if (n->outcnt() != required_outcnt) {
3344
// Check for a few special cases. Rethrow Nodes never take the
3345
// 'fall-thru' path, so expected kids is 1 less.
3346
if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
3347
if (n->in(0)->in(0)->is_Call()) {
3348
CallNode *call = n->in(0)->in(0)->as_Call();
3349
if (call->entry_point() == OptoRuntime::rethrow_stub()) {
3350
required_outcnt--; // Rethrow always has 1 less kid
3351
} else if (call->req() > TypeFunc::Parms &&
3352
call->is_CallDynamicJava()) {
3353
// Check for null receiver. In such case, the optimizer has
3354
// detected that the virtual call will always result in a null
3355
// pointer exception. The fall-through projection of this CatchNode
3356
// will not be populated.
3357
Node *arg0 = call->in(TypeFunc::Parms);
3358
if (arg0->is_Type() &&
3359
arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
3360
required_outcnt--;
3361
}
3362
} else if (call->entry_point() == OptoRuntime::new_array_Java() &&
3363
call->req() > TypeFunc::Parms+1 &&
3364
call->is_CallStaticJava()) {
3365
// Check for negative array length. In such case, the optimizer has
3366
// detected that the allocation attempt will always result in an
3367
// exception. There is no fall-through projection of this CatchNode .
3368
Node *arg1 = call->in(TypeFunc::Parms+1);
3369
if (arg1->is_Type() &&
3370
arg1->as_Type()->type()->join(TypeInt::POS)->empty()) {
3371
required_outcnt--;
3372
}
3373
}
3374
}
3375
}
3376
// Recheck with a better notion of 'required_outcnt'
3377
if (n->outcnt() != required_outcnt) {
3378
record_method_not_compilable("malformed control flow");
3379
return true; // Not all targets reachable!
3380
}
3381
}
3382
// Check that I actually visited all kids. Unreached kids
3383
// must be infinite loops.
3384
for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
3385
if (!frc._visited.test(n->fast_out(j)->_idx)) {
3386
record_method_not_compilable("infinite loop");
3387
return true; // Found unvisited kid; must be unreach
3388
}
3389
}
3390
3391
// If original bytecodes contained a mixture of floats and doubles
3392
// check if the optimizer has made it homogenous, item (3).
3393
if( Use24BitFPMode && Use24BitFP && UseSSE == 0 &&
3394
frc.get_float_count() > 32 &&
3395
frc.get_double_count() == 0 &&
3396
(10 * frc.get_call_count() < frc.get_float_count()) ) {
3397
set_24_bit_selection_and_mode( false, true );
3398
}
3399
3400
set_java_calls(frc.get_java_call_count());
3401
set_inner_loops(frc.get_inner_loop_count());
3402
3403
// No infinite loops, no reason to bail out.
3404
return false;
3405
}
3406
3407
//-----------------------------too_many_traps----------------------------------
3408
// Report if there are too many traps at the current method and bci.
3409
// Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
3410
bool Compile::too_many_traps(ciMethod* method,
3411
int bci,
3412
Deoptimization::DeoptReason reason) {
3413
ciMethodData* md = method->method_data();
3414
if (md->is_empty()) {
3415
// Assume the trap has not occurred, or that it occurred only
3416
// because of a transient condition during start-up in the interpreter.
3417
return false;
3418
}
3419
ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
3420
if (md->has_trap_at(bci, m, reason) != 0) {
3421
// Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
3422
// Also, if there are multiple reasons, or if there is no per-BCI record,
3423
// assume the worst.
3424
if (log())
3425
log()->elem("observe trap='%s' count='%d'",
3426
Deoptimization::trap_reason_name(reason),
3427
md->trap_count(reason));
3428
return true;
3429
} else {
3430
// Ignore method/bci and see if there have been too many globally.
3431
return too_many_traps(reason, md);
3432
}
3433
}
3434
3435
// Less-accurate variant which does not require a method and bci.
3436
bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
3437
ciMethodData* logmd) {
3438
if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
3439
// Too many traps globally.
3440
// Note that we use cumulative trap_count, not just md->trap_count.
3441
if (log()) {
3442
int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason);
3443
log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
3444
Deoptimization::trap_reason_name(reason),
3445
mcount, trap_count(reason));
3446
}
3447
return true;
3448
} else {
3449
// The coast is clear.
3450
return false;
3451
}
3452
}
3453
3454
//--------------------------too_many_recompiles--------------------------------
3455
// Report if there are too many recompiles at the current method and bci.
3456
// Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
3457
// Is not eager to return true, since this will cause the compiler to use
3458
// Action_none for a trap point, to avoid too many recompilations.
3459
bool Compile::too_many_recompiles(ciMethod* method,
3460
int bci,
3461
Deoptimization::DeoptReason reason) {
3462
ciMethodData* md = method->method_data();
3463
if (md->is_empty()) {
3464
// Assume the trap has not occurred, or that it occurred only
3465
// because of a transient condition during start-up in the interpreter.
3466
return false;
3467
}
3468
// Pick a cutoff point well within PerBytecodeRecompilationCutoff.
3469
uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
3470
uint m_cutoff = (uint) PerMethodRecompilationCutoff / 2 + 1; // not zero
3471
Deoptimization::DeoptReason per_bc_reason
3472
= Deoptimization::reason_recorded_per_bytecode_if_any(reason);
3473
ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
3474
if ((per_bc_reason == Deoptimization::Reason_none
3475
|| md->has_trap_at(bci, m, reason) != 0)
3476
// The trap frequency measure we care about is the recompile count:
3477
&& md->trap_recompiled_at(bci, m)
3478
&& md->overflow_recompile_count() >= bc_cutoff) {
3479
// Do not emit a trap here if it has already caused recompilations.
3480
// Also, if there are multiple reasons, or if there is no per-BCI record,
3481
// assume the worst.
3482
if (log())
3483
log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
3484
Deoptimization::trap_reason_name(reason),
3485
md->trap_count(reason),
3486
md->overflow_recompile_count());
3487
return true;
3488
} else if (trap_count(reason) != 0
3489
&& decompile_count() >= m_cutoff) {
3490
// Too many recompiles globally, and we have seen this sort of trap.
3491
// Use cumulative decompile_count, not just md->decompile_count.
3492
if (log())
3493
log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
3494
Deoptimization::trap_reason_name(reason),
3495
md->trap_count(reason), trap_count(reason),
3496
md->decompile_count(), decompile_count());
3497
return true;
3498
} else {
3499
// The coast is clear.
3500
return false;
3501
}
3502
}
3503
3504
// Compute when not to trap. Used by matching trap based nodes and
3505
// NullCheck optimization.
3506
void Compile::set_allowed_deopt_reasons() {
3507
_allowed_reasons = 0;
3508
if (is_method_compilation()) {
3509
for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
3510
assert(rs < BitsPerInt, "recode bit map");
3511
if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
3512
_allowed_reasons |= nth_bit(rs);
3513
}
3514
}
3515
}
3516
}
3517
3518
#ifndef PRODUCT
3519
//------------------------------verify_graph_edges---------------------------
3520
// Walk the Graph and verify that there is a one-to-one correspondence
3521
// between Use-Def edges and Def-Use edges in the graph.
3522
void Compile::verify_graph_edges(bool no_dead_code) {
3523
if (VerifyGraphEdges) {
3524
ResourceArea *area = Thread::current()->resource_area();
3525
Unique_Node_List visited(area);
3526
// Call recursive graph walk to check edges
3527
_root->verify_edges(visited);
3528
if (no_dead_code) {
3529
// Now make sure that no visited node is used by an unvisited node.
3530
bool dead_nodes = false;
3531
Unique_Node_List checked(area);
3532
while (visited.size() > 0) {
3533
Node* n = visited.pop();
3534
checked.push(n);
3535
for (uint i = 0; i < n->outcnt(); i++) {
3536
Node* use = n->raw_out(i);
3537
if (checked.member(use)) continue; // already checked
3538
if (visited.member(use)) continue; // already in the graph
3539
if (use->is_Con()) continue; // a dead ConNode is OK
3540
// At this point, we have found a dead node which is DU-reachable.
3541
if (!dead_nodes) {
3542
tty->print_cr("*** Dead nodes reachable via DU edges:");
3543
dead_nodes = true;
3544
}
3545
use->dump(2);
3546
tty->print_cr("---");
3547
checked.push(use); // No repeats; pretend it is now checked.
3548
}
3549
}
3550
assert(!dead_nodes, "using nodes must be reachable from root");
3551
}
3552
}
3553
}
3554
3555
// Verify GC barriers consistency
3556
// Currently supported:
3557
// - G1 pre-barriers (see GraphKit::g1_write_barrier_pre())
3558
void Compile::verify_barriers() {
3559
if (UseG1GC) {
3560
// Verify G1 pre-barriers
3561
const int marking_offset = in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active());
3562
3563
ResourceArea *area = Thread::current()->resource_area();
3564
Unique_Node_List visited(area);
3565
Node_List worklist(area);
3566
// We're going to walk control flow backwards starting from the Root
3567
worklist.push(_root);
3568
while (worklist.size() > 0) {
3569
Node* x = worklist.pop();
3570
if (x == NULL || x == top()) continue;
3571
if (visited.member(x)) {
3572
continue;
3573
} else {
3574
visited.push(x);
3575
}
3576
3577
if (x->is_Region()) {
3578
for (uint i = 1; i < x->req(); i++) {
3579
worklist.push(x->in(i));
3580
}
3581
} else {
3582
worklist.push(x->in(0));
3583
// We are looking for the pattern:
3584
// /->ThreadLocal
3585
// If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
3586
// \->ConI(0)
3587
// We want to verify that the If and the LoadB have the same control
3588
// See GraphKit::g1_write_barrier_pre()
3589
if (x->is_If()) {
3590
IfNode *iff = x->as_If();
3591
if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
3592
CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
3593
if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
3594
&& cmp->in(1)->is_Load()) {
3595
LoadNode* load = cmp->in(1)->as_Load();
3596
if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
3597
&& load->in(2)->in(3)->is_Con()
3598
&& load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == marking_offset) {
3599
3600
Node* if_ctrl = iff->in(0);
3601
Node* load_ctrl = load->in(0);
3602
3603
if (if_ctrl != load_ctrl) {
3604
// Skip possible CProj->NeverBranch in infinite loops
3605
if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
3606
&& (if_ctrl->in(0)->is_MultiBranch() && if_ctrl->in(0)->Opcode() == Op_NeverBranch)) {
3607
if_ctrl = if_ctrl->in(0)->in(0);
3608
}
3609
}
3610
assert(load_ctrl != NULL && if_ctrl == load_ctrl, "controls must match");
3611
}
3612
}
3613
}
3614
}
3615
}
3616
}
3617
}
3618
}
3619
3620
#endif
3621
3622
// The Compile object keeps track of failure reasons separately from the ciEnv.
3623
// This is required because there is not quite a 1-1 relation between the
3624
// ciEnv and its compilation task and the Compile object. Note that one
3625
// ciEnv might use two Compile objects, if C2Compiler::compile_method decides
3626
// to backtrack and retry without subsuming loads. Other than this backtracking
3627
// behavior, the Compile's failure reason is quietly copied up to the ciEnv
3628
// by the logic in C2Compiler.
3629
void Compile::record_failure(const char* reason) {
3630
if (log() != NULL) {
3631
log()->elem("failure reason='%s' phase='compile'", reason);
3632
}
3633
if (_failure_reason == NULL) {
3634
// Record the first failure reason.
3635
_failure_reason = reason;
3636
}
3637
3638
if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
3639
C->print_method(PHASE_FAILURE);
3640
}
3641
_root = NULL; // flush the graph, too
3642
}
3643
3644
Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator, bool dolog)
3645
: TraceTime(NULL, accumulator, false NOT_PRODUCT( || TimeCompiler ), false),
3646
_phase_name(name), _dolog(dolog)
3647
{
3648
if (dolog) {
3649
C = Compile::current();
3650
_log = C->log();
3651
} else {
3652
C = NULL;
3653
_log = NULL;
3654
}
3655
if (_log != NULL) {
3656
_log->begin_head("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
3657
_log->stamp();
3658
_log->end_head();
3659
}
3660
}
3661
3662
Compile::TracePhase::~TracePhase() {
3663
3664
C = Compile::current();
3665
if (_dolog) {
3666
_log = C->log();
3667
} else {
3668
_log = NULL;
3669
}
3670
3671
#ifdef ASSERT
3672
if (PrintIdealNodeCount) {
3673
tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
3674
_phase_name, C->unique(), C->live_nodes(), C->count_live_nodes_by_graph_walk());
3675
}
3676
3677
if (VerifyIdealNodeCount) {
3678
Compile::current()->print_missing_nodes();
3679
}
3680
#endif
3681
3682
if (_log != NULL) {
3683
_log->done("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
3684
}
3685
}
3686
3687
//=============================================================================
3688
// Two Constant's are equal when the type and the value are equal.
3689
bool Compile::Constant::operator==(const Constant& other) {
3690
if (type() != other.type() ) return false;
3691
if (can_be_reused() != other.can_be_reused()) return false;
3692
// For floating point values we compare the bit pattern.
3693
switch (type()) {
3694
case T_FLOAT: return (_v._value.i == other._v._value.i);
3695
case T_LONG:
3696
case T_DOUBLE: return (_v._value.j == other._v._value.j);
3697
case T_OBJECT:
3698
case T_ADDRESS: return (_v._value.l == other._v._value.l);
3699
case T_VOID: return (_v._value.l == other._v._value.l); // jump-table entries
3700
case T_METADATA: return (_v._metadata == other._v._metadata);
3701
default: ShouldNotReachHere();
3702
}
3703
return false;
3704
}
3705
3706
static int type_to_size_in_bytes(BasicType t) {
3707
switch (t) {
3708
case T_LONG: return sizeof(jlong );
3709
case T_FLOAT: return sizeof(jfloat );
3710
case T_DOUBLE: return sizeof(jdouble);
3711
case T_METADATA: return sizeof(Metadata*);
3712
// We use T_VOID as marker for jump-table entries (labels) which
3713
// need an internal word relocation.
3714
case T_VOID:
3715
case T_ADDRESS:
3716
case T_OBJECT: return sizeof(jobject);
3717
}
3718
3719
ShouldNotReachHere();
3720
return -1;
3721
}
3722
3723
int Compile::ConstantTable::qsort_comparator(Constant* a, Constant* b) {
3724
// sort descending
3725
if (a->freq() > b->freq()) return -1;
3726
if (a->freq() < b->freq()) return 1;
3727
return 0;
3728
}
3729
3730
void Compile::ConstantTable::calculate_offsets_and_size() {
3731
// First, sort the array by frequencies.
3732
_constants.sort(qsort_comparator);
3733
3734
#ifdef ASSERT
3735
// Make sure all jump-table entries were sorted to the end of the
3736
// array (they have a negative frequency).
3737
bool found_void = false;
3738
for (int i = 0; i < _constants.length(); i++) {
3739
Constant con = _constants.at(i);
3740
if (con.type() == T_VOID)
3741
found_void = true; // jump-tables
3742
else
3743
assert(!found_void, "wrong sorting");
3744
}
3745
#endif
3746
3747
int offset = 0;
3748
for (int i = 0; i < _constants.length(); i++) {
3749
Constant* con = _constants.adr_at(i);
3750
3751
// Align offset for type.
3752
int typesize = type_to_size_in_bytes(con->type());
3753
offset = align_size_up(offset, typesize);
3754
con->set_offset(offset); // set constant's offset
3755
3756
if (con->type() == T_VOID) {
3757
MachConstantNode* n = (MachConstantNode*) con->get_jobject();
3758
offset = offset + typesize * n->outcnt(); // expand jump-table
3759
} else {
3760
offset = offset + typesize;
3761
}
3762
}
3763
3764
// Align size up to the next section start (which is insts; see
3765
// CodeBuffer::align_at_start).
3766
assert(_size == -1, "already set?");
3767
_size = align_size_up(offset, CodeEntryAlignment);
3768
}
3769
3770
void Compile::ConstantTable::emit(CodeBuffer& cb) {
3771
MacroAssembler _masm(&cb);
3772
for (int i = 0; i < _constants.length(); i++) {
3773
Constant con = _constants.at(i);
3774
address constant_addr = NULL;
3775
switch (con.type()) {
3776
case T_LONG: constant_addr = _masm.long_constant( con.get_jlong() ); break;
3777
case T_FLOAT: constant_addr = _masm.float_constant( con.get_jfloat() ); break;
3778
case T_DOUBLE: constant_addr = _masm.double_constant(con.get_jdouble()); break;
3779
case T_OBJECT: {
3780
jobject obj = con.get_jobject();
3781
int oop_index = _masm.oop_recorder()->find_index(obj);
3782
constant_addr = _masm.address_constant((address) obj, oop_Relocation::spec(oop_index));
3783
break;
3784
}
3785
case T_ADDRESS: {
3786
address addr = (address) con.get_jobject();
3787
constant_addr = _masm.address_constant(addr);
3788
break;
3789
}
3790
// We use T_VOID as marker for jump-table entries (labels) which
3791
// need an internal word relocation.
3792
case T_VOID: {
3793
MachConstantNode* n = (MachConstantNode*) con.get_jobject();
3794
// Fill the jump-table with a dummy word. The real value is
3795
// filled in later in fill_jump_table.
3796
address dummy = (address) n;
3797
constant_addr = _masm.address_constant(dummy);
3798
// Expand jump-table
3799
for (uint i = 1; i < n->outcnt(); i++) {
3800
address temp_addr = _masm.address_constant(dummy + i);
3801
assert(temp_addr, "consts section too small");
3802
}
3803
break;
3804
}
3805
case T_METADATA: {
3806
Metadata* obj = con.get_metadata();
3807
int metadata_index = _masm.oop_recorder()->find_index(obj);
3808
constant_addr = _masm.address_constant((address) obj, metadata_Relocation::spec(metadata_index));
3809
break;
3810
}
3811
default: ShouldNotReachHere();
3812
}
3813
assert(constant_addr, "consts section too small");
3814
assert((constant_addr - _masm.code()->consts()->start()) == con.offset(),
3815
err_msg_res("must be: %d == %d", (int) (constant_addr - _masm.code()->consts()->start()), (int)(con.offset())));
3816
}
3817
}
3818
3819
int Compile::ConstantTable::find_offset(Constant& con) const {
3820
int idx = _constants.find(con);
3821
assert(idx != -1, "constant must be in constant table");
3822
int offset = _constants.at(idx).offset();
3823
assert(offset != -1, "constant table not emitted yet?");
3824
return offset;
3825
}
3826
3827
void Compile::ConstantTable::add(Constant& con) {
3828
if (con.can_be_reused()) {
3829
int idx = _constants.find(con);
3830
if (idx != -1 && _constants.at(idx).can_be_reused()) {
3831
_constants.adr_at(idx)->inc_freq(con.freq()); // increase the frequency by the current value
3832
return;
3833
}
3834
}
3835
(void) _constants.append(con);
3836
}
3837
3838
Compile::Constant Compile::ConstantTable::add(MachConstantNode* n, BasicType type, jvalue value) {
3839
Block* b = Compile::current()->cfg()->get_block_for_node(n);
3840
Constant con(type, value, b->_freq);
3841
add(con);
3842
return con;
3843
}
3844
3845
Compile::Constant Compile::ConstantTable::add(Metadata* metadata) {
3846
Constant con(metadata);
3847
add(con);
3848
return con;
3849
}
3850
3851
Compile::Constant Compile::ConstantTable::add(MachConstantNode* n, MachOper* oper) {
3852
jvalue value;
3853
BasicType type = oper->type()->basic_type();
3854
switch (type) {
3855
case T_LONG: value.j = oper->constantL(); break;
3856
case T_FLOAT: value.f = oper->constantF(); break;
3857
case T_DOUBLE: value.d = oper->constantD(); break;
3858
case T_OBJECT:
3859
case T_ADDRESS: value.l = (jobject) oper->constant(); break;
3860
case T_METADATA: return add((Metadata*)oper->constant()); break;
3861
default: guarantee(false, err_msg_res("unhandled type: %s", type2name(type)));
3862
}
3863
return add(n, type, value);
3864
}
3865
3866
Compile::Constant Compile::ConstantTable::add_jump_table(MachConstantNode* n) {
3867
jvalue value;
3868
// We can use the node pointer here to identify the right jump-table
3869
// as this method is called from Compile::Fill_buffer right before
3870
// the MachNodes are emitted and the jump-table is filled (means the
3871
// MachNode pointers do not change anymore).
3872
value.l = (jobject) n;
3873
Constant con(T_VOID, value, next_jump_table_freq(), false); // Labels of a jump-table cannot be reused.
3874
add(con);
3875
return con;
3876
}
3877
3878
void Compile::ConstantTable::fill_jump_table(CodeBuffer& cb, MachConstantNode* n, GrowableArray<Label*> labels) const {
3879
// If called from Compile::scratch_emit_size do nothing.
3880
if (Compile::current()->in_scratch_emit_size()) return;
3881
3882
assert(labels.is_nonempty(), "must be");
3883
assert((uint) labels.length() == n->outcnt(), err_msg_res("must be equal: %d == %d", labels.length(), n->outcnt()));
3884
3885
// Since MachConstantNode::constant_offset() also contains
3886
// table_base_offset() we need to subtract the table_base_offset()
3887
// to get the plain offset into the constant table.
3888
int offset = n->constant_offset() - table_base_offset();
3889
3890
MacroAssembler _masm(&cb);
3891
address* jump_table_base = (address*) (_masm.code()->consts()->start() + offset);
3892
3893
for (uint i = 0; i < n->outcnt(); i++) {
3894
address* constant_addr = &jump_table_base[i];
3895
assert(*constant_addr == (((address) n) + i), err_msg_res("all jump-table entries must contain adjusted node pointer: " INTPTR_FORMAT " == " INTPTR_FORMAT, p2i(*constant_addr), p2i(((address) n) + i)));
3896
*constant_addr = cb.consts()->target(*labels.at(i), (address) constant_addr);
3897
cb.consts()->relocate((address) constant_addr, relocInfo::internal_word_type);
3898
}
3899
}
3900
3901
void Compile::dump_inlining() {
3902
if (print_inlining() || print_intrinsics()) {
3903
// Print inlining message for candidates that we couldn't inline
3904
// for lack of space or non constant receiver
3905
for (int i = 0; i < _late_inlines.length(); i++) {
3906
CallGenerator* cg = _late_inlines.at(i);
3907
cg->print_inlining_late("live nodes > LiveNodeCountInliningCutoff");
3908
}
3909
Unique_Node_List useful;
3910
useful.push(root());
3911
for (uint next = 0; next < useful.size(); ++next) {
3912
Node* n = useful.at(next);
3913
if (n->is_Call() && n->as_Call()->generator() != NULL && n->as_Call()->generator()->call_node() == n) {
3914
CallNode* call = n->as_Call();
3915
CallGenerator* cg = call->generator();
3916
cg->print_inlining_late("receiver not constant");
3917
}
3918
uint max = n->len();
3919
for ( uint i = 0; i < max; ++i ) {
3920
Node *m = n->in(i);
3921
if ( m == NULL ) continue;
3922
useful.push(m);
3923
}
3924
}
3925
for (int i = 0; i < _print_inlining_list->length(); i++) {
3926
tty->print("%s", _print_inlining_list->adr_at(i)->ss()->as_string());
3927
}
3928
}
3929
}
3930
3931
// Dump inlining replay data to the stream.
3932
// Don't change thread state and acquire any locks.
3933
void Compile::dump_inline_data(outputStream* out) {
3934
InlineTree* inl_tree = ilt();
3935
if (inl_tree != NULL) {
3936
out->print(" inline %d", inl_tree->count());
3937
inl_tree->dump_replay_data(out);
3938
}
3939
}
3940
3941
int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
3942
if (n1->Opcode() < n2->Opcode()) return -1;
3943
else if (n1->Opcode() > n2->Opcode()) return 1;
3944
3945
assert(n1->req() == n2->req(), err_msg_res("can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req()));
3946
for (uint i = 1; i < n1->req(); i++) {
3947
if (n1->in(i) < n2->in(i)) return -1;
3948
else if (n1->in(i) > n2->in(i)) return 1;
3949
}
3950
3951
return 0;
3952
}
3953
3954
int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
3955
Node* n1 = *n1p;
3956
Node* n2 = *n2p;
3957
3958
return cmp_expensive_nodes(n1, n2);
3959
}
3960
3961
void Compile::sort_expensive_nodes() {
3962
if (!expensive_nodes_sorted()) {
3963
_expensive_nodes->sort(cmp_expensive_nodes);
3964
}
3965
}
3966
3967
bool Compile::expensive_nodes_sorted() const {
3968
for (int i = 1; i < _expensive_nodes->length(); i++) {
3969
if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i-1)) < 0) {
3970
return false;
3971
}
3972
}
3973
return true;
3974
}
3975
3976
bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
3977
if (_expensive_nodes->length() == 0) {
3978
return false;
3979
}
3980
3981
assert(OptimizeExpensiveOps, "optimization off?");
3982
3983
// Take this opportunity to remove dead nodes from the list
3984
int j = 0;
3985
for (int i = 0; i < _expensive_nodes->length(); i++) {
3986
Node* n = _expensive_nodes->at(i);
3987
if (!n->is_unreachable(igvn)) {
3988
assert(n->is_expensive(), "should be expensive");
3989
_expensive_nodes->at_put(j, n);
3990
j++;
3991
}
3992
}
3993
_expensive_nodes->trunc_to(j);
3994
3995
// Then sort the list so that similar nodes are next to each other
3996
// and check for at least two nodes of identical kind with same data
3997
// inputs.
3998
sort_expensive_nodes();
3999
4000
for (int i = 0; i < _expensive_nodes->length()-1; i++) {
4001
if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i+1)) == 0) {
4002
return true;
4003
}
4004
}
4005
4006
return false;
4007
}
4008
4009
void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
4010
if (_expensive_nodes->length() == 0) {
4011
return;
4012
}
4013
4014
assert(OptimizeExpensiveOps, "optimization off?");
4015
4016
// Sort to bring similar nodes next to each other and clear the
4017
// control input of nodes for which there's only a single copy.
4018
sort_expensive_nodes();
4019
4020
int j = 0;
4021
int identical = 0;
4022
int i = 0;
4023
for (; i < _expensive_nodes->length()-1; i++) {
4024
assert(j <= i, "can't write beyond current index");
4025
if (_expensive_nodes->at(i)->Opcode() == _expensive_nodes->at(i+1)->Opcode()) {
4026
identical++;
4027
_expensive_nodes->at_put(j++, _expensive_nodes->at(i));
4028
continue;
4029
}
4030
if (identical > 0) {
4031
_expensive_nodes->at_put(j++, _expensive_nodes->at(i));
4032
identical = 0;
4033
} else {
4034
Node* n = _expensive_nodes->at(i);
4035
igvn.hash_delete(n);
4036
n->set_req(0, NULL);
4037
igvn.hash_insert(n);
4038
}
4039
}
4040
if (identical > 0) {
4041
_expensive_nodes->at_put(j++, _expensive_nodes->at(i));
4042
} else if (_expensive_nodes->length() >= 1) {
4043
Node* n = _expensive_nodes->at(i);
4044
igvn.hash_delete(n);
4045
n->set_req(0, NULL);
4046
igvn.hash_insert(n);
4047
}
4048
_expensive_nodes->trunc_to(j);
4049
}
4050
4051
void Compile::add_expensive_node(Node * n) {
4052
assert(!_expensive_nodes->contains(n), "duplicate entry in expensive list");
4053
assert(n->is_expensive(), "expensive nodes with non-null control here only");
4054
assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
4055
if (OptimizeExpensiveOps) {
4056
_expensive_nodes->append(n);
4057
} else {
4058
// Clear control input and let IGVN optimize expensive nodes if
4059
// OptimizeExpensiveOps is off.
4060
n->set_req(0, NULL);
4061
}
4062
}
4063
4064
/**
4065
* Remove the speculative part of types and clean up the graph
4066
*/
4067
void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
4068
if (UseTypeSpeculation) {
4069
Unique_Node_List worklist;
4070
worklist.push(root());
4071
int modified = 0;
4072
// Go over all type nodes that carry a speculative type, drop the
4073
// speculative part of the type and enqueue the node for an igvn
4074
// which may optimize it out.
4075
for (uint next = 0; next < worklist.size(); ++next) {
4076
Node *n = worklist.at(next);
4077
if (n->is_Type()) {
4078
TypeNode* tn = n->as_Type();
4079
const Type* t = tn->type();
4080
const Type* t_no_spec = t->remove_speculative();
4081
if (t_no_spec != t) {
4082
bool in_hash = igvn.hash_delete(n);
4083
assert(in_hash, "node should be in igvn hash table");
4084
tn->set_type(t_no_spec);
4085
igvn.hash_insert(n);
4086
igvn._worklist.push(n); // give it a chance to go away
4087
modified++;
4088
}
4089
}
4090
uint max = n->len();
4091
for( uint i = 0; i < max; ++i ) {
4092
Node *m = n->in(i);
4093
if (not_a_node(m)) continue;
4094
worklist.push(m);
4095
}
4096
}
4097
// Drop the speculative part of all types in the igvn's type table
4098
igvn.remove_speculative_types();
4099
if (modified > 0) {
4100
igvn.optimize();
4101
}
4102
#ifdef ASSERT
4103
// Verify that after the IGVN is over no speculative type has resurfaced
4104
worklist.clear();
4105
worklist.push(root());
4106
for (uint next = 0; next < worklist.size(); ++next) {
4107
Node *n = worklist.at(next);
4108
const Type* t = igvn.type_or_null(n);
4109
assert((t == NULL) || (t == t->remove_speculative()), "no more speculative types");
4110
if (n->is_Type()) {
4111
t = n->as_Type()->type();
4112
assert(t == t->remove_speculative(), "no more speculative types");
4113
}
4114
uint max = n->len();
4115
for( uint i = 0; i < max; ++i ) {
4116
Node *m = n->in(i);
4117
if (not_a_node(m)) continue;
4118
worklist.push(m);
4119
}
4120
}
4121
igvn.check_no_speculative_types();
4122
#endif
4123
}
4124
}
4125
4126
// Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
4127
Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl) {
4128
if (ctrl != NULL) {
4129
// Express control dependency by a CastII node with a narrow type.
4130
value = new (phase->C) CastIINode(value, itype, false, true /* range check dependency */);
4131
// Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
4132
// node from floating above the range check during loop optimizations. Otherwise, the
4133
// ConvI2L node may be eliminated independently of the range check, causing the data path
4134
// to become TOP while the control path is still there (although it's unreachable).
4135
value->set_req(0, ctrl);
4136
// Save CastII node to remove it after loop optimizations.
4137
phase->C->add_range_check_cast(value);
4138
value = phase->transform(value);
4139
}
4140
const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
4141
return phase->transform(new (phase->C) ConvI2LNode(value, ltype));
4142
}
4143
4144
// Auxiliary method to support randomized stressing/fuzzing.
4145
//
4146
// This method can be called the arbitrary number of times, with current count
4147
// as the argument. The logic allows selecting a single candidate from the
4148
// running list of candidates as follows:
4149
// int count = 0;
4150
// Cand* selected = null;
4151
// while(cand = cand->next()) {
4152
// if (randomized_select(++count)) {
4153
// selected = cand;
4154
// }
4155
// }
4156
//
4157
// Including count equalizes the chances any candidate is "selected".
4158
// This is useful when we don't have the complete list of candidates to choose
4159
// from uniformly. In this case, we need to adjust the randomicity of the
4160
// selection, or else we will end up biasing the selection towards the latter
4161
// candidates.
4162
//
4163
// Quick back-envelope calculation shows that for the list of n candidates
4164
// the equal probability for the candidate to persist as "best" can be
4165
// achieved by replacing it with "next" k-th candidate with the probability
4166
// of 1/k. It can be easily shown that by the end of the run, the
4167
// probability for any candidate is converged to 1/n, thus giving the
4168
// uniform distribution among all the candidates.
4169
//
4170
// We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
4171
#define RANDOMIZED_DOMAIN_POW 29
4172
#define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
4173
#define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
4174
bool Compile::randomized_select(int count) {
4175
assert(count > 0, "only positive");
4176
return (os::random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
4177
}
4178
4179