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