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