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