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