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