1 /*
2 * Copyright (c) 1997, 2020, 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/javaClasses.hpp"
30 #include "code/exceptionHandlerTable.hpp"
31 #include "code/nmethod.hpp"
32 #include "compiler/compileBroker.hpp"
33 #include "compiler/compileLog.hpp"
34 #include "compiler/disassembler.hpp"
35 #include "compiler/oopMap.hpp"
36 #include "gc/shared/barrierSet.hpp"
37 #include "gc/shared/c2/barrierSetC2.hpp"
38 #include "jfr/jfrEvents.hpp"
39 #include "memory/resourceArea.hpp"
40 #include "opto/addnode.hpp"
41 #include "opto/block.hpp"
42 #include "opto/c2compiler.hpp"
43 #include "opto/callGenerator.hpp"
44 #include "opto/callnode.hpp"
45 #include "opto/castnode.hpp"
46 #include "opto/cfgnode.hpp"
47 #include "opto/chaitin.hpp"
48 #include "opto/compile.hpp"
49 #include "opto/connode.hpp"
50 #include "opto/convertnode.hpp"
51 #include "opto/divnode.hpp"
52 #include "opto/escape.hpp"
53 #include "opto/idealGraphPrinter.hpp"
54 #include "opto/loopnode.hpp"
55 #include "opto/machnode.hpp"
56 #include "opto/macro.hpp"
57 #include "opto/matcher.hpp"
58 #include "opto/mathexactnode.hpp"
59 #include "opto/memnode.hpp"
60 #include "opto/mulnode.hpp"
61 #include "opto/narrowptrnode.hpp"
62 #include "opto/node.hpp"
63 #include "opto/opcodes.hpp"
64 #include "opto/output.hpp"
65 #include "opto/parse.hpp"
66 #include "opto/phaseX.hpp"
67 #include "opto/rootnode.hpp"
68 #include "opto/runtime.hpp"
69 #include "opto/stringopts.hpp"
70 #include "opto/type.hpp"
71 #include "opto/vector.hpp"
72 #include "opto/vectornode.hpp"
73 #include "runtime/arguments.hpp"
74 #include "runtime/globals_extension.hpp"
75 #include "runtime/sharedRuntime.hpp"
76 #include "runtime/signature.hpp"
77 #include "runtime/stubRoutines.hpp"
78 #include "runtime/timer.hpp"
79 #include "utilities/align.hpp"
80 #include "utilities/copy.hpp"
81 #include "utilities/macros.hpp"
82 #include "utilities/resourceHash.hpp"
83
84
85 // -------------------- Compile::mach_constant_base_node -----------------------
86 // Constant table base node singleton.
mach_constant_base_node()87 MachConstantBaseNode* Compile::mach_constant_base_node() {
88 if (_mach_constant_base_node == NULL) {
89 _mach_constant_base_node = new MachConstantBaseNode();
90 _mach_constant_base_node->add_req(C->root());
91 }
92 return _mach_constant_base_node;
93 }
94
95
96 /// Support for intrinsics.
97
98 // Return the index at which m must be inserted (or already exists).
99 // The sort order is by the address of the ciMethod, with is_virtual as minor key.
100 class IntrinsicDescPair {
101 private:
102 ciMethod* _m;
103 bool _is_virtual;
104 public:
IntrinsicDescPair(ciMethod * m,bool is_virtual)105 IntrinsicDescPair(ciMethod* m, bool is_virtual) : _m(m), _is_virtual(is_virtual) {}
compare(IntrinsicDescPair * const & key,CallGenerator * const & elt)106 static int compare(IntrinsicDescPair* const& key, CallGenerator* const& elt) {
107 ciMethod* m= elt->method();
108 ciMethod* key_m = key->_m;
109 if (key_m < m) return -1;
110 else if (key_m > m) return 1;
111 else {
112 bool is_virtual = elt->is_virtual();
113 bool key_virtual = key->_is_virtual;
114 if (key_virtual < is_virtual) return -1;
115 else if (key_virtual > is_virtual) return 1;
116 else return 0;
117 }
118 }
119 };
intrinsic_insertion_index(ciMethod * m,bool is_virtual,bool & found)120 int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual, bool& found) {
121 #ifdef ASSERT
122 for (int i = 1; i < _intrinsics.length(); i++) {
123 CallGenerator* cg1 = _intrinsics.at(i-1);
124 CallGenerator* cg2 = _intrinsics.at(i);
125 assert(cg1->method() != cg2->method()
126 ? cg1->method() < cg2->method()
127 : cg1->is_virtual() < cg2->is_virtual(),
128 "compiler intrinsics list must stay sorted");
129 }
130 #endif
131 IntrinsicDescPair pair(m, is_virtual);
132 return _intrinsics.find_sorted<IntrinsicDescPair*, IntrinsicDescPair::compare>(&pair, found);
133 }
134
register_intrinsic(CallGenerator * cg)135 void Compile::register_intrinsic(CallGenerator* cg) {
136 bool found = false;
137 int index = intrinsic_insertion_index(cg->method(), cg->is_virtual(), found);
138 assert(!found, "registering twice");
139 _intrinsics.insert_before(index, cg);
140 assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked");
141 }
142
find_intrinsic(ciMethod * m,bool is_virtual)143 CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) {
144 assert(m->is_loaded(), "don't try this on unloaded methods");
145 if (_intrinsics.length() > 0) {
146 bool found = false;
147 int index = intrinsic_insertion_index(m, is_virtual, found);
148 if (found) {
149 return _intrinsics.at(index);
150 }
151 }
152 // Lazily create intrinsics for intrinsic IDs well-known in the runtime.
153 if (m->intrinsic_id() != vmIntrinsics::_none &&
154 m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) {
155 CallGenerator* cg = make_vm_intrinsic(m, is_virtual);
156 if (cg != NULL) {
157 // Save it for next time:
158 register_intrinsic(cg);
159 return cg;
160 } else {
161 gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled);
162 }
163 }
164 return NULL;
165 }
166
167 // Compile::make_vm_intrinsic is defined in library_call.cpp.
168
169 #ifndef PRODUCT
170 // statistics gathering...
171
172 juint Compile::_intrinsic_hist_count[vmIntrinsics::number_of_intrinsics()] = {0};
173 jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::number_of_intrinsics()] = {0};
174
as_int(vmIntrinsics::ID id)175 inline int as_int(vmIntrinsics::ID id) {
176 return vmIntrinsics::as_int(id);
177 }
178
gather_intrinsic_statistics(vmIntrinsics::ID id,bool is_virtual,int flags)179 bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) {
180 assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob");
181 int oflags = _intrinsic_hist_flags[as_int(id)];
182 assert(flags != 0, "what happened?");
183 if (is_virtual) {
184 flags |= _intrinsic_virtual;
185 }
186 bool changed = (flags != oflags);
187 if ((flags & _intrinsic_worked) != 0) {
188 juint count = (_intrinsic_hist_count[as_int(id)] += 1);
189 if (count == 1) {
190 changed = true; // first time
191 }
192 // increment the overall count also:
193 _intrinsic_hist_count[as_int(vmIntrinsics::_none)] += 1;
194 }
195 if (changed) {
196 if (((oflags ^ flags) & _intrinsic_virtual) != 0) {
197 // Something changed about the intrinsic's virtuality.
198 if ((flags & _intrinsic_virtual) != 0) {
199 // This is the first use of this intrinsic as a virtual call.
200 if (oflags != 0) {
201 // We already saw it as a non-virtual, so note both cases.
202 flags |= _intrinsic_both;
203 }
204 } else if ((oflags & _intrinsic_both) == 0) {
205 // This is the first use of this intrinsic as a non-virtual
206 flags |= _intrinsic_both;
207 }
208 }
209 _intrinsic_hist_flags[as_int(id)] = (jubyte) (oflags | flags);
210 }
211 // update the overall flags also:
212 _intrinsic_hist_flags[as_int(vmIntrinsics::_none)] |= (jubyte) flags;
213 return changed;
214 }
215
format_flags(int flags,char * buf)216 static char* format_flags(int flags, char* buf) {
217 buf[0] = 0;
218 if ((flags & Compile::_intrinsic_worked) != 0) strcat(buf, ",worked");
219 if ((flags & Compile::_intrinsic_failed) != 0) strcat(buf, ",failed");
220 if ((flags & Compile::_intrinsic_disabled) != 0) strcat(buf, ",disabled");
221 if ((flags & Compile::_intrinsic_virtual) != 0) strcat(buf, ",virtual");
222 if ((flags & Compile::_intrinsic_both) != 0) strcat(buf, ",nonvirtual");
223 if (buf[0] == 0) strcat(buf, ",");
224 assert(buf[0] == ',', "must be");
225 return &buf[1];
226 }
227
print_intrinsic_statistics()228 void Compile::print_intrinsic_statistics() {
229 char flagsbuf[100];
230 ttyLocker ttyl;
231 if (xtty != NULL) xtty->head("statistics type='intrinsic'");
232 tty->print_cr("Compiler intrinsic usage:");
233 juint total = _intrinsic_hist_count[as_int(vmIntrinsics::_none)];
234 if (total == 0) total = 1; // avoid div0 in case of no successes
235 #define PRINT_STAT_LINE(name, c, f) \
236 tty->print_cr(" %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f);
237 for (vmIntrinsicsIterator it = vmIntrinsicsRange.begin(); it != vmIntrinsicsRange.end(); ++it) {
238 vmIntrinsicID id = *it;
239 int flags = _intrinsic_hist_flags[as_int(id)];
240 juint count = _intrinsic_hist_count[as_int(id)];
241 if ((flags | count) != 0) {
242 PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf));
243 }
244 }
245 PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[as_int(vmIntrinsics::_none)], flagsbuf));
246 if (xtty != NULL) xtty->tail("statistics");
247 }
248
print_statistics()249 void Compile::print_statistics() {
250 { ttyLocker ttyl;
251 if (xtty != NULL) xtty->head("statistics type='opto'");
252 Parse::print_statistics();
253 PhaseCCP::print_statistics();
254 PhaseRegAlloc::print_statistics();
255 PhaseOutput::print_statistics();
256 PhasePeephole::print_statistics();
257 PhaseIdealLoop::print_statistics();
258 if (xtty != NULL) xtty->tail("statistics");
259 }
260 if (_intrinsic_hist_flags[as_int(vmIntrinsics::_none)] != 0) {
261 // put this under its own <statistics> element.
262 print_intrinsic_statistics();
263 }
264 }
265 #endif //PRODUCT
266
gvn_replace_by(Node * n,Node * nn)267 void Compile::gvn_replace_by(Node* n, Node* nn) {
268 for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) {
269 Node* use = n->last_out(i);
270 bool is_in_table = initial_gvn()->hash_delete(use);
271 uint uses_found = 0;
272 for (uint j = 0; j < use->len(); j++) {
273 if (use->in(j) == n) {
274 if (j < use->req())
275 use->set_req(j, nn);
276 else
277 use->set_prec(j, nn);
278 uses_found++;
279 }
280 }
281 if (is_in_table) {
282 // reinsert into table
283 initial_gvn()->hash_find_insert(use);
284 }
285 record_for_igvn(use);
286 i -= uses_found; // we deleted 1 or more copies of this edge
287 }
288 }
289
290
not_a_node(const Node * n)291 static inline bool not_a_node(const Node* n) {
292 if (n == NULL) return true;
293 if (((intptr_t)n & 1) != 0) return true; // uninitialized, etc.
294 if (*(address*)n == badAddress) return true; // kill by Node::destruct
295 return false;
296 }
297
298 // Identify all nodes that are reachable from below, useful.
299 // Use breadth-first pass that records state in a Unique_Node_List,
300 // recursive traversal is slower.
identify_useful_nodes(Unique_Node_List & useful)301 void Compile::identify_useful_nodes(Unique_Node_List &useful) {
302 int estimated_worklist_size = live_nodes();
303 useful.map( estimated_worklist_size, NULL ); // preallocate space
304
305 // Initialize worklist
306 if (root() != NULL) { useful.push(root()); }
307 // If 'top' is cached, declare it useful to preserve cached node
308 if( cached_top_node() ) { useful.push(cached_top_node()); }
309
310 // Push all useful nodes onto the list, breadthfirst
311 for( uint next = 0; next < useful.size(); ++next ) {
312 assert( next < unique(), "Unique useful nodes < total nodes");
313 Node *n = useful.at(next);
314 uint max = n->len();
315 for( uint i = 0; i < max; ++i ) {
316 Node *m = n->in(i);
317 if (not_a_node(m)) continue;
318 useful.push(m);
319 }
320 }
321 }
322
323 // Update dead_node_list with any missing dead nodes using useful
324 // list. Consider all non-useful nodes to be useless i.e., dead nodes.
update_dead_node_list(Unique_Node_List & useful)325 void Compile::update_dead_node_list(Unique_Node_List &useful) {
326 uint max_idx = unique();
327 VectorSet& useful_node_set = useful.member_set();
328
329 for (uint node_idx = 0; node_idx < max_idx; node_idx++) {
330 // If node with index node_idx is not in useful set,
331 // mark it as dead in dead node list.
332 if (!useful_node_set.test(node_idx)) {
333 record_dead_node(node_idx);
334 }
335 }
336 }
337
remove_useless_late_inlines(GrowableArray<CallGenerator * > * inlines,Unique_Node_List & useful)338 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) {
339 int shift = 0;
340 for (int i = 0; i < inlines->length(); i++) {
341 CallGenerator* cg = inlines->at(i);
342 if (useful.member(cg->call_node())) {
343 if (shift > 0) {
344 inlines->at_put(i - shift, cg);
345 }
346 } else {
347 shift++; // skip over the dead element
348 }
349 }
350 if (shift > 0) {
351 inlines->trunc_to(inlines->length() - shift); // remove last elements from compacted array
352 }
353 }
354
remove_useless_late_inlines(GrowableArray<CallGenerator * > * inlines,Node * dead)355 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Node* dead) {
356 assert(dead != NULL && dead->is_Call(), "sanity");
357 int found = 0;
358 for (int i = 0; i < inlines->length(); i++) {
359 if (inlines->at(i)->call_node() == dead) {
360 inlines->remove_at(i);
361 found++;
362 NOT_DEBUG( break; ) // elements are unique, so exit early
363 }
364 }
365 assert(found <= 1, "not unique");
366 }
367
remove_useless_nodes(GrowableArray<Node * > & node_list,Unique_Node_List & useful)368 void Compile::remove_useless_nodes(GrowableArray<Node*>& node_list, Unique_Node_List& useful) {
369 for (int i = node_list.length() - 1; i >= 0; i--) {
370 Node* n = node_list.at(i);
371 if (!useful.member(n)) {
372 node_list.delete_at(i); // replaces i-th with last element which is known to be useful (already processed)
373 }
374 }
375 }
376
remove_useless_node(Node * dead)377 void Compile::remove_useless_node(Node* dead) {
378 remove_modified_node(dead);
379
380 // Constant node that has no out-edges and has only one in-edge from
381 // root is usually dead. However, sometimes reshaping walk makes
382 // it reachable by adding use edges. So, we will NOT count Con nodes
383 // as dead to be conservative about the dead node count at any
384 // given time.
385 if (!dead->is_Con()) {
386 record_dead_node(dead->_idx);
387 }
388 if (dead->is_macro()) {
389 remove_macro_node(dead);
390 }
391 if (dead->is_expensive()) {
392 remove_expensive_node(dead);
393 }
394 if (dead->for_post_loop_opts_igvn()) {
395 remove_from_post_loop_opts_igvn(dead);
396 }
397 if (dead->is_Call()) {
398 remove_useless_late_inlines( &_late_inlines, dead);
399 remove_useless_late_inlines( &_string_late_inlines, dead);
400 remove_useless_late_inlines( &_boxing_late_inlines, dead);
401 remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead);
402 }
403 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
404 bs->unregister_potential_barrier_node(dead);
405 }
406
407 // Disconnect all useless nodes by disconnecting those at the boundary.
remove_useless_nodes(Unique_Node_List & useful)408 void Compile::remove_useless_nodes(Unique_Node_List &useful) {
409 uint next = 0;
410 while (next < useful.size()) {
411 Node *n = useful.at(next++);
412 if (n->is_SafePoint()) {
413 // We're done with a parsing phase. Replaced nodes are not valid
414 // beyond that point.
415 n->as_SafePoint()->delete_replaced_nodes();
416 }
417 // Use raw traversal of out edges since this code removes out edges
418 int max = n->outcnt();
419 for (int j = 0; j < max; ++j) {
420 Node* child = n->raw_out(j);
421 if (!useful.member(child)) {
422 assert(!child->is_top() || child != top(),
423 "If top is cached in Compile object it is in useful list");
424 // Only need to remove this out-edge to the useless node
425 n->raw_del_out(j);
426 --j;
427 --max;
428 }
429 }
430 if (n->outcnt() == 1 && n->has_special_unique_user()) {
431 record_for_igvn(n->unique_out());
432 }
433 }
434
435 remove_useless_nodes(_macro_nodes, useful); // remove useless macro and predicate opaq nodes
436 remove_useless_nodes(_expensive_nodes, useful); // remove useless expensive nodes
437 remove_useless_nodes(_for_post_loop_igvn, useful); // remove useless node recorded for post loop opts IGVN pass
438
439 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
440 bs->eliminate_useless_gc_barriers(useful, this);
441 // clean up the late inline lists
442 remove_useless_late_inlines( &_late_inlines, useful);
443 remove_useless_late_inlines( &_string_late_inlines, useful);
444 remove_useless_late_inlines( &_boxing_late_inlines, useful);
445 remove_useless_late_inlines(&_vector_reboxing_late_inlines, useful);
446 debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
447 }
448
449 // ============================================================================
450 //------------------------------CompileWrapper---------------------------------
451 class CompileWrapper : public StackObj {
452 Compile *const _compile;
453 public:
454 CompileWrapper(Compile* compile);
455
456 ~CompileWrapper();
457 };
458
CompileWrapper(Compile * compile)459 CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) {
460 // the Compile* pointer is stored in the current ciEnv:
461 ciEnv* env = compile->env();
462 assert(env == ciEnv::current(), "must already be a ciEnv active");
463 assert(env->compiler_data() == NULL, "compile already active?");
464 env->set_compiler_data(compile);
465 assert(compile == Compile::current(), "sanity");
466
467 compile->set_type_dict(NULL);
468 compile->set_clone_map(new Dict(cmpkey, hashkey, _compile->comp_arena()));
469 compile->clone_map().set_clone_idx(0);
470 compile->set_type_last_size(0);
471 compile->set_last_tf(NULL, NULL);
472 compile->set_indexSet_arena(NULL);
473 compile->set_indexSet_free_block_list(NULL);
474 compile->init_type_arena();
475 Type::Initialize(compile);
476 _compile->begin_method();
477 _compile->clone_map().set_debug(_compile->has_method() && _compile->directive()->CloneMapDebugOption);
478 }
~CompileWrapper()479 CompileWrapper::~CompileWrapper() {
480 _compile->end_method();
481 _compile->env()->set_compiler_data(NULL);
482 }
483
484
485 //----------------------------print_compile_messages---------------------------
print_compile_messages()486 void Compile::print_compile_messages() {
487 #ifndef PRODUCT
488 // Check if recompiling
489 if (_subsume_loads == false && PrintOpto) {
490 // Recompiling without allowing machine instructions to subsume loads
491 tty->print_cr("*********************************************************");
492 tty->print_cr("** Bailout: Recompile without subsuming loads **");
493 tty->print_cr("*********************************************************");
494 }
495 if (_do_escape_analysis != DoEscapeAnalysis && PrintOpto) {
496 // Recompiling without escape analysis
497 tty->print_cr("*********************************************************");
498 tty->print_cr("** Bailout: Recompile without escape analysis **");
499 tty->print_cr("*********************************************************");
500 }
501 if (_eliminate_boxing != EliminateAutoBox && PrintOpto) {
502 // Recompiling without boxing elimination
503 tty->print_cr("*********************************************************");
504 tty->print_cr("** Bailout: Recompile without boxing elimination **");
505 tty->print_cr("*********************************************************");
506 }
507 if (C->directive()->BreakAtCompileOption) {
508 // Open the debugger when compiling this method.
509 tty->print("### Breaking when compiling: ");
510 method()->print_short_name();
511 tty->cr();
512 BREAKPOINT;
513 }
514
515 if( PrintOpto ) {
516 if (is_osr_compilation()) {
517 tty->print("[OSR]%3d", _compile_id);
518 } else {
519 tty->print("%3d", _compile_id);
520 }
521 }
522 #endif
523 }
524
525 // ============================================================================
526 //------------------------------Compile standard-------------------------------
debug_only(int Compile::_debug_idx=100000;)527 debug_only( int Compile::_debug_idx = 100000; )
528
529 // Compile a method. entry_bci is -1 for normal compilations and indicates
530 // the continuation bci for on stack replacement.
531
532
533 Compile::Compile( ciEnv* ci_env, ciMethod* target, int osr_bci,
534 bool subsume_loads, bool do_escape_analysis, bool eliminate_boxing, bool install_code, DirectiveSet* directive)
535 : Phase(Compiler),
536 _compile_id(ci_env->compile_id()),
537 _save_argument_registers(false),
538 _subsume_loads(subsume_loads),
539 _do_escape_analysis(do_escape_analysis),
540 _install_code(install_code),
541 _eliminate_boxing(eliminate_boxing),
542 _method(target),
543 _entry_bci(osr_bci),
544 _stub_function(NULL),
545 _stub_name(NULL),
546 _stub_entry_point(NULL),
547 _max_node_limit(MaxNodeLimit),
548 _post_loop_opts_phase(false),
549 _inlining_progress(false),
550 _inlining_incrementally(false),
551 _do_cleanup(false),
552 _has_reserved_stack_access(target->has_reserved_stack_access()),
553 #ifndef PRODUCT
554 _trace_opto_output(directive->TraceOptoOutputOption),
555 _print_ideal(directive->PrintIdealOption),
556 #endif
557 _has_method_handle_invokes(false),
558 _clinit_barrier_on_entry(false),
559 _stress_seed(0),
560 _comp_arena(mtCompiler),
561 _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
562 _env(ci_env),
563 _directive(directive),
564 _log(ci_env->log()),
565 _failure_reason(NULL),
566 _intrinsics (comp_arena(), 0, 0, NULL),
567 _macro_nodes (comp_arena(), 8, 0, NULL),
568 _predicate_opaqs (comp_arena(), 8, 0, NULL),
569 _expensive_nodes (comp_arena(), 8, 0, NULL),
570 _for_post_loop_igvn(comp_arena(), 8, 0, NULL),
571 _congraph(NULL),
572 NOT_PRODUCT(_printer(NULL) COMMA)
573 _dead_node_list(comp_arena()),
574 _dead_node_count(0),
575 _node_arena(mtCompiler),
576 _old_arena(mtCompiler),
577 _mach_constant_base_node(NULL),
578 _Compile_types(mtCompiler),
579 _initial_gvn(NULL),
580 _for_igvn(NULL),
581 _warm_calls(NULL),
582 _late_inlines(comp_arena(), 2, 0, NULL),
583 _string_late_inlines(comp_arena(), 2, 0, NULL),
584 _boxing_late_inlines(comp_arena(), 2, 0, NULL),
585 _vector_reboxing_late_inlines(comp_arena(), 2, 0, NULL),
586 _late_inlines_pos(0),
587 _number_of_mh_late_inlines(0),
588 _native_invokers(comp_arena(), 1, 0, NULL),
589 _print_inlining_stream(NULL),
590 _print_inlining_list(NULL),
591 _print_inlining_idx(0),
592 _print_inlining_output(NULL),
593 _replay_inline_data(NULL),
594 _java_calls(0),
595 _inner_loops(0),
596 _interpreter_frame_size(0)
597 #ifndef PRODUCT
598 , _in_dump_cnt(0)
599 #endif
600 {
601 C = this;
602 CompileWrapper cw(this);
603
604 if (CITimeVerbose) {
605 tty->print(" ");
606 target->holder()->name()->print();
607 tty->print(".");
608 target->print_short_name();
609 tty->print(" ");
610 }
611 TraceTime t1("Total compilation time", &_t_totalCompilation, CITime, CITimeVerbose);
612 TraceTime t2(NULL, &_t_methodCompilation, CITime, false);
613
614 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
615 bool print_opto_assembly = directive->PrintOptoAssemblyOption;
616 // We can always print a disassembly, either abstract (hex dump) or
617 // with the help of a suitable hsdis library. Thus, we should not
618 // couple print_assembly and print_opto_assembly controls.
619 // But: always print opto and regular assembly on compile command 'print'.
620 bool print_assembly = directive->PrintAssemblyOption;
621 set_print_assembly(print_opto_assembly || print_assembly);
622 #else
623 set_print_assembly(false); // must initialize.
624 #endif
625
626 #ifndef PRODUCT
627 set_parsed_irreducible_loop(false);
628
629 if (directive->ReplayInlineOption) {
630 _replay_inline_data = ciReplay::load_inline_data(method(), entry_bci(), ci_env->comp_level());
631 }
632 #endif
633 set_print_inlining(directive->PrintInliningOption || PrintOptoInlining);
634 set_print_intrinsics(directive->PrintIntrinsicsOption);
635 set_has_irreducible_loop(true); // conservative until build_loop_tree() reset it
636
637 if (ProfileTraps RTM_OPT_ONLY( || UseRTMLocking )) {
638 // Make sure the method being compiled gets its own MDO,
639 // so we can at least track the decompile_count().
640 // Need MDO to record RTM code generation state.
641 method()->ensure_method_data();
642 }
643
644 Init(::AliasLevel);
645
646
647 print_compile_messages();
648
649 _ilt = InlineTree::build_inline_tree_root();
650
651 // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
652 assert(num_alias_types() >= AliasIdxRaw, "");
653
654 #define MINIMUM_NODE_HASH 1023
655 // Node list that Iterative GVN will start with
656 Unique_Node_List for_igvn(comp_arena());
657 set_for_igvn(&for_igvn);
658
659 // GVN that will be run immediately on new nodes
660 uint estimated_size = method()->code_size()*4+64;
661 estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
662 PhaseGVN gvn(node_arena(), estimated_size);
663 set_initial_gvn(&gvn);
664
665 print_inlining_init();
666 { // Scope for timing the parser
667 TracePhase tp("parse", &timers[_t_parser]);
668
669 // Put top into the hash table ASAP.
670 initial_gvn()->transform_no_reclaim(top());
671
672 // Set up tf(), start(), and find a CallGenerator.
673 CallGenerator* cg = NULL;
674 if (is_osr_compilation()) {
675 const TypeTuple *domain = StartOSRNode::osr_domain();
676 const TypeTuple *range = TypeTuple::make_range(method()->signature());
677 init_tf(TypeFunc::make(domain, range));
678 StartNode* s = new StartOSRNode(root(), domain);
679 initial_gvn()->set_type_bottom(s);
680 init_start(s);
681 cg = CallGenerator::for_osr(method(), entry_bci());
682 } else {
683 // Normal case.
684 init_tf(TypeFunc::make(method()));
685 StartNode* s = new StartNode(root(), tf()->domain());
686 initial_gvn()->set_type_bottom(s);
687 init_start(s);
688 if (method()->intrinsic_id() == vmIntrinsics::_Reference_get) {
689 // With java.lang.ref.reference.get() we must go through the
690 // intrinsic - even when get() is the root
691 // method of the compile - so that, if necessary, the value in
692 // the referent field of the reference object gets recorded by
693 // the pre-barrier code.
694 cg = find_intrinsic(method(), false);
695 }
696 if (cg == NULL) {
697 float past_uses = method()->interpreter_invocation_count();
698 float expected_uses = past_uses;
699 cg = CallGenerator::for_inline(method(), expected_uses);
700 }
701 }
702 if (failing()) return;
703 if (cg == NULL) {
704 record_method_not_compilable("cannot parse method");
705 return;
706 }
707 JVMState* jvms = build_start_state(start(), tf());
708 if ((jvms = cg->generate(jvms)) == NULL) {
709 if (!failure_reason_is(C2Compiler::retry_class_loading_during_parsing())) {
710 record_method_not_compilable("method parse failed");
711 }
712 return;
713 }
714 GraphKit kit(jvms);
715
716 if (!kit.stopped()) {
717 // Accept return values, and transfer control we know not where.
718 // This is done by a special, unique ReturnNode bound to root.
719 return_values(kit.jvms());
720 }
721
722 if (kit.has_exceptions()) {
723 // Any exceptions that escape from this call must be rethrown
724 // to whatever caller is dynamically above us on the stack.
725 // This is done by a special, unique RethrowNode bound to root.
726 rethrow_exceptions(kit.transfer_exceptions_into_jvms());
727 }
728
729 assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off");
730
731 if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) {
732 inline_string_calls(true);
733 }
734
735 if (failing()) return;
736
737 print_method(PHASE_BEFORE_REMOVEUSELESS, 3);
738
739 // Remove clutter produced by parsing.
740 if (!failing()) {
741 ResourceMark rm;
742 PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
743 }
744 }
745
746 // Note: Large methods are capped off in do_one_bytecode().
747 if (failing()) return;
748
749 // After parsing, node notes are no longer automagic.
750 // They must be propagated by register_new_node_with_optimizer(),
751 // clone(), or the like.
752 set_default_node_notes(NULL);
753
754 for (;;) {
755 int successes = Inline_Warm();
756 if (failing()) return;
757 if (successes == 0) break;
758 }
759
760 // Drain the list.
761 Finish_Warm();
762 #ifndef PRODUCT
763 if (should_print(1)) {
764 _printer->print_inlining();
765 }
766 #endif
767
768 if (failing()) return;
769 NOT_PRODUCT( verify_graph_edges(); )
770
771 // If LCM, GCM, or IGVN are randomized for stress testing, seed
772 // random number generation and log the seed for repeatability.
773 if (StressLCM || StressGCM || StressIGVN) {
774 _stress_seed = FLAG_IS_DEFAULT(StressSeed) ?
775 static_cast<uint>(Ticks::now().nanoseconds()) : StressSeed;
776 if (_log != NULL) {
777 _log->elem("stress_test seed='%u'", _stress_seed);
778 } else if (FLAG_IS_DEFAULT(StressSeed)) {
779 tty->print_cr("Warning: set +LogCompilation to log the seed.");
780 }
781 }
782
783 // Now optimize
784 Optimize();
785 if (failing()) return;
786 NOT_PRODUCT( verify_graph_edges(); )
787
788 #ifndef PRODUCT
789 if (print_ideal()) {
790 ttyLocker ttyl; // keep the following output all in one block
791 // This output goes directly to the tty, not the compiler log.
792 // To enable tools to match it up with the compilation activity,
793 // be sure to tag this tty output with the compile ID.
794 if (xtty != NULL) {
795 xtty->head("ideal compile_id='%d'%s", compile_id(),
796 is_osr_compilation() ? " compile_kind='osr'" :
797 "");
798 }
799 root()->dump(9999);
800 if (xtty != NULL) {
801 xtty->tail("ideal");
802 }
803 }
804 #endif
805
806 #ifdef ASSERT
807 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
808 bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen);
809 #endif
810
811 // Dump compilation data to replay it.
812 if (directive->DumpReplayOption) {
813 env()->dump_replay_data(_compile_id);
814 }
815 if (directive->DumpInlineOption && (ilt() != NULL)) {
816 env()->dump_inline_data(_compile_id);
817 }
818
819 // Now that we know the size of all the monitors we can add a fixed slot
820 // for the original deopt pc.
821 int next_slot = fixed_slots() + (sizeof(address) / VMRegImpl::stack_slot_size);
822 set_fixed_slots(next_slot);
823
824 // Compute when to use implicit null checks. Used by matching trap based
825 // nodes and NullCheck optimization.
826 set_allowed_deopt_reasons();
827
828 // Now generate code
829 Code_Gen();
830 }
831
832 //------------------------------Compile----------------------------------------
833 // Compile a runtime stub
Compile(ciEnv * ci_env,TypeFunc_generator generator,address stub_function,const char * stub_name,int is_fancy_jump,bool pass_tls,bool save_arg_registers,bool return_pc,DirectiveSet * directive)834 Compile::Compile( ciEnv* ci_env,
835 TypeFunc_generator generator,
836 address stub_function,
837 const char *stub_name,
838 int is_fancy_jump,
839 bool pass_tls,
840 bool save_arg_registers,
841 bool return_pc,
842 DirectiveSet* directive)
843 : Phase(Compiler),
844 _compile_id(0),
845 _save_argument_registers(save_arg_registers),
846 _subsume_loads(true),
847 _do_escape_analysis(false),
848 _install_code(true),
849 _eliminate_boxing(false),
850 _method(NULL),
851 _entry_bci(InvocationEntryBci),
852 _stub_function(stub_function),
853 _stub_name(stub_name),
854 _stub_entry_point(NULL),
855 _max_node_limit(MaxNodeLimit),
856 _post_loop_opts_phase(false),
857 _inlining_progress(false),
858 _inlining_incrementally(false),
859 _has_reserved_stack_access(false),
860 #ifndef PRODUCT
861 _trace_opto_output(directive->TraceOptoOutputOption),
862 _print_ideal(directive->PrintIdealOption),
863 #endif
864 _has_method_handle_invokes(false),
865 _clinit_barrier_on_entry(false),
866 _stress_seed(0),
867 _comp_arena(mtCompiler),
868 _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
869 _env(ci_env),
870 _directive(directive),
871 _log(ci_env->log()),
872 _failure_reason(NULL),
873 _congraph(NULL),
874 NOT_PRODUCT(_printer(NULL) COMMA)
875 _dead_node_list(comp_arena()),
876 _dead_node_count(0),
877 _node_arena(mtCompiler),
878 _old_arena(mtCompiler),
879 _mach_constant_base_node(NULL),
880 _Compile_types(mtCompiler),
881 _initial_gvn(NULL),
882 _for_igvn(NULL),
883 _warm_calls(NULL),
884 _number_of_mh_late_inlines(0),
885 _native_invokers(),
886 _print_inlining_stream(NULL),
887 _print_inlining_list(NULL),
888 _print_inlining_idx(0),
889 _print_inlining_output(NULL),
890 _replay_inline_data(NULL),
891 _java_calls(0),
892 _inner_loops(0),
893 _interpreter_frame_size(0),
894 #ifndef PRODUCT
895 _in_dump_cnt(0),
896 #endif
897 _allowed_reasons(0) {
898 C = this;
899
900 TraceTime t1(NULL, &_t_totalCompilation, CITime, false);
901 TraceTime t2(NULL, &_t_stubCompilation, CITime, false);
902
903 #ifndef PRODUCT
904 set_print_assembly(PrintFrameConverterAssembly);
905 set_parsed_irreducible_loop(false);
906 #else
907 set_print_assembly(false); // Must initialize.
908 #endif
909 set_has_irreducible_loop(false); // no loops
910
911 CompileWrapper cw(this);
912 Init(/*AliasLevel=*/ 0);
913 init_tf((*generator)());
914
915 {
916 // The following is a dummy for the sake of GraphKit::gen_stub
917 Unique_Node_List for_igvn(comp_arena());
918 set_for_igvn(&for_igvn); // not used, but some GraphKit guys push on this
919 PhaseGVN gvn(Thread::current()->resource_area(),255);
920 set_initial_gvn(&gvn); // not significant, but GraphKit guys use it pervasively
921 gvn.transform_no_reclaim(top());
922
923 GraphKit kit;
924 kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc);
925 }
926
927 NOT_PRODUCT( verify_graph_edges(); )
928
929 Code_Gen();
930 }
931
932 //------------------------------Init-------------------------------------------
933 // Prepare for a single compilation
Init(int aliaslevel)934 void Compile::Init(int aliaslevel) {
935 _unique = 0;
936 _regalloc = NULL;
937
938 _tf = NULL; // filled in later
939 _top = NULL; // cached later
940 _matcher = NULL; // filled in later
941 _cfg = NULL; // filled in later
942
943 IA32_ONLY( set_24_bit_selection_and_mode(true, false); )
944
945 _node_note_array = NULL;
946 _default_node_notes = NULL;
947 DEBUG_ONLY( _modified_nodes = NULL; ) // Used in Optimize()
948
949 _immutable_memory = NULL; // filled in at first inquiry
950
951 // Globally visible Nodes
952 // First set TOP to NULL to give safe behavior during creation of RootNode
953 set_cached_top_node(NULL);
954 set_root(new RootNode());
955 // Now that you have a Root to point to, create the real TOP
956 set_cached_top_node( new ConNode(Type::TOP) );
957 set_recent_alloc(NULL, NULL);
958
959 // Create Debug Information Recorder to record scopes, oopmaps, etc.
960 env()->set_oop_recorder(new OopRecorder(env()->arena()));
961 env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder()));
962 env()->set_dependencies(new Dependencies(env()));
963
964 _fixed_slots = 0;
965 set_has_split_ifs(false);
966 set_has_loops(false); // first approximation
967 set_has_stringbuilder(false);
968 set_has_boxed_value(false);
969 _trap_can_recompile = false; // no traps emitted yet
970 _major_progress = true; // start out assuming good things will happen
971 set_has_unsafe_access(false);
972 set_max_vector_size(0);
973 set_clear_upper_avx(false); //false as default for clear upper bits of ymm registers
974 Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
975 set_decompile_count(0);
976
977 set_do_freq_based_layout(_directive->BlockLayoutByFrequencyOption);
978 _loop_opts_cnt = LoopOptsCount;
979 set_do_inlining(Inline);
980 set_max_inline_size(MaxInlineSize);
981 set_freq_inline_size(FreqInlineSize);
982 set_do_scheduling(OptoScheduling);
983
984 set_do_vector_loop(false);
985
986 if (AllowVectorizeOnDemand) {
987 if (has_method() && (_directive->VectorizeOption || _directive->VectorizeDebugOption)) {
988 set_do_vector_loop(true);
989 NOT_PRODUCT(if (do_vector_loop() && Verbose) {tty->print("Compile::Init: do vectorized loops (SIMD like) for method %s\n", method()->name()->as_quoted_ascii());})
990 } else if (has_method() && method()->name() != 0 &&
991 method()->intrinsic_id() == vmIntrinsics::_forEachRemaining) {
992 set_do_vector_loop(true);
993 }
994 }
995 set_use_cmove(UseCMoveUnconditionally /* || do_vector_loop()*/); //TODO: consider do_vector_loop() mandate use_cmove unconditionally
996 NOT_PRODUCT(if (use_cmove() && Verbose && has_method()) {tty->print("Compile::Init: use CMove without profitability tests for method %s\n", method()->name()->as_quoted_ascii());})
997
998 set_age_code(has_method() && method()->profile_aging());
999 set_rtm_state(NoRTM); // No RTM lock eliding by default
1000 _max_node_limit = _directive->MaxNodeLimitOption;
1001
1002 #if INCLUDE_RTM_OPT
1003 if (UseRTMLocking && has_method() && (method()->method_data_or_null() != NULL)) {
1004 int rtm_state = method()->method_data()->rtm_state();
1005 if (method_has_option(CompileCommand::NoRTMLockEliding) || ((rtm_state & NoRTM) != 0)) {
1006 // Don't generate RTM lock eliding code.
1007 set_rtm_state(NoRTM);
1008 } else if (method_has_option(CompileCommand::UseRTMLockEliding) || ((rtm_state & UseRTM) != 0) || !UseRTMDeopt) {
1009 // Generate RTM lock eliding code without abort ratio calculation code.
1010 set_rtm_state(UseRTM);
1011 } else if (UseRTMDeopt) {
1012 // Generate RTM lock eliding code and include abort ratio calculation
1013 // code if UseRTMDeopt is on.
1014 set_rtm_state(ProfileRTM);
1015 }
1016 }
1017 #endif
1018 if (VM_Version::supports_fast_class_init_checks() && has_method() && !is_osr_compilation() && method()->needs_clinit_barrier()) {
1019 set_clinit_barrier_on_entry(true);
1020 }
1021 if (debug_info()->recording_non_safepoints()) {
1022 set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*>
1023 (comp_arena(), 8, 0, NULL));
1024 set_default_node_notes(Node_Notes::make(this));
1025 }
1026
1027 // // -- Initialize types before each compile --
1028 // // Update cached type information
1029 // if( _method && _method->constants() )
1030 // Type::update_loaded_types(_method, _method->constants());
1031
1032 // Init alias_type map.
1033 if (!_do_escape_analysis && aliaslevel == 3)
1034 aliaslevel = 2; // No unique types without escape analysis
1035 _AliasLevel = aliaslevel;
1036 const int grow_ats = 16;
1037 _max_alias_types = grow_ats;
1038 _alias_types = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats);
1039 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, grow_ats);
1040 Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats);
1041 {
1042 for (int i = 0; i < grow_ats; i++) _alias_types[i] = &ats[i];
1043 }
1044 // Initialize the first few types.
1045 _alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL);
1046 _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM);
1047 _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM);
1048 _num_alias_types = AliasIdxRaw+1;
1049 // Zero out the alias type cache.
1050 Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache));
1051 // A NULL adr_type hits in the cache right away. Preload the right answer.
1052 probe_alias_cache(NULL)->_index = AliasIdxTop;
1053
1054 #ifdef ASSERT
1055 _type_verify_symmetry = true;
1056 _phase_optimize_finished = false;
1057 _exception_backedge = false;
1058 #endif
1059 }
1060
1061 //---------------------------init_start----------------------------------------
1062 // Install the StartNode on this compile object.
init_start(StartNode * s)1063 void Compile::init_start(StartNode* s) {
1064 if (failing())
1065 return; // already failing
1066 assert(s == start(), "");
1067 }
1068
1069 /**
1070 * Return the 'StartNode'. We must not have a pending failure, since the ideal graph
1071 * can be in an inconsistent state, i.e., we can get segmentation faults when traversing
1072 * the ideal graph.
1073 */
start() const1074 StartNode* Compile::start() const {
1075 assert (!failing(), "Must not have pending failure. Reason is: %s", failure_reason());
1076 for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
1077 Node* start = root()->fast_out(i);
1078 if (start->is_Start()) {
1079 return start->as_Start();
1080 }
1081 }
1082 fatal("Did not find Start node!");
1083 return NULL;
1084 }
1085
1086 //-------------------------------immutable_memory-------------------------------------
1087 // Access immutable memory
immutable_memory()1088 Node* Compile::immutable_memory() {
1089 if (_immutable_memory != NULL) {
1090 return _immutable_memory;
1091 }
1092 StartNode* s = start();
1093 for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) {
1094 Node *p = s->fast_out(i);
1095 if (p != s && p->as_Proj()->_con == TypeFunc::Memory) {
1096 _immutable_memory = p;
1097 return _immutable_memory;
1098 }
1099 }
1100 ShouldNotReachHere();
1101 return NULL;
1102 }
1103
1104 //----------------------set_cached_top_node------------------------------------
1105 // Install the cached top node, and make sure Node::is_top works correctly.
set_cached_top_node(Node * tn)1106 void Compile::set_cached_top_node(Node* tn) {
1107 if (tn != NULL) verify_top(tn);
1108 Node* old_top = _top;
1109 _top = tn;
1110 // Calling Node::setup_is_top allows the nodes the chance to adjust
1111 // their _out arrays.
1112 if (_top != NULL) _top->setup_is_top();
1113 if (old_top != NULL) old_top->setup_is_top();
1114 assert(_top == NULL || top()->is_top(), "");
1115 }
1116
1117 #ifdef ASSERT
count_live_nodes_by_graph_walk()1118 uint Compile::count_live_nodes_by_graph_walk() {
1119 Unique_Node_List useful(comp_arena());
1120 // Get useful node list by walking the graph.
1121 identify_useful_nodes(useful);
1122 return useful.size();
1123 }
1124
print_missing_nodes()1125 void Compile::print_missing_nodes() {
1126
1127 // Return if CompileLog is NULL and PrintIdealNodeCount is false.
1128 if ((_log == NULL) && (! PrintIdealNodeCount)) {
1129 return;
1130 }
1131
1132 // This is an expensive function. It is executed only when the user
1133 // specifies VerifyIdealNodeCount option or otherwise knows the
1134 // additional work that needs to be done to identify reachable nodes
1135 // by walking the flow graph and find the missing ones using
1136 // _dead_node_list.
1137
1138 Unique_Node_List useful(comp_arena());
1139 // Get useful node list by walking the graph.
1140 identify_useful_nodes(useful);
1141
1142 uint l_nodes = C->live_nodes();
1143 uint l_nodes_by_walk = useful.size();
1144
1145 if (l_nodes != l_nodes_by_walk) {
1146 if (_log != NULL) {
1147 _log->begin_head("mismatched_nodes count='%d'", abs((int) (l_nodes - l_nodes_by_walk)));
1148 _log->stamp();
1149 _log->end_head();
1150 }
1151 VectorSet& useful_member_set = useful.member_set();
1152 int last_idx = l_nodes_by_walk;
1153 for (int i = 0; i < last_idx; i++) {
1154 if (useful_member_set.test(i)) {
1155 if (_dead_node_list.test(i)) {
1156 if (_log != NULL) {
1157 _log->elem("mismatched_node_info node_idx='%d' type='both live and dead'", i);
1158 }
1159 if (PrintIdealNodeCount) {
1160 // Print the log message to tty
1161 tty->print_cr("mismatched_node idx='%d' both live and dead'", i);
1162 useful.at(i)->dump();
1163 }
1164 }
1165 }
1166 else if (! _dead_node_list.test(i)) {
1167 if (_log != NULL) {
1168 _log->elem("mismatched_node_info node_idx='%d' type='neither live nor dead'", i);
1169 }
1170 if (PrintIdealNodeCount) {
1171 // Print the log message to tty
1172 tty->print_cr("mismatched_node idx='%d' type='neither live nor dead'", i);
1173 }
1174 }
1175 }
1176 if (_log != NULL) {
1177 _log->tail("mismatched_nodes");
1178 }
1179 }
1180 }
record_modified_node(Node * n)1181 void Compile::record_modified_node(Node* n) {
1182 if (_modified_nodes != NULL && !_inlining_incrementally && !n->is_Con()) {
1183 _modified_nodes->push(n);
1184 }
1185 }
1186
remove_modified_node(Node * n)1187 void Compile::remove_modified_node(Node* n) {
1188 if (_modified_nodes != NULL) {
1189 _modified_nodes->remove(n);
1190 }
1191 }
1192 #endif
1193
1194 #ifndef PRODUCT
verify_top(Node * tn) const1195 void Compile::verify_top(Node* tn) const {
1196 if (tn != NULL) {
1197 assert(tn->is_Con(), "top node must be a constant");
1198 assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type");
1199 assert(tn->in(0) != NULL, "must have live top node");
1200 }
1201 }
1202 #endif
1203
1204
1205 ///-------------------Managing Per-Node Debug & Profile Info-------------------
1206
grow_node_notes(GrowableArray<Node_Notes * > * arr,int grow_by)1207 void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) {
1208 guarantee(arr != NULL, "");
1209 int num_blocks = arr->length();
1210 if (grow_by < num_blocks) grow_by = num_blocks;
1211 int num_notes = grow_by * _node_notes_block_size;
1212 Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes);
1213 Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes));
1214 while (num_notes > 0) {
1215 arr->append(notes);
1216 notes += _node_notes_block_size;
1217 num_notes -= _node_notes_block_size;
1218 }
1219 assert(num_notes == 0, "exact multiple, please");
1220 }
1221
copy_node_notes_to(Node * dest,Node * source)1222 bool Compile::copy_node_notes_to(Node* dest, Node* source) {
1223 if (source == NULL || dest == NULL) return false;
1224
1225 if (dest->is_Con())
1226 return false; // Do not push debug info onto constants.
1227
1228 #ifdef ASSERT
1229 // Leave a bread crumb trail pointing to the original node:
1230 if (dest != NULL && dest != source && dest->debug_orig() == NULL) {
1231 dest->set_debug_orig(source);
1232 }
1233 #endif
1234
1235 if (node_note_array() == NULL)
1236 return false; // Not collecting any notes now.
1237
1238 // This is a copy onto a pre-existing node, which may already have notes.
1239 // If both nodes have notes, do not overwrite any pre-existing notes.
1240 Node_Notes* source_notes = node_notes_at(source->_idx);
1241 if (source_notes == NULL || source_notes->is_clear()) return false;
1242 Node_Notes* dest_notes = node_notes_at(dest->_idx);
1243 if (dest_notes == NULL || dest_notes->is_clear()) {
1244 return set_node_notes_at(dest->_idx, source_notes);
1245 }
1246
1247 Node_Notes merged_notes = (*source_notes);
1248 // The order of operations here ensures that dest notes will win...
1249 merged_notes.update_from(dest_notes);
1250 return set_node_notes_at(dest->_idx, &merged_notes);
1251 }
1252
1253
1254 //--------------------------allow_range_check_smearing-------------------------
1255 // Gating condition for coalescing similar range checks.
1256 // Sometimes we try 'speculatively' replacing a series of a range checks by a
1257 // single covering check that is at least as strong as any of them.
1258 // If the optimization succeeds, the simplified (strengthened) range check
1259 // will always succeed. If it fails, we will deopt, and then give up
1260 // on the optimization.
allow_range_check_smearing() const1261 bool Compile::allow_range_check_smearing() const {
1262 // If this method has already thrown a range-check,
1263 // assume it was because we already tried range smearing
1264 // and it failed.
1265 uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1266 return !already_trapped;
1267 }
1268
1269
1270 //------------------------------flatten_alias_type-----------------------------
flatten_alias_type(const TypePtr * tj) const1271 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1272 int offset = tj->offset();
1273 TypePtr::PTR ptr = tj->ptr();
1274
1275 // Known instance (scalarizable allocation) alias only with itself.
1276 bool is_known_inst = tj->isa_oopptr() != NULL &&
1277 tj->is_oopptr()->is_known_instance();
1278
1279 // Process weird unsafe references.
1280 if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1281 assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops");
1282 assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1283 tj = TypeOopPtr::BOTTOM;
1284 ptr = tj->ptr();
1285 offset = tj->offset();
1286 }
1287
1288 // Array pointers need some flattening
1289 const TypeAryPtr *ta = tj->isa_aryptr();
1290 if (ta && ta->is_stable()) {
1291 // Erase stability property for alias analysis.
1292 tj = ta = ta->cast_to_stable(false);
1293 }
1294 if( ta && is_known_inst ) {
1295 if ( offset != Type::OffsetBot &&
1296 offset > arrayOopDesc::length_offset_in_bytes() ) {
1297 offset = Type::OffsetBot; // Flatten constant access into array body only
1298 tj = ta = TypeAryPtr::make(ptr, ta->ary(), ta->klass(), true, offset, ta->instance_id());
1299 }
1300 } else if( ta && _AliasLevel >= 2 ) {
1301 // For arrays indexed by constant indices, we flatten the alias
1302 // space to include all of the array body. Only the header, klass
1303 // and array length can be accessed un-aliased.
1304 if( offset != Type::OffsetBot ) {
1305 if( ta->const_oop() ) { // MethodData* or Method*
1306 offset = Type::OffsetBot; // Flatten constant access into array body
1307 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1308 } else if( offset == arrayOopDesc::length_offset_in_bytes() ) {
1309 // range is OK as-is.
1310 tj = ta = TypeAryPtr::RANGE;
1311 } else if( offset == oopDesc::klass_offset_in_bytes() ) {
1312 tj = TypeInstPtr::KLASS; // all klass loads look alike
1313 ta = TypeAryPtr::RANGE; // generic ignored junk
1314 ptr = TypePtr::BotPTR;
1315 } else if( offset == oopDesc::mark_offset_in_bytes() ) {
1316 tj = TypeInstPtr::MARK;
1317 ta = TypeAryPtr::RANGE; // generic ignored junk
1318 ptr = TypePtr::BotPTR;
1319 } else { // Random constant offset into array body
1320 offset = Type::OffsetBot; // Flatten constant access into array body
1321 tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,offset);
1322 }
1323 }
1324 // Arrays of fixed size alias with arrays of unknown size.
1325 if (ta->size() != TypeInt::POS) {
1326 const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS);
1327 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset);
1328 }
1329 // Arrays of known objects become arrays of unknown objects.
1330 if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) {
1331 const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size());
1332 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1333 }
1334 if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) {
1335 const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size());
1336 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1337 }
1338 // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1339 // cannot be distinguished by bytecode alone.
1340 if (ta->elem() == TypeInt::BOOL) {
1341 const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size());
1342 ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE);
1343 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset);
1344 }
1345 // During the 2nd round of IterGVN, NotNull castings are removed.
1346 // Make sure the Bottom and NotNull variants alias the same.
1347 // Also, make sure exact and non-exact variants alias the same.
1348 if (ptr == TypePtr::NotNull || ta->klass_is_exact() || ta->speculative() != NULL) {
1349 tj = ta = TypeAryPtr::make(TypePtr::BotPTR,ta->ary(),ta->klass(),false,offset);
1350 }
1351 }
1352
1353 // Oop pointers need some flattening
1354 const TypeInstPtr *to = tj->isa_instptr();
1355 if( to && _AliasLevel >= 2 && to != TypeOopPtr::BOTTOM ) {
1356 ciInstanceKlass *k = to->klass()->as_instance_klass();
1357 if( ptr == TypePtr::Constant ) {
1358 if (to->klass() != ciEnv::current()->Class_klass() ||
1359 offset < k->size_helper() * wordSize) {
1360 // No constant oop pointers (such as Strings); they alias with
1361 // unknown strings.
1362 assert(!is_known_inst, "not scalarizable allocation");
1363 tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1364 }
1365 } else if( is_known_inst ) {
1366 tj = to; // Keep NotNull and klass_is_exact for instance type
1367 } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1368 // During the 2nd round of IterGVN, NotNull castings are removed.
1369 // Make sure the Bottom and NotNull variants alias the same.
1370 // Also, make sure exact and non-exact variants alias the same.
1371 tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1372 }
1373 if (to->speculative() != NULL) {
1374 tj = to = TypeInstPtr::make(to->ptr(),to->klass(),to->klass_is_exact(),to->const_oop(),to->offset(), to->instance_id());
1375 }
1376 // Canonicalize the holder of this field
1377 if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1378 // First handle header references such as a LoadKlassNode, even if the
1379 // object's klass is unloaded at compile time (4965979).
1380 if (!is_known_inst) { // Do it only for non-instance types
1381 tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset);
1382 }
1383 } else if (offset < 0 || offset >= k->size_helper() * wordSize) {
1384 // Static fields are in the space above the normal instance
1385 // fields in the java.lang.Class instance.
1386 if (to->klass() != ciEnv::current()->Class_klass()) {
1387 to = NULL;
1388 tj = TypeOopPtr::BOTTOM;
1389 offset = tj->offset();
1390 }
1391 } else {
1392 ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset);
1393 if (!k->equals(canonical_holder) || tj->offset() != offset) {
1394 if( is_known_inst ) {
1395 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id());
1396 } else {
1397 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset);
1398 }
1399 }
1400 }
1401 }
1402
1403 // Klass pointers to object array klasses need some flattening
1404 const TypeKlassPtr *tk = tj->isa_klassptr();
1405 if( tk ) {
1406 // If we are referencing a field within a Klass, we need
1407 // to assume the worst case of an Object. Both exact and
1408 // inexact types must flatten to the same alias class so
1409 // use NotNull as the PTR.
1410 if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1411
1412 tj = tk = TypeKlassPtr::make(TypePtr::NotNull,
1413 TypeKlassPtr::OBJECT->klass(),
1414 offset);
1415 }
1416
1417 ciKlass* klass = tk->klass();
1418 if( klass->is_obj_array_klass() ) {
1419 ciKlass* k = TypeAryPtr::OOPS->klass();
1420 if( !k || !k->is_loaded() ) // Only fails for some -Xcomp runs
1421 k = TypeInstPtr::BOTTOM->klass();
1422 tj = tk = TypeKlassPtr::make( TypePtr::NotNull, k, offset );
1423 }
1424
1425 // Check for precise loads from the primary supertype array and force them
1426 // to the supertype cache alias index. Check for generic array loads from
1427 // the primary supertype array and also force them to the supertype cache
1428 // alias index. Since the same load can reach both, we need to merge
1429 // these 2 disparate memories into the same alias class. Since the
1430 // primary supertype array is read-only, there's no chance of confusion
1431 // where we bypass an array load and an array store.
1432 int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1433 if (offset == Type::OffsetBot ||
1434 (offset >= primary_supers_offset &&
1435 offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1436 offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1437 offset = in_bytes(Klass::secondary_super_cache_offset());
1438 tj = tk = TypeKlassPtr::make( TypePtr::NotNull, tk->klass(), offset );
1439 }
1440 }
1441
1442 // Flatten all Raw pointers together.
1443 if (tj->base() == Type::RawPtr)
1444 tj = TypeRawPtr::BOTTOM;
1445
1446 if (tj->base() == Type::AnyPtr)
1447 tj = TypePtr::BOTTOM; // An error, which the caller must check for.
1448
1449 // Flatten all to bottom for now
1450 switch( _AliasLevel ) {
1451 case 0:
1452 tj = TypePtr::BOTTOM;
1453 break;
1454 case 1: // Flatten to: oop, static, field or array
1455 switch (tj->base()) {
1456 //case Type::AryPtr: tj = TypeAryPtr::RANGE; break;
1457 case Type::RawPtr: tj = TypeRawPtr::BOTTOM; break;
1458 case Type::AryPtr: // do not distinguish arrays at all
1459 case Type::InstPtr: tj = TypeInstPtr::BOTTOM; break;
1460 case Type::KlassPtr: tj = TypeKlassPtr::OBJECT; break;
1461 case Type::AnyPtr: tj = TypePtr::BOTTOM; break; // caller checks it
1462 default: ShouldNotReachHere();
1463 }
1464 break;
1465 case 2: // No collapsing at level 2; keep all splits
1466 case 3: // No collapsing at level 3; keep all splits
1467 break;
1468 default:
1469 Unimplemented();
1470 }
1471
1472 offset = tj->offset();
1473 assert( offset != Type::OffsetTop, "Offset has fallen from constant" );
1474
1475 assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) ||
1476 (offset == Type::OffsetBot && tj->base() == Type::AryPtr) ||
1477 (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) ||
1478 (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) ||
1479 (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1480 (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1481 (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr),
1482 "For oops, klasses, raw offset must be constant; for arrays the offset is never known" );
1483 assert( tj->ptr() != TypePtr::TopPTR &&
1484 tj->ptr() != TypePtr::AnyNull &&
1485 tj->ptr() != TypePtr::Null, "No imprecise addresses" );
1486 // assert( tj->ptr() != TypePtr::Constant ||
1487 // tj->base() == Type::RawPtr ||
1488 // tj->base() == Type::KlassPtr, "No constant oop addresses" );
1489
1490 return tj;
1491 }
1492
Init(int i,const TypePtr * at)1493 void Compile::AliasType::Init(int i, const TypePtr* at) {
1494 assert(AliasIdxTop <= i && i < Compile::current()->_max_alias_types, "Invalid alias index");
1495 _index = i;
1496 _adr_type = at;
1497 _field = NULL;
1498 _element = NULL;
1499 _is_rewritable = true; // default
1500 const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL;
1501 if (atoop != NULL && atoop->is_known_instance()) {
1502 const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot);
1503 _general_index = Compile::current()->get_alias_index(gt);
1504 } else {
1505 _general_index = 0;
1506 }
1507 }
1508
basic_type() const1509 BasicType Compile::AliasType::basic_type() const {
1510 if (element() != NULL) {
1511 const Type* element = adr_type()->is_aryptr()->elem();
1512 return element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type();
1513 } if (field() != NULL) {
1514 return field()->layout_type();
1515 } else {
1516 return T_ILLEGAL; // unknown
1517 }
1518 }
1519
1520 //---------------------------------print_on------------------------------------
1521 #ifndef PRODUCT
print_on(outputStream * st)1522 void Compile::AliasType::print_on(outputStream* st) {
1523 if (index() < 10)
1524 st->print("@ <%d> ", index());
1525 else st->print("@ <%d>", index());
1526 st->print(is_rewritable() ? " " : " RO");
1527 int offset = adr_type()->offset();
1528 if (offset == Type::OffsetBot)
1529 st->print(" +any");
1530 else st->print(" +%-3d", offset);
1531 st->print(" in ");
1532 adr_type()->dump_on(st);
1533 const TypeOopPtr* tjp = adr_type()->isa_oopptr();
1534 if (field() != NULL && tjp) {
1535 if (tjp->klass() != field()->holder() ||
1536 tjp->offset() != field()->offset_in_bytes()) {
1537 st->print(" != ");
1538 field()->print();
1539 st->print(" ***");
1540 }
1541 }
1542 }
1543
print_alias_types()1544 void print_alias_types() {
1545 Compile* C = Compile::current();
1546 tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1);
1547 for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) {
1548 C->alias_type(idx)->print_on(tty);
1549 tty->cr();
1550 }
1551 }
1552 #endif
1553
1554
1555 //----------------------------probe_alias_cache--------------------------------
probe_alias_cache(const TypePtr * adr_type)1556 Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) {
1557 intptr_t key = (intptr_t) adr_type;
1558 key ^= key >> logAliasCacheSize;
1559 return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1560 }
1561
1562
1563 //-----------------------------grow_alias_types--------------------------------
grow_alias_types()1564 void Compile::grow_alias_types() {
1565 const int old_ats = _max_alias_types; // how many before?
1566 const int new_ats = old_ats; // how many more?
1567 const int grow_ats = old_ats+new_ats; // how many now?
1568 _max_alias_types = grow_ats;
1569 _alias_types = REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats);
1570 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1571 Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1572 for (int i = 0; i < new_ats; i++) _alias_types[old_ats+i] = &ats[i];
1573 }
1574
1575
1576 //--------------------------------find_alias_type------------------------------
find_alias_type(const TypePtr * adr_type,bool no_create,ciField * original_field)1577 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) {
1578 if (_AliasLevel == 0)
1579 return alias_type(AliasIdxBot);
1580
1581 AliasCacheEntry* ace = probe_alias_cache(adr_type);
1582 if (ace->_adr_type == adr_type) {
1583 return alias_type(ace->_index);
1584 }
1585
1586 // Handle special cases.
1587 if (adr_type == NULL) return alias_type(AliasIdxTop);
1588 if (adr_type == TypePtr::BOTTOM) return alias_type(AliasIdxBot);
1589
1590 // Do it the slow way.
1591 const TypePtr* flat = flatten_alias_type(adr_type);
1592
1593 #ifdef ASSERT
1594 {
1595 ResourceMark rm;
1596 assert(flat == flatten_alias_type(flat), "not idempotent: adr_type = %s; flat = %s => %s",
1597 Type::str(adr_type), Type::str(flat), Type::str(flatten_alias_type(flat)));
1598 assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr: adr_type = %s",
1599 Type::str(adr_type));
1600 if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1601 const TypeOopPtr* foop = flat->is_oopptr();
1602 // Scalarizable allocations have exact klass always.
1603 bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1604 const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr();
1605 assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type: foop = %s; xoop = %s",
1606 Type::str(foop), Type::str(xoop));
1607 }
1608 }
1609 #endif
1610
1611 int idx = AliasIdxTop;
1612 for (int i = 0; i < num_alias_types(); i++) {
1613 if (alias_type(i)->adr_type() == flat) {
1614 idx = i;
1615 break;
1616 }
1617 }
1618
1619 if (idx == AliasIdxTop) {
1620 if (no_create) return NULL;
1621 // Grow the array if necessary.
1622 if (_num_alias_types == _max_alias_types) grow_alias_types();
1623 // Add a new alias type.
1624 idx = _num_alias_types++;
1625 _alias_types[idx]->Init(idx, flat);
1626 if (flat == TypeInstPtr::KLASS) alias_type(idx)->set_rewritable(false);
1627 if (flat == TypeAryPtr::RANGE) alias_type(idx)->set_rewritable(false);
1628 if (flat->isa_instptr()) {
1629 if (flat->offset() == java_lang_Class::klass_offset()
1630 && flat->is_instptr()->klass() == env()->Class_klass())
1631 alias_type(idx)->set_rewritable(false);
1632 }
1633 if (flat->isa_aryptr()) {
1634 #ifdef ASSERT
1635 const int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1636 // (T_BYTE has the weakest alignment and size restrictions...)
1637 assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1638 #endif
1639 if (flat->offset() == TypePtr::OffsetBot) {
1640 alias_type(idx)->set_element(flat->is_aryptr()->elem());
1641 }
1642 }
1643 if (flat->isa_klassptr()) {
1644 if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1645 alias_type(idx)->set_rewritable(false);
1646 if (flat->offset() == in_bytes(Klass::modifier_flags_offset()))
1647 alias_type(idx)->set_rewritable(false);
1648 if (flat->offset() == in_bytes(Klass::access_flags_offset()))
1649 alias_type(idx)->set_rewritable(false);
1650 if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1651 alias_type(idx)->set_rewritable(false);
1652 if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset()))
1653 alias_type(idx)->set_rewritable(false);
1654 }
1655 // %%% (We would like to finalize JavaThread::threadObj_offset(),
1656 // but the base pointer type is not distinctive enough to identify
1657 // references into JavaThread.)
1658
1659 // Check for final fields.
1660 const TypeInstPtr* tinst = flat->isa_instptr();
1661 if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1662 ciField* field;
1663 if (tinst->const_oop() != NULL &&
1664 tinst->klass() == ciEnv::current()->Class_klass() &&
1665 tinst->offset() >= (tinst->klass()->as_instance_klass()->size_helper() * wordSize)) {
1666 // static field
1667 ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1668 field = k->get_field_by_offset(tinst->offset(), true);
1669 } else {
1670 ciInstanceKlass *k = tinst->klass()->as_instance_klass();
1671 field = k->get_field_by_offset(tinst->offset(), false);
1672 }
1673 assert(field == NULL ||
1674 original_field == NULL ||
1675 (field->holder() == original_field->holder() &&
1676 field->offset() == original_field->offset() &&
1677 field->is_static() == original_field->is_static()), "wrong field?");
1678 // Set field() and is_rewritable() attributes.
1679 if (field != NULL) alias_type(idx)->set_field(field);
1680 }
1681 }
1682
1683 // Fill the cache for next time.
1684 ace->_adr_type = adr_type;
1685 ace->_index = idx;
1686 assert(alias_type(adr_type) == alias_type(idx), "type must be installed");
1687
1688 // Might as well try to fill the cache for the flattened version, too.
1689 AliasCacheEntry* face = probe_alias_cache(flat);
1690 if (face->_adr_type == NULL) {
1691 face->_adr_type = flat;
1692 face->_index = idx;
1693 assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1694 }
1695
1696 return alias_type(idx);
1697 }
1698
1699
alias_type(ciField * field)1700 Compile::AliasType* Compile::alias_type(ciField* field) {
1701 const TypeOopPtr* t;
1702 if (field->is_static())
1703 t = TypeInstPtr::make(field->holder()->java_mirror());
1704 else
1705 t = TypeOopPtr::make_from_klass_raw(field->holder());
1706 AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1707 assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1708 return atp;
1709 }
1710
1711
1712 //------------------------------have_alias_type--------------------------------
have_alias_type(const TypePtr * adr_type)1713 bool Compile::have_alias_type(const TypePtr* adr_type) {
1714 AliasCacheEntry* ace = probe_alias_cache(adr_type);
1715 if (ace->_adr_type == adr_type) {
1716 return true;
1717 }
1718
1719 // Handle special cases.
1720 if (adr_type == NULL) return true;
1721 if (adr_type == TypePtr::BOTTOM) return true;
1722
1723 return find_alias_type(adr_type, true, NULL) != NULL;
1724 }
1725
1726 //-----------------------------must_alias--------------------------------------
1727 // True if all values of the given address type are in the given alias category.
must_alias(const TypePtr * adr_type,int alias_idx)1728 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1729 if (alias_idx == AliasIdxBot) return true; // the universal category
1730 if (adr_type == NULL) return true; // NULL serves as TypePtr::TOP
1731 if (alias_idx == AliasIdxTop) return false; // the empty category
1732 if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1733
1734 // the only remaining possible overlap is identity
1735 int adr_idx = get_alias_index(adr_type);
1736 assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1737 assert(adr_idx == alias_idx ||
1738 (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1739 && adr_type != TypeOopPtr::BOTTOM),
1740 "should not be testing for overlap with an unsafe pointer");
1741 return adr_idx == alias_idx;
1742 }
1743
1744 //------------------------------can_alias--------------------------------------
1745 // True if any values of the given address type are in the given alias category.
can_alias(const TypePtr * adr_type,int alias_idx)1746 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1747 if (alias_idx == AliasIdxTop) return false; // the empty category
1748 if (adr_type == NULL) return false; // NULL serves as TypePtr::TOP
1749 // Known instance doesn't alias with bottom memory
1750 if (alias_idx == AliasIdxBot) return !adr_type->is_known_instance(); // the universal category
1751 if (adr_type->base() == Type::AnyPtr) return !C->get_adr_type(alias_idx)->is_known_instance(); // TypePtr::BOTTOM or its twins
1752
1753 // the only remaining possible overlap is identity
1754 int adr_idx = get_alias_index(adr_type);
1755 assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1756 return adr_idx == alias_idx;
1757 }
1758
1759
1760
1761 //---------------------------pop_warm_call-------------------------------------
pop_warm_call()1762 WarmCallInfo* Compile::pop_warm_call() {
1763 WarmCallInfo* wci = _warm_calls;
1764 if (wci != NULL) _warm_calls = wci->remove_from(wci);
1765 return wci;
1766 }
1767
1768 //----------------------------Inline_Warm--------------------------------------
Inline_Warm()1769 int Compile::Inline_Warm() {
1770 // If there is room, try to inline some more warm call sites.
1771 // %%% Do a graph index compaction pass when we think we're out of space?
1772 if (!InlineWarmCalls) return 0;
1773
1774 int calls_made_hot = 0;
1775 int room_to_grow = NodeCountInliningCutoff - unique();
1776 int amount_to_grow = MIN2(room_to_grow, (int)NodeCountInliningStep);
1777 int amount_grown = 0;
1778 WarmCallInfo* call;
1779 while (amount_to_grow > 0 && (call = pop_warm_call()) != NULL) {
1780 int est_size = (int)call->size();
1781 if (est_size > (room_to_grow - amount_grown)) {
1782 // This one won't fit anyway. Get rid of it.
1783 call->make_cold();
1784 continue;
1785 }
1786 call->make_hot();
1787 calls_made_hot++;
1788 amount_grown += est_size;
1789 amount_to_grow -= est_size;
1790 }
1791
1792 if (calls_made_hot > 0) set_major_progress();
1793 return calls_made_hot;
1794 }
1795
1796
1797 //----------------------------Finish_Warm--------------------------------------
Finish_Warm()1798 void Compile::Finish_Warm() {
1799 if (!InlineWarmCalls) return;
1800 if (failing()) return;
1801 if (warm_calls() == NULL) return;
1802
1803 // Clean up loose ends, if we are out of space for inlining.
1804 WarmCallInfo* call;
1805 while ((call = pop_warm_call()) != NULL) {
1806 call->make_cold();
1807 }
1808 }
1809
1810 //---------------------cleanup_loop_predicates-----------------------
1811 // Remove the opaque nodes that protect the predicates so that all unused
1812 // checks and uncommon_traps will be eliminated from the ideal graph
cleanup_loop_predicates(PhaseIterGVN & igvn)1813 void Compile::cleanup_loop_predicates(PhaseIterGVN &igvn) {
1814 if (predicate_count()==0) return;
1815 for (int i = predicate_count(); i > 0; i--) {
1816 Node * n = predicate_opaque1_node(i-1);
1817 assert(n->Opcode() == Op_Opaque1, "must be");
1818 igvn.replace_node(n, n->in(1));
1819 }
1820 assert(predicate_count()==0, "should be clean!");
1821 }
1822
record_for_post_loop_opts_igvn(Node * n)1823 void Compile::record_for_post_loop_opts_igvn(Node* n) {
1824 if (!n->for_post_loop_opts_igvn()) {
1825 assert(!_for_post_loop_igvn.contains(n), "duplicate");
1826 n->add_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1827 _for_post_loop_igvn.append(n);
1828 }
1829 }
1830
remove_from_post_loop_opts_igvn(Node * n)1831 void Compile::remove_from_post_loop_opts_igvn(Node* n) {
1832 n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1833 _for_post_loop_igvn.remove(n);
1834 }
1835
process_for_post_loop_opts_igvn(PhaseIterGVN & igvn)1836 void Compile::process_for_post_loop_opts_igvn(PhaseIterGVN& igvn) {
1837 // Verify that all previous optimizations produced a valid graph
1838 // at least to this point, even if no loop optimizations were done.
1839 PhaseIdealLoop::verify(igvn);
1840
1841 C->set_post_loop_opts_phase(); // no more loop opts allowed
1842
1843 assert(!C->major_progress(), "not cleared");
1844
1845 if (_for_post_loop_igvn.length() > 0) {
1846 while (_for_post_loop_igvn.length() > 0) {
1847 Node* n = _for_post_loop_igvn.pop();
1848 n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1849 igvn._worklist.push(n);
1850 }
1851 igvn.optimize();
1852 assert(_for_post_loop_igvn.length() == 0, "no more delayed nodes allowed");
1853
1854 // Sometimes IGVN sets major progress (e.g., when processing loop nodes).
1855 if (C->major_progress()) {
1856 C->clear_major_progress(); // ensure that major progress is now clear
1857 }
1858 }
1859 }
1860
1861 // StringOpts and late inlining of string methods
inline_string_calls(bool parse_time)1862 void Compile::inline_string_calls(bool parse_time) {
1863 {
1864 // remove useless nodes to make the usage analysis simpler
1865 ResourceMark rm;
1866 PhaseRemoveUseless pru(initial_gvn(), for_igvn());
1867 }
1868
1869 {
1870 ResourceMark rm;
1871 print_method(PHASE_BEFORE_STRINGOPTS, 3);
1872 PhaseStringOpts pso(initial_gvn(), for_igvn());
1873 print_method(PHASE_AFTER_STRINGOPTS, 3);
1874 }
1875
1876 // now inline anything that we skipped the first time around
1877 if (!parse_time) {
1878 _late_inlines_pos = _late_inlines.length();
1879 }
1880
1881 while (_string_late_inlines.length() > 0) {
1882 CallGenerator* cg = _string_late_inlines.pop();
1883 cg->do_late_inline();
1884 if (failing()) return;
1885 }
1886 _string_late_inlines.trunc_to(0);
1887 }
1888
1889 // Late inlining of boxing methods
inline_boxing_calls(PhaseIterGVN & igvn)1890 void Compile::inline_boxing_calls(PhaseIterGVN& igvn) {
1891 if (_boxing_late_inlines.length() > 0) {
1892 assert(has_boxed_value(), "inconsistent");
1893
1894 PhaseGVN* gvn = initial_gvn();
1895 set_inlining_incrementally(true);
1896
1897 assert( igvn._worklist.size() == 0, "should be done with igvn" );
1898 for_igvn()->clear();
1899 gvn->replace_with(&igvn);
1900
1901 _late_inlines_pos = _late_inlines.length();
1902
1903 while (_boxing_late_inlines.length() > 0) {
1904 CallGenerator* cg = _boxing_late_inlines.pop();
1905 cg->do_late_inline();
1906 if (failing()) return;
1907 }
1908 _boxing_late_inlines.trunc_to(0);
1909
1910 inline_incrementally_cleanup(igvn);
1911
1912 set_inlining_incrementally(false);
1913 }
1914 }
1915
inline_incrementally_one()1916 bool Compile::inline_incrementally_one() {
1917 assert(IncrementalInline, "incremental inlining should be on");
1918
1919 TracePhase tp("incrementalInline_inline", &timers[_t_incrInline_inline]);
1920
1921 set_inlining_progress(false);
1922 set_do_cleanup(false);
1923
1924 for (int i = 0; i < _late_inlines.length(); i++) {
1925 _late_inlines_pos = i+1;
1926 CallGenerator* cg = _late_inlines.at(i);
1927 bool does_dispatch = cg->is_virtual_late_inline() || cg->is_mh_late_inline();
1928 if (inlining_incrementally() || does_dispatch) { // a call can be either inlined or strength-reduced to a direct call
1929 cg->do_late_inline();
1930 assert(_late_inlines.at(i) == cg, "no insertions before current position allowed");
1931 if (failing()) {
1932 return false;
1933 } else if (inlining_progress()) {
1934 _late_inlines_pos = i+1; // restore the position in case new elements were inserted
1935 print_method(PHASE_INCREMENTAL_INLINE_STEP, cg->call_node(), 3);
1936 break; // process one call site at a time
1937 }
1938 } else {
1939 // Ignore late inline direct calls when inlining is not allowed.
1940 // They are left in the late inline list when node budget is exhausted until the list is fully drained.
1941 }
1942 }
1943 // Remove processed elements.
1944 _late_inlines.remove_till(_late_inlines_pos);
1945 _late_inlines_pos = 0;
1946
1947 assert(inlining_progress() || _late_inlines.length() == 0, "no progress");
1948
1949 bool needs_cleanup = do_cleanup() || over_inlining_cutoff();
1950
1951 set_inlining_progress(false);
1952 set_do_cleanup(false);
1953
1954 bool force_cleanup = directive()->IncrementalInlineForceCleanupOption;
1955 return (_late_inlines.length() > 0) && !needs_cleanup && !force_cleanup;
1956 }
1957
inline_incrementally_cleanup(PhaseIterGVN & igvn)1958 void Compile::inline_incrementally_cleanup(PhaseIterGVN& igvn) {
1959 {
1960 TracePhase tp("incrementalInline_pru", &timers[_t_incrInline_pru]);
1961 ResourceMark rm;
1962 PhaseRemoveUseless pru(initial_gvn(), for_igvn());
1963 }
1964 {
1965 TracePhase tp("incrementalInline_igvn", &timers[_t_incrInline_igvn]);
1966 igvn = PhaseIterGVN(initial_gvn());
1967 igvn.optimize();
1968 }
1969 print_method(PHASE_INCREMENTAL_INLINE_CLEANUP, 3);
1970 }
1971
1972 // Perform incremental inlining until bound on number of live nodes is reached
inline_incrementally(PhaseIterGVN & igvn)1973 void Compile::inline_incrementally(PhaseIterGVN& igvn) {
1974 TracePhase tp("incrementalInline", &timers[_t_incrInline]);
1975
1976 set_inlining_incrementally(true);
1977 uint low_live_nodes = 0;
1978
1979 while (_late_inlines.length() > 0) {
1980 if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
1981 if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) {
1982 TracePhase tp("incrementalInline_ideal", &timers[_t_incrInline_ideal]);
1983 // PhaseIdealLoop is expensive so we only try it once we are
1984 // out of live nodes and we only try it again if the previous
1985 // helped got the number of nodes down significantly
1986 PhaseIdealLoop::optimize(igvn, LoopOptsNone);
1987 if (failing()) return;
1988 low_live_nodes = live_nodes();
1989 _major_progress = true;
1990 }
1991
1992 if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
1993 bool do_print_inlining = print_inlining() || print_intrinsics();
1994 if (do_print_inlining || log() != NULL) {
1995 // Print inlining message for candidates that we couldn't inline for lack of space.
1996 for (int i = 0; i < _late_inlines.length(); i++) {
1997 CallGenerator* cg = _late_inlines.at(i);
1998 const char* msg = "live nodes > LiveNodeCountInliningCutoff";
1999 if (do_print_inlining) {
2000 cg->print_inlining_late(msg);
2001 }
2002 log_late_inline_failure(cg, msg);
2003 }
2004 }
2005 break; // finish
2006 }
2007 }
2008
2009 for_igvn()->clear();
2010 initial_gvn()->replace_with(&igvn);
2011
2012 while (inline_incrementally_one()) {
2013 assert(!failing(), "inconsistent");
2014 }
2015 if (failing()) return;
2016
2017 inline_incrementally_cleanup(igvn);
2018
2019 print_method(PHASE_INCREMENTAL_INLINE_STEP, 3);
2020
2021 if (failing()) return;
2022
2023 if (_late_inlines.length() == 0) {
2024 break; // no more progress
2025 }
2026 }
2027 assert( igvn._worklist.size() == 0, "should be done with igvn" );
2028
2029 if (_string_late_inlines.length() > 0) {
2030 assert(has_stringbuilder(), "inconsistent");
2031 for_igvn()->clear();
2032 initial_gvn()->replace_with(&igvn);
2033
2034 inline_string_calls(false);
2035
2036 if (failing()) return;
2037
2038 inline_incrementally_cleanup(igvn);
2039 }
2040
2041 set_inlining_incrementally(false);
2042 }
2043
process_late_inline_calls_no_inline(PhaseIterGVN & igvn)2044 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) {
2045 // "inlining_incrementally() == false" is used to signal that no inlining is allowed
2046 // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details).
2047 // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == NULL"
2048 // as if "inlining_incrementally() == true" were set.
2049 assert(inlining_incrementally() == false, "not allowed");
2050 assert(_modified_nodes == NULL, "not allowed");
2051 assert(_late_inlines.length() > 0, "sanity");
2052
2053 while (_late_inlines.length() > 0) {
2054 for_igvn()->clear();
2055 initial_gvn()->replace_with(&igvn);
2056
2057 while (inline_incrementally_one()) {
2058 assert(!failing(), "inconsistent");
2059 }
2060 if (failing()) return;
2061
2062 inline_incrementally_cleanup(igvn);
2063 }
2064 }
2065
optimize_loops(PhaseIterGVN & igvn,LoopOptsMode mode)2066 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
2067 if (_loop_opts_cnt > 0) {
2068 debug_only( int cnt = 0; );
2069 while (major_progress() && (_loop_opts_cnt > 0)) {
2070 TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2071 assert( cnt++ < 40, "infinite cycle in loop optimization" );
2072 PhaseIdealLoop::optimize(igvn, mode);
2073 _loop_opts_cnt--;
2074 if (failing()) return false;
2075 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2076 }
2077 }
2078 return true;
2079 }
2080
2081 // Remove edges from "root" to each SafePoint at a backward branch.
2082 // They were inserted during parsing (see add_safepoint()) to make
2083 // infinite loops without calls or exceptions visible to root, i.e.,
2084 // useful.
remove_root_to_sfpts_edges(PhaseIterGVN & igvn)2085 void Compile::remove_root_to_sfpts_edges(PhaseIterGVN& igvn) {
2086 Node *r = root();
2087 if (r != NULL) {
2088 for (uint i = r->req(); i < r->len(); ++i) {
2089 Node *n = r->in(i);
2090 if (n != NULL && n->is_SafePoint()) {
2091 r->rm_prec(i);
2092 if (n->outcnt() == 0) {
2093 igvn.remove_dead_node(n);
2094 }
2095 --i;
2096 }
2097 }
2098 // Parsing may have added top inputs to the root node (Path
2099 // leading to the Halt node proven dead). Make sure we get a
2100 // chance to clean them up.
2101 igvn._worklist.push(r);
2102 igvn.optimize();
2103 }
2104 }
2105
2106 //------------------------------Optimize---------------------------------------
2107 // Given a graph, optimize it.
Optimize()2108 void Compile::Optimize() {
2109 TracePhase tp("optimizer", &timers[_t_optimizer]);
2110
2111 #ifndef PRODUCT
2112 if (_directive->BreakAtCompileOption) {
2113 BREAKPOINT;
2114 }
2115
2116 #endif
2117
2118 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2119 #ifdef ASSERT
2120 bs->verify_gc_barriers(this, BarrierSetC2::BeforeOptimize);
2121 #endif
2122
2123 ResourceMark rm;
2124
2125 print_inlining_reinit();
2126
2127 NOT_PRODUCT( verify_graph_edges(); )
2128
2129 print_method(PHASE_AFTER_PARSING);
2130
2131 {
2132 // Iterative Global Value Numbering, including ideal transforms
2133 // Initialize IterGVN with types and values from parse-time GVN
2134 PhaseIterGVN igvn(initial_gvn());
2135 #ifdef ASSERT
2136 _modified_nodes = new (comp_arena()) Unique_Node_List(comp_arena());
2137 #endif
2138 {
2139 TracePhase tp("iterGVN", &timers[_t_iterGVN]);
2140 igvn.optimize();
2141 }
2142
2143 if (failing()) return;
2144
2145 print_method(PHASE_ITER_GVN1, 2);
2146
2147 inline_incrementally(igvn);
2148
2149 print_method(PHASE_INCREMENTAL_INLINE, 2);
2150
2151 if (failing()) return;
2152
2153 if (eliminate_boxing()) {
2154 // Inline valueOf() methods now.
2155 inline_boxing_calls(igvn);
2156
2157 if (AlwaysIncrementalInline) {
2158 inline_incrementally(igvn);
2159 }
2160
2161 print_method(PHASE_INCREMENTAL_BOXING_INLINE, 2);
2162
2163 if (failing()) return;
2164 }
2165
2166 // Now that all inlining is over, cut edge from root to loop
2167 // safepoints
2168 remove_root_to_sfpts_edges(igvn);
2169
2170 // Remove the speculative part of types and clean up the graph from
2171 // the extra CastPP nodes whose only purpose is to carry them. Do
2172 // that early so that optimizations are not disrupted by the extra
2173 // CastPP nodes.
2174 remove_speculative_types(igvn);
2175
2176 // No more new expensive nodes will be added to the list from here
2177 // so keep only the actual candidates for optimizations.
2178 cleanup_expensive_nodes(igvn);
2179
2180 assert(EnableVectorSupport || !has_vbox_nodes(), "sanity");
2181 if (EnableVectorSupport && has_vbox_nodes()) {
2182 TracePhase tp("", &timers[_t_vector]);
2183 PhaseVector pv(igvn);
2184 pv.optimize_vector_boxes();
2185
2186 print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2);
2187 }
2188 assert(!has_vbox_nodes(), "sanity");
2189
2190 if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2191 Compile::TracePhase tp("", &timers[_t_renumberLive]);
2192 initial_gvn()->replace_with(&igvn);
2193 for_igvn()->clear();
2194 Unique_Node_List new_worklist(C->comp_arena());
2195 {
2196 ResourceMark rm;
2197 PhaseRenumberLive prl = PhaseRenumberLive(initial_gvn(), for_igvn(), &new_worklist);
2198 }
2199 Unique_Node_List* save_for_igvn = for_igvn();
2200 set_for_igvn(&new_worklist);
2201 igvn = PhaseIterGVN(initial_gvn());
2202 igvn.optimize();
2203 set_for_igvn(save_for_igvn);
2204 }
2205
2206 // Perform escape analysis
2207 if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) {
2208 if (has_loops()) {
2209 // Cleanup graph (remove dead nodes).
2210 TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2211 PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
2212 if (major_progress()) print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2213 if (failing()) return;
2214 }
2215 ConnectionGraph::do_analysis(this, &igvn);
2216
2217 if (failing()) return;
2218
2219 // Optimize out fields loads from scalar replaceable allocations.
2220 igvn.optimize();
2221 print_method(PHASE_ITER_GVN_AFTER_EA, 2);
2222
2223 if (failing()) return;
2224
2225 if (congraph() != NULL && macro_count() > 0) {
2226 TracePhase tp("macroEliminate", &timers[_t_macroEliminate]);
2227 PhaseMacroExpand mexp(igvn);
2228 mexp.eliminate_macro_nodes();
2229 igvn.set_delay_transform(false);
2230
2231 igvn.optimize();
2232 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2233
2234 if (failing()) return;
2235 }
2236 }
2237
2238 // Loop transforms on the ideal graph. Range Check Elimination,
2239 // peeling, unrolling, etc.
2240
2241 // Set loop opts counter
2242 if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
2243 {
2244 TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2245 PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
2246 _loop_opts_cnt--;
2247 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
2248 if (failing()) return;
2249 }
2250 // Loop opts pass if partial peeling occurred in previous pass
2251 if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
2252 TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2253 PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2254 _loop_opts_cnt--;
2255 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
2256 if (failing()) return;
2257 }
2258 // Loop opts pass for loop-unrolling before CCP
2259 if(major_progress() && (_loop_opts_cnt > 0)) {
2260 TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2261 PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2262 _loop_opts_cnt--;
2263 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2);
2264 }
2265 if (!failing()) {
2266 // Verify that last round of loop opts produced a valid graph
2267 PhaseIdealLoop::verify(igvn);
2268 }
2269 }
2270 if (failing()) return;
2271
2272 // Conditional Constant Propagation;
2273 PhaseCCP ccp( &igvn );
2274 assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
2275 {
2276 TracePhase tp("ccp", &timers[_t_ccp]);
2277 ccp.do_transform();
2278 }
2279 print_method(PHASE_CPP1, 2);
2280
2281 assert( true, "Break here to ccp.dump_old2new_map()");
2282
2283 // Iterative Global Value Numbering, including ideal transforms
2284 {
2285 TracePhase tp("iterGVN2", &timers[_t_iterGVN2]);
2286 igvn = ccp;
2287 igvn.optimize();
2288 }
2289 print_method(PHASE_ITER_GVN2, 2);
2290
2291 if (failing()) return;
2292
2293 // Loop transforms on the ideal graph. Range Check Elimination,
2294 // peeling, unrolling, etc.
2295 if (!optimize_loops(igvn, LoopOptsDefault)) {
2296 return;
2297 }
2298
2299 if (failing()) return;
2300
2301 C->clear_major_progress(); // ensure that major progress is now clear
2302
2303 process_for_post_loop_opts_igvn(igvn);
2304
2305 #ifdef ASSERT
2306 bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
2307 #endif
2308
2309 {
2310 TracePhase tp("macroExpand", &timers[_t_macroExpand]);
2311 PhaseMacroExpand mex(igvn);
2312 if (mex.expand_macro_nodes()) {
2313 assert(failing(), "must bail out w/ explicit message");
2314 return;
2315 }
2316 print_method(PHASE_MACRO_EXPANSION, 2);
2317 }
2318
2319 {
2320 TracePhase tp("barrierExpand", &timers[_t_barrierExpand]);
2321 if (bs->expand_barriers(this, igvn)) {
2322 assert(failing(), "must bail out w/ explicit message");
2323 return;
2324 }
2325 print_method(PHASE_BARRIER_EXPANSION, 2);
2326 }
2327
2328 if (C->max_vector_size() > 0) {
2329 C->optimize_logic_cones(igvn);
2330 igvn.optimize();
2331 }
2332
2333 DEBUG_ONLY( _modified_nodes = NULL; )
2334
2335 assert(igvn._worklist.size() == 0, "not empty");
2336
2337 assert(_late_inlines.length() == 0 || IncrementalInlineMH || IncrementalInlineVirtual, "not empty");
2338
2339 if (_late_inlines.length() > 0) {
2340 // More opportunities to optimize virtual and MH calls.
2341 // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option.
2342 process_late_inline_calls_no_inline(igvn);
2343 }
2344 } // (End scope of igvn; run destructor if necessary for asserts.)
2345
2346 process_print_inlining();
2347
2348 // A method with only infinite loops has no edges entering loops from root
2349 {
2350 TracePhase tp("graphReshape", &timers[_t_graphReshaping]);
2351 if (final_graph_reshaping()) {
2352 assert(failing(), "must bail out w/ explicit message");
2353 return;
2354 }
2355 }
2356
2357 print_method(PHASE_OPTIMIZE_FINISHED, 2);
2358 DEBUG_ONLY(set_phase_optimize_finished();)
2359 }
2360
inline_vector_reboxing_calls()2361 void Compile::inline_vector_reboxing_calls() {
2362 if (C->_vector_reboxing_late_inlines.length() > 0) {
2363 _late_inlines_pos = C->_late_inlines.length();
2364 while (_vector_reboxing_late_inlines.length() > 0) {
2365 CallGenerator* cg = _vector_reboxing_late_inlines.pop();
2366 cg->do_late_inline();
2367 if (failing()) return;
2368 print_method(PHASE_INLINE_VECTOR_REBOX, cg->call_node());
2369 }
2370 _vector_reboxing_late_inlines.trunc_to(0);
2371 }
2372 }
2373
has_vbox_nodes()2374 bool Compile::has_vbox_nodes() {
2375 if (C->_vector_reboxing_late_inlines.length() > 0) {
2376 return true;
2377 }
2378 for (int macro_idx = C->macro_count() - 1; macro_idx >= 0; macro_idx--) {
2379 Node * n = C->macro_node(macro_idx);
2380 assert(n->is_macro(), "only macro nodes expected here");
2381 if (n->Opcode() == Op_VectorUnbox || n->Opcode() == Op_VectorBox || n->Opcode() == Op_VectorBoxAllocate) {
2382 return true;
2383 }
2384 }
2385 return false;
2386 }
2387
2388 //---------------------------- Bitwise operation packing optimization ---------------------------
2389
is_vector_unary_bitwise_op(Node * n)2390 static bool is_vector_unary_bitwise_op(Node* n) {
2391 return n->Opcode() == Op_XorV &&
2392 VectorNode::is_vector_bitwise_not_pattern(n);
2393 }
2394
is_vector_binary_bitwise_op(Node * n)2395 static bool is_vector_binary_bitwise_op(Node* n) {
2396 switch (n->Opcode()) {
2397 case Op_AndV:
2398 case Op_OrV:
2399 return true;
2400
2401 case Op_XorV:
2402 return !is_vector_unary_bitwise_op(n);
2403
2404 default:
2405 return false;
2406 }
2407 }
2408
is_vector_ternary_bitwise_op(Node * n)2409 static bool is_vector_ternary_bitwise_op(Node* n) {
2410 return n->Opcode() == Op_MacroLogicV;
2411 }
2412
is_vector_bitwise_op(Node * n)2413 static bool is_vector_bitwise_op(Node* n) {
2414 return is_vector_unary_bitwise_op(n) ||
2415 is_vector_binary_bitwise_op(n) ||
2416 is_vector_ternary_bitwise_op(n);
2417 }
2418
is_vector_bitwise_cone_root(Node * n)2419 static bool is_vector_bitwise_cone_root(Node* n) {
2420 if (!is_vector_bitwise_op(n)) {
2421 return false;
2422 }
2423 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2424 if (is_vector_bitwise_op(n->fast_out(i))) {
2425 return false;
2426 }
2427 }
2428 return true;
2429 }
2430
collect_unique_inputs(Node * n,Unique_Node_List & partition,Unique_Node_List & inputs)2431 static uint collect_unique_inputs(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) {
2432 uint cnt = 0;
2433 if (is_vector_bitwise_op(n)) {
2434 if (VectorNode::is_vector_bitwise_not_pattern(n)) {
2435 for (uint i = 1; i < n->req(); i++) {
2436 Node* in = n->in(i);
2437 bool skip = VectorNode::is_all_ones_vector(in);
2438 if (!skip && !inputs.member(in)) {
2439 inputs.push(in);
2440 cnt++;
2441 }
2442 }
2443 assert(cnt <= 1, "not unary");
2444 } else {
2445 uint last_req = n->req();
2446 if (is_vector_ternary_bitwise_op(n)) {
2447 last_req = n->req() - 1; // skip last input
2448 }
2449 for (uint i = 1; i < last_req; i++) {
2450 Node* def = n->in(i);
2451 if (!inputs.member(def)) {
2452 inputs.push(def);
2453 cnt++;
2454 }
2455 }
2456 }
2457 partition.push(n);
2458 } else { // not a bitwise operations
2459 if (!inputs.member(n)) {
2460 inputs.push(n);
2461 cnt++;
2462 }
2463 }
2464 return cnt;
2465 }
2466
collect_logic_cone_roots(Unique_Node_List & list)2467 void Compile::collect_logic_cone_roots(Unique_Node_List& list) {
2468 Unique_Node_List useful_nodes;
2469 C->identify_useful_nodes(useful_nodes);
2470
2471 for (uint i = 0; i < useful_nodes.size(); i++) {
2472 Node* n = useful_nodes.at(i);
2473 if (is_vector_bitwise_cone_root(n)) {
2474 list.push(n);
2475 }
2476 }
2477 }
2478
xform_to_MacroLogicV(PhaseIterGVN & igvn,const TypeVect * vt,Unique_Node_List & partition,Unique_Node_List & inputs)2479 Node* Compile::xform_to_MacroLogicV(PhaseIterGVN& igvn,
2480 const TypeVect* vt,
2481 Unique_Node_List& partition,
2482 Unique_Node_List& inputs) {
2483 assert(partition.size() == 2 || partition.size() == 3, "not supported");
2484 assert(inputs.size() == 2 || inputs.size() == 3, "not supported");
2485 assert(Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()), "not supported");
2486
2487 Node* in1 = inputs.at(0);
2488 Node* in2 = inputs.at(1);
2489 Node* in3 = (inputs.size() == 3 ? inputs.at(2) : in2);
2490
2491 uint func = compute_truth_table(partition, inputs);
2492 return igvn.transform(MacroLogicVNode::make(igvn, in3, in2, in1, func, vt));
2493 }
2494
extract_bit(uint func,uint pos)2495 static uint extract_bit(uint func, uint pos) {
2496 return (func & (1 << pos)) >> pos;
2497 }
2498
2499 //
2500 // A macro logic node represents a truth table. It has 4 inputs,
2501 // First three inputs corresponds to 3 columns of a truth table
2502 // and fourth input captures the logic function.
2503 //
2504 // eg. fn = (in1 AND in2) OR in3;
2505 //
2506 // MacroNode(in1,in2,in3,fn)
2507 //
2508 // -----------------
2509 // in1 in2 in3 fn
2510 // -----------------
2511 // 0 0 0 0
2512 // 0 0 1 1
2513 // 0 1 0 0
2514 // 0 1 1 1
2515 // 1 0 0 0
2516 // 1 0 1 1
2517 // 1 1 0 1
2518 // 1 1 1 1
2519 //
2520
eval_macro_logic_op(uint func,uint in1,uint in2,uint in3)2521 uint Compile::eval_macro_logic_op(uint func, uint in1 , uint in2, uint in3) {
2522 int res = 0;
2523 for (int i = 0; i < 8; i++) {
2524 int bit1 = extract_bit(in1, i);
2525 int bit2 = extract_bit(in2, i);
2526 int bit3 = extract_bit(in3, i);
2527
2528 int func_bit_pos = (bit1 << 2 | bit2 << 1 | bit3);
2529 int func_bit = extract_bit(func, func_bit_pos);
2530
2531 res |= func_bit << i;
2532 }
2533 return res;
2534 }
2535
eval_operand(Node * n,ResourceHashtable<Node *,uint> & eval_map)2536 static uint eval_operand(Node* n, ResourceHashtable<Node*,uint>& eval_map) {
2537 assert(n != NULL, "");
2538 assert(eval_map.contains(n), "absent");
2539 return *(eval_map.get(n));
2540 }
2541
eval_operands(Node * n,uint & func1,uint & func2,uint & func3,ResourceHashtable<Node *,uint> & eval_map)2542 static void eval_operands(Node* n,
2543 uint& func1, uint& func2, uint& func3,
2544 ResourceHashtable<Node*,uint>& eval_map) {
2545 assert(is_vector_bitwise_op(n), "");
2546
2547 if (is_vector_unary_bitwise_op(n)) {
2548 Node* opnd = n->in(1);
2549 if (VectorNode::is_vector_bitwise_not_pattern(n) && VectorNode::is_all_ones_vector(opnd)) {
2550 opnd = n->in(2);
2551 }
2552 func1 = eval_operand(opnd, eval_map);
2553 } else if (is_vector_binary_bitwise_op(n)) {
2554 func1 = eval_operand(n->in(1), eval_map);
2555 func2 = eval_operand(n->in(2), eval_map);
2556 } else {
2557 assert(is_vector_ternary_bitwise_op(n), "unknown operation");
2558 func1 = eval_operand(n->in(1), eval_map);
2559 func2 = eval_operand(n->in(2), eval_map);
2560 func3 = eval_operand(n->in(3), eval_map);
2561 }
2562 }
2563
compute_truth_table(Unique_Node_List & partition,Unique_Node_List & inputs)2564 uint Compile::compute_truth_table(Unique_Node_List& partition, Unique_Node_List& inputs) {
2565 assert(inputs.size() <= 3, "sanity");
2566 ResourceMark rm;
2567 uint res = 0;
2568 ResourceHashtable<Node*,uint> eval_map;
2569
2570 // Populate precomputed functions for inputs.
2571 // Each input corresponds to one column of 3 input truth-table.
2572 uint input_funcs[] = { 0xAA, // (_, _, a) -> a
2573 0xCC, // (_, b, _) -> b
2574 0xF0 }; // (c, _, _) -> c
2575 for (uint i = 0; i < inputs.size(); i++) {
2576 eval_map.put(inputs.at(i), input_funcs[i]);
2577 }
2578
2579 for (uint i = 0; i < partition.size(); i++) {
2580 Node* n = partition.at(i);
2581
2582 uint func1 = 0, func2 = 0, func3 = 0;
2583 eval_operands(n, func1, func2, func3, eval_map);
2584
2585 switch (n->Opcode()) {
2586 case Op_OrV:
2587 assert(func3 == 0, "not binary");
2588 res = func1 | func2;
2589 break;
2590 case Op_AndV:
2591 assert(func3 == 0, "not binary");
2592 res = func1 & func2;
2593 break;
2594 case Op_XorV:
2595 if (VectorNode::is_vector_bitwise_not_pattern(n)) {
2596 assert(func2 == 0 && func3 == 0, "not unary");
2597 res = (~func1) & 0xFF;
2598 } else {
2599 assert(func3 == 0, "not binary");
2600 res = func1 ^ func2;
2601 }
2602 break;
2603 case Op_MacroLogicV:
2604 // Ordering of inputs may change during evaluation of sub-tree
2605 // containing MacroLogic node as a child node, thus a re-evaluation
2606 // makes sure that function is evaluated in context of current
2607 // inputs.
2608 res = eval_macro_logic_op(n->in(4)->get_int(), func1, func2, func3);
2609 break;
2610
2611 default: assert(false, "not supported: %s", n->Name());
2612 }
2613 assert(res <= 0xFF, "invalid");
2614 eval_map.put(n, res);
2615 }
2616 return res;
2617 }
2618
compute_logic_cone(Node * n,Unique_Node_List & partition,Unique_Node_List & inputs)2619 bool Compile::compute_logic_cone(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) {
2620 assert(partition.size() == 0, "not empty");
2621 assert(inputs.size() == 0, "not empty");
2622 if (is_vector_ternary_bitwise_op(n)) {
2623 return false;
2624 }
2625
2626 bool is_unary_op = is_vector_unary_bitwise_op(n);
2627 if (is_unary_op) {
2628 assert(collect_unique_inputs(n, partition, inputs) == 1, "not unary");
2629 return false; // too few inputs
2630 }
2631
2632 assert(is_vector_binary_bitwise_op(n), "not binary");
2633 Node* in1 = n->in(1);
2634 Node* in2 = n->in(2);
2635
2636 int in1_unique_inputs_cnt = collect_unique_inputs(in1, partition, inputs);
2637 int in2_unique_inputs_cnt = collect_unique_inputs(in2, partition, inputs);
2638 partition.push(n);
2639
2640 // Too many inputs?
2641 if (inputs.size() > 3) {
2642 partition.clear();
2643 inputs.clear();
2644 { // Recompute in2 inputs
2645 Unique_Node_List not_used;
2646 in2_unique_inputs_cnt = collect_unique_inputs(in2, not_used, not_used);
2647 }
2648 // Pick the node with minimum number of inputs.
2649 if (in1_unique_inputs_cnt >= 3 && in2_unique_inputs_cnt >= 3) {
2650 return false; // still too many inputs
2651 }
2652 // Recompute partition & inputs.
2653 Node* child = (in1_unique_inputs_cnt < in2_unique_inputs_cnt ? in1 : in2);
2654 collect_unique_inputs(child, partition, inputs);
2655
2656 Node* other_input = (in1_unique_inputs_cnt < in2_unique_inputs_cnt ? in2 : in1);
2657 inputs.push(other_input);
2658
2659 partition.push(n);
2660 }
2661
2662 return (partition.size() == 2 || partition.size() == 3) &&
2663 (inputs.size() == 2 || inputs.size() == 3);
2664 }
2665
2666
process_logic_cone_root(PhaseIterGVN & igvn,Node * n,VectorSet & visited)2667 void Compile::process_logic_cone_root(PhaseIterGVN &igvn, Node *n, VectorSet &visited) {
2668 assert(is_vector_bitwise_op(n), "not a root");
2669
2670 visited.set(n->_idx);
2671
2672 // 1) Do a DFS walk over the logic cone.
2673 for (uint i = 1; i < n->req(); i++) {
2674 Node* in = n->in(i);
2675 if (!visited.test(in->_idx) && is_vector_bitwise_op(in)) {
2676 process_logic_cone_root(igvn, in, visited);
2677 }
2678 }
2679
2680 // 2) Bottom up traversal: Merge node[s] with
2681 // the parent to form macro logic node.
2682 Unique_Node_List partition;
2683 Unique_Node_List inputs;
2684 if (compute_logic_cone(n, partition, inputs)) {
2685 const TypeVect* vt = n->bottom_type()->is_vect();
2686 Node* macro_logic = xform_to_MacroLogicV(igvn, vt, partition, inputs);
2687 igvn.replace_node(n, macro_logic);
2688 }
2689 }
2690
optimize_logic_cones(PhaseIterGVN & igvn)2691 void Compile::optimize_logic_cones(PhaseIterGVN &igvn) {
2692 ResourceMark rm;
2693 if (Matcher::match_rule_supported(Op_MacroLogicV)) {
2694 Unique_Node_List list;
2695 collect_logic_cone_roots(list);
2696
2697 while (list.size() > 0) {
2698 Node* n = list.pop();
2699 const TypeVect* vt = n->bottom_type()->is_vect();
2700 bool supported = Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type());
2701 if (supported) {
2702 VectorSet visited(comp_arena());
2703 process_logic_cone_root(igvn, n, visited);
2704 }
2705 }
2706 }
2707 }
2708
2709 //------------------------------Code_Gen---------------------------------------
2710 // Given a graph, generate code for it
Code_Gen()2711 void Compile::Code_Gen() {
2712 if (failing()) {
2713 return;
2714 }
2715
2716 // Perform instruction selection. You might think we could reclaim Matcher
2717 // memory PDQ, but actually the Matcher is used in generating spill code.
2718 // Internals of the Matcher (including some VectorSets) must remain live
2719 // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
2720 // set a bit in reclaimed memory.
2721
2722 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2723 // nodes. Mapping is only valid at the root of each matched subtree.
2724 NOT_PRODUCT( verify_graph_edges(); )
2725
2726 Matcher matcher;
2727 _matcher = &matcher;
2728 {
2729 TracePhase tp("matcher", &timers[_t_matcher]);
2730 matcher.match();
2731 if (failing()) {
2732 return;
2733 }
2734 print_method(PHASE_AFTER_MATCHING, 3);
2735 }
2736 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2737 // nodes. Mapping is only valid at the root of each matched subtree.
2738 NOT_PRODUCT( verify_graph_edges(); )
2739
2740 // If you have too many nodes, or if matching has failed, bail out
2741 check_node_count(0, "out of nodes matching instructions");
2742 if (failing()) {
2743 return;
2744 }
2745
2746 print_method(PHASE_MATCHING, 2);
2747
2748 // Build a proper-looking CFG
2749 PhaseCFG cfg(node_arena(), root(), matcher);
2750 _cfg = &cfg;
2751 {
2752 TracePhase tp("scheduler", &timers[_t_scheduler]);
2753 bool success = cfg.do_global_code_motion();
2754 if (!success) {
2755 return;
2756 }
2757
2758 print_method(PHASE_GLOBAL_CODE_MOTION, 2);
2759 NOT_PRODUCT( verify_graph_edges(); )
2760 debug_only( cfg.verify(); )
2761 }
2762
2763 PhaseChaitin regalloc(unique(), cfg, matcher, false);
2764 _regalloc = ®alloc;
2765 {
2766 TracePhase tp("regalloc", &timers[_t_registerAllocation]);
2767 // Perform register allocation. After Chaitin, use-def chains are
2768 // no longer accurate (at spill code) and so must be ignored.
2769 // Node->LRG->reg mappings are still accurate.
2770 _regalloc->Register_Allocate();
2771
2772 // Bail out if the allocator builds too many nodes
2773 if (failing()) {
2774 return;
2775 }
2776 }
2777
2778 // Prior to register allocation we kept empty basic blocks in case the
2779 // the allocator needed a place to spill. After register allocation we
2780 // are not adding any new instructions. If any basic block is empty, we
2781 // can now safely remove it.
2782 {
2783 TracePhase tp("blockOrdering", &timers[_t_blockOrdering]);
2784 cfg.remove_empty_blocks();
2785 if (do_freq_based_layout()) {
2786 PhaseBlockLayout layout(cfg);
2787 } else {
2788 cfg.set_loop_alignment();
2789 }
2790 cfg.fixup_flow();
2791 }
2792
2793 // Apply peephole optimizations
2794 if( OptoPeephole ) {
2795 TracePhase tp("peephole", &timers[_t_peephole]);
2796 PhasePeephole peep( _regalloc, cfg);
2797 peep.do_transform();
2798 }
2799
2800 // Do late expand if CPU requires this.
2801 if (Matcher::require_postalloc_expand) {
2802 TracePhase tp("postalloc_expand", &timers[_t_postalloc_expand]);
2803 cfg.postalloc_expand(_regalloc);
2804 }
2805
2806 // Convert Nodes to instruction bits in a buffer
2807 {
2808 TracePhase tp("output", &timers[_t_output]);
2809 PhaseOutput output;
2810 output.Output();
2811 if (failing()) return;
2812 output.install();
2813 }
2814
2815 print_method(PHASE_FINAL_CODE);
2816
2817 // He's dead, Jim.
2818 _cfg = (PhaseCFG*)((intptr_t)0xdeadbeef);
2819 _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
2820 }
2821
2822 //------------------------------Final_Reshape_Counts---------------------------
2823 // This class defines counters to help identify when a method
2824 // may/must be executed using hardware with only 24-bit precision.
2825 struct Final_Reshape_Counts : public StackObj {
2826 int _call_count; // count non-inlined 'common' calls
2827 int _float_count; // count float ops requiring 24-bit precision
2828 int _double_count; // count double ops requiring more precision
2829 int _java_call_count; // count non-inlined 'java' calls
2830 int _inner_loop_count; // count loops which need alignment
2831 VectorSet _visited; // Visitation flags
2832 Node_List _tests; // Set of IfNodes & PCTableNodes
2833
Final_Reshape_CountsFinal_Reshape_Counts2834 Final_Reshape_Counts() :
2835 _call_count(0), _float_count(0), _double_count(0),
2836 _java_call_count(0), _inner_loop_count(0) { }
2837
inc_call_countFinal_Reshape_Counts2838 void inc_call_count () { _call_count ++; }
inc_float_countFinal_Reshape_Counts2839 void inc_float_count () { _float_count ++; }
inc_double_countFinal_Reshape_Counts2840 void inc_double_count() { _double_count++; }
inc_java_call_countFinal_Reshape_Counts2841 void inc_java_call_count() { _java_call_count++; }
inc_inner_loop_countFinal_Reshape_Counts2842 void inc_inner_loop_count() { _inner_loop_count++; }
2843
get_call_countFinal_Reshape_Counts2844 int get_call_count () const { return _call_count ; }
get_float_countFinal_Reshape_Counts2845 int get_float_count () const { return _float_count ; }
get_double_countFinal_Reshape_Counts2846 int get_double_count() const { return _double_count; }
get_java_call_countFinal_Reshape_Counts2847 int get_java_call_count() const { return _java_call_count; }
get_inner_loop_countFinal_Reshape_Counts2848 int get_inner_loop_count() const { return _inner_loop_count; }
2849 };
2850
2851 // Eliminate trivially redundant StoreCMs and accumulate their
2852 // precedence edges.
eliminate_redundant_card_marks(Node * n)2853 void Compile::eliminate_redundant_card_marks(Node* n) {
2854 assert(n->Opcode() == Op_StoreCM, "expected StoreCM");
2855 if (n->in(MemNode::Address)->outcnt() > 1) {
2856 // There are multiple users of the same address so it might be
2857 // possible to eliminate some of the StoreCMs
2858 Node* mem = n->in(MemNode::Memory);
2859 Node* adr = n->in(MemNode::Address);
2860 Node* val = n->in(MemNode::ValueIn);
2861 Node* prev = n;
2862 bool done = false;
2863 // Walk the chain of StoreCMs eliminating ones that match. As
2864 // long as it's a chain of single users then the optimization is
2865 // safe. Eliminating partially redundant StoreCMs would require
2866 // cloning copies down the other paths.
2867 while (mem->Opcode() == Op_StoreCM && mem->outcnt() == 1 && !done) {
2868 if (adr == mem->in(MemNode::Address) &&
2869 val == mem->in(MemNode::ValueIn)) {
2870 // redundant StoreCM
2871 if (mem->req() > MemNode::OopStore) {
2872 // Hasn't been processed by this code yet.
2873 n->add_prec(mem->in(MemNode::OopStore));
2874 } else {
2875 // Already converted to precedence edge
2876 for (uint i = mem->req(); i < mem->len(); i++) {
2877 // Accumulate any precedence edges
2878 if (mem->in(i) != NULL) {
2879 n->add_prec(mem->in(i));
2880 }
2881 }
2882 // Everything above this point has been processed.
2883 done = true;
2884 }
2885 // Eliminate the previous StoreCM
2886 prev->set_req(MemNode::Memory, mem->in(MemNode::Memory));
2887 assert(mem->outcnt() == 0, "should be dead");
2888 mem->disconnect_inputs(this);
2889 } else {
2890 prev = mem;
2891 }
2892 mem = prev->in(MemNode::Memory);
2893 }
2894 }
2895 }
2896
2897 //------------------------------final_graph_reshaping_impl----------------------
2898 // Implement items 1-5 from final_graph_reshaping below.
final_graph_reshaping_impl(Node * n,Final_Reshape_Counts & frc)2899 void Compile::final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &frc) {
2900
2901 if ( n->outcnt() == 0 ) return; // dead node
2902 uint nop = n->Opcode();
2903
2904 // Check for 2-input instruction with "last use" on right input.
2905 // Swap to left input. Implements item (2).
2906 if( n->req() == 3 && // two-input instruction
2907 n->in(1)->outcnt() > 1 && // left use is NOT a last use
2908 (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
2909 n->in(2)->outcnt() == 1 &&// right use IS a last use
2910 !n->in(2)->is_Con() ) { // right use is not a constant
2911 // Check for commutative opcode
2912 switch( nop ) {
2913 case Op_AddI: case Op_AddF: case Op_AddD: case Op_AddL:
2914 case Op_MaxI: case Op_MaxL: case Op_MaxF: case Op_MaxD:
2915 case Op_MinI: case Op_MinL: case Op_MinF: case Op_MinD:
2916 case Op_MulI: case Op_MulF: case Op_MulD: case Op_MulL:
2917 case Op_AndL: case Op_XorL: case Op_OrL:
2918 case Op_AndI: case Op_XorI: case Op_OrI: {
2919 // Move "last use" input to left by swapping inputs
2920 n->swap_edges(1, 2);
2921 break;
2922 }
2923 default:
2924 break;
2925 }
2926 }
2927
2928 #ifdef ASSERT
2929 if( n->is_Mem() ) {
2930 int alias_idx = get_alias_index(n->as_Mem()->adr_type());
2931 assert( n->in(0) != NULL || alias_idx != Compile::AliasIdxRaw ||
2932 // oop will be recorded in oop map if load crosses safepoint
2933 n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
2934 LoadNode::is_immutable_value(n->in(MemNode::Address))),
2935 "raw memory operations should have control edge");
2936 }
2937 if (n->is_MemBar()) {
2938 MemBarNode* mb = n->as_MemBar();
2939 if (mb->trailing_store() || mb->trailing_load_store()) {
2940 assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair");
2941 Node* mem = BarrierSet::barrier_set()->barrier_set_c2()->step_over_gc_barrier(mb->in(MemBarNode::Precedent));
2942 assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) ||
2943 (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op");
2944 } else if (mb->leading()) {
2945 assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair");
2946 }
2947 }
2948 #endif
2949 // Count FPU ops and common calls, implements item (3)
2950 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->final_graph_reshaping(this, n, nop);
2951 if (!gc_handled) {
2952 final_graph_reshaping_main_switch(n, frc, nop);
2953 }
2954
2955 // Collect CFG split points
2956 if (n->is_MultiBranch() && !n->is_RangeCheck()) {
2957 frc._tests.push(n);
2958 }
2959 }
2960
final_graph_reshaping_main_switch(Node * n,Final_Reshape_Counts & frc,uint nop)2961 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop) {
2962 switch( nop ) {
2963 // Count all float operations that may use FPU
2964 case Op_AddF:
2965 case Op_SubF:
2966 case Op_MulF:
2967 case Op_DivF:
2968 case Op_NegF:
2969 case Op_ModF:
2970 case Op_ConvI2F:
2971 case Op_ConF:
2972 case Op_CmpF:
2973 case Op_CmpF3:
2974 case Op_StoreF:
2975 case Op_LoadF:
2976 // case Op_ConvL2F: // longs are split into 32-bit halves
2977 frc.inc_float_count();
2978 break;
2979
2980 case Op_ConvF2D:
2981 case Op_ConvD2F:
2982 frc.inc_float_count();
2983 frc.inc_double_count();
2984 break;
2985
2986 // Count all double operations that may use FPU
2987 case Op_AddD:
2988 case Op_SubD:
2989 case Op_MulD:
2990 case Op_DivD:
2991 case Op_NegD:
2992 case Op_ModD:
2993 case Op_ConvI2D:
2994 case Op_ConvD2I:
2995 // case Op_ConvL2D: // handled by leaf call
2996 // case Op_ConvD2L: // handled by leaf call
2997 case Op_ConD:
2998 case Op_CmpD:
2999 case Op_CmpD3:
3000 case Op_StoreD:
3001 case Op_LoadD:
3002 case Op_LoadD_unaligned:
3003 frc.inc_double_count();
3004 break;
3005 case Op_Opaque1: // Remove Opaque Nodes before matching
3006 case Op_Opaque2: // Remove Opaque Nodes before matching
3007 case Op_Opaque3:
3008 n->subsume_by(n->in(1), this);
3009 break;
3010 case Op_CallStaticJava:
3011 case Op_CallJava:
3012 case Op_CallDynamicJava:
3013 frc.inc_java_call_count(); // Count java call site;
3014 case Op_CallRuntime:
3015 case Op_CallLeaf:
3016 case Op_CallNative:
3017 case Op_CallLeafNoFP: {
3018 assert (n->is_Call(), "");
3019 CallNode *call = n->as_Call();
3020 // Count call sites where the FP mode bit would have to be flipped.
3021 // Do not count uncommon runtime calls:
3022 // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
3023 // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
3024 if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) {
3025 frc.inc_call_count(); // Count the call site
3026 } else { // See if uncommon argument is shared
3027 Node *n = call->in(TypeFunc::Parms);
3028 int nop = n->Opcode();
3029 // Clone shared simple arguments to uncommon calls, item (1).
3030 if (n->outcnt() > 1 &&
3031 !n->is_Proj() &&
3032 nop != Op_CreateEx &&
3033 nop != Op_CheckCastPP &&
3034 nop != Op_DecodeN &&
3035 nop != Op_DecodeNKlass &&
3036 !n->is_Mem() &&
3037 !n->is_Phi()) {
3038 Node *x = n->clone();
3039 call->set_req(TypeFunc::Parms, x);
3040 }
3041 }
3042 break;
3043 }
3044
3045 case Op_StoreCM:
3046 {
3047 // Convert OopStore dependence into precedence edge
3048 Node* prec = n->in(MemNode::OopStore);
3049 n->del_req(MemNode::OopStore);
3050 n->add_prec(prec);
3051 eliminate_redundant_card_marks(n);
3052 }
3053
3054 // fall through
3055
3056 case Op_StoreB:
3057 case Op_StoreC:
3058 case Op_StorePConditional:
3059 case Op_StoreI:
3060 case Op_StoreL:
3061 case Op_StoreIConditional:
3062 case Op_StoreLConditional:
3063 case Op_CompareAndSwapB:
3064 case Op_CompareAndSwapS:
3065 case Op_CompareAndSwapI:
3066 case Op_CompareAndSwapL:
3067 case Op_CompareAndSwapP:
3068 case Op_CompareAndSwapN:
3069 case Op_WeakCompareAndSwapB:
3070 case Op_WeakCompareAndSwapS:
3071 case Op_WeakCompareAndSwapI:
3072 case Op_WeakCompareAndSwapL:
3073 case Op_WeakCompareAndSwapP:
3074 case Op_WeakCompareAndSwapN:
3075 case Op_CompareAndExchangeB:
3076 case Op_CompareAndExchangeS:
3077 case Op_CompareAndExchangeI:
3078 case Op_CompareAndExchangeL:
3079 case Op_CompareAndExchangeP:
3080 case Op_CompareAndExchangeN:
3081 case Op_GetAndAddS:
3082 case Op_GetAndAddB:
3083 case Op_GetAndAddI:
3084 case Op_GetAndAddL:
3085 case Op_GetAndSetS:
3086 case Op_GetAndSetB:
3087 case Op_GetAndSetI:
3088 case Op_GetAndSetL:
3089 case Op_GetAndSetP:
3090 case Op_GetAndSetN:
3091 case Op_StoreP:
3092 case Op_StoreN:
3093 case Op_StoreNKlass:
3094 case Op_LoadB:
3095 case Op_LoadUB:
3096 case Op_LoadUS:
3097 case Op_LoadI:
3098 case Op_LoadKlass:
3099 case Op_LoadNKlass:
3100 case Op_LoadL:
3101 case Op_LoadL_unaligned:
3102 case Op_LoadPLocked:
3103 case Op_LoadP:
3104 case Op_LoadN:
3105 case Op_LoadRange:
3106 case Op_LoadS:
3107 break;
3108
3109 case Op_AddP: { // Assert sane base pointers
3110 Node *addp = n->in(AddPNode::Address);
3111 assert( !addp->is_AddP() ||
3112 addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
3113 addp->in(AddPNode::Base) == n->in(AddPNode::Base),
3114 "Base pointers must match (addp %u)", addp->_idx );
3115 #ifdef _LP64
3116 if ((UseCompressedOops || UseCompressedClassPointers) &&
3117 addp->Opcode() == Op_ConP &&
3118 addp == n->in(AddPNode::Base) &&
3119 n->in(AddPNode::Offset)->is_Con()) {
3120 // If the transformation of ConP to ConN+DecodeN is beneficial depends
3121 // on the platform and on the compressed oops mode.
3122 // Use addressing with narrow klass to load with offset on x86.
3123 // Some platforms can use the constant pool to load ConP.
3124 // Do this transformation here since IGVN will convert ConN back to ConP.
3125 const Type* t = addp->bottom_type();
3126 bool is_oop = t->isa_oopptr() != NULL;
3127 bool is_klass = t->isa_klassptr() != NULL;
3128
3129 if ((is_oop && Matcher::const_oop_prefer_decode() ) ||
3130 (is_klass && Matcher::const_klass_prefer_decode())) {
3131 Node* nn = NULL;
3132
3133 int op = is_oop ? Op_ConN : Op_ConNKlass;
3134
3135 // Look for existing ConN node of the same exact type.
3136 Node* r = root();
3137 uint cnt = r->outcnt();
3138 for (uint i = 0; i < cnt; i++) {
3139 Node* m = r->raw_out(i);
3140 if (m!= NULL && m->Opcode() == op &&
3141 m->bottom_type()->make_ptr() == t) {
3142 nn = m;
3143 break;
3144 }
3145 }
3146 if (nn != NULL) {
3147 // Decode a narrow oop to match address
3148 // [R12 + narrow_oop_reg<<3 + offset]
3149 if (is_oop) {
3150 nn = new DecodeNNode(nn, t);
3151 } else {
3152 nn = new DecodeNKlassNode(nn, t);
3153 }
3154 // Check for succeeding AddP which uses the same Base.
3155 // Otherwise we will run into the assertion above when visiting that guy.
3156 for (uint i = 0; i < n->outcnt(); ++i) {
3157 Node *out_i = n->raw_out(i);
3158 if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) {
3159 out_i->set_req(AddPNode::Base, nn);
3160 #ifdef ASSERT
3161 for (uint j = 0; j < out_i->outcnt(); ++j) {
3162 Node *out_j = out_i->raw_out(j);
3163 assert(out_j == NULL || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp,
3164 "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx);
3165 }
3166 #endif
3167 }
3168 }
3169 n->set_req(AddPNode::Base, nn);
3170 n->set_req(AddPNode::Address, nn);
3171 if (addp->outcnt() == 0) {
3172 addp->disconnect_inputs(this);
3173 }
3174 }
3175 }
3176 }
3177 #endif
3178 // platform dependent reshaping of the address expression
3179 reshape_address(n->as_AddP());
3180 break;
3181 }
3182
3183 case Op_CastPP: {
3184 // Remove CastPP nodes to gain more freedom during scheduling but
3185 // keep the dependency they encode as control or precedence edges
3186 // (if control is set already) on memory operations. Some CastPP
3187 // nodes don't have a control (don't carry a dependency): skip
3188 // those.
3189 if (n->in(0) != NULL) {
3190 ResourceMark rm;
3191 Unique_Node_List wq;
3192 wq.push(n);
3193 for (uint next = 0; next < wq.size(); ++next) {
3194 Node *m = wq.at(next);
3195 for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
3196 Node* use = m->fast_out(i);
3197 if (use->is_Mem() || use->is_EncodeNarrowPtr()) {
3198 use->ensure_control_or_add_prec(n->in(0));
3199 } else {
3200 switch(use->Opcode()) {
3201 case Op_AddP:
3202 case Op_DecodeN:
3203 case Op_DecodeNKlass:
3204 case Op_CheckCastPP:
3205 case Op_CastPP:
3206 wq.push(use);
3207 break;
3208 }
3209 }
3210 }
3211 }
3212 }
3213 const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false);
3214 if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
3215 Node* in1 = n->in(1);
3216 const Type* t = n->bottom_type();
3217 Node* new_in1 = in1->clone();
3218 new_in1->as_DecodeN()->set_type(t);
3219
3220 if (!Matcher::narrow_oop_use_complex_address()) {
3221 //
3222 // x86, ARM and friends can handle 2 adds in addressing mode
3223 // and Matcher can fold a DecodeN node into address by using
3224 // a narrow oop directly and do implicit NULL check in address:
3225 //
3226 // [R12 + narrow_oop_reg<<3 + offset]
3227 // NullCheck narrow_oop_reg
3228 //
3229 // On other platforms (Sparc) we have to keep new DecodeN node and
3230 // use it to do implicit NULL check in address:
3231 //
3232 // decode_not_null narrow_oop_reg, base_reg
3233 // [base_reg + offset]
3234 // NullCheck base_reg
3235 //
3236 // Pin the new DecodeN node to non-null path on these platform (Sparc)
3237 // to keep the information to which NULL check the new DecodeN node
3238 // corresponds to use it as value in implicit_null_check().
3239 //
3240 new_in1->set_req(0, n->in(0));
3241 }
3242
3243 n->subsume_by(new_in1, this);
3244 if (in1->outcnt() == 0) {
3245 in1->disconnect_inputs(this);
3246 }
3247 } else {
3248 n->subsume_by(n->in(1), this);
3249 if (n->outcnt() == 0) {
3250 n->disconnect_inputs(this);
3251 }
3252 }
3253 break;
3254 }
3255 #ifdef _LP64
3256 case Op_CmpP:
3257 // Do this transformation here to preserve CmpPNode::sub() and
3258 // other TypePtr related Ideal optimizations (for example, ptr nullness).
3259 if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
3260 Node* in1 = n->in(1);
3261 Node* in2 = n->in(2);
3262 if (!in1->is_DecodeNarrowPtr()) {
3263 in2 = in1;
3264 in1 = n->in(2);
3265 }
3266 assert(in1->is_DecodeNarrowPtr(), "sanity");
3267
3268 Node* new_in2 = NULL;
3269 if (in2->is_DecodeNarrowPtr()) {
3270 assert(in2->Opcode() == in1->Opcode(), "must be same node type");
3271 new_in2 = in2->in(1);
3272 } else if (in2->Opcode() == Op_ConP) {
3273 const Type* t = in2->bottom_type();
3274 if (t == TypePtr::NULL_PTR) {
3275 assert(in1->is_DecodeN(), "compare klass to null?");
3276 // Don't convert CmpP null check into CmpN if compressed
3277 // oops implicit null check is not generated.
3278 // This will allow to generate normal oop implicit null check.
3279 if (Matcher::gen_narrow_oop_implicit_null_checks())
3280 new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR);
3281 //
3282 // This transformation together with CastPP transformation above
3283 // will generated code for implicit NULL checks for compressed oops.
3284 //
3285 // The original code after Optimize()
3286 //
3287 // LoadN memory, narrow_oop_reg
3288 // decode narrow_oop_reg, base_reg
3289 // CmpP base_reg, NULL
3290 // CastPP base_reg // NotNull
3291 // Load [base_reg + offset], val_reg
3292 //
3293 // after these transformations will be
3294 //
3295 // LoadN memory, narrow_oop_reg
3296 // CmpN narrow_oop_reg, NULL
3297 // decode_not_null narrow_oop_reg, base_reg
3298 // Load [base_reg + offset], val_reg
3299 //
3300 // and the uncommon path (== NULL) will use narrow_oop_reg directly
3301 // since narrow oops can be used in debug info now (see the code in
3302 // final_graph_reshaping_walk()).
3303 //
3304 // At the end the code will be matched to
3305 // on x86:
3306 //
3307 // Load_narrow_oop memory, narrow_oop_reg
3308 // Load [R12 + narrow_oop_reg<<3 + offset], val_reg
3309 // NullCheck narrow_oop_reg
3310 //
3311 // and on sparc:
3312 //
3313 // Load_narrow_oop memory, narrow_oop_reg
3314 // decode_not_null narrow_oop_reg, base_reg
3315 // Load [base_reg + offset], val_reg
3316 // NullCheck base_reg
3317 //
3318 } else if (t->isa_oopptr()) {
3319 new_in2 = ConNode::make(t->make_narrowoop());
3320 } else if (t->isa_klassptr()) {
3321 new_in2 = ConNode::make(t->make_narrowklass());
3322 }
3323 }
3324 if (new_in2 != NULL) {
3325 Node* cmpN = new CmpNNode(in1->in(1), new_in2);
3326 n->subsume_by(cmpN, this);
3327 if (in1->outcnt() == 0) {
3328 in1->disconnect_inputs(this);
3329 }
3330 if (in2->outcnt() == 0) {
3331 in2->disconnect_inputs(this);
3332 }
3333 }
3334 }
3335 break;
3336
3337 case Op_DecodeN:
3338 case Op_DecodeNKlass:
3339 assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
3340 // DecodeN could be pinned when it can't be fold into
3341 // an address expression, see the code for Op_CastPP above.
3342 assert(n->in(0) == NULL || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
3343 break;
3344
3345 case Op_EncodeP:
3346 case Op_EncodePKlass: {
3347 Node* in1 = n->in(1);
3348 if (in1->is_DecodeNarrowPtr()) {
3349 n->subsume_by(in1->in(1), this);
3350 } else if (in1->Opcode() == Op_ConP) {
3351 const Type* t = in1->bottom_type();
3352 if (t == TypePtr::NULL_PTR) {
3353 assert(t->isa_oopptr(), "null klass?");
3354 n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this);
3355 } else if (t->isa_oopptr()) {
3356 n->subsume_by(ConNode::make(t->make_narrowoop()), this);
3357 } else if (t->isa_klassptr()) {
3358 n->subsume_by(ConNode::make(t->make_narrowklass()), this);
3359 }
3360 }
3361 if (in1->outcnt() == 0) {
3362 in1->disconnect_inputs(this);
3363 }
3364 break;
3365 }
3366
3367 case Op_Proj: {
3368 if (OptimizeStringConcat || IncrementalInline) {
3369 ProjNode* proj = n->as_Proj();
3370 if (proj->_is_io_use) {
3371 assert(proj->_con == TypeFunc::I_O || proj->_con == TypeFunc::Memory, "");
3372 // Separate projections were used for the exception path which
3373 // are normally removed by a late inline. If it wasn't inlined
3374 // then they will hang around and should just be replaced with
3375 // the original one. Merge them.
3376 Node* non_io_proj = proj->in(0)->as_Multi()->proj_out_or_null(proj->_con, false /*is_io_use*/);
3377 if (non_io_proj != NULL) {
3378 proj->subsume_by(non_io_proj , this);
3379 }
3380 }
3381 }
3382 break;
3383 }
3384
3385 case Op_Phi:
3386 if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
3387 // The EncodeP optimization may create Phi with the same edges
3388 // for all paths. It is not handled well by Register Allocator.
3389 Node* unique_in = n->in(1);
3390 assert(unique_in != NULL, "");
3391 uint cnt = n->req();
3392 for (uint i = 2; i < cnt; i++) {
3393 Node* m = n->in(i);
3394 assert(m != NULL, "");
3395 if (unique_in != m)
3396 unique_in = NULL;
3397 }
3398 if (unique_in != NULL) {
3399 n->subsume_by(unique_in, this);
3400 }
3401 }
3402 break;
3403
3404 #endif
3405
3406 #ifdef ASSERT
3407 case Op_CastII:
3408 // Verify that all range check dependent CastII nodes were removed.
3409 if (n->isa_CastII()->has_range_check()) {
3410 n->dump(3);
3411 assert(false, "Range check dependent CastII node was not removed");
3412 }
3413 break;
3414 #endif
3415
3416 case Op_ModI:
3417 if (UseDivMod) {
3418 // Check if a%b and a/b both exist
3419 Node* d = n->find_similar(Op_DivI);
3420 if (d) {
3421 // Replace them with a fused divmod if supported
3422 if (Matcher::has_match_rule(Op_DivModI)) {
3423 DivModINode* divmod = DivModINode::make(n);
3424 d->subsume_by(divmod->div_proj(), this);
3425 n->subsume_by(divmod->mod_proj(), this);
3426 } else {
3427 // replace a%b with a-((a/b)*b)
3428 Node* mult = new MulINode(d, d->in(2));
3429 Node* sub = new SubINode(d->in(1), mult);
3430 n->subsume_by(sub, this);
3431 }
3432 }
3433 }
3434 break;
3435
3436 case Op_ModL:
3437 if (UseDivMod) {
3438 // Check if a%b and a/b both exist
3439 Node* d = n->find_similar(Op_DivL);
3440 if (d) {
3441 // Replace them with a fused divmod if supported
3442 if (Matcher::has_match_rule(Op_DivModL)) {
3443 DivModLNode* divmod = DivModLNode::make(n);
3444 d->subsume_by(divmod->div_proj(), this);
3445 n->subsume_by(divmod->mod_proj(), this);
3446 } else {
3447 // replace a%b with a-((a/b)*b)
3448 Node* mult = new MulLNode(d, d->in(2));
3449 Node* sub = new SubLNode(d->in(1), mult);
3450 n->subsume_by(sub, this);
3451 }
3452 }
3453 }
3454 break;
3455
3456 case Op_LoadVector:
3457 case Op_StoreVector:
3458 case Op_LoadVectorGather:
3459 case Op_StoreVectorScatter:
3460 case Op_VectorMaskGen:
3461 case Op_LoadVectorMasked:
3462 case Op_StoreVectorMasked:
3463 break;
3464
3465 case Op_AddReductionVI:
3466 case Op_AddReductionVL:
3467 case Op_AddReductionVF:
3468 case Op_AddReductionVD:
3469 case Op_MulReductionVI:
3470 case Op_MulReductionVL:
3471 case Op_MulReductionVF:
3472 case Op_MulReductionVD:
3473 case Op_MinReductionV:
3474 case Op_MaxReductionV:
3475 case Op_AndReductionV:
3476 case Op_OrReductionV:
3477 case Op_XorReductionV:
3478 break;
3479
3480 case Op_PackB:
3481 case Op_PackS:
3482 case Op_PackI:
3483 case Op_PackF:
3484 case Op_PackL:
3485 case Op_PackD:
3486 if (n->req()-1 > 2) {
3487 // Replace many operand PackNodes with a binary tree for matching
3488 PackNode* p = (PackNode*) n;
3489 Node* btp = p->binary_tree_pack(1, n->req());
3490 n->subsume_by(btp, this);
3491 }
3492 break;
3493 case Op_Loop:
3494 assert(!n->as_Loop()->is_transformed_long_loop() || _loop_opts_cnt == 0, "should have been turned into a counted loop");
3495 case Op_CountedLoop:
3496 case Op_LongCountedLoop:
3497 case Op_OuterStripMinedLoop:
3498 if (n->as_Loop()->is_inner_loop()) {
3499 frc.inc_inner_loop_count();
3500 }
3501 n->as_Loop()->verify_strip_mined(0);
3502 break;
3503 case Op_LShiftI:
3504 case Op_RShiftI:
3505 case Op_URShiftI:
3506 case Op_LShiftL:
3507 case Op_RShiftL:
3508 case Op_URShiftL:
3509 if (Matcher::need_masked_shift_count) {
3510 // The cpu's shift instructions don't restrict the count to the
3511 // lower 5/6 bits. We need to do the masking ourselves.
3512 Node* in2 = n->in(2);
3513 juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
3514 const TypeInt* t = in2->find_int_type();
3515 if (t != NULL && t->is_con()) {
3516 juint shift = t->get_con();
3517 if (shift > mask) { // Unsigned cmp
3518 n->set_req(2, ConNode::make(TypeInt::make(shift & mask)));
3519 }
3520 } else {
3521 if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
3522 Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask)));
3523 n->set_req(2, shift);
3524 }
3525 }
3526 if (in2->outcnt() == 0) { // Remove dead node
3527 in2->disconnect_inputs(this);
3528 }
3529 }
3530 break;
3531 case Op_MemBarStoreStore:
3532 case Op_MemBarRelease:
3533 // Break the link with AllocateNode: it is no longer useful and
3534 // confuses register allocation.
3535 if (n->req() > MemBarNode::Precedent) {
3536 n->set_req(MemBarNode::Precedent, top());
3537 }
3538 break;
3539 case Op_MemBarAcquire: {
3540 if (n->as_MemBar()->trailing_load() && n->req() > MemBarNode::Precedent) {
3541 // At parse time, the trailing MemBarAcquire for a volatile load
3542 // is created with an edge to the load. After optimizations,
3543 // that input may be a chain of Phis. If those phis have no
3544 // other use, then the MemBarAcquire keeps them alive and
3545 // register allocation can be confused.
3546 ResourceMark rm;
3547 Unique_Node_List wq;
3548 wq.push(n->in(MemBarNode::Precedent));
3549 n->set_req(MemBarNode::Precedent, top());
3550 while (wq.size() > 0) {
3551 Node* m = wq.pop();
3552 if (m->outcnt() == 0) {
3553 for (uint j = 0; j < m->req(); j++) {
3554 Node* in = m->in(j);
3555 if (in != NULL) {
3556 wq.push(in);
3557 }
3558 }
3559 m->disconnect_inputs(this);
3560 }
3561 }
3562 }
3563 break;
3564 }
3565 case Op_RangeCheck: {
3566 RangeCheckNode* rc = n->as_RangeCheck();
3567 Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt);
3568 n->subsume_by(iff, this);
3569 frc._tests.push(iff);
3570 break;
3571 }
3572 case Op_ConvI2L: {
3573 if (!Matcher::convi2l_type_required) {
3574 // Code generation on some platforms doesn't need accurate
3575 // ConvI2L types. Widening the type can help remove redundant
3576 // address computations.
3577 n->as_Type()->set_type(TypeLong::INT);
3578 ResourceMark rm;
3579 Unique_Node_List wq;
3580 wq.push(n);
3581 for (uint next = 0; next < wq.size(); next++) {
3582 Node *m = wq.at(next);
3583
3584 for(;;) {
3585 // Loop over all nodes with identical inputs edges as m
3586 Node* k = m->find_similar(m->Opcode());
3587 if (k == NULL) {
3588 break;
3589 }
3590 // Push their uses so we get a chance to remove node made
3591 // redundant
3592 for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) {
3593 Node* u = k->fast_out(i);
3594 if (u->Opcode() == Op_LShiftL ||
3595 u->Opcode() == Op_AddL ||
3596 u->Opcode() == Op_SubL ||
3597 u->Opcode() == Op_AddP) {
3598 wq.push(u);
3599 }
3600 }
3601 // Replace all nodes with identical edges as m with m
3602 k->subsume_by(m, this);
3603 }
3604 }
3605 }
3606 break;
3607 }
3608 case Op_CmpUL: {
3609 if (!Matcher::has_match_rule(Op_CmpUL)) {
3610 // No support for unsigned long comparisons
3611 ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
3612 Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
3613 Node* orl = new OrLNode(n->in(1), sign_bit_mask);
3614 ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
3615 Node* andl = new AndLNode(orl, remove_sign_mask);
3616 Node* cmp = new CmpLNode(andl, n->in(2));
3617 n->subsume_by(cmp, this);
3618 }
3619 break;
3620 }
3621 default:
3622 assert(!n->is_Call(), "");
3623 assert(!n->is_Mem(), "");
3624 assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3625 break;
3626 }
3627 }
3628
3629 //------------------------------final_graph_reshaping_walk---------------------
3630 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3631 // requires that the walk visits a node's inputs before visiting the node.
final_graph_reshaping_walk(Node_Stack & nstack,Node * root,Final_Reshape_Counts & frc)3632 void Compile::final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &frc ) {
3633 Unique_Node_List sfpt;
3634
3635 frc._visited.set(root->_idx); // first, mark node as visited
3636 uint cnt = root->req();
3637 Node *n = root;
3638 uint i = 0;
3639 while (true) {
3640 if (i < cnt) {
3641 // Place all non-visited non-null inputs onto stack
3642 Node* m = n->in(i);
3643 ++i;
3644 if (m != NULL && !frc._visited.test_set(m->_idx)) {
3645 if (m->is_SafePoint() && m->as_SafePoint()->jvms() != NULL) {
3646 // compute worst case interpreter size in case of a deoptimization
3647 update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
3648
3649 sfpt.push(m);
3650 }
3651 cnt = m->req();
3652 nstack.push(n, i); // put on stack parent and next input's index
3653 n = m;
3654 i = 0;
3655 }
3656 } else {
3657 // Now do post-visit work
3658 final_graph_reshaping_impl( n, frc );
3659 if (nstack.is_empty())
3660 break; // finished
3661 n = nstack.node(); // Get node from stack
3662 cnt = n->req();
3663 i = nstack.index();
3664 nstack.pop(); // Shift to the next node on stack
3665 }
3666 }
3667
3668 // Skip next transformation if compressed oops are not used.
3669 if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) ||
3670 (!UseCompressedOops && !UseCompressedClassPointers))
3671 return;
3672
3673 // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
3674 // It could be done for an uncommon traps or any safepoints/calls
3675 // if the DecodeN/DecodeNKlass node is referenced only in a debug info.
3676 while (sfpt.size() > 0) {
3677 n = sfpt.pop();
3678 JVMState *jvms = n->as_SafePoint()->jvms();
3679 assert(jvms != NULL, "sanity");
3680 int start = jvms->debug_start();
3681 int end = n->req();
3682 bool is_uncommon = (n->is_CallStaticJava() &&
3683 n->as_CallStaticJava()->uncommon_trap_request() != 0);
3684 for (int j = start; j < end; j++) {
3685 Node* in = n->in(j);
3686 if (in->is_DecodeNarrowPtr()) {
3687 bool safe_to_skip = true;
3688 if (!is_uncommon ) {
3689 // Is it safe to skip?
3690 for (uint i = 0; i < in->outcnt(); i++) {
3691 Node* u = in->raw_out(i);
3692 if (!u->is_SafePoint() ||
3693 (u->is_Call() && u->as_Call()->has_non_debug_use(n))) {
3694 safe_to_skip = false;
3695 }
3696 }
3697 }
3698 if (safe_to_skip) {
3699 n->set_req(j, in->in(1));
3700 }
3701 if (in->outcnt() == 0) {
3702 in->disconnect_inputs(this);
3703 }
3704 }
3705 }
3706 }
3707 }
3708
3709 //------------------------------final_graph_reshaping--------------------------
3710 // Final Graph Reshaping.
3711 //
3712 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
3713 // and not commoned up and forced early. Must come after regular
3714 // optimizations to avoid GVN undoing the cloning. Clone constant
3715 // inputs to Loop Phis; these will be split by the allocator anyways.
3716 // Remove Opaque nodes.
3717 // (2) Move last-uses by commutative operations to the left input to encourage
3718 // Intel update-in-place two-address operations and better register usage
3719 // on RISCs. Must come after regular optimizations to avoid GVN Ideal
3720 // calls canonicalizing them back.
3721 // (3) Count the number of double-precision FP ops, single-precision FP ops
3722 // and call sites. On Intel, we can get correct rounding either by
3723 // forcing singles to memory (requires extra stores and loads after each
3724 // FP bytecode) or we can set a rounding mode bit (requires setting and
3725 // clearing the mode bit around call sites). The mode bit is only used
3726 // if the relative frequency of single FP ops to calls is low enough.
3727 // This is a key transform for SPEC mpeg_audio.
3728 // (4) Detect infinite loops; blobs of code reachable from above but not
3729 // below. Several of the Code_Gen algorithms fail on such code shapes,
3730 // so we simply bail out. Happens a lot in ZKM.jar, but also happens
3731 // from time to time in other codes (such as -Xcomp finalizer loops, etc).
3732 // Detection is by looking for IfNodes where only 1 projection is
3733 // reachable from below or CatchNodes missing some targets.
3734 // (5) Assert for insane oop offsets in debug mode.
3735
final_graph_reshaping()3736 bool Compile::final_graph_reshaping() {
3737 // an infinite loop may have been eliminated by the optimizer,
3738 // in which case the graph will be empty.
3739 if (root()->req() == 1) {
3740 record_method_not_compilable("trivial infinite loop");
3741 return true;
3742 }
3743
3744 // Expensive nodes have their control input set to prevent the GVN
3745 // from freely commoning them. There's no GVN beyond this point so
3746 // no need to keep the control input. We want the expensive nodes to
3747 // be freely moved to the least frequent code path by gcm.
3748 assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
3749 for (int i = 0; i < expensive_count(); i++) {
3750 _expensive_nodes.at(i)->set_req(0, NULL);
3751 }
3752
3753 Final_Reshape_Counts frc;
3754
3755 // Visit everybody reachable!
3756 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
3757 Node_Stack nstack(live_nodes() >> 1);
3758 final_graph_reshaping_walk(nstack, root(), frc);
3759
3760 // Check for unreachable (from below) code (i.e., infinite loops).
3761 for( uint i = 0; i < frc._tests.size(); i++ ) {
3762 MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
3763 // Get number of CFG targets.
3764 // Note that PCTables include exception targets after calls.
3765 uint required_outcnt = n->required_outcnt();
3766 if (n->outcnt() != required_outcnt) {
3767 // Check for a few special cases. Rethrow Nodes never take the
3768 // 'fall-thru' path, so expected kids is 1 less.
3769 if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
3770 if (n->in(0)->in(0)->is_Call()) {
3771 CallNode *call = n->in(0)->in(0)->as_Call();
3772 if (call->entry_point() == OptoRuntime::rethrow_stub()) {
3773 required_outcnt--; // Rethrow always has 1 less kid
3774 } else if (call->req() > TypeFunc::Parms &&
3775 call->is_CallDynamicJava()) {
3776 // Check for null receiver. In such case, the optimizer has
3777 // detected that the virtual call will always result in a null
3778 // pointer exception. The fall-through projection of this CatchNode
3779 // will not be populated.
3780 Node *arg0 = call->in(TypeFunc::Parms);
3781 if (arg0->is_Type() &&
3782 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
3783 required_outcnt--;
3784 }
3785 } else if (call->entry_point() == OptoRuntime::new_array_Java() &&
3786 call->req() > TypeFunc::Parms+1 &&
3787 call->is_CallStaticJava()) {
3788 // Check for negative array length. In such case, the optimizer has
3789 // detected that the allocation attempt will always result in an
3790 // exception. There is no fall-through projection of this CatchNode .
3791 Node *arg1 = call->in(TypeFunc::Parms+1);
3792 if (arg1->is_Type() &&
3793 arg1->as_Type()->type()->join(TypeInt::POS)->empty()) {
3794 required_outcnt--;
3795 }
3796 }
3797 }
3798 }
3799 // Recheck with a better notion of 'required_outcnt'
3800 if (n->outcnt() != required_outcnt) {
3801 record_method_not_compilable("malformed control flow");
3802 return true; // Not all targets reachable!
3803 }
3804 }
3805 // Check that I actually visited all kids. Unreached kids
3806 // must be infinite loops.
3807 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
3808 if (!frc._visited.test(n->fast_out(j)->_idx)) {
3809 record_method_not_compilable("infinite loop");
3810 return true; // Found unvisited kid; must be unreach
3811 }
3812
3813 // Here so verification code in final_graph_reshaping_walk()
3814 // always see an OuterStripMinedLoopEnd
3815 if (n->is_OuterStripMinedLoopEnd() || n->is_LongCountedLoopEnd()) {
3816 IfNode* init_iff = n->as_If();
3817 Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt);
3818 n->subsume_by(iff, this);
3819 }
3820 }
3821
3822 #ifdef IA32
3823 // If original bytecodes contained a mixture of floats and doubles
3824 // check if the optimizer has made it homogenous, item (3).
3825 if (UseSSE == 0 &&
3826 frc.get_float_count() > 32 &&
3827 frc.get_double_count() == 0 &&
3828 (10 * frc.get_call_count() < frc.get_float_count()) ) {
3829 set_24_bit_selection_and_mode(false, true);
3830 }
3831 #endif // IA32
3832
3833 set_java_calls(frc.get_java_call_count());
3834 set_inner_loops(frc.get_inner_loop_count());
3835
3836 // No infinite loops, no reason to bail out.
3837 return false;
3838 }
3839
3840 //-----------------------------too_many_traps----------------------------------
3841 // Report if there are too many traps at the current method and bci.
3842 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
too_many_traps(ciMethod * method,int bci,Deoptimization::DeoptReason reason)3843 bool Compile::too_many_traps(ciMethod* method,
3844 int bci,
3845 Deoptimization::DeoptReason reason) {
3846 ciMethodData* md = method->method_data();
3847 if (md->is_empty()) {
3848 // Assume the trap has not occurred, or that it occurred only
3849 // because of a transient condition during start-up in the interpreter.
3850 return false;
3851 }
3852 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
3853 if (md->has_trap_at(bci, m, reason) != 0) {
3854 // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
3855 // Also, if there are multiple reasons, or if there is no per-BCI record,
3856 // assume the worst.
3857 if (log())
3858 log()->elem("observe trap='%s' count='%d'",
3859 Deoptimization::trap_reason_name(reason),
3860 md->trap_count(reason));
3861 return true;
3862 } else {
3863 // Ignore method/bci and see if there have been too many globally.
3864 return too_many_traps(reason, md);
3865 }
3866 }
3867
3868 // Less-accurate variant which does not require a method and bci.
too_many_traps(Deoptimization::DeoptReason reason,ciMethodData * logmd)3869 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
3870 ciMethodData* logmd) {
3871 if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
3872 // Too many traps globally.
3873 // Note that we use cumulative trap_count, not just md->trap_count.
3874 if (log()) {
3875 int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason);
3876 log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
3877 Deoptimization::trap_reason_name(reason),
3878 mcount, trap_count(reason));
3879 }
3880 return true;
3881 } else {
3882 // The coast is clear.
3883 return false;
3884 }
3885 }
3886
3887 //--------------------------too_many_recompiles--------------------------------
3888 // Report if there are too many recompiles at the current method and bci.
3889 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
3890 // Is not eager to return true, since this will cause the compiler to use
3891 // Action_none for a trap point, to avoid too many recompilations.
too_many_recompiles(ciMethod * method,int bci,Deoptimization::DeoptReason reason)3892 bool Compile::too_many_recompiles(ciMethod* method,
3893 int bci,
3894 Deoptimization::DeoptReason reason) {
3895 ciMethodData* md = method->method_data();
3896 if (md->is_empty()) {
3897 // Assume the trap has not occurred, or that it occurred only
3898 // because of a transient condition during start-up in the interpreter.
3899 return false;
3900 }
3901 // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
3902 uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
3903 uint m_cutoff = (uint) PerMethodRecompilationCutoff / 2 + 1; // not zero
3904 Deoptimization::DeoptReason per_bc_reason
3905 = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
3906 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
3907 if ((per_bc_reason == Deoptimization::Reason_none
3908 || md->has_trap_at(bci, m, reason) != 0)
3909 // The trap frequency measure we care about is the recompile count:
3910 && md->trap_recompiled_at(bci, m)
3911 && md->overflow_recompile_count() >= bc_cutoff) {
3912 // Do not emit a trap here if it has already caused recompilations.
3913 // Also, if there are multiple reasons, or if there is no per-BCI record,
3914 // assume the worst.
3915 if (log())
3916 log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
3917 Deoptimization::trap_reason_name(reason),
3918 md->trap_count(reason),
3919 md->overflow_recompile_count());
3920 return true;
3921 } else if (trap_count(reason) != 0
3922 && decompile_count() >= m_cutoff) {
3923 // Too many recompiles globally, and we have seen this sort of trap.
3924 // Use cumulative decompile_count, not just md->decompile_count.
3925 if (log())
3926 log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
3927 Deoptimization::trap_reason_name(reason),
3928 md->trap_count(reason), trap_count(reason),
3929 md->decompile_count(), decompile_count());
3930 return true;
3931 } else {
3932 // The coast is clear.
3933 return false;
3934 }
3935 }
3936
3937 // Compute when not to trap. Used by matching trap based nodes and
3938 // NullCheck optimization.
set_allowed_deopt_reasons()3939 void Compile::set_allowed_deopt_reasons() {
3940 _allowed_reasons = 0;
3941 if (is_method_compilation()) {
3942 for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
3943 assert(rs < BitsPerInt, "recode bit map");
3944 if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
3945 _allowed_reasons |= nth_bit(rs);
3946 }
3947 }
3948 }
3949 }
3950
needs_clinit_barrier(ciMethod * method,ciMethod * accessing_method)3951 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
3952 return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
3953 }
3954
needs_clinit_barrier(ciField * field,ciMethod * accessing_method)3955 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
3956 return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
3957 }
3958
needs_clinit_barrier(ciInstanceKlass * holder,ciMethod * accessing_method)3959 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
3960 if (holder->is_initialized()) {
3961 return false;
3962 }
3963 if (holder->is_being_initialized()) {
3964 if (accessing_method->holder() == holder) {
3965 // Access inside a class. The barrier can be elided when access happens in <clinit>,
3966 // <init>, or a static method. In all those cases, there was an initialization
3967 // barrier on the holder klass passed.
3968 if (accessing_method->is_static_initializer() ||
3969 accessing_method->is_object_initializer() ||
3970 accessing_method->is_static()) {
3971 return false;
3972 }
3973 } else if (accessing_method->holder()->is_subclass_of(holder)) {
3974 // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
3975 // In case of <init> or a static method, the barrier is on the subclass is not enough:
3976 // child class can become fully initialized while its parent class is still being initialized.
3977 if (accessing_method->is_static_initializer()) {
3978 return false;
3979 }
3980 }
3981 ciMethod* root = method(); // the root method of compilation
3982 if (root != accessing_method) {
3983 return needs_clinit_barrier(holder, root); // check access in the context of compilation root
3984 }
3985 }
3986 return true;
3987 }
3988
3989 #ifndef PRODUCT
3990 //------------------------------verify_graph_edges---------------------------
3991 // Walk the Graph and verify that there is a one-to-one correspondence
3992 // between Use-Def edges and Def-Use edges in the graph.
verify_graph_edges(bool no_dead_code)3993 void Compile::verify_graph_edges(bool no_dead_code) {
3994 if (VerifyGraphEdges) {
3995 Unique_Node_List visited;
3996 // Call recursive graph walk to check edges
3997 _root->verify_edges(visited);
3998 if (no_dead_code) {
3999 // Now make sure that no visited node is used by an unvisited node.
4000 bool dead_nodes = false;
4001 Unique_Node_List checked;
4002 while (visited.size() > 0) {
4003 Node* n = visited.pop();
4004 checked.push(n);
4005 for (uint i = 0; i < n->outcnt(); i++) {
4006 Node* use = n->raw_out(i);
4007 if (checked.member(use)) continue; // already checked
4008 if (visited.member(use)) continue; // already in the graph
4009 if (use->is_Con()) continue; // a dead ConNode is OK
4010 // At this point, we have found a dead node which is DU-reachable.
4011 if (!dead_nodes) {
4012 tty->print_cr("*** Dead nodes reachable via DU edges:");
4013 dead_nodes = true;
4014 }
4015 use->dump(2);
4016 tty->print_cr("---");
4017 checked.push(use); // No repeats; pretend it is now checked.
4018 }
4019 }
4020 assert(!dead_nodes, "using nodes must be reachable from root");
4021 }
4022 }
4023 }
4024 #endif
4025
4026 // The Compile object keeps track of failure reasons separately from the ciEnv.
4027 // This is required because there is not quite a 1-1 relation between the
4028 // ciEnv and its compilation task and the Compile object. Note that one
4029 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
4030 // to backtrack and retry without subsuming loads. Other than this backtracking
4031 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
4032 // by the logic in C2Compiler.
record_failure(const char * reason)4033 void Compile::record_failure(const char* reason) {
4034 if (log() != NULL) {
4035 log()->elem("failure reason='%s' phase='compile'", reason);
4036 }
4037 if (_failure_reason == NULL) {
4038 // Record the first failure reason.
4039 _failure_reason = reason;
4040 }
4041
4042 if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
4043 C->print_method(PHASE_FAILURE);
4044 }
4045 _root = NULL; // flush the graph, too
4046 }
4047
TracePhase(const char * name,elapsedTimer * accumulator)4048 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator)
4049 : TraceTime(name, accumulator, CITime, CITimeVerbose),
4050 _phase_name(name), _dolog(CITimeVerbose)
4051 {
4052 if (_dolog) {
4053 C = Compile::current();
4054 _log = C->log();
4055 } else {
4056 C = NULL;
4057 _log = NULL;
4058 }
4059 if (_log != NULL) {
4060 _log->begin_head("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
4061 _log->stamp();
4062 _log->end_head();
4063 }
4064 }
4065
~TracePhase()4066 Compile::TracePhase::~TracePhase() {
4067
4068 C = Compile::current();
4069 if (_dolog) {
4070 _log = C->log();
4071 } else {
4072 _log = NULL;
4073 }
4074
4075 #ifdef ASSERT
4076 if (PrintIdealNodeCount) {
4077 tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
4078 _phase_name, C->unique(), C->live_nodes(), C->count_live_nodes_by_graph_walk());
4079 }
4080
4081 if (VerifyIdealNodeCount) {
4082 Compile::current()->print_missing_nodes();
4083 }
4084 #endif
4085
4086 if (_log != NULL) {
4087 _log->done("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
4088 }
4089 }
4090
4091 //----------------------------static_subtype_check-----------------------------
4092 // Shortcut important common cases when superklass is exact:
4093 // (0) superklass is java.lang.Object (can occur in reflective code)
4094 // (1) subklass is already limited to a subtype of superklass => always ok
4095 // (2) subklass does not overlap with superklass => always fail
4096 // (3) superklass has NO subtypes and we can check with a simple compare.
static_subtype_check(ciKlass * superk,ciKlass * subk)4097 int Compile::static_subtype_check(ciKlass* superk, ciKlass* subk) {
4098 if (StressReflectiveCode) {
4099 return SSC_full_test; // Let caller generate the general case.
4100 }
4101
4102 if (superk == env()->Object_klass()) {
4103 return SSC_always_true; // (0) this test cannot fail
4104 }
4105
4106 ciType* superelem = superk;
4107 if (superelem->is_array_klass())
4108 superelem = superelem->as_array_klass()->base_element_type();
4109
4110 if (!subk->is_interface()) { // cannot trust static interface types yet
4111 if (subk->is_subtype_of(superk)) {
4112 return SSC_always_true; // (1) false path dead; no dynamic test needed
4113 }
4114 if (!(superelem->is_klass() && superelem->as_klass()->is_interface()) &&
4115 !superk->is_subtype_of(subk)) {
4116 return SSC_always_false;
4117 }
4118 }
4119
4120 // If casting to an instance klass, it must have no subtypes
4121 if (superk->is_interface()) {
4122 // Cannot trust interfaces yet.
4123 // %%% S.B. superk->nof_implementors() == 1
4124 } else if (superelem->is_instance_klass()) {
4125 ciInstanceKlass* ik = superelem->as_instance_klass();
4126 if (!ik->has_subklass() && !ik->is_interface()) {
4127 if (!ik->is_final()) {
4128 // Add a dependency if there is a chance of a later subclass.
4129 dependencies()->assert_leaf_type(ik);
4130 }
4131 return SSC_easy_test; // (3) caller can do a simple ptr comparison
4132 }
4133 } else {
4134 // A primitive array type has no subtypes.
4135 return SSC_easy_test; // (3) caller can do a simple ptr comparison
4136 }
4137
4138 return SSC_full_test;
4139 }
4140
conv_I2X_index(PhaseGVN * phase,Node * idx,const TypeInt * sizetype,Node * ctrl)4141 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) {
4142 #ifdef _LP64
4143 // The scaled index operand to AddP must be a clean 64-bit value.
4144 // Java allows a 32-bit int to be incremented to a negative
4145 // value, which appears in a 64-bit register as a large
4146 // positive number. Using that large positive number as an
4147 // operand in pointer arithmetic has bad consequences.
4148 // On the other hand, 32-bit overflow is rare, and the possibility
4149 // can often be excluded, if we annotate the ConvI2L node with
4150 // a type assertion that its value is known to be a small positive
4151 // number. (The prior range check has ensured this.)
4152 // This assertion is used by ConvI2LNode::Ideal.
4153 int index_max = max_jint - 1; // array size is max_jint, index is one less
4154 if (sizetype != NULL) index_max = sizetype->_hi - 1;
4155 const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax);
4156 idx = constrained_convI2L(phase, idx, iidxtype, ctrl);
4157 #endif
4158 return idx;
4159 }
4160
4161 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
constrained_convI2L(PhaseGVN * phase,Node * value,const TypeInt * itype,Node * ctrl)4162 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl) {
4163 if (ctrl != NULL) {
4164 // Express control dependency by a CastII node with a narrow type.
4165 value = new CastIINode(value, itype, false, true /* range check dependency */);
4166 // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
4167 // node from floating above the range check during loop optimizations. Otherwise, the
4168 // ConvI2L node may be eliminated independently of the range check, causing the data path
4169 // to become TOP while the control path is still there (although it's unreachable).
4170 value->set_req(0, ctrl);
4171 value = phase->transform(value);
4172 }
4173 const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
4174 return phase->transform(new ConvI2LNode(value, ltype));
4175 }
4176
print_inlining_stream_free()4177 void Compile::print_inlining_stream_free() {
4178 if (_print_inlining_stream != NULL) {
4179 _print_inlining_stream->~stringStream();
4180 _print_inlining_stream = NULL;
4181 }
4182 }
4183
4184 // The message about the current inlining is accumulated in
4185 // _print_inlining_stream and transfered into the _print_inlining_list
4186 // once we know whether inlining succeeds or not. For regular
4187 // inlining, messages are appended to the buffer pointed by
4188 // _print_inlining_idx in the _print_inlining_list. For late inlining,
4189 // a new buffer is added after _print_inlining_idx in the list. This
4190 // way we can update the inlining message for late inlining call site
4191 // when the inlining is attempted again.
print_inlining_init()4192 void Compile::print_inlining_init() {
4193 if (print_inlining() || print_intrinsics()) {
4194 // print_inlining_init is actually called several times.
4195 print_inlining_stream_free();
4196 _print_inlining_stream = new stringStream();
4197 // Watch out: The memory initialized by the constructor call PrintInliningBuffer()
4198 // will be copied into the only initial element. The default destructor of
4199 // PrintInliningBuffer will be called when leaving the scope here. If it
4200 // would destuct the enclosed stringStream _print_inlining_list[0]->_ss
4201 // would be destructed, too!
4202 _print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer>(comp_arena(), 1, 1, PrintInliningBuffer());
4203 }
4204 }
4205
print_inlining_reinit()4206 void Compile::print_inlining_reinit() {
4207 if (print_inlining() || print_intrinsics()) {
4208 print_inlining_stream_free();
4209 // Re allocate buffer when we change ResourceMark
4210 _print_inlining_stream = new stringStream();
4211 }
4212 }
4213
print_inlining_reset()4214 void Compile::print_inlining_reset() {
4215 _print_inlining_stream->reset();
4216 }
4217
print_inlining_commit()4218 void Compile::print_inlining_commit() {
4219 assert(print_inlining() || print_intrinsics(), "PrintInlining off?");
4220 // Transfer the message from _print_inlining_stream to the current
4221 // _print_inlining_list buffer and clear _print_inlining_stream.
4222 _print_inlining_list->at(_print_inlining_idx).ss()->write(_print_inlining_stream->base(), _print_inlining_stream->size());
4223 print_inlining_reset();
4224 }
4225
print_inlining_push()4226 void Compile::print_inlining_push() {
4227 // Add new buffer to the _print_inlining_list at current position
4228 _print_inlining_idx++;
4229 _print_inlining_list->insert_before(_print_inlining_idx, PrintInliningBuffer());
4230 }
4231
print_inlining_current()4232 Compile::PrintInliningBuffer& Compile::print_inlining_current() {
4233 return _print_inlining_list->at(_print_inlining_idx);
4234 }
4235
print_inlining_update(CallGenerator * cg)4236 void Compile::print_inlining_update(CallGenerator* cg) {
4237 if (print_inlining() || print_intrinsics()) {
4238 if (cg->is_late_inline()) {
4239 if (print_inlining_current().cg() != cg &&
4240 (print_inlining_current().cg() != NULL ||
4241 print_inlining_current().ss()->size() != 0)) {
4242 print_inlining_push();
4243 }
4244 print_inlining_commit();
4245 print_inlining_current().set_cg(cg);
4246 } else {
4247 if (print_inlining_current().cg() != NULL) {
4248 print_inlining_push();
4249 }
4250 print_inlining_commit();
4251 }
4252 }
4253 }
4254
print_inlining_move_to(CallGenerator * cg)4255 void Compile::print_inlining_move_to(CallGenerator* cg) {
4256 // We resume inlining at a late inlining call site. Locate the
4257 // corresponding inlining buffer so that we can update it.
4258 if (print_inlining() || print_intrinsics()) {
4259 for (int i = 0; i < _print_inlining_list->length(); i++) {
4260 if (_print_inlining_list->adr_at(i)->cg() == cg) {
4261 _print_inlining_idx = i;
4262 return;
4263 }
4264 }
4265 ShouldNotReachHere();
4266 }
4267 }
4268
print_inlining_update_delayed(CallGenerator * cg)4269 void Compile::print_inlining_update_delayed(CallGenerator* cg) {
4270 if (print_inlining() || print_intrinsics()) {
4271 assert(_print_inlining_stream->size() > 0, "missing inlining msg");
4272 assert(print_inlining_current().cg() == cg, "wrong entry");
4273 // replace message with new message
4274 _print_inlining_list->at_put(_print_inlining_idx, PrintInliningBuffer());
4275 print_inlining_commit();
4276 print_inlining_current().set_cg(cg);
4277 }
4278 }
4279
print_inlining_assert_ready()4280 void Compile::print_inlining_assert_ready() {
4281 assert(!_print_inlining || _print_inlining_stream->size() == 0, "loosing data");
4282 }
4283
process_print_inlining()4284 void Compile::process_print_inlining() {
4285 assert(_late_inlines.length() == 0, "not drained yet");
4286 if (print_inlining() || print_intrinsics()) {
4287 ResourceMark rm;
4288 stringStream ss;
4289 assert(_print_inlining_list != NULL, "process_print_inlining should be called only once.");
4290 for (int i = 0; i < _print_inlining_list->length(); i++) {
4291 ss.print("%s", _print_inlining_list->adr_at(i)->ss()->as_string());
4292 _print_inlining_list->at(i).freeStream();
4293 }
4294 // Reset _print_inlining_list, it only contains destructed objects.
4295 // It is on the arena, so it will be freed when the arena is reset.
4296 _print_inlining_list = NULL;
4297 // _print_inlining_stream won't be used anymore, either.
4298 print_inlining_stream_free();
4299 size_t end = ss.size();
4300 _print_inlining_output = NEW_ARENA_ARRAY(comp_arena(), char, end+1);
4301 strncpy(_print_inlining_output, ss.base(), end+1);
4302 _print_inlining_output[end] = 0;
4303 }
4304 }
4305
dump_print_inlining()4306 void Compile::dump_print_inlining() {
4307 if (_print_inlining_output != NULL) {
4308 tty->print_raw(_print_inlining_output);
4309 }
4310 }
4311
log_late_inline(CallGenerator * cg)4312 void Compile::log_late_inline(CallGenerator* cg) {
4313 if (log() != NULL) {
4314 log()->head("late_inline method='%d' inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()),
4315 cg->unique_id());
4316 JVMState* p = cg->call_node()->jvms();
4317 while (p != NULL) {
4318 log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method()));
4319 p = p->caller();
4320 }
4321 log()->tail("late_inline");
4322 }
4323 }
4324
log_late_inline_failure(CallGenerator * cg,const char * msg)4325 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) {
4326 log_late_inline(cg);
4327 if (log() != NULL) {
4328 log()->inline_fail(msg);
4329 }
4330 }
4331
log_inline_id(CallGenerator * cg)4332 void Compile::log_inline_id(CallGenerator* cg) {
4333 if (log() != NULL) {
4334 // The LogCompilation tool needs a unique way to identify late
4335 // inline call sites. This id must be unique for this call site in
4336 // this compilation. Try to have it unique across compilations as
4337 // well because it can be convenient when grepping through the log
4338 // file.
4339 // Distinguish OSR compilations from others in case CICountOSR is
4340 // on.
4341 jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0);
4342 cg->set_unique_id(id);
4343 log()->elem("inline_id id='" JLONG_FORMAT "'", id);
4344 }
4345 }
4346
log_inline_failure(const char * msg)4347 void Compile::log_inline_failure(const char* msg) {
4348 if (C->log() != NULL) {
4349 C->log()->inline_fail(msg);
4350 }
4351 }
4352
4353
4354 // Dump inlining replay data to the stream.
4355 // Don't change thread state and acquire any locks.
dump_inline_data(outputStream * out)4356 void Compile::dump_inline_data(outputStream* out) {
4357 InlineTree* inl_tree = ilt();
4358 if (inl_tree != NULL) {
4359 out->print(" inline %d", inl_tree->count());
4360 inl_tree->dump_replay_data(out);
4361 }
4362 }
4363
cmp_expensive_nodes(Node * n1,Node * n2)4364 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
4365 if (n1->Opcode() < n2->Opcode()) return -1;
4366 else if (n1->Opcode() > n2->Opcode()) return 1;
4367
4368 assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req());
4369 for (uint i = 1; i < n1->req(); i++) {
4370 if (n1->in(i) < n2->in(i)) return -1;
4371 else if (n1->in(i) > n2->in(i)) return 1;
4372 }
4373
4374 return 0;
4375 }
4376
cmp_expensive_nodes(Node ** n1p,Node ** n2p)4377 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
4378 Node* n1 = *n1p;
4379 Node* n2 = *n2p;
4380
4381 return cmp_expensive_nodes(n1, n2);
4382 }
4383
sort_expensive_nodes()4384 void Compile::sort_expensive_nodes() {
4385 if (!expensive_nodes_sorted()) {
4386 _expensive_nodes.sort(cmp_expensive_nodes);
4387 }
4388 }
4389
expensive_nodes_sorted() const4390 bool Compile::expensive_nodes_sorted() const {
4391 for (int i = 1; i < _expensive_nodes.length(); i++) {
4392 if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i-1)) < 0) {
4393 return false;
4394 }
4395 }
4396 return true;
4397 }
4398
should_optimize_expensive_nodes(PhaseIterGVN & igvn)4399 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
4400 if (_expensive_nodes.length() == 0) {
4401 return false;
4402 }
4403
4404 assert(OptimizeExpensiveOps, "optimization off?");
4405
4406 // Take this opportunity to remove dead nodes from the list
4407 int j = 0;
4408 for (int i = 0; i < _expensive_nodes.length(); i++) {
4409 Node* n = _expensive_nodes.at(i);
4410 if (!n->is_unreachable(igvn)) {
4411 assert(n->is_expensive(), "should be expensive");
4412 _expensive_nodes.at_put(j, n);
4413 j++;
4414 }
4415 }
4416 _expensive_nodes.trunc_to(j);
4417
4418 // Then sort the list so that similar nodes are next to each other
4419 // and check for at least two nodes of identical kind with same data
4420 // inputs.
4421 sort_expensive_nodes();
4422
4423 for (int i = 0; i < _expensive_nodes.length()-1; i++) {
4424 if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i+1)) == 0) {
4425 return true;
4426 }
4427 }
4428
4429 return false;
4430 }
4431
cleanup_expensive_nodes(PhaseIterGVN & igvn)4432 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
4433 if (_expensive_nodes.length() == 0) {
4434 return;
4435 }
4436
4437 assert(OptimizeExpensiveOps, "optimization off?");
4438
4439 // Sort to bring similar nodes next to each other and clear the
4440 // control input of nodes for which there's only a single copy.
4441 sort_expensive_nodes();
4442
4443 int j = 0;
4444 int identical = 0;
4445 int i = 0;
4446 bool modified = false;
4447 for (; i < _expensive_nodes.length()-1; i++) {
4448 assert(j <= i, "can't write beyond current index");
4449 if (_expensive_nodes.at(i)->Opcode() == _expensive_nodes.at(i+1)->Opcode()) {
4450 identical++;
4451 _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4452 continue;
4453 }
4454 if (identical > 0) {
4455 _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4456 identical = 0;
4457 } else {
4458 Node* n = _expensive_nodes.at(i);
4459 igvn.replace_input_of(n, 0, NULL);
4460 igvn.hash_insert(n);
4461 modified = true;
4462 }
4463 }
4464 if (identical > 0) {
4465 _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4466 } else if (_expensive_nodes.length() >= 1) {
4467 Node* n = _expensive_nodes.at(i);
4468 igvn.replace_input_of(n, 0, NULL);
4469 igvn.hash_insert(n);
4470 modified = true;
4471 }
4472 _expensive_nodes.trunc_to(j);
4473 if (modified) {
4474 igvn.optimize();
4475 }
4476 }
4477
add_expensive_node(Node * n)4478 void Compile::add_expensive_node(Node * n) {
4479 assert(!_expensive_nodes.contains(n), "duplicate entry in expensive list");
4480 assert(n->is_expensive(), "expensive nodes with non-null control here only");
4481 assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
4482 if (OptimizeExpensiveOps) {
4483 _expensive_nodes.append(n);
4484 } else {
4485 // Clear control input and let IGVN optimize expensive nodes if
4486 // OptimizeExpensiveOps is off.
4487 n->set_req(0, NULL);
4488 }
4489 }
4490
4491 /**
4492 * Remove the speculative part of types and clean up the graph
4493 */
remove_speculative_types(PhaseIterGVN & igvn)4494 void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
4495 if (UseTypeSpeculation) {
4496 Unique_Node_List worklist;
4497 worklist.push(root());
4498 int modified = 0;
4499 // Go over all type nodes that carry a speculative type, drop the
4500 // speculative part of the type and enqueue the node for an igvn
4501 // which may optimize it out.
4502 for (uint next = 0; next < worklist.size(); ++next) {
4503 Node *n = worklist.at(next);
4504 if (n->is_Type()) {
4505 TypeNode* tn = n->as_Type();
4506 const Type* t = tn->type();
4507 const Type* t_no_spec = t->remove_speculative();
4508 if (t_no_spec != t) {
4509 bool in_hash = igvn.hash_delete(n);
4510 assert(in_hash, "node should be in igvn hash table");
4511 tn->set_type(t_no_spec);
4512 igvn.hash_insert(n);
4513 igvn._worklist.push(n); // give it a chance to go away
4514 modified++;
4515 }
4516 }
4517 uint max = n->len();
4518 for( uint i = 0; i < max; ++i ) {
4519 Node *m = n->in(i);
4520 if (not_a_node(m)) continue;
4521 worklist.push(m);
4522 }
4523 }
4524 // Drop the speculative part of all types in the igvn's type table
4525 igvn.remove_speculative_types();
4526 if (modified > 0) {
4527 igvn.optimize();
4528 }
4529 #ifdef ASSERT
4530 // Verify that after the IGVN is over no speculative type has resurfaced
4531 worklist.clear();
4532 worklist.push(root());
4533 for (uint next = 0; next < worklist.size(); ++next) {
4534 Node *n = worklist.at(next);
4535 const Type* t = igvn.type_or_null(n);
4536 assert((t == NULL) || (t == t->remove_speculative()), "no more speculative types");
4537 if (n->is_Type()) {
4538 t = n->as_Type()->type();
4539 assert(t == t->remove_speculative(), "no more speculative types");
4540 }
4541 uint max = n->len();
4542 for( uint i = 0; i < max; ++i ) {
4543 Node *m = n->in(i);
4544 if (not_a_node(m)) continue;
4545 worklist.push(m);
4546 }
4547 }
4548 igvn.check_no_speculative_types();
4549 #endif
4550 }
4551 }
4552
4553 // Auxiliary methods to support randomized stressing/fuzzing.
4554
random()4555 int Compile::random() {
4556 _stress_seed = os::next_random(_stress_seed);
4557 return static_cast<int>(_stress_seed);
4558 }
4559
4560 // This method can be called the arbitrary number of times, with current count
4561 // as the argument. The logic allows selecting a single candidate from the
4562 // running list of candidates as follows:
4563 // int count = 0;
4564 // Cand* selected = null;
4565 // while(cand = cand->next()) {
4566 // if (randomized_select(++count)) {
4567 // selected = cand;
4568 // }
4569 // }
4570 //
4571 // Including count equalizes the chances any candidate is "selected".
4572 // This is useful when we don't have the complete list of candidates to choose
4573 // from uniformly. In this case, we need to adjust the randomicity of the
4574 // selection, or else we will end up biasing the selection towards the latter
4575 // candidates.
4576 //
4577 // Quick back-envelope calculation shows that for the list of n candidates
4578 // the equal probability for the candidate to persist as "best" can be
4579 // achieved by replacing it with "next" k-th candidate with the probability
4580 // of 1/k. It can be easily shown that by the end of the run, the
4581 // probability for any candidate is converged to 1/n, thus giving the
4582 // uniform distribution among all the candidates.
4583 //
4584 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
4585 #define RANDOMIZED_DOMAIN_POW 29
4586 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
4587 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
randomized_select(int count)4588 bool Compile::randomized_select(int count) {
4589 assert(count > 0, "only positive");
4590 return (random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
4591 }
4592
clone_map()4593 CloneMap& Compile::clone_map() { return _clone_map; }
set_clone_map(Dict * d)4594 void Compile::set_clone_map(Dict* d) { _clone_map._dict = d; }
4595
dump() const4596 void NodeCloneInfo::dump() const {
4597 tty->print(" {%d:%d} ", idx(), gen());
4598 }
4599
clone(Node * old,Node * nnn,int gen)4600 void CloneMap::clone(Node* old, Node* nnn, int gen) {
4601 uint64_t val = value(old->_idx);
4602 NodeCloneInfo cio(val);
4603 assert(val != 0, "old node should be in the map");
4604 NodeCloneInfo cin(cio.idx(), gen + cio.gen());
4605 insert(nnn->_idx, cin.get());
4606 #ifndef PRODUCT
4607 if (is_debug()) {
4608 tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen());
4609 }
4610 #endif
4611 }
4612
verify_insert_and_clone(Node * old,Node * nnn,int gen)4613 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) {
4614 NodeCloneInfo cio(value(old->_idx));
4615 if (cio.get() == 0) {
4616 cio.set(old->_idx, 0);
4617 insert(old->_idx, cio.get());
4618 #ifndef PRODUCT
4619 if (is_debug()) {
4620 tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen());
4621 }
4622 #endif
4623 }
4624 clone(old, nnn, gen);
4625 }
4626
max_gen() const4627 int CloneMap::max_gen() const {
4628 int g = 0;
4629 DictI di(_dict);
4630 for(; di.test(); ++di) {
4631 int t = gen(di._key);
4632 if (g < t) {
4633 g = t;
4634 #ifndef PRODUCT
4635 if (is_debug()) {
4636 tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key));
4637 }
4638 #endif
4639 }
4640 }
4641 return g;
4642 }
4643
dump(node_idx_t key) const4644 void CloneMap::dump(node_idx_t key) const {
4645 uint64_t val = value(key);
4646 if (val != 0) {
4647 NodeCloneInfo ni(val);
4648 ni.dump();
4649 }
4650 }
4651
4652 // Move Allocate nodes to the start of the list
sort_macro_nodes()4653 void Compile::sort_macro_nodes() {
4654 int count = macro_count();
4655 int allocates = 0;
4656 for (int i = 0; i < count; i++) {
4657 Node* n = macro_node(i);
4658 if (n->is_Allocate()) {
4659 if (i != allocates) {
4660 Node* tmp = macro_node(allocates);
4661 _macro_nodes.at_put(allocates, n);
4662 _macro_nodes.at_put(i, tmp);
4663 }
4664 allocates++;
4665 }
4666 }
4667 }
4668
print_method(CompilerPhaseType cpt,const char * name,int level,int idx)4669 void Compile::print_method(CompilerPhaseType cpt, const char *name, int level, int idx) {
4670 EventCompilerPhase event;
4671 if (event.should_commit()) {
4672 CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, cpt, C->_compile_id, level);
4673 }
4674 #ifndef PRODUCT
4675 if (should_print(level)) {
4676 _printer->print_method(name, level);
4677 }
4678 #endif
4679 C->_latest_stage_start_counter.stamp();
4680 }
4681
print_method(CompilerPhaseType cpt,int level,int idx)4682 void Compile::print_method(CompilerPhaseType cpt, int level, int idx) {
4683 char output[1024];
4684 #ifndef PRODUCT
4685 if (idx != 0) {
4686 jio_snprintf(output, sizeof(output), "%s:%d", CompilerPhaseTypeHelper::to_string(cpt), idx);
4687 } else {
4688 jio_snprintf(output, sizeof(output), "%s", CompilerPhaseTypeHelper::to_string(cpt));
4689 }
4690 #endif
4691 print_method(cpt, output, level, idx);
4692 }
4693
print_method(CompilerPhaseType cpt,Node * n,int level)4694 void Compile::print_method(CompilerPhaseType cpt, Node* n, int level) {
4695 ResourceMark rm;
4696 stringStream ss;
4697 ss.print_raw(CompilerPhaseTypeHelper::to_string(cpt));
4698 if (n != NULL) {
4699 ss.print(": %d %s ", n->_idx, NodeClassNames[n->Opcode()]);
4700 } else {
4701 ss.print_raw(": NULL");
4702 }
4703 C->print_method(cpt, ss.as_string(), level);
4704 }
4705
end_method(int level)4706 void Compile::end_method(int level) {
4707 EventCompilerPhase event;
4708 if (event.should_commit()) {
4709 CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, PHASE_END, C->_compile_id, level);
4710 }
4711
4712 #ifndef PRODUCT
4713 if (_method != NULL && should_print(level)) {
4714 _printer->end_method();
4715 }
4716 #endif
4717 }
4718
4719
4720 #ifndef PRODUCT
4721 IdealGraphPrinter* Compile::_debug_file_printer = NULL;
4722 IdealGraphPrinter* Compile::_debug_network_printer = NULL;
4723
4724 // Called from debugger. Prints method to the default file with the default phase name.
4725 // This works regardless of any Ideal Graph Visualizer flags set or not.
igv_print()4726 void igv_print() {
4727 Compile::current()->igv_print_method_to_file();
4728 }
4729
4730 // Same as igv_print() above but with a specified phase name.
igv_print(const char * phase_name)4731 void igv_print(const char* phase_name) {
4732 Compile::current()->igv_print_method_to_file(phase_name);
4733 }
4734
4735 // Called from debugger. Prints method with the default phase name to the default network or the one specified with
4736 // the network flags for the Ideal Graph Visualizer, or to the default file depending on the 'network' argument.
4737 // This works regardless of any Ideal Graph Visualizer flags set or not.
igv_print(bool network)4738 void igv_print(bool network) {
4739 if (network) {
4740 Compile::current()->igv_print_method_to_network();
4741 } else {
4742 Compile::current()->igv_print_method_to_file();
4743 }
4744 }
4745
4746 // Same as igv_print(bool network) above but with a specified phase name.
igv_print(bool network,const char * phase_name)4747 void igv_print(bool network, const char* phase_name) {
4748 if (network) {
4749 Compile::current()->igv_print_method_to_network(phase_name);
4750 } else {
4751 Compile::current()->igv_print_method_to_file(phase_name);
4752 }
4753 }
4754
4755 // Called from debugger. Normal write to the default _printer. Only works if Ideal Graph Visualizer printing flags are set.
igv_print_default()4756 void igv_print_default() {
4757 Compile::current()->print_method(PHASE_DEBUG, 0, 0);
4758 }
4759
4760 // Called from debugger, especially when replaying a trace in which the program state cannot be altered like with rr replay.
4761 // A method is appended to an existing default file with the default phase name. This means that igv_append() must follow
4762 // an earlier igv_print(*) call which sets up the file. This works regardless of any Ideal Graph Visualizer flags set or not.
igv_append()4763 void igv_append() {
4764 Compile::current()->igv_print_method_to_file("Debug", true);
4765 }
4766
4767 // Same as igv_append() above but with a specified phase name.
igv_append(const char * phase_name)4768 void igv_append(const char* phase_name) {
4769 Compile::current()->igv_print_method_to_file(phase_name, true);
4770 }
4771
igv_print_method_to_file(const char * phase_name,bool append)4772 void Compile::igv_print_method_to_file(const char* phase_name, bool append) {
4773 const char* file_name = "custom_debug.xml";
4774 if (_debug_file_printer == NULL) {
4775 _debug_file_printer = new IdealGraphPrinter(C, file_name, append);
4776 } else {
4777 _debug_file_printer->update_compiled_method(C->method());
4778 }
4779 tty->print_cr("Method %s to %s", append ? "appended" : "printed", file_name);
4780 _debug_file_printer->print_method(phase_name, 0);
4781 }
4782
igv_print_method_to_network(const char * phase_name)4783 void Compile::igv_print_method_to_network(const char* phase_name) {
4784 if (_debug_network_printer == NULL) {
4785 _debug_network_printer = new IdealGraphPrinter(C);
4786 } else {
4787 _debug_network_printer->update_compiled_method(C->method());
4788 }
4789 tty->print_cr("Method printed over network stream to IGV");
4790 _debug_network_printer->print_method(phase_name, 0);
4791 }
4792 #endif
4793
add_native_invoker(BufferBlob * stub)4794 void Compile::add_native_invoker(BufferBlob* stub) {
4795 _native_invokers.append(stub);
4796 }
4797