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