7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.hpp"
26 #include "asm/macroAssembler.inline.hpp"
27 #include "ci/ciReplay.hpp"
28 #include "classfile/javaClasses.hpp"
29 #include "code/aotCodeCache.hpp"
30 #include "code/exceptionHandlerTable.hpp"
31 #include "code/nmethod.hpp"
32 #include "compiler/compilationFailureInfo.hpp"
33 #include "compiler/compilationMemoryStatistic.hpp"
34 #include "compiler/compileBroker.hpp"
35 #include "compiler/compileLog.hpp"
36 #include "compiler/compiler_globals.hpp"
37 #include "compiler/compilerDefinitions.hpp"
38 #include "compiler/compilerOracle.hpp"
39 #include "compiler/disassembler.hpp"
40 #include "compiler/oopMap.hpp"
41 #include "gc/shared/barrierSet.hpp"
42 #include "gc/shared/c2/barrierSetC2.hpp"
43 #include "jfr/jfrEvents.hpp"
44 #include "jvm_io.h"
45 #include "memory/allocation.hpp"
46 #include "memory/arena.hpp"
47 #include "memory/resourceArea.hpp"
48 #include "opto/addnode.hpp"
49 #include "opto/block.hpp"
50 #include "opto/c2compiler.hpp"
51 #include "opto/callGenerator.hpp"
52 #include "opto/callnode.hpp"
53 #include "opto/castnode.hpp"
54 #include "opto/cfgnode.hpp"
55 #include "opto/chaitin.hpp"
56 #include "opto/compile.hpp"
57 #include "opto/connode.hpp"
58 #include "opto/convertnode.hpp"
59 #include "opto/divnode.hpp"
60 #include "opto/escape.hpp"
61 #include "opto/idealGraphPrinter.hpp"
62 #include "opto/locknode.hpp"
63 #include "opto/loopnode.hpp"
64 #include "opto/machnode.hpp"
65 #include "opto/macro.hpp"
66 #include "opto/matcher.hpp"
67 #include "opto/mathexactnode.hpp"
68 #include "opto/memnode.hpp"
69 #include "opto/mulnode.hpp"
70 #include "opto/narrowptrnode.hpp"
71 #include "opto/node.hpp"
72 #include "opto/opaquenode.hpp"
73 #include "opto/opcodes.hpp"
74 #include "opto/output.hpp"
75 #include "opto/parse.hpp"
76 #include "opto/phaseX.hpp"
77 #include "opto/reachability.hpp"
78 #include "opto/rootnode.hpp"
79 #include "opto/runtime.hpp"
80 #include "opto/stringopts.hpp"
81 #include "opto/type.hpp"
82 #include "opto/vector.hpp"
83 #include "opto/vectornode.hpp"
84 #include "runtime/globals_extension.hpp"
85 #include "runtime/sharedRuntime.hpp"
86 #include "runtime/signature.hpp"
87 #include "runtime/stubRoutines.hpp"
88 #include "runtime/timer.hpp"
89 #include "utilities/align.hpp"
90 #include "utilities/copy.hpp"
91 #include "utilities/hashTable.hpp"
92 #include "utilities/macros.hpp"
93
94 // -------------------- Compile::mach_constant_base_node -----------------------
95 // Constant table base node singleton.
96 MachConstantBaseNode* Compile::mach_constant_base_node() {
97 if (_mach_constant_base_node == nullptr) {
98 _mach_constant_base_node = new MachConstantBaseNode();
99 _mach_constant_base_node->add_req(C->root());
100 }
101 return _mach_constant_base_node;
102 }
103
392 record_dead_node(dead->_idx);
393 }
394 if (dead->is_macro()) {
395 remove_macro_node(dead);
396 }
397 if (dead->is_expensive()) {
398 remove_expensive_node(dead);
399 }
400 if (dead->is_ReachabilityFence()) {
401 remove_reachability_fence(dead->as_ReachabilityFence());
402 }
403 if (dead->is_OpaqueTemplateAssertionPredicate()) {
404 remove_template_assertion_predicate_opaque(dead->as_OpaqueTemplateAssertionPredicate());
405 }
406 if (dead->is_ParsePredicate()) {
407 remove_parse_predicate(dead->as_ParsePredicate());
408 }
409 if (dead->for_post_loop_opts_igvn()) {
410 remove_from_post_loop_opts_igvn(dead);
411 }
412 if (dead->for_merge_stores_igvn()) {
413 remove_from_merge_stores_igvn(dead);
414 }
415 if (dead->is_Call()) {
416 remove_useless_late_inlines( &_late_inlines, dead);
417 remove_useless_late_inlines( &_string_late_inlines, dead);
418 remove_useless_late_inlines( &_boxing_late_inlines, dead);
419 remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead);
420
421 if (dead->is_CallStaticJava()) {
422 remove_unstable_if_trap(dead->as_CallStaticJava(), false);
423 }
424 }
425 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
426 bs->unregister_potential_barrier_node(dead);
427 }
428
429 // Disconnect all useless nodes by disconnecting those at the boundary.
430 void Compile::disconnect_useless_nodes(Unique_Node_List& useful, Unique_Node_List& worklist, const Unique_Node_List* root_and_safepoints) {
431 uint next = 0;
439 // Use raw traversal of out edges since this code removes out edges
440 int max = n->outcnt();
441 for (int j = 0; j < max; ++j) {
442 Node* child = n->raw_out(j);
443 if (!useful.member(child)) {
444 assert(!child->is_top() || child != top(),
445 "If top is cached in Compile object it is in useful list");
446 // Only need to remove this out-edge to the useless node
447 n->raw_del_out(j);
448 --j;
449 --max;
450 if (child->is_data_proj_of_pure_function(n)) {
451 worklist.push(n);
452 }
453 }
454 }
455 if (n->outcnt() == 1 && n->has_special_unique_user()) {
456 assert(useful.member(n->unique_out()), "do not push a useless node");
457 worklist.push(n->unique_out());
458 }
459 }
460
461 remove_useless_nodes(_macro_nodes, useful); // remove useless macro nodes
462 remove_useless_nodes(_parse_predicates, useful); // remove useless Parse Predicate nodes
463 // Remove useless Template Assertion Predicate opaque nodes
464 remove_useless_nodes(_template_assertion_predicate_opaques, useful);
465 remove_useless_nodes(_expensive_nodes, useful); // remove useless expensive nodes
466 remove_useless_nodes(_reachability_fences, useful); // remove useless node recorded for post loop opts IGVN pass
467 remove_useless_nodes(_for_post_loop_igvn, useful); // remove useless node recorded for post loop opts IGVN pass
468 remove_useless_nodes(_for_merge_stores_igvn, useful); // remove useless node recorded for merge stores IGVN pass
469 remove_useless_unstable_if_traps(useful); // remove useless unstable_if traps
470 remove_useless_coarsened_locks(useful); // remove useless coarsened locks nodes
471 #ifdef ASSERT
472 if (_modified_nodes != nullptr) {
473 _modified_nodes->remove_useless_nodes(useful.member_set());
474 }
475 #endif
476
477 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
478 bs->eliminate_useless_gc_barriers(useful, this);
479 // clean up the late inline lists
480 remove_useless_late_inlines( &_late_inlines, useful);
481 remove_useless_late_inlines( &_string_late_inlines, useful);
482 remove_useless_late_inlines( &_boxing_late_inlines, useful);
483 remove_useless_late_inlines(&_vector_reboxing_late_inlines, useful);
484 DEBUG_ONLY(verify_graph_edges(true /*check for no_dead_code*/, root_and_safepoints);)
485 }
486
487 // ============================================================================
635
636 Compile::Compile(ciEnv* ci_env, ciMethod* target, int osr_bci,
637 Options options, DirectiveSet* directive)
638 : Phase(Compiler),
639 _compile_id(ci_env->compile_id()),
640 _options(options),
641 _method(target),
642 _entry_bci(osr_bci),
643 _ilt(nullptr),
644 _stub_function(nullptr),
645 _stub_name(nullptr),
646 _stub_id(StubId::NO_STUBID),
647 _stub_entry_point(nullptr),
648 _max_node_limit(MaxNodeLimit),
649 _node_count_inlining_cutoff(NodeCountInliningCutoff),
650 _post_loop_opts_phase(false),
651 _merge_stores_phase(false),
652 _allow_macro_nodes(true),
653 _inlining_progress(false),
654 _inlining_incrementally(false),
655 _do_cleanup(false),
656 _has_reserved_stack_access(target->has_reserved_stack_access()),
657 #ifndef PRODUCT
658 _igv_idx(0),
659 _trace_opto_output(directive->TraceOptoOutputOption),
660 #endif
661 _clinit_barrier_on_entry(false),
662 _stress_seed(0),
663 _comp_arena(mtCompiler, Arena::Tag::tag_comp),
664 _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
665 _env(ci_env),
666 _directive(directive),
667 _log(ci_env->log()),
668 _first_failure_details(nullptr),
669 _intrinsics(comp_arena(), 0, 0, nullptr),
670 _macro_nodes(comp_arena(), 8, 0, nullptr),
671 _parse_predicates(comp_arena(), 8, 0, nullptr),
672 _template_assertion_predicate_opaques(comp_arena(), 8, 0, nullptr),
673 _expensive_nodes(comp_arena(), 8, 0, nullptr),
674 _reachability_fences(comp_arena(), 8, 0, nullptr),
675 _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),
676 _for_merge_stores_igvn(comp_arena(), 8, 0, nullptr),
677 _unstable_if_traps(comp_arena(), 8, 0, nullptr),
678 _coarsened_locks(comp_arena(), 8, 0, nullptr),
679 _congraph(nullptr),
680 NOT_PRODUCT(_igv_printer(nullptr) COMMA)
681 _unique(0),
682 _dead_node_count(0),
683 _dead_node_list(comp_arena()),
684 _node_arena_one(mtCompiler, Arena::Tag::tag_node),
685 _node_arena_two(mtCompiler, Arena::Tag::tag_node),
686 _node_arena(&_node_arena_one),
687 _mach_constant_base_node(nullptr),
688 _Compile_types(mtCompiler, Arena::Tag::tag_type),
689 _initial_gvn(nullptr),
690 _igvn_worklist(nullptr),
691 _types(nullptr),
692 _node_hash(nullptr),
693 _late_inlines(comp_arena(), 2, 0, nullptr),
694 _string_late_inlines(comp_arena(), 2, 0, nullptr),
695 _boxing_late_inlines(comp_arena(), 2, 0, nullptr),
765 #define MINIMUM_NODE_HASH 1023
766
767 // GVN that will be run immediately on new nodes
768 uint estimated_size = method()->code_size()*4+64;
769 estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
770 _igvn_worklist = new (comp_arena()) Unique_Node_List(comp_arena());
771 _types = new (comp_arena()) Type_Array(comp_arena());
772 _node_hash = new (comp_arena()) NodeHash(comp_arena(), estimated_size);
773 PhaseGVN gvn;
774 set_initial_gvn(&gvn);
775
776 { // Scope for timing the parser
777 TracePhase tp(_t_parser);
778
779 // Put top into the hash table ASAP.
780 initial_gvn()->transform(top());
781
782 // Set up tf(), start(), and find a CallGenerator.
783 CallGenerator* cg = nullptr;
784 if (is_osr_compilation()) {
785 const TypeTuple *domain = StartOSRNode::osr_domain();
786 const TypeTuple *range = TypeTuple::make_range(method()->signature());
787 init_tf(TypeFunc::make(domain, range));
788 StartNode* s = new StartOSRNode(root(), domain);
789 initial_gvn()->set_type_bottom(s);
790 verify_start(s);
791 cg = CallGenerator::for_osr(method(), entry_bci());
792 } else {
793 // Normal case.
794 init_tf(TypeFunc::make(method()));
795 StartNode* s = new StartNode(root(), tf()->domain());
796 initial_gvn()->set_type_bottom(s);
797 verify_start(s);
798 float past_uses = method()->interpreter_invocation_count();
799 float expected_uses = past_uses;
800 cg = CallGenerator::for_inline(method(), expected_uses);
801 }
802 if (failing()) return;
803 if (cg == nullptr) {
804 const char* reason = InlineTree::check_can_parse(method());
805 assert(reason != nullptr, "expect reason for parse failure");
806 stringStream ss;
807 ss.print("cannot parse method: %s", reason);
808 record_method_not_compilable(ss.as_string());
809 return;
810 }
811
812 gvn.set_type(root(), root()->bottom_type());
813
814 JVMState* jvms = build_start_state(start(), tf());
815 if ((jvms = cg->generate(jvms)) == nullptr) {
875 if (should_print_ideal()) {
876 print_ideal_ir("PrintIdeal");
877 }
878 #endif
879
880 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
881 bs->final_refinement(this);
882
883 #ifdef ASSERT
884 bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen);
885 #endif
886
887 // Dump compilation data to replay it.
888 if (directive->DumpReplayOption) {
889 env()->dump_replay_data(_compile_id);
890 }
891 if (directive->DumpInlineOption && (ilt() != nullptr)) {
892 env()->dump_inline_data(_compile_id);
893 }
894
895 // Now that we know the size of all the monitors we can add a fixed slot
896 // for the original deopt pc.
897 int next_slot = fixed_slots() + (sizeof(address) / VMRegImpl::stack_slot_size);
898 set_fixed_slots(next_slot);
899
900 // Compute when to use implicit null checks. Used by matching trap based
901 // nodes and NullCheck optimization.
902 set_allowed_deopt_reasons();
903
904 // Now generate code
905 Code_Gen();
906 }
907
908 // C2 uses runtime stubs serialized generation to initialize its static tables
909 // shared by all compilations, like Type::_shared_type_dict.
910 // At least one stub have to be completely generated to execute intialization
911 // before we can skip the rest stubs generation by loading AOT cached stubs.
912
913 static bool c2_do_stub_init_complete = false;
914
915 //------------------------------Compile----------------------------------------
916 // Compile a runtime stub
917 Compile::Compile(ciEnv* ci_env,
923 bool pass_tls,
924 bool return_pc,
925 DirectiveSet* directive)
926 : Phase(Compiler),
927 _compile_id(0),
928 _options(Options::for_runtime_stub()),
929 _method(nullptr),
930 _entry_bci(InvocationEntryBci),
931 _stub_function(stub_function),
932 _stub_name(stub_name),
933 _stub_id(stub_id),
934 _stub_entry_point(nullptr),
935 _max_node_limit(MaxNodeLimit),
936 _node_count_inlining_cutoff(NodeCountInliningCutoff),
937 _post_loop_opts_phase(false),
938 _merge_stores_phase(false),
939 _allow_macro_nodes(true),
940 _inlining_progress(false),
941 _inlining_incrementally(false),
942 _has_reserved_stack_access(false),
943 #ifndef PRODUCT
944 _igv_idx(0),
945 _trace_opto_output(directive->TraceOptoOutputOption),
946 #endif
947 _clinit_barrier_on_entry(false),
948 _stress_seed(0),
949 _comp_arena(mtCompiler, Arena::Tag::tag_comp),
950 _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
951 _env(ci_env),
952 _directive(directive),
953 _log(ci_env->log()),
954 _first_failure_details(nullptr),
955 _reachability_fences(comp_arena(), 8, 0, nullptr),
956 _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),
957 _for_merge_stores_igvn(comp_arena(), 8, 0, nullptr),
958 _congraph(nullptr),
959 NOT_PRODUCT(_igv_printer(nullptr) COMMA)
960 _unique(0),
961 _dead_node_count(0),
962 _dead_node_list(comp_arena()),
1082 _fixed_slots = 0;
1083 set_has_split_ifs(false);
1084 set_has_loops(false); // first approximation
1085 set_has_stringbuilder(false);
1086 set_has_boxed_value(false);
1087 _trap_can_recompile = false; // no traps emitted yet
1088 _major_progress = true; // start out assuming good things will happen
1089 set_has_unsafe_access(false);
1090 set_max_vector_size(0);
1091 set_clear_upper_avx(false); //false as default for clear upper bits of ymm registers
1092 Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
1093 set_decompile_count(0);
1094
1095 #ifndef PRODUCT
1096 _phase_counter = 0;
1097 Copy::zero_to_bytes(_igv_phase_iter, sizeof(_igv_phase_iter));
1098 #endif
1099
1100 set_do_freq_based_layout(_directive->BlockLayoutByFrequencyOption);
1101 _loop_opts_cnt = LoopOptsCount;
1102 set_do_inlining(Inline);
1103 set_max_inline_size(MaxInlineSize);
1104 set_freq_inline_size(FreqInlineSize);
1105 set_do_scheduling(OptoScheduling);
1106
1107 set_do_vector_loop(false);
1108 set_has_monitors(false);
1109 set_has_scoped_access(false);
1110
1111 if (AllowVectorizeOnDemand) {
1112 if (has_method() && _directive->VectorizeOption) {
1113 set_do_vector_loop(true);
1114 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());})
1115 } else if (has_method() && method()->name() != nullptr &&
1116 method()->intrinsic_id() == vmIntrinsics::_forEachRemaining) {
1117 set_do_vector_loop(true);
1118 }
1119 }
1120 set_use_cmove(UseCMoveUnconditionally /* || do_vector_loop()*/); //TODO: consider do_vector_loop() mandate use_cmove unconditionally
1121 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());})
1353 // If this method has already thrown a range-check,
1354 // assume it was because we already tried range smearing
1355 // and it failed.
1356 uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1357 return !already_trapped;
1358 }
1359
1360
1361 //------------------------------flatten_alias_type-----------------------------
1362 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1363 assert(do_aliasing(), "Aliasing should be enabled");
1364 int offset = tj->offset();
1365 TypePtr::PTR ptr = tj->ptr();
1366
1367 // Known instance (scalarizable allocation) alias only with itself.
1368 bool is_known_inst = tj->isa_oopptr() != nullptr &&
1369 tj->is_oopptr()->is_known_instance();
1370
1371 // Process weird unsafe references.
1372 if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1373 assert(InlineUnsafeOps || StressReflectiveCode, "indeterminate pointers come only from unsafe ops");
1374 assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1375 tj = TypeOopPtr::BOTTOM;
1376 ptr = tj->ptr();
1377 offset = tj->offset();
1378 }
1379
1380 // Array pointers need some flattening
1381 const TypeAryPtr* ta = tj->isa_aryptr();
1382 if (ta && ta->is_stable()) {
1383 // Erase stability property for alias analysis.
1384 tj = ta = ta->cast_to_stable(false);
1385 }
1386 if( ta && is_known_inst ) {
1387 if ( offset != Type::OffsetBot &&
1388 offset > arrayOopDesc::length_offset_in_bytes() ) {
1389 offset = Type::OffsetBot; // Flatten constant access into array body only
1390 tj = ta = ta->
1391 remove_speculative()->
1392 cast_to_ptr_type(ptr)->
1393 with_offset(offset);
1394 }
1395 } else if (ta != nullptr) {
1396 // Common slices
1397 if (offset == arrayOopDesc::length_offset_in_bytes()) {
1398 return TypeAryPtr::RANGE;
1399 } else if (offset == oopDesc::klass_offset_in_bytes()) {
1400 return TypeInstPtr::KLASS;
1401 } else if (offset == oopDesc::mark_offset_in_bytes()) {
1402 return TypeInstPtr::MARK;
1403 }
1404
1405 // Remove size and stability
1406 const TypeAry* normalized_ary = TypeAry::make(ta->elem(), TypeInt::POS, false);
1407 // Remove ptr, const_oop, and offset
1408 if (ta->elem() == Type::BOTTOM) {
1409 // Bottom array (meet of int[] and byte[] for example), accesses to it will be done with
1410 // Unsafe. This should alias with all arrays. For now just leave it as it is (this is
1411 // incorrect, see JDK-8331133).
1412 tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, nullptr, false, Type::OffsetBot);
1413 } else if (ta->elem()->make_oopptr() != nullptr) {
1414 // Object arrays, all of them share the same slice
1415 const TypeAry* tary = TypeAry::make(TypeInstPtr::BOTTOM, TypeInt::POS, false);
1416 tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, tary, nullptr, false, Type::OffsetBot);
1417 } else {
1418 // Primitive arrays
1419 tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, ta->exact_klass(), true, Type::OffsetBot);
1420 }
1421
1422 // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1423 // cannot be distinguished by bytecode alone.
1424 if (ta->elem() == TypeInt::BOOL) {
1425 tj = ta = TypeAryPtr::BYTES;
1426 }
1427 }
1428
1429 // Oop pointers need some flattening
1430 const TypeInstPtr *to = tj->isa_instptr();
1431 if (to && to != TypeOopPtr::BOTTOM) {
1432 ciInstanceKlass* ik = to->instance_klass();
1433 if( ptr == TypePtr::Constant ) {
1434 if (ik != ciEnv::current()->Class_klass() ||
1435 offset < ik->layout_helper_size_in_bytes()) {
1436 // No constant oop pointers (such as Strings); they alias with
1437 // unknown strings.
1438 assert(!is_known_inst, "not scalarizable allocation");
1439 tj = to = to->
1440 cast_to_instance_id(TypeOopPtr::InstanceBot)->
1441 remove_speculative()->
1442 cast_to_ptr_type(TypePtr::BotPTR)->
1443 cast_to_exactness(false);
1444 }
1445 } else if( is_known_inst ) {
1446 tj = to; // Keep NotNull and klass_is_exact for instance type
1447 } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1448 // During the 2nd round of IterGVN, NotNull castings are removed.
1449 // Make sure the Bottom and NotNull variants alias the same.
1450 // Also, make sure exact and non-exact variants alias the same.
1451 tj = to = to->
1452 remove_speculative()->
1453 cast_to_instance_id(TypeOopPtr::InstanceBot)->
1454 cast_to_ptr_type(TypePtr::BotPTR)->
1455 cast_to_exactness(false);
1456 }
1457 if (to->speculative() != nullptr) {
1458 tj = to = to->remove_speculative();
1459 }
1460 // Canonicalize the holder of this field
1461 if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1462 // First handle header references such as a LoadKlassNode, even if the
1463 // object's klass is unloaded at compile time (4965979).
1464 if (!is_known_inst) { // Do it only for non-instance types
1465 tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, nullptr, offset);
1466 }
1467 } else if (offset < 0 || offset >= ik->layout_helper_size_in_bytes()) {
1468 // Static fields are in the space above the normal instance
1469 // fields in the java.lang.Class instance.
1470 if (ik != ciEnv::current()->Class_klass()) {
1471 to = nullptr;
1472 tj = TypeOopPtr::BOTTOM;
1473 offset = tj->offset();
1474 }
1475 } else {
1476 ciInstanceKlass *canonical_holder = ik->get_canonical_holder(offset);
1477 assert(offset < canonical_holder->layout_helper_size_in_bytes(), "");
1478 assert(tj->offset() == offset, "no change to offset expected");
1479 bool xk = to->klass_is_exact();
1480 int instance_id = to->instance_id();
1481
1482 // If the input type's class is the holder: if exact, the type only includes interfaces implemented by the holder
1483 // but if not exact, it may include extra interfaces: build new type from the holder class to make sure only
1484 // its interfaces are included.
1485 if (xk && ik->equals(canonical_holder)) {
1486 assert(tj == TypeInstPtr::make(to->ptr(), canonical_holder, is_known_inst, nullptr, offset, instance_id), "exact type should be canonical type");
1487 } else {
1488 assert(xk || !is_known_inst, "Known instance should be exact type");
1489 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, is_known_inst, nullptr, offset, instance_id);
1490 }
1491 }
1492 }
1493
1494 // Klass pointers to object array klasses need some flattening
1495 const TypeKlassPtr *tk = tj->isa_klassptr();
1496 if( tk ) {
1497 // If we are referencing a field within a Klass, we need
1498 // to assume the worst case of an Object. Both exact and
1499 // inexact types must flatten to the same alias class so
1500 // use NotNull as the PTR.
1501 if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1502 tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull,
1503 env()->Object_klass(),
1504 offset);
1505 }
1506
1507 if (tk->isa_aryklassptr() && tk->is_aryklassptr()->elem()->isa_klassptr()) {
1508 ciKlass* k = ciObjArrayKlass::make(env()->Object_klass());
1509 if (!k || !k->is_loaded()) { // Only fails for some -Xcomp runs
1510 tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull, env()->Object_klass(), offset);
1511 } else {
1512 tj = tk = TypeAryKlassPtr::make(TypePtr::NotNull, tk->is_aryklassptr()->elem(), k, offset);
1513 }
1514 }
1515
1516 // Check for precise loads from the primary supertype array and force them
1517 // to the supertype cache alias index. Check for generic array loads from
1518 // the primary supertype array and also force them to the supertype cache
1519 // alias index. Since the same load can reach both, we need to merge
1520 // these 2 disparate memories into the same alias class. Since the
1521 // primary supertype array is read-only, there's no chance of confusion
1522 // where we bypass an array load and an array store.
1523 int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1524 if (offset == Type::OffsetBot ||
1525 (offset >= primary_supers_offset &&
1526 offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1527 offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1528 offset = in_bytes(Klass::secondary_super_cache_offset());
1529 tj = tk = tk->with_offset(offset);
1530 }
1531 }
1532
1533 // Flatten all Raw pointers together.
1534 if (tj->base() == Type::RawPtr)
1535 tj = TypeRawPtr::BOTTOM;
1625 intptr_t key = (intptr_t) adr_type;
1626 key ^= key >> logAliasCacheSize;
1627 return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1628 }
1629
1630
1631 //-----------------------------grow_alias_types--------------------------------
1632 void Compile::grow_alias_types() {
1633 const int old_ats = _max_alias_types; // how many before?
1634 const int new_ats = old_ats; // how many more?
1635 const int grow_ats = old_ats+new_ats; // how many now?
1636 _max_alias_types = grow_ats;
1637 _alias_types = REALLOC_ARENA_ARRAY(comp_arena(), _alias_types, old_ats, grow_ats);
1638 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1639 Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1640 for (int i = 0; i < new_ats; i++) _alias_types[old_ats+i] = &ats[i];
1641 }
1642
1643
1644 //--------------------------------find_alias_type------------------------------
1645 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) {
1646 if (!do_aliasing()) {
1647 return alias_type(AliasIdxBot);
1648 }
1649
1650 AliasCacheEntry* ace = probe_alias_cache(adr_type);
1651 if (ace->_adr_type == adr_type) {
1652 return alias_type(ace->_index);
1653 }
1654
1655 // Handle special cases.
1656 if (adr_type == nullptr) return alias_type(AliasIdxTop);
1657 if (adr_type == TypePtr::BOTTOM) return alias_type(AliasIdxBot);
1658
1659 // Do it the slow way.
1660 const TypePtr* flat = flatten_alias_type(adr_type);
1661
1662 #ifdef ASSERT
1663 {
1664 ResourceMark rm;
1665 assert(flat == flatten_alias_type(flat), "not idempotent: adr_type = %s; flat = %s => %s",
1666 Type::str(adr_type), Type::str(flat), Type::str(flatten_alias_type(flat)));
1667 assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr: adr_type = %s",
1668 Type::str(adr_type));
1669 if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1670 const TypeOopPtr* foop = flat->is_oopptr();
1671 // Scalarizable allocations have exact klass always.
1672 bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1682 if (alias_type(i)->adr_type() == flat) {
1683 idx = i;
1684 break;
1685 }
1686 }
1687
1688 if (idx == AliasIdxTop) {
1689 if (no_create) return nullptr;
1690 // Grow the array if necessary.
1691 if (_num_alias_types == _max_alias_types) grow_alias_types();
1692 // Add a new alias type.
1693 idx = _num_alias_types++;
1694 _alias_types[idx]->Init(idx, flat);
1695 if (flat == TypeInstPtr::KLASS) alias_type(idx)->set_rewritable(false);
1696 if (flat == TypeAryPtr::RANGE) alias_type(idx)->set_rewritable(false);
1697 if (flat->isa_instptr()) {
1698 if (flat->offset() == java_lang_Class::klass_offset()
1699 && flat->is_instptr()->instance_klass() == env()->Class_klass())
1700 alias_type(idx)->set_rewritable(false);
1701 }
1702 if (flat->isa_aryptr()) {
1703 #ifdef ASSERT
1704 const int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1705 // (T_BYTE has the weakest alignment and size restrictions...)
1706 assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1707 #endif
1708 if (flat->offset() == TypePtr::OffsetBot) {
1709 alias_type(idx)->set_element(flat->is_aryptr()->elem());
1710 }
1711 }
1712 if (flat->isa_klassptr()) {
1713 if (UseCompactObjectHeaders) {
1714 if (flat->offset() == in_bytes(Klass::prototype_header_offset()))
1715 alias_type(idx)->set_rewritable(false);
1716 }
1717 if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1718 alias_type(idx)->set_rewritable(false);
1719 if (flat->offset() == in_bytes(Klass::misc_flags_offset()))
1720 alias_type(idx)->set_rewritable(false);
1721 if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1722 alias_type(idx)->set_rewritable(false);
1723 if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset()))
1724 alias_type(idx)->set_rewritable(false);
1725 }
1726
1727 if (flat->isa_instklassptr()) {
1728 if (flat->offset() == in_bytes(InstanceKlass::access_flags_offset())) {
1729 alias_type(idx)->set_rewritable(false);
1730 }
1731 }
1732 // %%% (We would like to finalize JavaThread::threadObj_offset(),
1733 // but the base pointer type is not distinctive enough to identify
1734 // references into JavaThread.)
1735
1736 // Check for final fields.
1737 const TypeInstPtr* tinst = flat->isa_instptr();
1738 if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1739 ciField* field;
1740 if (tinst->const_oop() != nullptr &&
1741 tinst->instance_klass() == ciEnv::current()->Class_klass() &&
1742 tinst->offset() >= (tinst->instance_klass()->layout_helper_size_in_bytes())) {
1743 // static field
1744 ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1745 field = k->get_field_by_offset(tinst->offset(), true);
1746 } else {
1747 ciInstanceKlass *k = tinst->instance_klass();
1748 field = k->get_field_by_offset(tinst->offset(), false);
1749 }
1750 assert(field == nullptr ||
1751 original_field == nullptr ||
1752 (field->holder() == original_field->holder() &&
1753 field->offset_in_bytes() == original_field->offset_in_bytes() &&
1754 field->is_static() == original_field->is_static()), "wrong field?");
1755 // Set field() and is_rewritable() attributes.
1756 if (field != nullptr) alias_type(idx)->set_field(field);
1757 }
1758 }
1759
1760 // Fill the cache for next time.
1761 ace->_adr_type = adr_type;
1762 ace->_index = idx;
1763 assert(alias_type(adr_type) == alias_type(idx), "type must be installed");
1764
1765 // Might as well try to fill the cache for the flattened version, too.
1766 AliasCacheEntry* face = probe_alias_cache(flat);
1767 if (face->_adr_type == nullptr) {
1768 face->_adr_type = flat;
1769 face->_index = idx;
1770 assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1771 }
1772
1773 return alias_type(idx);
1774 }
1775
1776
1777 Compile::AliasType* Compile::alias_type(ciField* field) {
1778 const TypeOopPtr* t;
1779 if (field->is_static())
1780 t = TypeInstPtr::make(field->holder()->java_mirror());
1781 else
1782 t = TypeOopPtr::make_from_klass_raw(field->holder());
1783 AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1784 assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1785 return atp;
1786 }
1787
1788
1789 //------------------------------have_alias_type--------------------------------
1790 bool Compile::have_alias_type(const TypePtr* adr_type) {
1872 assert(!C->major_progress(), "not cleared");
1873
1874 if (_for_post_loop_igvn.length() > 0) {
1875 while (_for_post_loop_igvn.length() > 0) {
1876 Node* n = _for_post_loop_igvn.pop();
1877 n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1878 igvn._worklist.push(n);
1879 }
1880 igvn.optimize();
1881 if (failing()) return;
1882 assert(_for_post_loop_igvn.length() == 0, "no more delayed nodes allowed");
1883 assert(C->parse_predicate_count() == 0, "all parse predicates should have been removed now");
1884
1885 // Sometimes IGVN sets major progress (e.g., when processing loop nodes).
1886 if (C->major_progress()) {
1887 C->clear_major_progress(); // ensure that major progress is now clear
1888 }
1889 }
1890 }
1891
1892 void Compile::record_for_merge_stores_igvn(Node* n) {
1893 if (!n->for_merge_stores_igvn()) {
1894 assert(!_for_merge_stores_igvn.contains(n), "duplicate");
1895 n->add_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
1896 _for_merge_stores_igvn.append(n);
1897 }
1898 }
1899
1900 void Compile::remove_from_merge_stores_igvn(Node* n) {
1901 n->remove_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
1902 _for_merge_stores_igvn.remove(n);
1903 }
1904
1905 // We need to wait with merging stores until RangeCheck smearing has removed the RangeChecks during
1906 // the post loops IGVN phase. If we do it earlier, then there may still be some RangeChecks between
1907 // the stores, and we merge the wrong sequence of stores.
1908 // Example:
1909 // StoreI RangeCheck StoreI StoreI RangeCheck StoreI
1910 // Apply MergeStores:
1911 // StoreI RangeCheck [ StoreL ] RangeCheck StoreI
1990 assert(next_bci == iter.next_bci() || next_bci == iter.get_dest(), "wrong next_bci at unstable_if");
1991 Bytecodes::Code c = iter.cur_bc();
1992 Node* lhs = nullptr;
1993 Node* rhs = nullptr;
1994 if (c == Bytecodes::_if_acmpeq || c == Bytecodes::_if_acmpne) {
1995 lhs = unc->peek_operand(0);
1996 rhs = unc->peek_operand(1);
1997 } else if (c == Bytecodes::_ifnull || c == Bytecodes::_ifnonnull) {
1998 lhs = unc->peek_operand(0);
1999 }
2000
2001 ResourceMark rm;
2002 const MethodLivenessResult& live_locals = method->liveness_at_bci(next_bci);
2003 assert(live_locals.is_valid(), "broken liveness info");
2004 int len = (int)live_locals.size();
2005
2006 for (int i = 0; i < len; i++) {
2007 Node* local = unc->local(jvms, i);
2008 // kill local using the liveness of next_bci.
2009 // give up when the local looks like an operand to secure reexecution.
2010 if (!live_locals.at(i) && !local->is_top() && local != lhs && local!= rhs) {
2011 uint idx = jvms->locoff() + i;
2012 #ifdef ASSERT
2013 if (PrintOpto && Verbose) {
2014 tty->print("[unstable_if] kill local#%d: ", idx);
2015 local->dump();
2016 tty->cr();
2017 }
2018 #endif
2019 igvn.replace_input_of(unc, idx, top());
2020 modified = true;
2021 }
2022 }
2023 }
2024
2025 // keep the mondified trap for late query
2026 if (modified) {
2027 trap->set_modified();
2028 } else {
2029 _unstable_if_traps.delete_at(i);
2030 }
2031 }
2032 igvn.optimize();
2033 }
2034
2035 // StringOpts and late inlining of string methods
2036 void Compile::inline_string_calls(bool parse_time) {
2037 {
2038 // remove useless nodes to make the usage analysis simpler
2039 ResourceMark rm;
2040 PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
2041 }
2042
2043 {
2044 ResourceMark rm;
2045 print_method(PHASE_BEFORE_STRINGOPTS, 3);
2243
2244 if (_string_late_inlines.length() > 0) {
2245 assert(has_stringbuilder(), "inconsistent");
2246
2247 inline_string_calls(false);
2248
2249 if (failing()) return;
2250
2251 inline_incrementally_cleanup(igvn);
2252 }
2253
2254 set_inlining_incrementally(false);
2255 }
2256
2257 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) {
2258 // "inlining_incrementally() == false" is used to signal that no inlining is allowed
2259 // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details).
2260 // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == nullptr"
2261 // as if "inlining_incrementally() == true" were set.
2262 assert(inlining_incrementally() == false, "not allowed");
2263 assert(_modified_nodes == nullptr, "not allowed");
2264 assert(_late_inlines.length() > 0, "sanity");
2265
2266 if (StressIncrementalInlining) {
2267 shuffle_late_inlines();
2268 }
2269
2270 while (_late_inlines.length() > 0) {
2271 igvn_worklist()->ensure_empty(); // should be done with igvn
2272
2273 while (inline_incrementally_one()) {
2274 assert(!failing_internal() || failure_is_artificial(), "inconsistent");
2275 }
2276 if (failing()) return;
2277
2278 inline_incrementally_cleanup(igvn);
2279 }
2280 }
2281
2282 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
2283 if (_loop_opts_cnt > 0) {
2284 while (major_progress() && (_loop_opts_cnt > 0)) {
2285 TracePhase tp(_t_idealLoop);
2286 PhaseIdealLoop::optimize(igvn, mode);
2287 _loop_opts_cnt--;
2288 if (failing()) return false;
2289 if (major_progress()) {
2290 print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2291 }
2292 }
2293 }
2294 return true;
2295 }
2296
2297 // Remove edges from "root" to each SafePoint at a backward branch.
2298 // They were inserted during parsing (see add_safepoint()) to make
2299 // infinite loops without calls or exceptions visible to root, i.e.,
2405 print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2);
2406 }
2407 assert(!has_vbox_nodes(), "sanity");
2408
2409 if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2410 Compile::TracePhase tp(_t_renumberLive);
2411 igvn_worklist()->ensure_empty(); // should be done with igvn
2412 {
2413 ResourceMark rm;
2414 PhaseRenumberLive prl(initial_gvn(), *igvn_worklist());
2415 }
2416 igvn.reset();
2417 igvn.optimize(true);
2418 if (failing()) return;
2419 }
2420
2421 // Now that all inlining is over and no PhaseRemoveUseless will run, cut edge from root to loop
2422 // safepoints
2423 remove_root_to_sfpts_edges(igvn);
2424
2425 if (failing()) return;
2426
2427 _print_phase_loop_opts = has_loops();
2428 if (_print_phase_loop_opts) {
2429 print_method(PHASE_BEFORE_LOOP_OPTS, 2);
2430 }
2431
2432 // Perform escape analysis
2433 if (do_escape_analysis() && ConnectionGraph::has_candidates(this)) {
2434 if (has_loops()) {
2435 // Cleanup graph (remove dead nodes).
2436 TracePhase tp(_t_idealLoop);
2437 PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
2438 if (failing()) return;
2439 }
2440 bool progress;
2441 print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2442 do {
2443 ConnectionGraph::do_analysis(this, &igvn);
2444
2445 if (failing()) return;
2446
2447 int mcount = macro_count(); // Record number of allocations and locks before IGVN
2448
2449 // Optimize out fields loads from scalar replaceable allocations.
2450 igvn.optimize(true);
2451 print_method(PHASE_ITER_GVN_AFTER_EA, 2);
2452
2453 if (failing()) return;
2454
2455 if (congraph() != nullptr && macro_count() > 0) {
2456 TracePhase tp(_t_macroEliminate);
2457 PhaseMacroExpand mexp(igvn);
2458 mexp.eliminate_macro_nodes();
2459 if (failing()) return;
2460 print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
2461
2462 igvn.set_delay_transform(false);
2463 igvn.optimize();
2464 if (failing()) return;
2465
2466 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2467 }
2468
2469 ConnectionGraph::verify_ram_nodes(this, root());
2470 if (failing()) return;
2471
2472 progress = do_iterative_escape_analysis() &&
2473 (macro_count() < mcount) &&
2474 ConnectionGraph::has_candidates(this);
2475 // Try again if candidates exist and made progress
2476 // by removing some allocations and/or locks.
2477 } while (progress);
2478 }
2479
2480 // Loop transforms on the ideal graph. Range Check Elimination,
2481 // peeling, unrolling, etc.
2482
2483 // Set loop opts counter
2484 if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
2485 {
2486 TracePhase tp(_t_idealLoop);
2487 PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
2488 _loop_opts_cnt--;
2489 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
2490 if (failing()) return;
2491 }
2492 // Loop opts pass if partial peeling occurred in previous pass
2493 if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
2494 TracePhase tp(_t_idealLoop);
2495 PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2496 _loop_opts_cnt--;
2497 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
2498 if (failing()) return;
2499 }
2547
2548 // Once loop optimizations are over, it is safe to get rid of all reachability fence nodes and
2549 // migrate reachability edges to safepoints.
2550 if (OptimizeReachabilityFences && _reachability_fences.length() > 0) {
2551 TracePhase tp1(_t_idealLoop);
2552 TracePhase tp2(_t_reachability);
2553 PhaseIdealLoop::optimize(igvn, PostLoopOptsExpandReachabilityFences);
2554 print_method(PHASE_EXPAND_REACHABILITY_FENCES, 2);
2555 if (failing()) return;
2556 assert(_reachability_fences.length() == 0 || PreserveReachabilityFencesOnConstants, "no RF nodes allowed");
2557 }
2558
2559 process_for_merge_stores_igvn(igvn);
2560
2561 if (failing()) return;
2562
2563 #ifdef ASSERT
2564 bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
2565 #endif
2566
2567 {
2568 TracePhase tp(_t_macroExpand);
2569 print_method(PHASE_BEFORE_MACRO_EXPANSION, 3);
2570 PhaseMacroExpand mex(igvn);
2571 // Do not allow new macro nodes once we start to eliminate and expand
2572 C->reset_allow_macro_nodes();
2573 // Last attempt to eliminate macro nodes before expand
2574 mex.eliminate_macro_nodes();
2575 if (failing()) {
2576 return;
2577 }
2578 mex.eliminate_opaque_looplimit_macro_nodes();
2579 if (failing()) {
2580 return;
2581 }
2582 print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
2583 if (mex.expand_macro_nodes()) {
2584 assert(failing(), "must bail out w/ explicit message");
2585 return;
2586 }
2587 print_method(PHASE_AFTER_MACRO_EXPANSION, 2);
2588 }
2589
2590 {
2591 TracePhase tp(_t_barrierExpand);
2592 if (bs->expand_barriers(this, igvn)) {
2593 assert(failing(), "must bail out w/ explicit message");
2594 return;
2595 }
2596 print_method(PHASE_BARRIER_EXPANSION, 2);
2597 }
2598
2599 if (C->max_vector_size() > 0) {
2600 C->optimize_logic_cones(igvn);
2601 igvn.optimize();
2602 if (failing()) return;
2603 }
2604
2605 DEBUG_ONLY( _modified_nodes = nullptr; )
2606
2607 assert(igvn._worklist.size() == 0, "not empty");
2608
2609 if (_late_inlines.length() > 0) {
2610 // More opportunities to optimize virtual and MH calls.
2611 // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option.
2612 process_late_inline_calls_no_inline(igvn);
2613 if (failing()) return;
2614 }
2615 assert(_late_inlines.length() == 0, "late inline queue must be drained");
2616 } // (End scope of igvn; run destructor if necessary for asserts.)
2617
2618 check_no_dead_use();
2619
2620 // We will never use the NodeHash table any more. Clear it so that final_graph_reshaping does not have
2621 // to remove hashes to unlock nodes for modifications.
2622 C->node_hash()->clear();
2623
2624 // A method with only infinite loops has no edges entering loops from root
2625 {
2626 TracePhase tp(_t_graphReshaping);
2627 if (final_graph_reshaping()) {
2628 assert(failing(), "must bail out w/ explicit message");
2629 return;
2630 }
2631 }
2632
2633 print_method(PHASE_OPTIMIZE_FINISHED, 2);
2634 DEBUG_ONLY(set_phase_optimize_finished();)
2635 }
3312 mul->subsume_by(mul_hi_lo->first_proj(), this);
3313 n->subsume_by(mul_hi_lo->second_proj(), this);
3314 }
3315
3316 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) {
3317 switch( nop ) {
3318 case Op_Opaque1: // Remove Opaque Nodes before matching
3319 n->subsume_by(n->in(1), this);
3320 break;
3321 case Op_CallLeafPure: {
3322 // If the pure call is not supported, then lower to a CallLeaf.
3323 if (!Matcher::match_rule_supported(Op_CallLeafPure)) {
3324 CallNode* call = n->as_Call();
3325 CallNode* new_call = new CallLeafNode(call->tf(), call->entry_point(),
3326 call->_name, TypeRawPtr::BOTTOM);
3327 new_call->init_req(TypeFunc::Control, call->in(TypeFunc::Control));
3328 new_call->init_req(TypeFunc::I_O, C->top());
3329 new_call->init_req(TypeFunc::Memory, C->top());
3330 new_call->init_req(TypeFunc::ReturnAdr, C->top());
3331 new_call->init_req(TypeFunc::FramePtr, C->top());
3332 for (unsigned int i = TypeFunc::Parms; i < call->tf()->domain()->cnt(); i++) {
3333 new_call->init_req(i, call->in(i));
3334 }
3335 n->subsume_by(new_call, this);
3336 }
3337 break;
3338 }
3339 case Op_CallStaticJava:
3340 case Op_CallJava:
3341 case Op_CallDynamicJava:
3342 frc.inc_java_call_count(); // Count java call site;
3343 case Op_CallRuntime:
3344 case Op_CallLeaf:
3345 case Op_CallLeafVector:
3346 case Op_CallLeafNoFP: {
3347 assert (n->is_Call(), "");
3348 CallNode *call = n->as_Call();
3349 // See if uncommon argument is shared
3350 if (call->is_CallStaticJava() && call->as_CallStaticJava()->_name) {
3351 Node *n = call->in(TypeFunc::Parms);
3352 int nop = n->Opcode();
3359 nop != Op_DecodeNKlass &&
3360 !n->is_Mem() &&
3361 !n->is_Phi()) {
3362 Node *x = n->clone();
3363 call->set_req(TypeFunc::Parms, x);
3364 }
3365 }
3366 break;
3367 }
3368
3369 // Mem nodes need explicit cases to satisfy assert(!n->is_Mem()) in default.
3370 case Op_StoreF:
3371 case Op_LoadF:
3372 case Op_StoreD:
3373 case Op_LoadD:
3374 case Op_LoadD_unaligned:
3375 case Op_StoreB:
3376 case Op_StoreC:
3377 case Op_StoreI:
3378 case Op_StoreL:
3379 case Op_CompareAndSwapB:
3380 case Op_CompareAndSwapS:
3381 case Op_CompareAndSwapI:
3382 case Op_CompareAndSwapL:
3383 case Op_CompareAndSwapP:
3384 case Op_CompareAndSwapN:
3385 case Op_WeakCompareAndSwapB:
3386 case Op_WeakCompareAndSwapS:
3387 case Op_WeakCompareAndSwapI:
3388 case Op_WeakCompareAndSwapL:
3389 case Op_WeakCompareAndSwapP:
3390 case Op_WeakCompareAndSwapN:
3391 case Op_CompareAndExchangeB:
3392 case Op_CompareAndExchangeS:
3393 case Op_CompareAndExchangeI:
3394 case Op_CompareAndExchangeL:
3395 case Op_CompareAndExchangeP:
3396 case Op_CompareAndExchangeN:
3397 case Op_GetAndAddS:
3398 case Op_GetAndAddB:
3914 k->subsume_by(m, this);
3915 }
3916 }
3917 }
3918 break;
3919 }
3920 case Op_CmpUL: {
3921 if (!Matcher::has_match_rule(Op_CmpUL)) {
3922 // No support for unsigned long comparisons
3923 ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
3924 Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
3925 Node* orl = new OrLNode(n->in(1), sign_bit_mask);
3926 ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
3927 Node* andl = new AndLNode(orl, remove_sign_mask);
3928 Node* cmp = new CmpLNode(andl, n->in(2));
3929 n->subsume_by(cmp, this);
3930 }
3931 break;
3932 }
3933 #ifdef ASSERT
3934 case Op_ConNKlass: {
3935 const TypePtr* tp = n->as_Type()->type()->make_ptr();
3936 ciKlass* klass = tp->is_klassptr()->exact_klass();
3937 assert(klass->is_in_encoding_range(), "klass cannot be compressed");
3938 break;
3939 }
3940 #endif
3941 default:
3942 assert(!n->is_Call(), "");
3943 assert(!n->is_Mem(), "");
3944 assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3945 break;
3946 }
3947 }
3948
3949 //------------------------------final_graph_reshaping_walk---------------------
3950 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3951 // requires that the walk visits a node's inputs before visiting the node.
3952 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
3953 Unique_Node_List sfpt;
4286 }
4287 }
4288
4289 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
4290 return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
4291 }
4292
4293 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
4294 return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
4295 }
4296
4297 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
4298 if (holder->is_initialized()) {
4299 return false;
4300 }
4301 if (holder->is_being_initialized()) {
4302 if (accessing_method->holder() == holder) {
4303 // Access inside a class. The barrier can be elided when access happens in <clinit>,
4304 // <init>, or a static method. In all those cases, there was an initialization
4305 // barrier on the holder klass passed.
4306 if (accessing_method->is_static_initializer() ||
4307 accessing_method->is_object_initializer() ||
4308 accessing_method->is_static()) {
4309 return false;
4310 }
4311 } else if (accessing_method->holder()->is_subclass_of(holder)) {
4312 // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
4313 // In case of <init> or a static method, the barrier is on the subclass is not enough:
4314 // child class can become fully initialized while its parent class is still being initialized.
4315 if (accessing_method->is_static_initializer()) {
4316 return false;
4317 }
4318 }
4319 ciMethod* root = method(); // the root method of compilation
4320 if (root != accessing_method) {
4321 return needs_clinit_barrier(holder, root); // check access in the context of compilation root
4322 }
4323 }
4324 return true;
4325 }
4326
4327 #ifndef PRODUCT
4328 //------------------------------verify_bidirectional_edges---------------------
4329 // For each input edge to a node (ie - for each Use-Def edge), verify that
4330 // there is a corresponding Def-Use edge.
4331 void Compile::verify_bidirectional_edges(Unique_Node_List& visited, const Unique_Node_List* root_and_safepoints) const {
4332 // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc
4333 uint stack_size = live_nodes() >> 4;
4334 Node_List nstack(MAX2(stack_size, (uint) OptoNodeListSize));
4335 if (root_and_safepoints != nullptr) {
4365 if (in != nullptr && !in->is_top()) {
4366 // Count instances of `next`
4367 int cnt = 0;
4368 for (uint idx = 0; idx < in->_outcnt; idx++) {
4369 if (in->_out[idx] == n) {
4370 cnt++;
4371 }
4372 }
4373 assert(cnt > 0, "Failed to find Def-Use edge.");
4374 // Check for duplicate edges
4375 // walk the input array downcounting the input edges to n
4376 for (uint j = 0; j < length; j++) {
4377 if (n->in(j) == in) {
4378 cnt--;
4379 }
4380 }
4381 assert(cnt == 0, "Mismatched edge count.");
4382 } else if (in == nullptr) {
4383 assert(i == 0 || i >= n->req() ||
4384 n->is_Region() || n->is_Phi() || n->is_ArrayCopy() ||
4385 (n->is_Unlock() && i == (n->req() - 1)) ||
4386 (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
4387 "only region, phi, arraycopy, unlock or membar nodes have null data edges");
4388 } else {
4389 assert(in->is_top(), "sanity");
4390 // Nothing to check.
4391 }
4392 }
4393 }
4394 }
4395
4396 //------------------------------verify_graph_edges---------------------------
4397 // Walk the Graph and verify that there is a one-to-one correspondence
4398 // between Use-Def edges and Def-Use edges in the graph.
4399 void Compile::verify_graph_edges(bool no_dead_code, const Unique_Node_List* root_and_safepoints) const {
4400 if (VerifyGraphEdges) {
4401 Unique_Node_List visited;
4402
4403 // Call graph walk to check edges
4404 verify_bidirectional_edges(visited, root_and_safepoints);
4405 if (no_dead_code) {
4406 // Now make sure that no visited node is used by an unvisited node.
4407 bool dead_nodes = false;
4518 // (1) subklass is already limited to a subtype of superklass => always ok
4519 // (2) subklass does not overlap with superklass => always fail
4520 // (3) superklass has NO subtypes and we can check with a simple compare.
4521 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) {
4522 if (skip) {
4523 return SSC_full_test; // Let caller generate the general case.
4524 }
4525
4526 if (subk->is_java_subtype_of(superk)) {
4527 return SSC_always_true; // (0) and (1) this test cannot fail
4528 }
4529
4530 if (!subk->maybe_java_subtype_of(superk)) {
4531 return SSC_always_false; // (2) true path dead; no dynamic test needed
4532 }
4533
4534 const Type* superelem = superk;
4535 if (superk->isa_aryklassptr()) {
4536 int ignored;
4537 superelem = superk->is_aryklassptr()->base_element_type(ignored);
4538 }
4539
4540 if (superelem->isa_instklassptr()) {
4541 ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass();
4542 if (!ik->has_subklass()) {
4543 if (!ik->is_final()) {
4544 // Add a dependency if there is a chance of a later subclass.
4545 dependencies()->assert_leaf_type(ik);
4546 }
4547 if (!superk->maybe_java_subtype_of(subk)) {
4548 return SSC_always_false;
4549 }
4550 return SSC_easy_test; // (3) caller can do a simple ptr comparison
4551 }
4552 } else {
4553 // A primitive array type has no subtypes.
4554 return SSC_easy_test; // (3) caller can do a simple ptr comparison
4555 }
4556
4557 return SSC_full_test;
5354 _debug_network_printer->print(name, C->root(), visible_nodes, fr);
5355 }
5356 #endif // !PRODUCT
5357
5358 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
5359 precond(type != nullptr);
5360
5361 if (phase->type(value)->higher_equal(type)) {
5362 return value;
5363 }
5364 Node* result = nullptr;
5365 if (bt == T_BYTE) {
5366 result = phase->transform(new LShiftINode(value, phase->intcon(24)));
5367 result = new RShiftINode(result, phase->intcon(24));
5368 } else if (bt == T_BOOLEAN) {
5369 assert(type == TypeInt::BOOL || type == TypeInt::UBYTE, "unexpected boolean type: %s", Type::str(type));
5370 Node* mask = phase->intcon(type == TypeInt::BOOL ? 1 : 0xFF);
5371 result = new AndINode(value, mask);
5372 } else if (bt == T_CHAR) {
5373 result = new AndINode(value,phase->intcon(0xFFFF));
5374 } else {
5375 assert(bt == T_SHORT, "unexpected narrow type");
5376 result = phase->transform(new LShiftINode(value, phase->intcon(16)));
5377 result = new RShiftINode(result, phase->intcon(16));
5378 }
5379 if (transform_res) {
5380 result = phase->transform(result);
5381 }
5382 return result;
5383 }
5384
5385 void Compile::record_method_not_compilable_oom() {
5386 record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit());
5387 }
5388
5389 #ifndef PRODUCT
5390 // Collects all the control inputs from nodes on the worklist and from their data dependencies
5391 static void find_candidate_control_inputs(Unique_Node_List& worklist, Unique_Node_List& candidates) {
5392 // Follow non-control edges until we reach CFG nodes
5393 for (uint i = 0; i < worklist.size(); i++) {
|
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.hpp"
26 #include "asm/macroAssembler.inline.hpp"
27 #include "ci/ciFlatArray.hpp"
28 #include "ci/ciInlineKlass.hpp"
29 #include "ci/ciReplay.hpp"
30 #include "classfile/javaClasses.hpp"
31 #include "code/aotCodeCache.hpp"
32 #include "code/exceptionHandlerTable.hpp"
33 #include "code/nmethod.hpp"
34 #include "compiler/compilationFailureInfo.hpp"
35 #include "compiler/compilationMemoryStatistic.hpp"
36 #include "compiler/compileBroker.hpp"
37 #include "compiler/compileLog.hpp"
38 #include "compiler/compiler_globals.hpp"
39 #include "compiler/compilerDefinitions.hpp"
40 #include "compiler/compilerOracle.hpp"
41 #include "compiler/disassembler.hpp"
42 #include "compiler/oopMap.hpp"
43 #include "gc/shared/barrierSet.hpp"
44 #include "gc/shared/c2/barrierSetC2.hpp"
45 #include "jfr/jfrEvents.hpp"
46 #include "jvm_io.h"
47 #include "memory/allocation.hpp"
48 #include "memory/arena.hpp"
49 #include "memory/resourceArea.hpp"
50 #include "opto/addnode.hpp"
51 #include "opto/block.hpp"
52 #include "opto/c2compiler.hpp"
53 #include "opto/callGenerator.hpp"
54 #include "opto/callnode.hpp"
55 #include "opto/castnode.hpp"
56 #include "opto/cfgnode.hpp"
57 #include "opto/chaitin.hpp"
58 #include "opto/compile.hpp"
59 #include "opto/connode.hpp"
60 #include "opto/convertnode.hpp"
61 #include "opto/divnode.hpp"
62 #include "opto/escape.hpp"
63 #include "opto/idealGraphPrinter.hpp"
64 #include "opto/inlinetypenode.hpp"
65 #include "opto/locknode.hpp"
66 #include "opto/loopnode.hpp"
67 #include "opto/machnode.hpp"
68 #include "opto/macro.hpp"
69 #include "opto/matcher.hpp"
70 #include "opto/mathexactnode.hpp"
71 #include "opto/memnode.hpp"
72 #include "opto/movenode.hpp"
73 #include "opto/mulnode.hpp"
74 #include "opto/multnode.hpp"
75 #include "opto/narrowptrnode.hpp"
76 #include "opto/node.hpp"
77 #include "opto/opaquenode.hpp"
78 #include "opto/opcodes.hpp"
79 #include "opto/output.hpp"
80 #include "opto/parse.hpp"
81 #include "opto/phaseX.hpp"
82 #include "opto/reachability.hpp"
83 #include "opto/rootnode.hpp"
84 #include "opto/runtime.hpp"
85 #include "opto/stringopts.hpp"
86 #include "opto/type.hpp"
87 #include "opto/vector.hpp"
88 #include "opto/vectornode.hpp"
89 #include "runtime/arguments.hpp"
90 #include "runtime/globals_extension.hpp"
91 #include "runtime/sharedRuntime.hpp"
92 #include "runtime/signature.hpp"
93 #include "runtime/stubRoutines.hpp"
94 #include "runtime/timer.hpp"
95 #include "utilities/align.hpp"
96 #include "utilities/copy.hpp"
97 #include "utilities/hashTable.hpp"
98 #include "utilities/macros.hpp"
99
100 // -------------------- Compile::mach_constant_base_node -----------------------
101 // Constant table base node singleton.
102 MachConstantBaseNode* Compile::mach_constant_base_node() {
103 if (_mach_constant_base_node == nullptr) {
104 _mach_constant_base_node = new MachConstantBaseNode();
105 _mach_constant_base_node->add_req(C->root());
106 }
107 return _mach_constant_base_node;
108 }
109
398 record_dead_node(dead->_idx);
399 }
400 if (dead->is_macro()) {
401 remove_macro_node(dead);
402 }
403 if (dead->is_expensive()) {
404 remove_expensive_node(dead);
405 }
406 if (dead->is_ReachabilityFence()) {
407 remove_reachability_fence(dead->as_ReachabilityFence());
408 }
409 if (dead->is_OpaqueTemplateAssertionPredicate()) {
410 remove_template_assertion_predicate_opaque(dead->as_OpaqueTemplateAssertionPredicate());
411 }
412 if (dead->is_ParsePredicate()) {
413 remove_parse_predicate(dead->as_ParsePredicate());
414 }
415 if (dead->for_post_loop_opts_igvn()) {
416 remove_from_post_loop_opts_igvn(dead);
417 }
418 if (dead->is_InlineType()) {
419 remove_inline_type(dead);
420 }
421 if (dead->is_LoadFlat() || dead->is_StoreFlat()) {
422 remove_flat_access(dead);
423 }
424 if (dead->for_merge_stores_igvn()) {
425 remove_from_merge_stores_igvn(dead);
426 }
427 if (dead->is_Call()) {
428 remove_useless_late_inlines( &_late_inlines, dead);
429 remove_useless_late_inlines( &_string_late_inlines, dead);
430 remove_useless_late_inlines( &_boxing_late_inlines, dead);
431 remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead);
432
433 if (dead->is_CallStaticJava()) {
434 remove_unstable_if_trap(dead->as_CallStaticJava(), false);
435 }
436 }
437 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
438 bs->unregister_potential_barrier_node(dead);
439 }
440
441 // Disconnect all useless nodes by disconnecting those at the boundary.
442 void Compile::disconnect_useless_nodes(Unique_Node_List& useful, Unique_Node_List& worklist, const Unique_Node_List* root_and_safepoints) {
443 uint next = 0;
451 // Use raw traversal of out edges since this code removes out edges
452 int max = n->outcnt();
453 for (int j = 0; j < max; ++j) {
454 Node* child = n->raw_out(j);
455 if (!useful.member(child)) {
456 assert(!child->is_top() || child != top(),
457 "If top is cached in Compile object it is in useful list");
458 // Only need to remove this out-edge to the useless node
459 n->raw_del_out(j);
460 --j;
461 --max;
462 if (child->is_data_proj_of_pure_function(n)) {
463 worklist.push(n);
464 }
465 }
466 }
467 if (n->outcnt() == 1 && n->has_special_unique_user()) {
468 assert(useful.member(n->unique_out()), "do not push a useless node");
469 worklist.push(n->unique_out());
470 }
471 if (n->outcnt() == 0) {
472 worklist.push(n);
473 }
474 }
475
476 remove_useless_nodes(_macro_nodes, useful); // remove useless macro nodes
477 remove_useless_nodes(_parse_predicates, useful); // remove useless Parse Predicate nodes
478 // Remove useless Template Assertion Predicate opaque nodes
479 remove_useless_nodes(_template_assertion_predicate_opaques, useful);
480 remove_useless_nodes(_expensive_nodes, useful); // remove useless expensive nodes
481 remove_useless_nodes(_reachability_fences, useful); // remove useless node recorded for post loop opts IGVN pass
482 remove_useless_nodes(_for_post_loop_igvn, useful); // remove useless node recorded for post loop opts IGVN pass
483 remove_useless_nodes(_inline_type_nodes, useful); // remove useless inline type nodes
484 remove_useless_nodes(_flat_access_nodes, useful); // remove useless flat access nodes
485 #ifdef ASSERT
486 if (_modified_nodes != nullptr) {
487 _modified_nodes->remove_useless_nodes(useful.member_set());
488 }
489 #endif
490 remove_useless_nodes(_for_merge_stores_igvn, useful); // remove useless node recorded for merge stores IGVN pass
491 remove_useless_unstable_if_traps(useful); // remove useless unstable_if traps
492 remove_useless_coarsened_locks(useful); // remove useless coarsened locks nodes
493 #ifdef ASSERT
494 if (_modified_nodes != nullptr) {
495 _modified_nodes->remove_useless_nodes(useful.member_set());
496 }
497 #endif
498
499 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
500 bs->eliminate_useless_gc_barriers(useful, this);
501 // clean up the late inline lists
502 remove_useless_late_inlines( &_late_inlines, useful);
503 remove_useless_late_inlines( &_string_late_inlines, useful);
504 remove_useless_late_inlines( &_boxing_late_inlines, useful);
505 remove_useless_late_inlines(&_vector_reboxing_late_inlines, useful);
506 DEBUG_ONLY(verify_graph_edges(true /*check for no_dead_code*/, root_and_safepoints);)
507 }
508
509 // ============================================================================
657
658 Compile::Compile(ciEnv* ci_env, ciMethod* target, int osr_bci,
659 Options options, DirectiveSet* directive)
660 : Phase(Compiler),
661 _compile_id(ci_env->compile_id()),
662 _options(options),
663 _method(target),
664 _entry_bci(osr_bci),
665 _ilt(nullptr),
666 _stub_function(nullptr),
667 _stub_name(nullptr),
668 _stub_id(StubId::NO_STUBID),
669 _stub_entry_point(nullptr),
670 _max_node_limit(MaxNodeLimit),
671 _node_count_inlining_cutoff(NodeCountInliningCutoff),
672 _post_loop_opts_phase(false),
673 _merge_stores_phase(false),
674 _allow_macro_nodes(true),
675 _inlining_progress(false),
676 _inlining_incrementally(false),
677 _strength_reduction(false),
678 _do_cleanup(false),
679 _has_reserved_stack_access(target->has_reserved_stack_access()),
680 _has_circular_inline_type(false),
681 #ifndef PRODUCT
682 _igv_idx(0),
683 _trace_opto_output(directive->TraceOptoOutputOption),
684 #endif
685 _clinit_barrier_on_entry(false),
686 _stress_seed(0),
687 _comp_arena(mtCompiler, Arena::Tag::tag_comp),
688 _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
689 _env(ci_env),
690 _directive(directive),
691 _log(ci_env->log()),
692 _first_failure_details(nullptr),
693 _intrinsics(comp_arena(), 0, 0, nullptr),
694 _macro_nodes(comp_arena(), 8, 0, nullptr),
695 _parse_predicates(comp_arena(), 8, 0, nullptr),
696 _template_assertion_predicate_opaques(comp_arena(), 8, 0, nullptr),
697 _expensive_nodes(comp_arena(), 8, 0, nullptr),
698 _reachability_fences(comp_arena(), 8, 0, nullptr),
699 _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),
700 _inline_type_nodes (comp_arena(), 8, 0, nullptr),
701 _flat_access_nodes(comp_arena(), 8, 0, nullptr),
702 _for_merge_stores_igvn(comp_arena(), 8, 0, nullptr),
703 _unstable_if_traps(comp_arena(), 8, 0, nullptr),
704 _coarsened_locks(comp_arena(), 8, 0, nullptr),
705 _congraph(nullptr),
706 NOT_PRODUCT(_igv_printer(nullptr) COMMA)
707 _unique(0),
708 _dead_node_count(0),
709 _dead_node_list(comp_arena()),
710 _node_arena_one(mtCompiler, Arena::Tag::tag_node),
711 _node_arena_two(mtCompiler, Arena::Tag::tag_node),
712 _node_arena(&_node_arena_one),
713 _mach_constant_base_node(nullptr),
714 _Compile_types(mtCompiler, Arena::Tag::tag_type),
715 _initial_gvn(nullptr),
716 _igvn_worklist(nullptr),
717 _types(nullptr),
718 _node_hash(nullptr),
719 _late_inlines(comp_arena(), 2, 0, nullptr),
720 _string_late_inlines(comp_arena(), 2, 0, nullptr),
721 _boxing_late_inlines(comp_arena(), 2, 0, nullptr),
791 #define MINIMUM_NODE_HASH 1023
792
793 // GVN that will be run immediately on new nodes
794 uint estimated_size = method()->code_size()*4+64;
795 estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
796 _igvn_worklist = new (comp_arena()) Unique_Node_List(comp_arena());
797 _types = new (comp_arena()) Type_Array(comp_arena());
798 _node_hash = new (comp_arena()) NodeHash(comp_arena(), estimated_size);
799 PhaseGVN gvn;
800 set_initial_gvn(&gvn);
801
802 { // Scope for timing the parser
803 TracePhase tp(_t_parser);
804
805 // Put top into the hash table ASAP.
806 initial_gvn()->transform(top());
807
808 // Set up tf(), start(), and find a CallGenerator.
809 CallGenerator* cg = nullptr;
810 if (is_osr_compilation()) {
811 init_tf(TypeFunc::make(method(), false, /* is_osr_compilation = */ true));
812 StartNode* s = new StartOSRNode(root(), tf()->domain_sig());
813 initial_gvn()->set_type_bottom(s);
814 verify_start(s);
815 cg = CallGenerator::for_osr(method(), entry_bci());
816 } else {
817 // Normal case.
818 init_tf(TypeFunc::make(method(), false));
819 StartNode* s = new StartNode(root(), tf()->domain_cc());
820 initial_gvn()->set_type_bottom(s);
821 verify_start(s);
822 float past_uses = method()->interpreter_invocation_count();
823 float expected_uses = past_uses;
824 cg = CallGenerator::for_inline(method(), expected_uses);
825 }
826 if (failing()) return;
827 if (cg == nullptr) {
828 const char* reason = InlineTree::check_can_parse(method());
829 assert(reason != nullptr, "expect reason for parse failure");
830 stringStream ss;
831 ss.print("cannot parse method: %s", reason);
832 record_method_not_compilable(ss.as_string());
833 return;
834 }
835
836 gvn.set_type(root(), root()->bottom_type());
837
838 JVMState* jvms = build_start_state(start(), tf());
839 if ((jvms = cg->generate(jvms)) == nullptr) {
899 if (should_print_ideal()) {
900 print_ideal_ir("PrintIdeal");
901 }
902 #endif
903
904 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
905 bs->final_refinement(this);
906
907 #ifdef ASSERT
908 bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen);
909 #endif
910
911 // Dump compilation data to replay it.
912 if (directive->DumpReplayOption) {
913 env()->dump_replay_data(_compile_id);
914 }
915 if (directive->DumpInlineOption && (ilt() != nullptr)) {
916 env()->dump_inline_data(_compile_id);
917 }
918
919 // Now that we know the size of all the monitors we can add fixed slots:
920 // [...]
921 // rsp+80: saved fp register
922 // rsp+76: Fixed slot 7
923 // rsp+72: Fixed slot 6 (stack increment)
924 // rsp+68: Fixed slot 5
925 // rsp+64: Fixed slot 4 (null marker)
926 // rsp+60: Fixed slot 3
927 // rsp+56: Fixed slot 2 (original deopt pc)
928 // rsp+52: Fixed slot 1
929 // rsp+48: Fixed slot 0 (monitors)
930 // rsp+44: spill
931 // [...]
932
933 // One extra slot for the original deopt pc.
934 int next_slot = fixed_slots();
935 next_slot += VMRegImpl::slots_per_word;
936
937 // One extra slot for the special stack increment value.
938 if (needs_stack_repair()) {
939 next_slot += VMRegImpl::slots_per_word;
940 }
941
942 // One extra slot to hold the null marker at scalarized returns.
943 if (needs_nm_slot()) {
944 next_slot += VMRegImpl::slots_per_word;
945 }
946 set_fixed_slots(next_slot);
947
948 // Compute when to use implicit null checks. Used by matching trap based
949 // nodes and NullCheck optimization.
950 set_allowed_deopt_reasons();
951
952 // Now generate code
953 Code_Gen();
954 }
955
956 // C2 uses runtime stubs serialized generation to initialize its static tables
957 // shared by all compilations, like Type::_shared_type_dict.
958 // At least one stub have to be completely generated to execute intialization
959 // before we can skip the rest stubs generation by loading AOT cached stubs.
960
961 static bool c2_do_stub_init_complete = false;
962
963 //------------------------------Compile----------------------------------------
964 // Compile a runtime stub
965 Compile::Compile(ciEnv* ci_env,
971 bool pass_tls,
972 bool return_pc,
973 DirectiveSet* directive)
974 : Phase(Compiler),
975 _compile_id(0),
976 _options(Options::for_runtime_stub()),
977 _method(nullptr),
978 _entry_bci(InvocationEntryBci),
979 _stub_function(stub_function),
980 _stub_name(stub_name),
981 _stub_id(stub_id),
982 _stub_entry_point(nullptr),
983 _max_node_limit(MaxNodeLimit),
984 _node_count_inlining_cutoff(NodeCountInliningCutoff),
985 _post_loop_opts_phase(false),
986 _merge_stores_phase(false),
987 _allow_macro_nodes(true),
988 _inlining_progress(false),
989 _inlining_incrementally(false),
990 _has_reserved_stack_access(false),
991 _has_circular_inline_type(false),
992 #ifndef PRODUCT
993 _igv_idx(0),
994 _trace_opto_output(directive->TraceOptoOutputOption),
995 #endif
996 _clinit_barrier_on_entry(false),
997 _stress_seed(0),
998 _comp_arena(mtCompiler, Arena::Tag::tag_comp),
999 _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
1000 _env(ci_env),
1001 _directive(directive),
1002 _log(ci_env->log()),
1003 _first_failure_details(nullptr),
1004 _reachability_fences(comp_arena(), 8, 0, nullptr),
1005 _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),
1006 _for_merge_stores_igvn(comp_arena(), 8, 0, nullptr),
1007 _congraph(nullptr),
1008 NOT_PRODUCT(_igv_printer(nullptr) COMMA)
1009 _unique(0),
1010 _dead_node_count(0),
1011 _dead_node_list(comp_arena()),
1131 _fixed_slots = 0;
1132 set_has_split_ifs(false);
1133 set_has_loops(false); // first approximation
1134 set_has_stringbuilder(false);
1135 set_has_boxed_value(false);
1136 _trap_can_recompile = false; // no traps emitted yet
1137 _major_progress = true; // start out assuming good things will happen
1138 set_has_unsafe_access(false);
1139 set_max_vector_size(0);
1140 set_clear_upper_avx(false); //false as default for clear upper bits of ymm registers
1141 Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
1142 set_decompile_count(0);
1143
1144 #ifndef PRODUCT
1145 _phase_counter = 0;
1146 Copy::zero_to_bytes(_igv_phase_iter, sizeof(_igv_phase_iter));
1147 #endif
1148
1149 set_do_freq_based_layout(_directive->BlockLayoutByFrequencyOption);
1150 _loop_opts_cnt = LoopOptsCount;
1151 _has_flat_accesses = false;
1152 _flat_accesses_share_alias = true;
1153 _scalarize_in_safepoints = false;
1154 _needs_nm_slot = false;
1155
1156 set_do_inlining(Inline);
1157 set_max_inline_size(MaxInlineSize);
1158 set_freq_inline_size(FreqInlineSize);
1159 set_do_scheduling(OptoScheduling);
1160
1161 set_do_vector_loop(false);
1162 set_has_monitors(false);
1163 set_has_scoped_access(false);
1164
1165 if (AllowVectorizeOnDemand) {
1166 if (has_method() && _directive->VectorizeOption) {
1167 set_do_vector_loop(true);
1168 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());})
1169 } else if (has_method() && method()->name() != nullptr &&
1170 method()->intrinsic_id() == vmIntrinsics::_forEachRemaining) {
1171 set_do_vector_loop(true);
1172 }
1173 }
1174 set_use_cmove(UseCMoveUnconditionally /* || do_vector_loop()*/); //TODO: consider do_vector_loop() mandate use_cmove unconditionally
1175 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());})
1407 // If this method has already thrown a range-check,
1408 // assume it was because we already tried range smearing
1409 // and it failed.
1410 uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1411 return !already_trapped;
1412 }
1413
1414
1415 //------------------------------flatten_alias_type-----------------------------
1416 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1417 assert(do_aliasing(), "Aliasing should be enabled");
1418 int offset = tj->offset();
1419 TypePtr::PTR ptr = tj->ptr();
1420
1421 // Known instance (scalarizable allocation) alias only with itself.
1422 bool is_known_inst = tj->isa_oopptr() != nullptr &&
1423 tj->is_oopptr()->is_known_instance();
1424
1425 // Process weird unsafe references.
1426 if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1427 assert(InlineUnsafeOps || StressReflectiveCode || UseAcmpFastPath, "indeterminate pointers come only from unsafe ops");
1428 assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1429 tj = TypeOopPtr::BOTTOM;
1430 ptr = tj->ptr();
1431 offset = tj->offset();
1432 }
1433
1434 // Array pointers need some flattening
1435 const TypeAryPtr* ta = tj->isa_aryptr();
1436 if( ta && is_known_inst ) {
1437 if ( offset != Type::OffsetBot &&
1438 offset > arrayOopDesc::length_offset_in_bytes() ) {
1439 offset = Type::OffsetBot; // Flatten constant access into array body only
1440 tj = ta = ta->
1441 remove_speculative()->
1442 cast_to_ptr_type(ptr)->
1443 with_offset(offset);
1444 }
1445 } else if (ta != nullptr) {
1446 // Common slices
1447 if (offset == arrayOopDesc::length_offset_in_bytes()) {
1448 return TypeAryPtr::RANGE;
1449 } else if (offset == oopDesc::klass_offset_in_bytes()) {
1450 return TypeInstPtr::KLASS;
1451 } else if (offset == oopDesc::mark_offset_in_bytes()) {
1452 return TypeInstPtr::MARK;
1453 }
1454
1455 // Remove size and stability
1456 const TypeAry* normalized_ary = TypeAry::make(ta->elem(), TypeInt::POS, false, ta->is_flat(), ta->is_not_flat(), ta->is_not_null_free(), ta->is_atomic());
1457 // Remove ptr, const_oop, and offset
1458 if (ta->elem() == Type::BOTTOM) {
1459 // Bottom array (meet of int[] and byte[] for example), accesses to it will be done with
1460 // Unsafe. This should alias with all arrays. For now just leave it as it is (this is
1461 // incorrect, see JDK-8331133).
1462 tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, nullptr, false, Type::Offset::bottom);
1463 } else if (ta->elem()->make_oopptr() != nullptr) {
1464 // Object arrays, keep field_offset
1465 tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, nullptr, ta->klass_is_exact(), Type::Offset::bottom, Type::Offset(ta->field_offset()));
1466 } else {
1467 // Primitive arrays
1468 tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, ta->exact_klass(), true, Type::Offset::bottom);
1469 }
1470
1471 // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1472 // cannot be distinguished by bytecode alone.
1473 if (ta->elem() == TypeInt::BOOL) {
1474 tj = ta = TypeAryPtr::BYTES;
1475 }
1476
1477 // All arrays of references share the same slice
1478 if (!ta->is_flat() && ta->elem()->make_oopptr() != nullptr) {
1479 const TypeAry* tary = TypeAry::make(TypeInstPtr::BOTTOM, TypeInt::POS, false, false, true, true, true);
1480 tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, tary, nullptr, false, Type::Offset::bottom);
1481 }
1482
1483 if (ta->is_flat()) {
1484 if (_flat_accesses_share_alias) {
1485 // Initially all flattened array accesses share a single slice
1486 tj = ta = TypeAryPtr::INLINES;
1487 } else {
1488 // Flat accesses are always exact
1489 tj = ta = ta->cast_to_exactness(true);
1490 }
1491 }
1492 }
1493
1494 // Oop pointers need some flattening
1495 const TypeInstPtr *to = tj->isa_instptr();
1496 if (to && to != TypeOopPtr::BOTTOM) {
1497 ciInstanceKlass* ik = to->instance_klass();
1498 tj = to = to->cast_to_maybe_flat_in_array(); // flatten to maybe flat in array
1499 if( ptr == TypePtr::Constant ) {
1500 if (ik != ciEnv::current()->Class_klass() ||
1501 offset < ik->layout_helper_size_in_bytes()) {
1502 // No constant oop pointers (such as Strings); they alias with
1503 // unknown strings.
1504 assert(!is_known_inst, "not scalarizable allocation");
1505 tj = to = to->
1506 cast_to_instance_id(TypeOopPtr::InstanceBot)->
1507 remove_speculative()->
1508 cast_to_ptr_type(TypePtr::BotPTR)->
1509 cast_to_exactness(false);
1510 }
1511 } else if( is_known_inst ) {
1512 tj = to; // Keep NotNull and klass_is_exact for instance type
1513 } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1514 // During the 2nd round of IterGVN, NotNull castings are removed.
1515 // Make sure the Bottom and NotNull variants alias the same.
1516 // Also, make sure exact and non-exact variants alias the same.
1517 tj = to = to->
1518 remove_speculative()->
1519 cast_to_instance_id(TypeOopPtr::InstanceBot)->
1520 cast_to_ptr_type(TypePtr::BotPTR)->
1521 cast_to_exactness(false);
1522 }
1523 if (to->speculative() != nullptr) {
1524 tj = to = to->remove_speculative();
1525 }
1526 // Canonicalize the holder of this field
1527 if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1528 // First handle header references such as a LoadKlassNode, even if the
1529 // object's klass is unloaded at compile time (4965979).
1530 if (!is_known_inst) { // Do it only for non-instance types
1531 tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, nullptr, Type::Offset(offset));
1532 }
1533 } else if (offset < 0 || offset >= ik->layout_helper_size_in_bytes()) {
1534 // Static fields are in the space above the normal instance
1535 // fields in the java.lang.Class instance.
1536 if (ik != ciEnv::current()->Class_klass()) {
1537 to = nullptr;
1538 tj = TypeOopPtr::BOTTOM;
1539 offset = tj->offset();
1540 }
1541 } else {
1542 ciInstanceKlass *canonical_holder = ik->get_canonical_holder(offset);
1543 assert(offset < canonical_holder->layout_helper_size_in_bytes(), "");
1544 assert(tj->offset() == offset, "no change to offset expected");
1545 bool xk = to->klass_is_exact();
1546 int instance_id = to->instance_id();
1547
1548 // If the input type's class is the holder: if exact, the type only includes interfaces implemented by the holder
1549 // but if not exact, it may include extra interfaces: build new type from the holder class to make sure only
1550 // its interfaces are included.
1551 if (xk && ik->equals(canonical_holder)) {
1552 assert(tj == TypeInstPtr::make(to->ptr(), canonical_holder, is_known_inst, nullptr, Type::Offset(offset), instance_id,
1553 TypePtr::MaybeFlat), "exact type should be canonical type");
1554 } else {
1555 assert(xk || !is_known_inst, "Known instance should be exact type");
1556 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, is_known_inst, nullptr, Type::Offset(offset), instance_id,
1557 TypePtr::MaybeFlat);
1558 }
1559 }
1560 }
1561
1562 // Klass pointers to object array klasses need some flattening
1563 const TypeKlassPtr *tk = tj->isa_klassptr();
1564 if( tk ) {
1565 // If we are referencing a field within a Klass, we need
1566 // to assume the worst case of an Object. Both exact and
1567 // inexact types must flatten to the same alias class so
1568 // use NotNull as the PTR.
1569 if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1570 tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull,
1571 env()->Object_klass(),
1572 Type::Offset(offset),
1573 TypePtr::MaybeFlat);
1574 }
1575
1576 if (tk->isa_aryklassptr() && tk->is_aryklassptr()->elem()->isa_klassptr()) {
1577 ciKlass* k = ciObjArrayKlass::make(env()->Object_klass());
1578 if (!k || !k->is_loaded()) { // Only fails for some -Xcomp runs
1579 tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull, env()->Object_klass(), Type::Offset(offset), TypePtr::MaybeFlat);
1580 } else {
1581 tj = tk = TypeAryKlassPtr::make(TypePtr::NotNull, tk->is_aryklassptr()->elem(), k, Type::Offset(offset), tk->is_not_flat(), tk->is_not_null_free(), tk->is_flat(), tk->is_null_free(), tk->is_atomic(), tk->is_aryklassptr()->is_refined_type());
1582 }
1583 }
1584 // Check for precise loads from the primary supertype array and force them
1585 // to the supertype cache alias index. Check for generic array loads from
1586 // the primary supertype array and also force them to the supertype cache
1587 // alias index. Since the same load can reach both, we need to merge
1588 // these 2 disparate memories into the same alias class. Since the
1589 // primary supertype array is read-only, there's no chance of confusion
1590 // where we bypass an array load and an array store.
1591 int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1592 if (offset == Type::OffsetBot ||
1593 (offset >= primary_supers_offset &&
1594 offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1595 offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1596 offset = in_bytes(Klass::secondary_super_cache_offset());
1597 tj = tk = tk->with_offset(offset);
1598 }
1599 }
1600
1601 // Flatten all Raw pointers together.
1602 if (tj->base() == Type::RawPtr)
1603 tj = TypeRawPtr::BOTTOM;
1693 intptr_t key = (intptr_t) adr_type;
1694 key ^= key >> logAliasCacheSize;
1695 return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1696 }
1697
1698
1699 //-----------------------------grow_alias_types--------------------------------
1700 void Compile::grow_alias_types() {
1701 const int old_ats = _max_alias_types; // how many before?
1702 const int new_ats = old_ats; // how many more?
1703 const int grow_ats = old_ats+new_ats; // how many now?
1704 _max_alias_types = grow_ats;
1705 _alias_types = REALLOC_ARENA_ARRAY(comp_arena(), _alias_types, old_ats, grow_ats);
1706 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1707 Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1708 for (int i = 0; i < new_ats; i++) _alias_types[old_ats+i] = &ats[i];
1709 }
1710
1711
1712 //--------------------------------find_alias_type------------------------------
1713 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field, bool uncached) {
1714 if (!do_aliasing()) {
1715 return alias_type(AliasIdxBot);
1716 }
1717
1718 AliasCacheEntry* ace = nullptr;
1719 if (!uncached) {
1720 ace = probe_alias_cache(adr_type);
1721 if (ace->_adr_type == adr_type) {
1722 return alias_type(ace->_index);
1723 }
1724 }
1725
1726 // Handle special cases.
1727 if (adr_type == nullptr) return alias_type(AliasIdxTop);
1728 if (adr_type == TypePtr::BOTTOM) return alias_type(AliasIdxBot);
1729
1730 // Do it the slow way.
1731 const TypePtr* flat = flatten_alias_type(adr_type);
1732
1733 #ifdef ASSERT
1734 {
1735 ResourceMark rm;
1736 assert(flat == flatten_alias_type(flat), "not idempotent: adr_type = %s; flat = %s => %s",
1737 Type::str(adr_type), Type::str(flat), Type::str(flatten_alias_type(flat)));
1738 assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr: adr_type = %s",
1739 Type::str(adr_type));
1740 if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1741 const TypeOopPtr* foop = flat->is_oopptr();
1742 // Scalarizable allocations have exact klass always.
1743 bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1753 if (alias_type(i)->adr_type() == flat) {
1754 idx = i;
1755 break;
1756 }
1757 }
1758
1759 if (idx == AliasIdxTop) {
1760 if (no_create) return nullptr;
1761 // Grow the array if necessary.
1762 if (_num_alias_types == _max_alias_types) grow_alias_types();
1763 // Add a new alias type.
1764 idx = _num_alias_types++;
1765 _alias_types[idx]->Init(idx, flat);
1766 if (flat == TypeInstPtr::KLASS) alias_type(idx)->set_rewritable(false);
1767 if (flat == TypeAryPtr::RANGE) alias_type(idx)->set_rewritable(false);
1768 if (flat->isa_instptr()) {
1769 if (flat->offset() == java_lang_Class::klass_offset()
1770 && flat->is_instptr()->instance_klass() == env()->Class_klass())
1771 alias_type(idx)->set_rewritable(false);
1772 }
1773 ciField* field = nullptr;
1774 if (flat->isa_aryptr()) {
1775 #ifdef ASSERT
1776 const int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1777 // (T_BYTE has the weakest alignment and size restrictions...)
1778 assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1779 #endif
1780 const Type* elemtype = flat->is_aryptr()->elem();
1781 if (flat->offset() == TypePtr::OffsetBot) {
1782 alias_type(idx)->set_element(elemtype);
1783 }
1784 int field_offset = flat->is_aryptr()->field_offset().get();
1785 if (flat->is_flat() &&
1786 field_offset != Type::OffsetBot) {
1787 ciInlineKlass* vk = elemtype->inline_klass();
1788 field_offset += vk->payload_offset();
1789 field = vk->get_field_by_offset(field_offset, false);
1790 }
1791 }
1792 if (flat->isa_klassptr()) {
1793 if (UseCompactObjectHeaders) {
1794 if (flat->offset() == in_bytes(Klass::prototype_header_offset()))
1795 alias_type(idx)->set_rewritable(false);
1796 }
1797 if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1798 alias_type(idx)->set_rewritable(false);
1799 if (flat->offset() == in_bytes(Klass::misc_flags_offset()))
1800 alias_type(idx)->set_rewritable(false);
1801 if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1802 alias_type(idx)->set_rewritable(false);
1803 if (flat->offset() == in_bytes(Klass::layout_helper_offset()))
1804 alias_type(idx)->set_rewritable(false);
1805 if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset()))
1806 alias_type(idx)->set_rewritable(false);
1807 }
1808
1809 if (flat->isa_instklassptr()) {
1810 if (flat->offset() == in_bytes(InstanceKlass::access_flags_offset())) {
1811 alias_type(idx)->set_rewritable(false);
1812 }
1813 }
1814 // %%% (We would like to finalize JavaThread::threadObj_offset(),
1815 // but the base pointer type is not distinctive enough to identify
1816 // references into JavaThread.)
1817
1818 // Check for final fields.
1819 const TypeInstPtr* tinst = flat->isa_instptr();
1820 if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1821 if (tinst->const_oop() != nullptr &&
1822 tinst->instance_klass() == ciEnv::current()->Class_klass() &&
1823 tinst->offset() >= (tinst->instance_klass()->layout_helper_size_in_bytes())) {
1824 // static field
1825 ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1826 field = k->get_field_by_offset(tinst->offset(), true);
1827 } else if (tinst->is_inlinetypeptr()) {
1828 // Inline type field
1829 ciInlineKlass* vk = tinst->inline_klass();
1830 field = vk->get_field_by_offset(tinst->offset(), false);
1831 } else {
1832 ciInstanceKlass *k = tinst->instance_klass();
1833 field = k->get_field_by_offset(tinst->offset(), false);
1834 }
1835 }
1836 assert(field == nullptr ||
1837 original_field == nullptr ||
1838 (field->holder() == original_field->holder() &&
1839 field->offset_in_bytes() == original_field->offset_in_bytes() &&
1840 field->is_static() == original_field->is_static()), "wrong field?");
1841 // Set field() and is_rewritable() attributes.
1842 if (field != nullptr) {
1843 alias_type(idx)->set_field(field);
1844 if (flat->isa_aryptr()) {
1845 // Fields of flat arrays are rewritable although they are declared final
1846 assert(flat->is_flat(), "must be a flat array");
1847 alias_type(idx)->set_rewritable(true);
1848 }
1849 }
1850 }
1851
1852 // Fill the cache for next time.
1853 if (!uncached) {
1854 ace->_adr_type = adr_type;
1855 ace->_index = idx;
1856 assert(alias_type(adr_type) == alias_type(idx), "type must be installed");
1857
1858 // Might as well try to fill the cache for the flattened version, too.
1859 AliasCacheEntry* face = probe_alias_cache(flat);
1860 if (face->_adr_type == nullptr) {
1861 face->_adr_type = flat;
1862 face->_index = idx;
1863 assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1864 }
1865 }
1866
1867 return alias_type(idx);
1868 }
1869
1870
1871 Compile::AliasType* Compile::alias_type(ciField* field) {
1872 const TypeOopPtr* t;
1873 if (field->is_static())
1874 t = TypeInstPtr::make(field->holder()->java_mirror());
1875 else
1876 t = TypeOopPtr::make_from_klass_raw(field->holder());
1877 AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1878 assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1879 return atp;
1880 }
1881
1882
1883 //------------------------------have_alias_type--------------------------------
1884 bool Compile::have_alias_type(const TypePtr* adr_type) {
1966 assert(!C->major_progress(), "not cleared");
1967
1968 if (_for_post_loop_igvn.length() > 0) {
1969 while (_for_post_loop_igvn.length() > 0) {
1970 Node* n = _for_post_loop_igvn.pop();
1971 n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1972 igvn._worklist.push(n);
1973 }
1974 igvn.optimize();
1975 if (failing()) return;
1976 assert(_for_post_loop_igvn.length() == 0, "no more delayed nodes allowed");
1977 assert(C->parse_predicate_count() == 0, "all parse predicates should have been removed now");
1978
1979 // Sometimes IGVN sets major progress (e.g., when processing loop nodes).
1980 if (C->major_progress()) {
1981 C->clear_major_progress(); // ensure that major progress is now clear
1982 }
1983 }
1984 }
1985
1986 void Compile::add_inline_type(Node* n) {
1987 assert(n->is_InlineType(), "unexpected node");
1988 _inline_type_nodes.push(n);
1989 }
1990
1991 void Compile::remove_inline_type(Node* n) {
1992 assert(n->is_InlineType(), "unexpected node");
1993 if (_inline_type_nodes.contains(n)) {
1994 _inline_type_nodes.remove(n);
1995 }
1996 }
1997
1998 // Does the return value keep otherwise useless inline type allocations alive?
1999 static bool return_val_keeps_allocations_alive(Node* ret_val) {
2000 ResourceMark rm;
2001 Unique_Node_List wq;
2002 wq.push(ret_val);
2003 bool some_allocations = false;
2004 for (uint i = 0; i < wq.size(); i++) {
2005 Node* n = wq.at(i);
2006 if (n->outcnt() > 1) {
2007 // Some other use for the allocation
2008 return false;
2009 } else if (n->is_InlineType()) {
2010 wq.push(n->in(1));
2011 } else if (n->is_Phi()) {
2012 for (uint j = 1; j < n->req(); j++) {
2013 wq.push(n->in(j));
2014 }
2015 } else if (n->is_CheckCastPP() &&
2016 n->in(1)->is_Proj() &&
2017 n->in(1)->in(0)->is_Allocate()) {
2018 some_allocations = true;
2019 } else if (n->is_CheckCastPP() || n->is_CastPP()) {
2020 wq.push(n->in(1));
2021 }
2022 }
2023 return some_allocations;
2024 }
2025
2026 bool Compile::clear_argument_if_only_used_as_buffer_at_calls(Node* result_cast, PhaseIterGVN& igvn) {
2027 ResourceMark rm;
2028 Unique_Node_List wq;
2029 wq.push(result_cast);
2030 Node_List calls;
2031 for (uint i = 0; i < wq.size(); ++i) {
2032 Node* n = wq.at(i);
2033 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
2034 Node* u = n->fast_out(j);
2035 if (u->is_Phi()) {
2036 wq.push(u);
2037 } else if (u->is_InlineType() && u->as_InlineType()->get_oop() == n) {
2038 wq.push(u);
2039 } else if (u->is_CallJava()) {
2040 CallJavaNode* call = u->as_CallJava();
2041 if (call->method() != nullptr && call->method()->mismatch()) {
2042 return false;
2043 }
2044 uint nargs = call->tf()->domain_cc()->cnt();
2045 for (uint k = TypeFunc::Parms; k < nargs; k++) {
2046 Node* in = call->in(k);
2047 if (in == n && (call->method() == nullptr || !call->method()->is_scalarized_buffer_arg(k - TypeFunc::Parms))) {
2048 return false;
2049 }
2050 }
2051 calls.push(call);
2052 } else if (u->Opcode() == Op_EncodeP) {
2053 wq.push(u);
2054 } else if (u->is_AddP()) {
2055 wq.push(u);
2056 } else if (u->is_Store() && u->in(MemNode::Address) == n) {
2057 // storing to the buffer is fine
2058 } else if (u->is_SafePoint()) {
2059 SafePointNode* sfpt = u->as_SafePoint();
2060 int input = u->find_edge(n);
2061 JVMState* jvms = sfpt->jvms();
2062 if (jvms != nullptr) {
2063 if (input < (int)jvms->debug_start()) {
2064 return false;
2065 }
2066 }
2067 } else {
2068 return false;
2069 }
2070 }
2071 }
2072 for (uint i = 0; i < calls.size(); ++i) {
2073 CallJavaNode* call = calls.at(i)->as_CallJava();
2074 uint nargs = call->tf()->domain_cc()->cnt();
2075 for (uint k = TypeFunc::Parms; k < nargs; k++) {
2076 Node* in = call->in(k);
2077 if (wq.member(in)) {
2078 assert(call->method()->is_scalarized_buffer_arg(k - TypeFunc::Parms), "only buffer argument removed here");
2079 igvn.replace_input_of(call, k, igvn.zerocon(T_OBJECT));
2080 }
2081 }
2082 }
2083 return true;
2084 }
2085
2086 void Compile::process_inline_types(PhaseIterGVN &igvn, bool remove) {
2087 // Make sure that the return value does not keep an otherwise unused allocation alive
2088 if (tf()->returns_inline_type_as_fields()) {
2089 Node* ret = nullptr;
2090 for (uint i = 1; i < root()->req(); i++) {
2091 Node* in = root()->in(i);
2092 if (in->Opcode() == Op_Return) {
2093 assert(ret == nullptr, "only one return");
2094 ret = in;
2095 }
2096 }
2097 if (ret != nullptr) {
2098 Node* ret_val = ret->in(TypeFunc::Parms);
2099 if (igvn.type(ret_val)->isa_oopptr() &&
2100 return_val_keeps_allocations_alive(ret_val)) {
2101 igvn.replace_input_of(ret, TypeFunc::Parms, InlineTypeNode::tagged_klass(igvn.type(ret_val)->inline_klass(), igvn));
2102 assert(ret_val->outcnt() == 0, "should be dead now");
2103 igvn.remove_dead_node(ret_val, PhaseIterGVN::NodeOrigin::Graph);
2104 }
2105 }
2106 }
2107 // if a newly allocated object is a value that's only passed as argument to calls as (possibly null) buffers, then
2108 // clear the call argument inputs so the allocation node can be removed
2109 for (int i = 0; i < C->macro_count(); ++i) {
2110 Node* macro_node = C->macro_node(i);
2111 if (macro_node->Opcode() == Op_Allocate) {
2112 AllocateNode* allocate = macro_node->as_Allocate();
2113 Node* result_cast = allocate->result_cast();
2114 if (result_cast != nullptr) {
2115 const Type* result_type = igvn.type(result_cast);
2116 if (result_type->is_inlinetypeptr()) {
2117 clear_argument_if_only_used_as_buffer_at_calls(result_cast, igvn);
2118 }
2119 }
2120 }
2121 }
2122
2123 if (_inline_type_nodes.length() == 0) {
2124 // keep the graph canonical
2125 igvn.optimize();
2126 return;
2127 }
2128 // Scalarize inline types in safepoint debug info.
2129 // Delay this until all inlining is over to avoid getting inconsistent debug info.
2130 set_scalarize_in_safepoints(true);
2131 for (int i = _inline_type_nodes.length()-1; i >= 0; i--) {
2132 InlineTypeNode* vt = _inline_type_nodes.at(i)->as_InlineType();
2133 vt->make_scalar_in_safepoints(&igvn);
2134 igvn.record_for_igvn(vt);
2135 }
2136 if (remove) {
2137 // Remove inline type nodes by replacing them with their oop input
2138 while (_inline_type_nodes.length() > 0) {
2139 InlineTypeNode* vt = _inline_type_nodes.pop()->as_InlineType();
2140 if (vt->outcnt() == 0) {
2141 igvn.remove_dead_node(vt, PhaseIterGVN::NodeOrigin::Graph);
2142 continue;
2143 }
2144 for (DUIterator i = vt->outs(); vt->has_out(i); i++) {
2145 DEBUG_ONLY(bool must_be_buffered = false);
2146 Node* u = vt->out(i);
2147 // Check if any users are blackholes. If so, rewrite them to use either the
2148 // allocated buffer, or individual components, instead of the inline type node
2149 // that goes away.
2150 if (u->is_Blackhole()) {
2151 BlackholeNode* bh = u->as_Blackhole();
2152
2153 // Unlink the old input
2154 int idx = bh->find_edge(vt);
2155 assert(idx != -1, "The edge should be there");
2156 bh->del_req(idx);
2157 --i;
2158
2159 if (vt->is_allocated(&igvn)) {
2160 // Already has the allocated instance, blackhole that
2161 bh->add_req(vt->get_oop());
2162 } else {
2163 // Not allocated yet, blackhole the components
2164 for (uint c = 0; c < vt->field_count(); c++) {
2165 bh->add_req(vt->field_value(c));
2166 }
2167 }
2168
2169 // Node modified, record for IGVN
2170 igvn.record_for_igvn(bh);
2171 }
2172 #ifdef ASSERT
2173 // Verify that inline type is buffered when replacing by oop
2174 else if (u->is_InlineType()) {
2175 // InlineType uses don't need buffering because they are about to be replaced as well
2176 } else {
2177 must_be_buffered = true;
2178 }
2179 if (must_be_buffered && !vt->is_allocated(&igvn)) {
2180 vt->dump(0);
2181 u->dump(0);
2182 assert(false, "Should have been buffered");
2183 }
2184 #endif
2185 }
2186 igvn.replace_node(vt, vt->get_oop());
2187 }
2188 }
2189 igvn.optimize();
2190 }
2191
2192 void Compile::add_flat_access(Node* n) {
2193 assert(n != nullptr && (n->Opcode() == Op_LoadFlat || n->Opcode() == Op_StoreFlat), "unexpected node %s", n == nullptr ? "nullptr" : n->Name());
2194 assert(!_flat_access_nodes.contains(n), "duplicate insertion");
2195 _flat_access_nodes.push(n);
2196 }
2197
2198 void Compile::remove_flat_access(Node* n) {
2199 assert(n != nullptr && (n->Opcode() == Op_LoadFlat || n->Opcode() == Op_StoreFlat), "unexpected node %s", n == nullptr ? "nullptr" : n->Name());
2200 _flat_access_nodes.remove_if_existing(n);
2201 }
2202
2203 void Compile::process_flat_accesses(PhaseIterGVN& igvn) {
2204 assert(igvn._worklist.size() == 0, "should be empty");
2205 igvn.set_delay_transform(true);
2206 for (int i = _flat_access_nodes.length() - 1; i >= 0; i--) {
2207 Node* n = _flat_access_nodes.at(i);
2208 assert(n != nullptr, "unexpected nullptr");
2209 if (n->is_LoadFlat()) {
2210 LoadFlatNode* loadn = n->as_LoadFlat();
2211 // Expending a flat load atomically means that we get a chunk of memory spanning multiple fields
2212 // that we chop with bitwise operations. That is too subtle for some optimizations, especially
2213 // constant folding when fields are constant. If we can get a constant object from which we are
2214 // flat-loading, we can simply replace the loads at compilation-time by the field of the constant
2215 // object.
2216 ciInstance* loaded_from = nullptr;
2217 if (FoldStableValues) {
2218 const TypeOopPtr* base_type = igvn.type(loadn->base())->is_oopptr();
2219 ciObject* oop = base_type->const_oop();
2220 int off = igvn.type(loadn->ptr())->isa_ptr()->offset();
2221
2222 if (oop != nullptr && oop->is_instance()) {
2223 ciInstance* holder = oop->as_instance();
2224 ciKlass* klass = holder->klass();
2225 ciInstanceKlass* iklass = klass->as_instance_klass();
2226 ciField* field = iklass->get_non_flat_field_by_offset(off);
2227
2228 if (field->is_stable()) {
2229 ciConstant fv = holder->field_value(field);
2230 if (is_reference_type(fv.basic_type()) && fv.as_object()->is_instance()) {
2231 // The field value is an object, not null. We can use stability.
2232 loaded_from = fv.as_object()->as_instance();
2233 }
2234 }
2235 } else if (oop != nullptr && oop->is_array() && off != Type::OffsetBot) {
2236 ciArray* array = oop->as_array();
2237 ciConstant elt = array->element_value_by_offset(off);
2238 const TypeAryPtr* aryptr = base_type->is_aryptr();
2239 if (aryptr->is_stable() && aryptr->is_atomic() && is_reference_type(elt.basic_type()) && elt.as_object()->is_instance()) {
2240 loaded_from = elt.as_object()->as_instance();
2241 }
2242 }
2243 }
2244
2245 if (loaded_from != nullptr) {
2246 loadn->expand_constant(igvn, loaded_from);
2247 } else {
2248 loadn->expand_atomic(igvn);
2249 }
2250 } else {
2251 n->as_StoreFlat()->expand_atomic(igvn);
2252 }
2253 }
2254 _flat_access_nodes.clear_and_deallocate();
2255 igvn.set_delay_transform(false);
2256 igvn.optimize();
2257 }
2258
2259 void Compile::adjust_flat_array_access_aliases(PhaseIterGVN& igvn) {
2260 DEBUG_ONLY(igvn.verify_empty_worklist(nullptr));
2261 if (!_has_flat_accesses) {
2262 return;
2263 }
2264 // Initially, all flat array accesses share the same slice to
2265 // keep dependencies with Object[] array accesses (that could be
2266 // to a flat array) correct. We're done with parsing so we
2267 // now know all flat array accesses in this compile
2268 // unit. Let's move flat array accesses to their own slice,
2269 // one per element field. This should help memory access
2270 // optimizations.
2271 ResourceMark rm;
2272 Unique_Node_List wq;
2273 wq.push(root());
2274
2275 Node_List mergememnodes;
2276 Node_List memnodes;
2277
2278 // Alias index currently shared by all flat memory accesses
2279 int index = get_alias_index(TypeAryPtr::INLINES);
2280
2281 // Find MergeMem nodes and flat array accesses
2282 for (uint i = 0; i < wq.size(); i++) {
2283 Node* n = wq.at(i);
2284 if (n->is_Mem()) {
2285 const TypePtr* adr_type = nullptr;
2286 adr_type = get_adr_type(get_alias_index(n->adr_type()));
2287 if (adr_type == TypeAryPtr::INLINES) {
2288 memnodes.push(n);
2289 }
2290 } else if (n->is_MergeMem()) {
2291 MergeMemNode* mm = n->as_MergeMem();
2292 if (mm->memory_at(index) != mm->base_memory()) {
2293 mergememnodes.push(n);
2294 }
2295 }
2296 for (uint j = 0; j < n->req(); j++) {
2297 Node* m = n->in(j);
2298 if (m != nullptr) {
2299 wq.push(m);
2300 }
2301 }
2302 }
2303
2304 _flat_accesses_share_alias = false;
2305
2306 // We are going to change the slice for the flat array
2307 // accesses so we need to clear the cache entries that refer to
2308 // them.
2309 for (uint i = 0; i < AliasCacheSize; i++) {
2310 AliasCacheEntry* ace = &_alias_cache[i];
2311 if (ace->_adr_type != nullptr &&
2312 ace->_adr_type->is_flat()) {
2313 ace->_adr_type = nullptr;
2314 ace->_index = (i != 0) ? 0 : AliasIdxTop; // Make sure the nullptr adr_type resolves to AliasIdxTop
2315 }
2316 }
2317
2318 #ifdef ASSERT
2319 for (uint i = 0; i < memnodes.size(); i++) {
2320 Node* m = memnodes.at(i);
2321 const TypePtr* adr_type = m->adr_type();
2322 m->as_Mem()->set_adr_type(adr_type);
2323 }
2324 #endif // ASSERT
2325
2326 int start_alias = num_alias_types(); // Start of new aliases
2327 Node_Stack stack(0);
2328 #ifdef ASSERT
2329 VectorSet seen(Thread::current()->resource_area());
2330 #endif
2331 // Now let's fix the memory graph so each flat array access
2332 // is moved to the right slice. Start from the MergeMem nodes.
2333 uint last = unique();
2334 for (uint i = 0; i < mergememnodes.size(); i++) {
2335 MergeMemNode* current = mergememnodes.at(i)->as_MergeMem();
2336 if (current->outcnt() == 0) {
2337 // This node is killed by a previous iteration
2338 continue;
2339 }
2340
2341 Node* n = current->memory_at(index);
2342 MergeMemNode* mm = nullptr;
2343 do {
2344 // Follow memory edges through memory accesses, phis and
2345 // narrow membars and push nodes on the stack. Once we hit
2346 // bottom memory, we pop element off the stack one at a
2347 // time, in reverse order, and move them to the right slice
2348 // by changing their memory edges.
2349 if ((n->is_Phi() && n->adr_type() != TypePtr::BOTTOM) || n->is_Mem() ||
2350 (n->adr_type() == TypeAryPtr::INLINES && !n->is_NarrowMemProj())) {
2351 assert(!seen.test_set(n->_idx), "");
2352 // Uses (a load for instance) will need to be moved to the
2353 // right slice as well and will get a new memory state
2354 // that we don't know yet. The use could also be the
2355 // backedge of a loop. We put a place holder node between
2356 // the memory node and its uses. We replace that place
2357 // holder with the correct memory state once we know it,
2358 // i.e. when nodes are popped off the stack. Using the
2359 // place holder make the logic work in the presence of
2360 // loops.
2361 if (n->outcnt() > 1) {
2362 Node* place_holder = nullptr;
2363 assert(!n->has_out_with(Op_Node), "");
2364 for (DUIterator k = n->outs(); n->has_out(k); k++) {
2365 Node* u = n->out(k);
2366 if (u != current && u->_idx < last) {
2367 bool success = false;
2368 for (uint l = 0; l < u->req(); l++) {
2369 if (!stack.is_empty() && u == stack.node() && l == stack.index()) {
2370 continue;
2371 }
2372 Node* in = u->in(l);
2373 if (in == n) {
2374 if (place_holder == nullptr) {
2375 place_holder = new Node(1);
2376 place_holder->init_req(0, n);
2377 }
2378 igvn.replace_input_of(u, l, place_holder);
2379 success = true;
2380 }
2381 }
2382 if (success) {
2383 --k;
2384 }
2385 }
2386 }
2387 }
2388 if (n->is_Phi()) {
2389 stack.push(n, 1);
2390 n = n->in(1);
2391 } else if (n->is_Mem()) {
2392 stack.push(n, n->req());
2393 n = n->in(MemNode::Memory);
2394 } else {
2395 assert(n->is_Proj() && n->in(0)->Opcode() == Op_MemBarCPUOrder, "");
2396 stack.push(n, n->req());
2397 n = n->in(0)->in(TypeFunc::Memory);
2398 }
2399 } else {
2400 assert(n->adr_type() == TypePtr::BOTTOM || (n->Opcode() == Op_Node && n->_idx >= last) || n->is_NarrowMemProj(), "");
2401 // Build a new MergeMem node to carry the new memory state
2402 // as we build it. IGVN should fold extraneous MergeMem
2403 // nodes.
2404 if (n->is_NarrowMemProj()) {
2405 // We need 1 NarrowMemProj for each slice of this array
2406 InitializeNode* init = n->in(0)->as_Initialize();
2407 AllocateNode* alloc = init->allocation();
2408 Node* klass_node = alloc->in(AllocateNode::KlassNode);
2409 const TypeAryKlassPtr* klass_type = klass_node->bottom_type()->isa_aryklassptr();
2410 assert(klass_type != nullptr, "must be an array");
2411 assert(klass_type->klass_is_exact(), "must be an exact klass");
2412 ciArrayKlass* klass = klass_type->exact_klass()->as_array_klass();
2413 assert(klass->is_flat_array_klass(), "must be a flat array");
2414 ciInlineKlass* elem_klass = klass->element_klass()->as_inline_klass();
2415 const TypeAryPtr* oop_type = klass_type->as_exact_instance_type()->is_aryptr();
2416 assert(oop_type->klass_is_exact(), "must be an exact klass");
2417
2418 Node* base = alloc->in(TypeFunc::Memory);
2419 assert(base->bottom_type() == Type::MEMORY, "the memory input of AllocateNode must be a memory");
2420 assert(base->adr_type() == TypePtr::BOTTOM, "the memory input of AllocateNode must be a bottom memory");
2421 // Must create a MergeMem with base as the base memory, do not clone if base is a
2422 // MergeMem because it may not be processed yet
2423 mm = MergeMemNode::make(nullptr);
2424 mm->set_base_memory(base);
2425 for (int j = 0; j < elem_klass->nof_nonstatic_fields(); j++) {
2426 int field_offset = elem_klass->nonstatic_field_at(j)->offset_in_bytes() - elem_klass->payload_offset();
2427 const TypeAryPtr* field_ptr = oop_type->with_offset(Type::OffsetBot)->with_field_offset(field_offset);
2428 int field_alias_idx = get_alias_index(field_ptr);
2429 assert(field_ptr == get_adr_type(field_alias_idx), "must match");
2430 Node* new_proj = new NarrowMemProjNode(init, field_ptr);
2431 igvn.register_new_node_with_optimizer(new_proj);
2432 mm->set_memory_at(field_alias_idx, new_proj);
2433 }
2434 if (!klass->is_elem_null_free()) {
2435 int nm_offset = elem_klass->null_marker_offset_in_payload();
2436 const TypeAryPtr* nm_ptr = oop_type->with_offset(Type::OffsetBot)->with_field_offset(nm_offset);
2437 int nm_alias_idx = get_alias_index(nm_ptr);
2438 assert(nm_ptr == get_adr_type(nm_alias_idx), "must match");
2439 Node* new_proj = new NarrowMemProjNode(init, nm_ptr);
2440 igvn.register_new_node_with_optimizer(new_proj);
2441 mm->set_memory_at(nm_alias_idx, new_proj);
2442 }
2443
2444 // Replace all uses of the old NarrowMemProj with the correct state
2445 MergeMemNode* new_n = MergeMemNode::make(mm);
2446 igvn.register_new_node_with_optimizer(new_n);
2447 igvn.replace_node(n, new_n);
2448 } else {
2449 // Must create a MergeMem with n as the base memory, do not clone if n is a MergeMem
2450 // because it may not be processed yet
2451 mm = MergeMemNode::make(nullptr);
2452 mm->set_base_memory(n);
2453 }
2454
2455 igvn.register_new_node_with_optimizer(mm);
2456 while (stack.size() > 0) {
2457 Node* m = stack.node();
2458 uint idx = stack.index();
2459 if (m->is_Mem()) {
2460 // Move memory node to its new slice
2461 const TypePtr* adr_type = m->adr_type();
2462 int alias = get_alias_index(adr_type);
2463 Node* prev = mm->memory_at(alias);
2464 igvn.replace_input_of(m, MemNode::Memory, prev);
2465 mm->set_memory_at(alias, m);
2466 } else if (m->is_Phi()) {
2467 // We need as many new phis as there are new aliases
2468 Node* new_phi_in = MergeMemNode::make(mm);
2469 igvn.register_new_node_with_optimizer(new_phi_in);
2470 igvn.replace_input_of(m, idx, new_phi_in);
2471 if (idx == m->req()-1) {
2472 Node* r = m->in(0);
2473 for (int j = start_alias; j < num_alias_types(); j++) {
2474 const TypePtr* adr_type = get_adr_type(j);
2475 if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2476 continue;
2477 }
2478 Node* phi = new PhiNode(r, Type::MEMORY, get_adr_type(j));
2479 igvn.register_new_node_with_optimizer(phi);
2480 for (uint k = 1; k < m->req(); k++) {
2481 phi->init_req(k, m->in(k)->as_MergeMem()->memory_at(j));
2482 }
2483 mm->set_memory_at(j, phi);
2484 }
2485 Node* base_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2486 igvn.register_new_node_with_optimizer(base_phi);
2487 for (uint k = 1; k < m->req(); k++) {
2488 base_phi->init_req(k, m->in(k)->as_MergeMem()->base_memory());
2489 }
2490 mm->set_base_memory(base_phi);
2491 }
2492 } else {
2493 // This is a MemBarCPUOrder node from
2494 // Parse::array_load()/Parse::array_store(), in the
2495 // branch that handles flat arrays hidden under
2496 // an Object[] array. We also need one new membar per
2497 // new alias to keep the unknown access that the
2498 // membars protect properly ordered with accesses to
2499 // known flat array.
2500 assert(m->is_Proj(), "projection expected");
2501 Node* ctrl = m->in(0)->in(TypeFunc::Control);
2502 igvn.replace_input_of(m->in(0), TypeFunc::Control, top());
2503 for (int j = start_alias; j < num_alias_types(); j++) {
2504 const TypePtr* adr_type = get_adr_type(j);
2505 if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2506 continue;
2507 }
2508 MemBarNode* mb = new MemBarCPUOrderNode(this, j, nullptr);
2509 igvn.register_new_node_with_optimizer(mb);
2510 Node* mem = mm->memory_at(j);
2511 mb->init_req(TypeFunc::Control, ctrl);
2512 mb->init_req(TypeFunc::Memory, mem);
2513 ctrl = new ProjNode(mb, TypeFunc::Control);
2514 igvn.register_new_node_with_optimizer(ctrl);
2515 mem = new ProjNode(mb, TypeFunc::Memory);
2516 igvn.register_new_node_with_optimizer(mem);
2517 mm->set_memory_at(j, mem);
2518 }
2519 igvn.replace_node(m->in(0)->as_Multi()->proj_out(TypeFunc::Control), ctrl);
2520 }
2521 if (idx < m->req()-1) {
2522 idx += 1;
2523 stack.set_index(idx);
2524 n = m->in(idx);
2525 break;
2526 }
2527 // Take care of place holder nodes
2528 if (m->has_out_with(Op_Node)) {
2529 Node* place_holder = m->find_out_with(Op_Node);
2530 if (place_holder != nullptr) {
2531 Node* mm_clone = mm->clone();
2532 igvn.register_new_node_with_optimizer(mm_clone);
2533 Node* hook = new Node(1);
2534 hook->init_req(0, mm);
2535 igvn.replace_node(place_holder, mm_clone);
2536 hook->destruct(&igvn);
2537 }
2538 assert(!m->has_out_with(Op_Node), "place holder should be gone now");
2539 }
2540 stack.pop();
2541 }
2542 }
2543 } while(stack.size() > 0);
2544 // Fix the memory state at the MergeMem we started from
2545 igvn.rehash_node_delayed(current);
2546 for (int j = start_alias; j < num_alias_types(); j++) {
2547 const TypePtr* adr_type = get_adr_type(j);
2548 if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2549 continue;
2550 }
2551 current->set_memory_at(j, mm);
2552 }
2553 current->set_memory_at(index, current->base_memory());
2554 }
2555 igvn.optimize();
2556
2557 #ifdef ASSERT
2558 wq.clear();
2559 wq.push(root());
2560 for (uint i = 0; i < wq.size(); i++) {
2561 Node* n = wq.at(i);
2562 assert(n->adr_type() != TypeAryPtr::INLINES, "should have been removed from the graph");
2563 for (uint j = 0; j < n->req(); j++) {
2564 Node* m = n->in(j);
2565 if (m != nullptr) {
2566 wq.push(m);
2567 }
2568 }
2569 }
2570 #endif
2571
2572 print_method(PHASE_SPLIT_INLINES_ARRAY, 2);
2573 }
2574
2575 void Compile::record_for_merge_stores_igvn(Node* n) {
2576 if (!n->for_merge_stores_igvn()) {
2577 assert(!_for_merge_stores_igvn.contains(n), "duplicate");
2578 n->add_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
2579 _for_merge_stores_igvn.append(n);
2580 }
2581 }
2582
2583 void Compile::remove_from_merge_stores_igvn(Node* n) {
2584 n->remove_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
2585 _for_merge_stores_igvn.remove(n);
2586 }
2587
2588 // We need to wait with merging stores until RangeCheck smearing has removed the RangeChecks during
2589 // the post loops IGVN phase. If we do it earlier, then there may still be some RangeChecks between
2590 // the stores, and we merge the wrong sequence of stores.
2591 // Example:
2592 // StoreI RangeCheck StoreI StoreI RangeCheck StoreI
2593 // Apply MergeStores:
2594 // StoreI RangeCheck [ StoreL ] RangeCheck StoreI
2673 assert(next_bci == iter.next_bci() || next_bci == iter.get_dest(), "wrong next_bci at unstable_if");
2674 Bytecodes::Code c = iter.cur_bc();
2675 Node* lhs = nullptr;
2676 Node* rhs = nullptr;
2677 if (c == Bytecodes::_if_acmpeq || c == Bytecodes::_if_acmpne) {
2678 lhs = unc->peek_operand(0);
2679 rhs = unc->peek_operand(1);
2680 } else if (c == Bytecodes::_ifnull || c == Bytecodes::_ifnonnull) {
2681 lhs = unc->peek_operand(0);
2682 }
2683
2684 ResourceMark rm;
2685 const MethodLivenessResult& live_locals = method->liveness_at_bci(next_bci);
2686 assert(live_locals.is_valid(), "broken liveness info");
2687 int len = (int)live_locals.size();
2688
2689 for (int i = 0; i < len; i++) {
2690 Node* local = unc->local(jvms, i);
2691 // kill local using the liveness of next_bci.
2692 // give up when the local looks like an operand to secure reexecution.
2693 if (!live_locals.at(i) && !local->is_top() && local != lhs && local != rhs) {
2694 uint idx = jvms->locoff() + i;
2695 #ifdef ASSERT
2696 if (PrintOpto && Verbose) {
2697 tty->print("[unstable_if] kill local#%d: ", idx);
2698 local->dump();
2699 tty->cr();
2700 }
2701 #endif
2702 igvn.replace_input_of(unc, idx, top());
2703 modified = true;
2704 }
2705 }
2706 }
2707
2708 // keep the modified trap for late query
2709 if (modified) {
2710 trap->set_modified();
2711 } else {
2712 _unstable_if_traps.delete_at(i);
2713 }
2714 }
2715 igvn.optimize();
2716 }
2717
2718 // StringOpts and late inlining of string methods
2719 void Compile::inline_string_calls(bool parse_time) {
2720 {
2721 // remove useless nodes to make the usage analysis simpler
2722 ResourceMark rm;
2723 PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
2724 }
2725
2726 {
2727 ResourceMark rm;
2728 print_method(PHASE_BEFORE_STRINGOPTS, 3);
2926
2927 if (_string_late_inlines.length() > 0) {
2928 assert(has_stringbuilder(), "inconsistent");
2929
2930 inline_string_calls(false);
2931
2932 if (failing()) return;
2933
2934 inline_incrementally_cleanup(igvn);
2935 }
2936
2937 set_inlining_incrementally(false);
2938 }
2939
2940 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) {
2941 // "inlining_incrementally() == false" is used to signal that no inlining is allowed
2942 // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details).
2943 // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == nullptr"
2944 // as if "inlining_incrementally() == true" were set.
2945 assert(inlining_incrementally() == false, "not allowed");
2946 set_strength_reduction(true);
2947 #ifdef ASSERT
2948 Unique_Node_List* modified_nodes = _modified_nodes;
2949 _modified_nodes = nullptr;
2950 #endif
2951 assert(_late_inlines.length() > 0, "sanity");
2952
2953 if (StressIncrementalInlining) {
2954 shuffle_late_inlines();
2955 }
2956
2957 while (_late_inlines.length() > 0) {
2958 igvn_worklist()->ensure_empty(); // should be done with igvn
2959
2960 while (inline_incrementally_one()) {
2961 assert(!failing_internal() || failure_is_artificial(), "inconsistent");
2962 }
2963 if (failing()) return;
2964
2965 inline_incrementally_cleanup(igvn);
2966 }
2967 DEBUG_ONLY( _modified_nodes = modified_nodes; )
2968 set_strength_reduction(false);
2969 }
2970
2971 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
2972 if (_loop_opts_cnt > 0) {
2973 while (major_progress() && (_loop_opts_cnt > 0)) {
2974 TracePhase tp(_t_idealLoop);
2975 PhaseIdealLoop::optimize(igvn, mode);
2976 _loop_opts_cnt--;
2977 if (failing()) return false;
2978 if (major_progress()) {
2979 print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2980 }
2981 }
2982 }
2983 return true;
2984 }
2985
2986 // Remove edges from "root" to each SafePoint at a backward branch.
2987 // They were inserted during parsing (see add_safepoint()) to make
2988 // infinite loops without calls or exceptions visible to root, i.e.,
3094 print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2);
3095 }
3096 assert(!has_vbox_nodes(), "sanity");
3097
3098 if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
3099 Compile::TracePhase tp(_t_renumberLive);
3100 igvn_worklist()->ensure_empty(); // should be done with igvn
3101 {
3102 ResourceMark rm;
3103 PhaseRenumberLive prl(initial_gvn(), *igvn_worklist());
3104 }
3105 igvn.reset();
3106 igvn.optimize(true);
3107 if (failing()) return;
3108 }
3109
3110 // Now that all inlining is over and no PhaseRemoveUseless will run, cut edge from root to loop
3111 // safepoints
3112 remove_root_to_sfpts_edges(igvn);
3113
3114 // Process inline type nodes now that all inlining is over
3115 process_inline_types(igvn);
3116
3117 adjust_flat_array_access_aliases(igvn);
3118
3119 if (failing()) return;
3120
3121 if (C->macro_count() > 0) {
3122 // Eliminate some macro nodes before EA to reduce analysis pressure
3123 PhaseMacroExpand mexp(igvn);
3124 mexp.eliminate_macro_nodes(/* eliminate_locks= */ false);
3125 if (failing()) {
3126 return;
3127 }
3128 igvn.set_delay_transform(false);
3129 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
3130 }
3131
3132 _print_phase_loop_opts = has_loops();
3133 if (_print_phase_loop_opts) {
3134 print_method(PHASE_BEFORE_LOOP_OPTS, 2);
3135 }
3136
3137 // Perform escape analysis
3138 if (do_escape_analysis() && ConnectionGraph::has_candidates(this)) {
3139 if (has_loops()) {
3140 // Cleanup graph (remove dead nodes).
3141 TracePhase tp(_t_idealLoop);
3142 PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
3143 if (failing()) {
3144 return;
3145 }
3146 print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
3147 if (C->macro_count() > 0) {
3148 // Eliminate some macro nodes before EA to reduce analysis pressure
3149 PhaseMacroExpand mexp(igvn);
3150 mexp.eliminate_macro_nodes(/* eliminate_locks= */ false);
3151 if (failing()) {
3152 return;
3153 }
3154 igvn.set_delay_transform(false);
3155 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
3156 }
3157 }
3158
3159 bool progress;
3160 do {
3161 ConnectionGraph::do_analysis(this, &igvn);
3162
3163 if (failing()) return;
3164
3165 int mcount = macro_count(); // Record number of allocations and locks before IGVN
3166
3167 // Optimize out fields loads from scalar replaceable allocations.
3168 igvn.optimize(true);
3169 print_method(PHASE_ITER_GVN_AFTER_EA, 2);
3170
3171 if (failing()) return;
3172
3173 if (congraph() != nullptr && macro_count() > 0) {
3174 TracePhase tp(_t_macroEliminate);
3175 PhaseMacroExpand mexp(igvn);
3176 mexp.eliminate_macro_nodes();
3177 if (failing()) {
3178 return;
3179 }
3180 print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
3181
3182 igvn.set_delay_transform(false);
3183 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
3184 }
3185
3186 ConnectionGraph::verify_ram_nodes(this, root());
3187 if (failing()) return;
3188
3189 progress = do_iterative_escape_analysis() &&
3190 (macro_count() < mcount) &&
3191 ConnectionGraph::has_candidates(this);
3192 // Try again if candidates exist and made progress
3193 // by removing some allocations and/or locks.
3194 } while (progress);
3195 }
3196
3197 process_flat_accesses(igvn);
3198 if (failing()) {
3199 return;
3200 }
3201
3202 // Loop transforms on the ideal graph. Range Check Elimination,
3203 // peeling, unrolling, etc.
3204
3205 // Set loop opts counter
3206 if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
3207 {
3208 TracePhase tp(_t_idealLoop);
3209 PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
3210 _loop_opts_cnt--;
3211 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
3212 if (failing()) return;
3213 }
3214 // Loop opts pass if partial peeling occurred in previous pass
3215 if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
3216 TracePhase tp(_t_idealLoop);
3217 PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
3218 _loop_opts_cnt--;
3219 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
3220 if (failing()) return;
3221 }
3269
3270 // Once loop optimizations are over, it is safe to get rid of all reachability fence nodes and
3271 // migrate reachability edges to safepoints.
3272 if (OptimizeReachabilityFences && _reachability_fences.length() > 0) {
3273 TracePhase tp1(_t_idealLoop);
3274 TracePhase tp2(_t_reachability);
3275 PhaseIdealLoop::optimize(igvn, PostLoopOptsExpandReachabilityFences);
3276 print_method(PHASE_EXPAND_REACHABILITY_FENCES, 2);
3277 if (failing()) return;
3278 assert(_reachability_fences.length() == 0 || PreserveReachabilityFencesOnConstants, "no RF nodes allowed");
3279 }
3280
3281 process_for_merge_stores_igvn(igvn);
3282
3283 if (failing()) return;
3284
3285 #ifdef ASSERT
3286 bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
3287 #endif
3288
3289 if (_late_inlines.length() > 0) {
3290 // More opportunities to optimize virtual and MH calls.
3291 // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option.
3292 process_late_inline_calls_no_inline(igvn);
3293 if (failing()) {
3294 return;
3295 }
3296 }
3297 assert(_late_inlines.length() == 0, "late inline queue must be drained");
3298
3299 // Process inline types before macro expansion. Otherwise, we will not be able to
3300 // remove unused allocations because it cannot match the expanded allocation.
3301 process_inline_types(igvn);
3302
3303 {
3304 TracePhase tp(_t_macroExpand);
3305 PhaseMacroExpand mex(igvn);
3306 // Last attempt to eliminate macro nodes.
3307 mex.eliminate_macro_nodes();
3308 if (failing()) {
3309 return;
3310 }
3311
3312 print_method(PHASE_BEFORE_MACRO_EXPANSION, 3);
3313 // Do not allow new macro nodes once we start to eliminate and expand
3314 C->reset_allow_macro_nodes();
3315 // Last attempt to eliminate macro nodes before expand
3316 mex.eliminate_macro_nodes();
3317 if (failing()) {
3318 return;
3319 }
3320 mex.eliminate_opaque_looplimit_macro_nodes();
3321 if (failing()) {
3322 return;
3323 }
3324 print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
3325 if (mex.expand_macro_nodes()) {
3326 assert(failing(), "must bail out w/ explicit message");
3327 return;
3328 }
3329 print_method(PHASE_AFTER_MACRO_EXPANSION, 2);
3330 }
3331
3332 // Process inline type nodes again and remove them. From here
3333 // on we don't need to keep track of field values anymore.
3334 process_inline_types(igvn, /* remove= */ true);
3335
3336 {
3337 TracePhase tp(_t_barrierExpand);
3338 if (bs->expand_barriers(this, igvn)) {
3339 assert(failing(), "must bail out w/ explicit message");
3340 return;
3341 }
3342 print_method(PHASE_BARRIER_EXPANSION, 2);
3343 }
3344
3345 if (C->max_vector_size() > 0) {
3346 C->optimize_logic_cones(igvn);
3347 igvn.optimize();
3348 if (failing()) return;
3349 }
3350
3351 DEBUG_ONLY( _modified_nodes = nullptr; )
3352 DEBUG_ONLY( _late_inlines.clear(); )
3353
3354 assert(igvn._worklist.size() == 0, "not empty");
3355 } // (End scope of igvn; run destructor if necessary for asserts.)
3356
3357 check_no_dead_use();
3358
3359 // We will never use the NodeHash table any more. Clear it so that final_graph_reshaping does not have
3360 // to remove hashes to unlock nodes for modifications.
3361 C->node_hash()->clear();
3362
3363 // A method with only infinite loops has no edges entering loops from root
3364 {
3365 TracePhase tp(_t_graphReshaping);
3366 if (final_graph_reshaping()) {
3367 assert(failing(), "must bail out w/ explicit message");
3368 return;
3369 }
3370 }
3371
3372 print_method(PHASE_OPTIMIZE_FINISHED, 2);
3373 DEBUG_ONLY(set_phase_optimize_finished();)
3374 }
4051 mul->subsume_by(mul_hi_lo->first_proj(), this);
4052 n->subsume_by(mul_hi_lo->second_proj(), this);
4053 }
4054
4055 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) {
4056 switch( nop ) {
4057 case Op_Opaque1: // Remove Opaque Nodes before matching
4058 n->subsume_by(n->in(1), this);
4059 break;
4060 case Op_CallLeafPure: {
4061 // If the pure call is not supported, then lower to a CallLeaf.
4062 if (!Matcher::match_rule_supported(Op_CallLeafPure)) {
4063 CallNode* call = n->as_Call();
4064 CallNode* new_call = new CallLeafNode(call->tf(), call->entry_point(),
4065 call->_name, TypeRawPtr::BOTTOM);
4066 new_call->init_req(TypeFunc::Control, call->in(TypeFunc::Control));
4067 new_call->init_req(TypeFunc::I_O, C->top());
4068 new_call->init_req(TypeFunc::Memory, C->top());
4069 new_call->init_req(TypeFunc::ReturnAdr, C->top());
4070 new_call->init_req(TypeFunc::FramePtr, C->top());
4071 for (unsigned int i = TypeFunc::Parms; i < call->tf()->domain_sig()->cnt(); i++) {
4072 new_call->init_req(i, call->in(i));
4073 }
4074 n->subsume_by(new_call, this);
4075 }
4076 break;
4077 }
4078 case Op_CallStaticJava:
4079 case Op_CallJava:
4080 case Op_CallDynamicJava:
4081 frc.inc_java_call_count(); // Count java call site;
4082 case Op_CallRuntime:
4083 case Op_CallLeaf:
4084 case Op_CallLeafVector:
4085 case Op_CallLeafNoFP: {
4086 assert (n->is_Call(), "");
4087 CallNode *call = n->as_Call();
4088 // See if uncommon argument is shared
4089 if (call->is_CallStaticJava() && call->as_CallStaticJava()->_name) {
4090 Node *n = call->in(TypeFunc::Parms);
4091 int nop = n->Opcode();
4098 nop != Op_DecodeNKlass &&
4099 !n->is_Mem() &&
4100 !n->is_Phi()) {
4101 Node *x = n->clone();
4102 call->set_req(TypeFunc::Parms, x);
4103 }
4104 }
4105 break;
4106 }
4107
4108 // Mem nodes need explicit cases to satisfy assert(!n->is_Mem()) in default.
4109 case Op_StoreF:
4110 case Op_LoadF:
4111 case Op_StoreD:
4112 case Op_LoadD:
4113 case Op_LoadD_unaligned:
4114 case Op_StoreB:
4115 case Op_StoreC:
4116 case Op_StoreI:
4117 case Op_StoreL:
4118 case Op_StoreLSpecial:
4119 case Op_CompareAndSwapB:
4120 case Op_CompareAndSwapS:
4121 case Op_CompareAndSwapI:
4122 case Op_CompareAndSwapL:
4123 case Op_CompareAndSwapP:
4124 case Op_CompareAndSwapN:
4125 case Op_WeakCompareAndSwapB:
4126 case Op_WeakCompareAndSwapS:
4127 case Op_WeakCompareAndSwapI:
4128 case Op_WeakCompareAndSwapL:
4129 case Op_WeakCompareAndSwapP:
4130 case Op_WeakCompareAndSwapN:
4131 case Op_CompareAndExchangeB:
4132 case Op_CompareAndExchangeS:
4133 case Op_CompareAndExchangeI:
4134 case Op_CompareAndExchangeL:
4135 case Op_CompareAndExchangeP:
4136 case Op_CompareAndExchangeN:
4137 case Op_GetAndAddS:
4138 case Op_GetAndAddB:
4654 k->subsume_by(m, this);
4655 }
4656 }
4657 }
4658 break;
4659 }
4660 case Op_CmpUL: {
4661 if (!Matcher::has_match_rule(Op_CmpUL)) {
4662 // No support for unsigned long comparisons
4663 ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
4664 Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
4665 Node* orl = new OrLNode(n->in(1), sign_bit_mask);
4666 ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
4667 Node* andl = new AndLNode(orl, remove_sign_mask);
4668 Node* cmp = new CmpLNode(andl, n->in(2));
4669 n->subsume_by(cmp, this);
4670 }
4671 break;
4672 }
4673 #ifdef ASSERT
4674 case Op_InlineType: {
4675 n->dump(-1);
4676 assert(false, "inline type node was not removed");
4677 break;
4678 }
4679 case Op_ConNKlass: {
4680 const TypePtr* tp = n->as_Type()->type()->make_ptr();
4681 ciKlass* klass = tp->is_klassptr()->exact_klass();
4682 assert(klass->is_in_encoding_range(), "klass cannot be compressed");
4683 break;
4684 }
4685 #endif
4686 default:
4687 assert(!n->is_Call(), "");
4688 assert(!n->is_Mem(), "");
4689 assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
4690 break;
4691 }
4692 }
4693
4694 //------------------------------final_graph_reshaping_walk---------------------
4695 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
4696 // requires that the walk visits a node's inputs before visiting the node.
4697 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
4698 Unique_Node_List sfpt;
5031 }
5032 }
5033
5034 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
5035 return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
5036 }
5037
5038 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
5039 return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
5040 }
5041
5042 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
5043 if (holder->is_initialized()) {
5044 return false;
5045 }
5046 if (holder->is_being_initialized()) {
5047 if (accessing_method->holder() == holder) {
5048 // Access inside a class. The barrier can be elided when access happens in <clinit>,
5049 // <init>, or a static method. In all those cases, there was an initialization
5050 // barrier on the holder klass passed.
5051 if (accessing_method->is_class_initializer() ||
5052 accessing_method->is_object_constructor() ||
5053 accessing_method->is_static()) {
5054 return false;
5055 }
5056 } else if (accessing_method->holder()->is_subclass_of(holder)) {
5057 // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
5058 // In case of <init> or a static method, the barrier is on the subclass is not enough:
5059 // child class can become fully initialized while its parent class is still being initialized.
5060 if (accessing_method->is_class_initializer()) {
5061 return false;
5062 }
5063 }
5064 ciMethod* root = method(); // the root method of compilation
5065 if (root != accessing_method) {
5066 return needs_clinit_barrier(holder, root); // check access in the context of compilation root
5067 }
5068 }
5069 return true;
5070 }
5071
5072 #ifndef PRODUCT
5073 //------------------------------verify_bidirectional_edges---------------------
5074 // For each input edge to a node (ie - for each Use-Def edge), verify that
5075 // there is a corresponding Def-Use edge.
5076 void Compile::verify_bidirectional_edges(Unique_Node_List& visited, const Unique_Node_List* root_and_safepoints) const {
5077 // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc
5078 uint stack_size = live_nodes() >> 4;
5079 Node_List nstack(MAX2(stack_size, (uint) OptoNodeListSize));
5080 if (root_and_safepoints != nullptr) {
5110 if (in != nullptr && !in->is_top()) {
5111 // Count instances of `next`
5112 int cnt = 0;
5113 for (uint idx = 0; idx < in->_outcnt; idx++) {
5114 if (in->_out[idx] == n) {
5115 cnt++;
5116 }
5117 }
5118 assert(cnt > 0, "Failed to find Def-Use edge.");
5119 // Check for duplicate edges
5120 // walk the input array downcounting the input edges to n
5121 for (uint j = 0; j < length; j++) {
5122 if (n->in(j) == in) {
5123 cnt--;
5124 }
5125 }
5126 assert(cnt == 0, "Mismatched edge count.");
5127 } else if (in == nullptr) {
5128 assert(i == 0 || i >= n->req() ||
5129 n->is_Region() || n->is_Phi() || n->is_ArrayCopy() ||
5130 (n->is_Allocate() && i >= AllocateNode::InlineType) ||
5131 (n->is_Unlock() && i == (n->req() - 1)) ||
5132 (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
5133 "only region, phi, arraycopy, allocate, unlock or membar nodes have null data edges");
5134 } else {
5135 assert(in->is_top(), "sanity");
5136 // Nothing to check.
5137 }
5138 }
5139 }
5140 }
5141
5142 //------------------------------verify_graph_edges---------------------------
5143 // Walk the Graph and verify that there is a one-to-one correspondence
5144 // between Use-Def edges and Def-Use edges in the graph.
5145 void Compile::verify_graph_edges(bool no_dead_code, const Unique_Node_List* root_and_safepoints) const {
5146 if (VerifyGraphEdges) {
5147 Unique_Node_List visited;
5148
5149 // Call graph walk to check edges
5150 verify_bidirectional_edges(visited, root_and_safepoints);
5151 if (no_dead_code) {
5152 // Now make sure that no visited node is used by an unvisited node.
5153 bool dead_nodes = false;
5264 // (1) subklass is already limited to a subtype of superklass => always ok
5265 // (2) subklass does not overlap with superklass => always fail
5266 // (3) superklass has NO subtypes and we can check with a simple compare.
5267 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) {
5268 if (skip) {
5269 return SSC_full_test; // Let caller generate the general case.
5270 }
5271
5272 if (subk->is_java_subtype_of(superk)) {
5273 return SSC_always_true; // (0) and (1) this test cannot fail
5274 }
5275
5276 if (!subk->maybe_java_subtype_of(superk)) {
5277 return SSC_always_false; // (2) true path dead; no dynamic test needed
5278 }
5279
5280 const Type* superelem = superk;
5281 if (superk->isa_aryklassptr()) {
5282 int ignored;
5283 superelem = superk->is_aryklassptr()->base_element_type(ignored);
5284
5285 // Do not fold the subtype check to an array klass pointer comparison for null-able inline type arrays
5286 // because null-free [LMyValue <: null-able [LMyValue but the klasses are different. Perform a full test.
5287 if (!superk->is_aryklassptr()->is_null_free() && superk->is_aryklassptr()->elem()->isa_instklassptr() &&
5288 superk->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->is_inlinetype()) {
5289 return SSC_full_test;
5290 }
5291 }
5292
5293 if (superelem->isa_instklassptr()) {
5294 ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass();
5295 if (!ik->has_subklass()) {
5296 if (!ik->is_final()) {
5297 // Add a dependency if there is a chance of a later subclass.
5298 dependencies()->assert_leaf_type(ik);
5299 }
5300 if (!superk->maybe_java_subtype_of(subk)) {
5301 return SSC_always_false;
5302 }
5303 return SSC_easy_test; // (3) caller can do a simple ptr comparison
5304 }
5305 } else {
5306 // A primitive array type has no subtypes.
5307 return SSC_easy_test; // (3) caller can do a simple ptr comparison
5308 }
5309
5310 return SSC_full_test;
6107 _debug_network_printer->print(name, C->root(), visible_nodes, fr);
6108 }
6109 #endif // !PRODUCT
6110
6111 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
6112 precond(type != nullptr);
6113
6114 if (phase->type(value)->higher_equal(type)) {
6115 return value;
6116 }
6117 Node* result = nullptr;
6118 if (bt == T_BYTE) {
6119 result = phase->transform(new LShiftINode(value, phase->intcon(24)));
6120 result = new RShiftINode(result, phase->intcon(24));
6121 } else if (bt == T_BOOLEAN) {
6122 assert(type == TypeInt::BOOL || type == TypeInt::UBYTE, "unexpected boolean type: %s", Type::str(type));
6123 Node* mask = phase->intcon(type == TypeInt::BOOL ? 1 : 0xFF);
6124 result = new AndINode(value, mask);
6125 } else if (bt == T_CHAR) {
6126 result = new AndINode(value,phase->intcon(0xFFFF));
6127 } else if (bt == T_FLOAT) {
6128 result = new MoveI2FNode(value);
6129 } else {
6130 assert(bt == T_SHORT, "unexpected narrow type");
6131 result = phase->transform(new LShiftINode(value, phase->intcon(16)));
6132 result = new RShiftINode(result, phase->intcon(16));
6133 }
6134 if (transform_res) {
6135 result = phase->transform(result);
6136 }
6137 return result;
6138 }
6139
6140 void Compile::record_method_not_compilable_oom() {
6141 record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit());
6142 }
6143
6144 #ifndef PRODUCT
6145 // Collects all the control inputs from nodes on the worklist and from their data dependencies
6146 static void find_candidate_control_inputs(Unique_Node_List& worklist, Unique_Node_List& candidates) {
6147 // Follow non-control edges until we reach CFG nodes
6148 for (uint i = 0; i < worklist.size(); i++) {
|