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