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