1 /* 2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2024, Alibaba Group Holding Limited. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 * 24 */ 25 26 #include "classfile/javaClasses.hpp" 27 #include "compiler/compileLog.hpp" 28 #include "gc/shared/barrierSet.hpp" 29 #include "gc/shared/c2/barrierSetC2.hpp" 30 #include "gc/shared/tlab_globals.hpp" 31 #include "memory/allocation.inline.hpp" 32 #include "memory/resourceArea.hpp" 33 #include "oops/objArrayKlass.hpp" 34 #include "opto/addnode.hpp" 35 #include "opto/arraycopynode.hpp" 36 #include "opto/cfgnode.hpp" 37 #include "opto/regalloc.hpp" 38 #include "opto/compile.hpp" 39 #include "opto/connode.hpp" 40 #include "opto/convertnode.hpp" 41 #include "opto/loopnode.hpp" 42 #include "opto/machnode.hpp" 43 #include "opto/matcher.hpp" 44 #include "opto/memnode.hpp" 45 #include "opto/mempointer.hpp" 46 #include "opto/mulnode.hpp" 47 #include "opto/narrowptrnode.hpp" 48 #include "opto/phaseX.hpp" 49 #include "opto/regmask.hpp" 50 #include "opto/rootnode.hpp" 51 #include "opto/traceMergeStoresTag.hpp" 52 #include "opto/vectornode.hpp" 53 #include "utilities/align.hpp" 54 #include "utilities/copy.hpp" 55 #include "utilities/macros.hpp" 56 #include "utilities/powerOfTwo.hpp" 57 #include "utilities/vmError.hpp" 58 59 // Portions of code courtesy of Clifford Click 60 61 // Optimization - Graph Style 62 63 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st); 64 65 //============================================================================= 66 uint MemNode::size_of() const { return sizeof(*this); } 67 68 const TypePtr *MemNode::adr_type() const { 69 Node* adr = in(Address); 70 if (adr == nullptr) return nullptr; // node is dead 71 const TypePtr* cross_check = nullptr; 72 DEBUG_ONLY(cross_check = _adr_type); 73 return calculate_adr_type(adr->bottom_type(), cross_check); 74 } 75 76 bool MemNode::check_if_adr_maybe_raw(Node* adr) { 77 if (adr != nullptr) { 78 if (adr->bottom_type()->base() == Type::RawPtr || adr->bottom_type()->base() == Type::AnyPtr) { 79 return true; 80 } 81 } 82 return false; 83 } 84 85 #ifndef PRODUCT 86 void MemNode::dump_spec(outputStream *st) const { 87 if (in(Address) == nullptr) return; // node is dead 88 #ifndef ASSERT 89 // fake the missing field 90 const TypePtr* _adr_type = nullptr; 91 if (in(Address) != nullptr) 92 _adr_type = in(Address)->bottom_type()->isa_ptr(); 93 #endif 94 dump_adr_type(this, _adr_type, st); 95 96 Compile* C = Compile::current(); 97 if (C->alias_type(_adr_type)->is_volatile()) { 98 st->print(" Volatile!"); 99 } 100 if (_unaligned_access) { 101 st->print(" unaligned"); 102 } 103 if (_mismatched_access) { 104 st->print(" mismatched"); 105 } 106 if (_unsafe_access) { 107 st->print(" unsafe"); 108 } 109 } 110 111 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) { 112 st->print(" @"); 113 if (adr_type == nullptr) { 114 st->print("null"); 115 } else { 116 adr_type->dump_on(st); 117 Compile* C = Compile::current(); 118 Compile::AliasType* atp = nullptr; 119 if (C->have_alias_type(adr_type)) atp = C->alias_type(adr_type); 120 if (atp == nullptr) 121 st->print(", idx=?\?;"); 122 else if (atp->index() == Compile::AliasIdxBot) 123 st->print(", idx=Bot;"); 124 else if (atp->index() == Compile::AliasIdxTop) 125 st->print(", idx=Top;"); 126 else if (atp->index() == Compile::AliasIdxRaw) 127 st->print(", idx=Raw;"); 128 else { 129 ciField* field = atp->field(); 130 if (field) { 131 st->print(", name="); 132 field->print_name_on(st); 133 } 134 st->print(", idx=%d;", atp->index()); 135 } 136 } 137 } 138 139 extern void print_alias_types(); 140 141 #endif 142 143 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) { 144 assert((t_oop != nullptr), "sanity"); 145 bool is_instance = t_oop->is_known_instance_field(); 146 bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() && 147 (load != nullptr) && load->is_Load() && 148 (phase->is_IterGVN() != nullptr); 149 if (!(is_instance || is_boxed_value_load)) 150 return mchain; // don't try to optimize non-instance types 151 uint instance_id = t_oop->instance_id(); 152 Node *start_mem = phase->C->start()->proj_out_or_null(TypeFunc::Memory); 153 Node *prev = nullptr; 154 Node *result = mchain; 155 while (prev != result) { 156 prev = result; 157 if (result == start_mem) 158 break; // hit one of our sentinels 159 // skip over a call which does not affect this memory slice 160 if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) { 161 Node *proj_in = result->in(0); 162 if (proj_in->is_Allocate() && proj_in->_idx == instance_id) { 163 break; // hit one of our sentinels 164 } else if (proj_in->is_Call()) { 165 // ArrayCopyNodes processed here as well 166 CallNode *call = proj_in->as_Call(); 167 if (!call->may_modify(t_oop, phase)) { // returns false for instances 168 result = call->in(TypeFunc::Memory); 169 } 170 } else if (proj_in->is_Initialize()) { 171 AllocateNode* alloc = proj_in->as_Initialize()->allocation(); 172 // Stop if this is the initialization for the object instance which 173 // contains this memory slice, otherwise skip over it. 174 if ((alloc == nullptr) || (alloc->_idx == instance_id)) { 175 break; 176 } 177 if (is_instance) { 178 result = proj_in->in(TypeFunc::Memory); 179 } else if (is_boxed_value_load) { 180 Node* klass = alloc->in(AllocateNode::KlassNode); 181 const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr(); 182 if (tklass->klass_is_exact() && !tklass->exact_klass()->equals(t_oop->is_instptr()->exact_klass())) { 183 result = proj_in->in(TypeFunc::Memory); // not related allocation 184 } 185 } 186 } else if (proj_in->is_MemBar()) { 187 ArrayCopyNode* ac = nullptr; 188 if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase, ac)) { 189 break; 190 } 191 result = proj_in->in(TypeFunc::Memory); 192 } else if (proj_in->is_top()) { 193 break; // dead code 194 } else { 195 assert(false, "unexpected projection"); 196 } 197 } else if (result->is_ClearArray()) { 198 if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) { 199 // Can not bypass initialization of the instance 200 // we are looking for. 201 break; 202 } 203 // Otherwise skip it (the call updated 'result' value). 204 } else if (result->is_MergeMem()) { 205 result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, nullptr, tty); 206 } 207 } 208 return result; 209 } 210 211 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) { 212 const TypeOopPtr* t_oop = t_adr->isa_oopptr(); 213 if (t_oop == nullptr) 214 return mchain; // don't try to optimize non-oop types 215 Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase); 216 bool is_instance = t_oop->is_known_instance_field(); 217 PhaseIterGVN *igvn = phase->is_IterGVN(); 218 if (is_instance && igvn != nullptr && result->is_Phi()) { 219 PhiNode *mphi = result->as_Phi(); 220 assert(mphi->bottom_type() == Type::MEMORY, "memory phi required"); 221 const TypePtr *t = mphi->adr_type(); 222 bool do_split = false; 223 // In the following cases, Load memory input can be further optimized based on 224 // its precise address type 225 if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ) { 226 do_split = true; 227 } else if (t->isa_oopptr() && !t->is_oopptr()->is_known_instance()) { 228 const TypeOopPtr* mem_t = 229 t->is_oopptr()->cast_to_exactness(true) 230 ->is_oopptr()->cast_to_ptr_type(t_oop->ptr()) 231 ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()); 232 if (t_oop->isa_aryptr()) { 233 mem_t = mem_t->is_aryptr() 234 ->cast_to_stable(t_oop->is_aryptr()->is_stable()) 235 ->cast_to_size(t_oop->is_aryptr()->size()) 236 ->with_offset(t_oop->is_aryptr()->offset()) 237 ->is_aryptr(); 238 } 239 do_split = mem_t == t_oop; 240 } 241 if (do_split) { 242 // clone the Phi with our address type 243 result = mphi->split_out_instance(t_adr, igvn); 244 } else { 245 assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain"); 246 } 247 } 248 return result; 249 } 250 251 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st) { 252 uint alias_idx = phase->C->get_alias_index(tp); 253 Node *mem = mmem; 254 #ifdef ASSERT 255 { 256 // Check that current type is consistent with the alias index used during graph construction 257 assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx"); 258 bool consistent = adr_check == nullptr || adr_check->empty() || 259 phase->C->must_alias(adr_check, alias_idx ); 260 // Sometimes dead array references collapse to a[-1], a[-2], or a[-3] 261 if( !consistent && adr_check != nullptr && !adr_check->empty() && 262 tp->isa_aryptr() && tp->offset() == Type::OffsetBot && 263 adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot && 264 ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() || 265 adr_check->offset() == oopDesc::klass_offset_in_bytes() || 266 adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) { 267 // don't assert if it is dead code. 268 consistent = true; 269 } 270 if( !consistent ) { 271 st->print("alias_idx==%d, adr_check==", alias_idx); 272 if( adr_check == nullptr ) { 273 st->print("null"); 274 } else { 275 adr_check->dump(); 276 } 277 st->cr(); 278 print_alias_types(); 279 assert(consistent, "adr_check must match alias idx"); 280 } 281 } 282 #endif 283 // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally 284 // means an array I have not precisely typed yet. Do not do any 285 // alias stuff with it any time soon. 286 const TypeOopPtr *toop = tp->isa_oopptr(); 287 if (tp->base() != Type::AnyPtr && 288 !(toop && 289 toop->isa_instptr() && 290 toop->is_instptr()->instance_klass()->is_java_lang_Object() && 291 toop->offset() == Type::OffsetBot)) { 292 // compress paths and change unreachable cycles to TOP 293 // If not, we can update the input infinitely along a MergeMem cycle 294 // Equivalent code in PhiNode::Ideal 295 Node* m = phase->transform(mmem); 296 // If transformed to a MergeMem, get the desired slice 297 // Otherwise the returned node represents memory for every slice 298 mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m; 299 // Update input if it is progress over what we have now 300 } 301 return mem; 302 } 303 304 //--------------------------Ideal_common--------------------------------------- 305 // Look for degenerate control and memory inputs. Bypass MergeMem inputs. 306 // Unhook non-raw memories from complete (macro-expanded) initializations. 307 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) { 308 // If our control input is a dead region, kill all below the region 309 Node *ctl = in(MemNode::Control); 310 if (ctl && remove_dead_region(phase, can_reshape)) 311 return this; 312 ctl = in(MemNode::Control); 313 // Don't bother trying to transform a dead node 314 if (ctl && ctl->is_top()) return NodeSentinel; 315 316 PhaseIterGVN *igvn = phase->is_IterGVN(); 317 // Wait if control on the worklist. 318 if (ctl && can_reshape && igvn != nullptr) { 319 Node* bol = nullptr; 320 Node* cmp = nullptr; 321 if (ctl->in(0)->is_If()) { 322 assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity"); 323 bol = ctl->in(0)->in(1); 324 if (bol->is_Bool()) 325 cmp = ctl->in(0)->in(1)->in(1); 326 } 327 if (igvn->_worklist.member(ctl) || 328 (bol != nullptr && igvn->_worklist.member(bol)) || 329 (cmp != nullptr && igvn->_worklist.member(cmp)) ) { 330 // This control path may be dead. 331 // Delay this memory node transformation until the control is processed. 332 igvn->_worklist.push(this); 333 return NodeSentinel; // caller will return null 334 } 335 } 336 // Ignore if memory is dead, or self-loop 337 Node *mem = in(MemNode::Memory); 338 if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return null 339 assert(mem != this, "dead loop in MemNode::Ideal"); 340 341 if (can_reshape && igvn != nullptr && igvn->_worklist.member(mem)) { 342 // This memory slice may be dead. 343 // Delay this mem node transformation until the memory is processed. 344 igvn->_worklist.push(this); 345 return NodeSentinel; // caller will return null 346 } 347 348 Node *address = in(MemNode::Address); 349 const Type *t_adr = phase->type(address); 350 if (t_adr == Type::TOP) return NodeSentinel; // caller will return null 351 352 if (can_reshape && is_unsafe_access() && (t_adr == TypePtr::NULL_PTR)) { 353 // Unsafe off-heap access with zero address. Remove access and other control users 354 // to not confuse optimizations and add a HaltNode to fail if this is ever executed. 355 assert(ctl != nullptr, "unsafe accesses should be control dependent"); 356 for (DUIterator_Fast imax, i = ctl->fast_outs(imax); i < imax; i++) { 357 Node* u = ctl->fast_out(i); 358 if (u != ctl) { 359 igvn->rehash_node_delayed(u); 360 int nb = u->replace_edge(ctl, phase->C->top(), igvn); 361 --i, imax -= nb; 362 } 363 } 364 Node* frame = igvn->transform(new ParmNode(phase->C->start(), TypeFunc::FramePtr)); 365 Node* halt = igvn->transform(new HaltNode(ctl, frame, "unsafe off-heap access with zero address")); 366 phase->C->root()->add_req(halt); 367 return this; 368 } 369 370 if (can_reshape && igvn != nullptr && 371 (igvn->_worklist.member(address) || 372 (igvn->_worklist.size() > 0 && t_adr != adr_type())) ) { 373 // The address's base and type may change when the address is processed. 374 // Delay this mem node transformation until the address is processed. 375 igvn->_worklist.push(this); 376 return NodeSentinel; // caller will return null 377 } 378 379 // Do NOT remove or optimize the next lines: ensure a new alias index 380 // is allocated for an oop pointer type before Escape Analysis. 381 // Note: C++ will not remove it since the call has side effect. 382 if (t_adr->isa_oopptr()) { 383 int alias_idx = phase->C->get_alias_index(t_adr->is_ptr()); 384 } 385 386 Node* base = nullptr; 387 if (address->is_AddP()) { 388 base = address->in(AddPNode::Base); 389 } 390 if (base != nullptr && phase->type(base)->higher_equal(TypePtr::NULL_PTR) && 391 !t_adr->isa_rawptr()) { 392 // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true. 393 // Skip this node optimization if its address has TOP base. 394 return NodeSentinel; // caller will return null 395 } 396 397 // Avoid independent memory operations 398 Node* old_mem = mem; 399 400 // The code which unhooks non-raw memories from complete (macro-expanded) 401 // initializations was removed. After macro-expansion all stores caught 402 // by Initialize node became raw stores and there is no information 403 // which memory slices they modify. So it is unsafe to move any memory 404 // operation above these stores. Also in most cases hooked non-raw memories 405 // were already unhooked by using information from detect_ptr_independence() 406 // and find_previous_store(). 407 408 if (mem->is_MergeMem()) { 409 MergeMemNode* mmem = mem->as_MergeMem(); 410 const TypePtr *tp = t_adr->is_ptr(); 411 412 mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty); 413 } 414 415 if (mem != old_mem) { 416 set_req_X(MemNode::Memory, mem, phase); 417 if (phase->type(mem) == Type::TOP) return NodeSentinel; 418 return this; 419 } 420 421 // let the subclass continue analyzing... 422 return nullptr; 423 } 424 425 // Helper function for proving some simple control dominations. 426 // Attempt to prove that all control inputs of 'dom' dominate 'sub'. 427 // Already assumes that 'dom' is available at 'sub', and that 'sub' 428 // is not a constant (dominated by the method's StartNode). 429 // Used by MemNode::find_previous_store to prove that the 430 // control input of a memory operation predates (dominates) 431 // an allocation it wants to look past. 432 // Returns 'DomResult::Dominate' if all control inputs of 'dom' 433 // dominate 'sub', 'DomResult::NotDominate' if not, 434 // and 'DomResult::EncounteredDeadCode' if we can't decide due to 435 // dead code, but at the end of IGVN, we know the definite result 436 // once the dead code is cleaned up. 437 Node::DomResult MemNode::maybe_all_controls_dominate(Node* dom, Node* sub) { 438 if (dom == nullptr || dom->is_top() || sub == nullptr || sub->is_top()) { 439 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 440 } 441 442 // Check 'dom'. Skip Proj and CatchProj nodes. 443 dom = dom->find_exact_control(dom); 444 if (dom == nullptr || dom->is_top()) { 445 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 446 } 447 448 if (dom == sub) { 449 // For the case when, for example, 'sub' is Initialize and the original 450 // 'dom' is Proj node of the 'sub'. 451 return DomResult::NotDominate; 452 } 453 454 if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub) { 455 return DomResult::Dominate; 456 } 457 458 // 'dom' dominates 'sub' if its control edge and control edges 459 // of all its inputs dominate or equal to sub's control edge. 460 461 // Currently 'sub' is either Allocate, Initialize or Start nodes. 462 // Or Region for the check in LoadNode::Ideal(); 463 // 'sub' should have sub->in(0) != nullptr. 464 assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() || 465 sub->is_Region() || sub->is_Call(), "expecting only these nodes"); 466 467 // Get control edge of 'sub'. 468 Node* orig_sub = sub; 469 sub = sub->find_exact_control(sub->in(0)); 470 if (sub == nullptr || sub->is_top()) { 471 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 472 } 473 474 assert(sub->is_CFG(), "expecting control"); 475 476 if (sub == dom) { 477 return DomResult::Dominate; 478 } 479 480 if (sub->is_Start() || sub->is_Root()) { 481 return DomResult::NotDominate; 482 } 483 484 { 485 // Check all control edges of 'dom'. 486 487 ResourceMark rm; 488 Node_List nlist; 489 Unique_Node_List dom_list; 490 491 dom_list.push(dom); 492 bool only_dominating_controls = false; 493 494 for (uint next = 0; next < dom_list.size(); next++) { 495 Node* n = dom_list.at(next); 496 if (n == orig_sub) { 497 return DomResult::NotDominate; // One of dom's inputs dominated by sub. 498 } 499 if (!n->is_CFG() && n->pinned()) { 500 // Check only own control edge for pinned non-control nodes. 501 n = n->find_exact_control(n->in(0)); 502 if (n == nullptr || n->is_top()) { 503 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 504 } 505 assert(n->is_CFG(), "expecting control"); 506 dom_list.push(n); 507 } else if (n->is_Con() || n->is_Start() || n->is_Root()) { 508 only_dominating_controls = true; 509 } else if (n->is_CFG()) { 510 DomResult dom_result = n->dominates(sub, nlist); 511 if (dom_result == DomResult::Dominate) { 512 only_dominating_controls = true; 513 } else { 514 return dom_result; 515 } 516 } else { 517 // First, own control edge. 518 Node* m = n->find_exact_control(n->in(0)); 519 if (m != nullptr) { 520 if (m->is_top()) { 521 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 522 } 523 dom_list.push(m); 524 } 525 // Now, the rest of edges. 526 uint cnt = n->req(); 527 for (uint i = 1; i < cnt; i++) { 528 m = n->find_exact_control(n->in(i)); 529 if (m == nullptr || m->is_top()) { 530 continue; 531 } 532 dom_list.push(m); 533 } 534 } 535 } 536 return only_dominating_controls ? DomResult::Dominate : DomResult::NotDominate; 537 } 538 } 539 540 //---------------------detect_ptr_independence--------------------------------- 541 // Used by MemNode::find_previous_store to prove that two base 542 // pointers are never equal. 543 // The pointers are accompanied by their associated allocations, 544 // if any, which have been previously discovered by the caller. 545 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1, 546 Node* p2, AllocateNode* a2, 547 PhaseTransform* phase) { 548 // Attempt to prove that these two pointers cannot be aliased. 549 // They may both manifestly be allocations, and they should differ. 550 // Or, if they are not both allocations, they can be distinct constants. 551 // Otherwise, one is an allocation and the other a pre-existing value. 552 if (a1 == nullptr && a2 == nullptr) { // neither an allocation 553 return (p1 != p2) && p1->is_Con() && p2->is_Con(); 554 } else if (a1 != nullptr && a2 != nullptr) { // both allocations 555 return (a1 != a2); 556 } else if (a1 != nullptr) { // one allocation a1 557 // (Note: p2->is_Con implies p2->in(0)->is_Root, which dominates.) 558 return all_controls_dominate(p2, a1); 559 } else { //(a2 != null) // one allocation a2 560 return all_controls_dominate(p1, a2); 561 } 562 return false; 563 } 564 565 566 // Find an arraycopy ac that produces the memory state represented by parameter mem. 567 // Return ac if 568 // (a) can_see_stored_value=true and ac must have set the value for this load or if 569 // (b) can_see_stored_value=false and ac could have set the value for this load or if 570 // (c) can_see_stored_value=false and ac cannot have set the value for this load. 571 // In case (c) change the parameter mem to the memory input of ac to skip it 572 // when searching stored value. 573 // Otherwise return null. 574 Node* LoadNode::find_previous_arraycopy(PhaseValues* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const { 575 ArrayCopyNode* ac = find_array_copy_clone(ld_alloc, mem); 576 if (ac != nullptr) { 577 Node* ld_addp = in(MemNode::Address); 578 Node* src = ac->in(ArrayCopyNode::Src); 579 const TypeAryPtr* ary_t = phase->type(src)->isa_aryptr(); 580 581 // This is a load from a cloned array. The corresponding arraycopy ac must 582 // have set the value for the load and we can return ac but only if the load 583 // is known to be within bounds. This is checked below. 584 if (ary_t != nullptr && ld_addp->is_AddP()) { 585 Node* ld_offs = ld_addp->in(AddPNode::Offset); 586 BasicType ary_elem = ary_t->elem()->array_element_basic_type(); 587 jlong header = arrayOopDesc::base_offset_in_bytes(ary_elem); 588 jlong elemsize = type2aelembytes(ary_elem); 589 590 const TypeX* ld_offs_t = phase->type(ld_offs)->isa_intptr_t(); 591 const TypeInt* sizetype = ary_t->size(); 592 593 if (ld_offs_t->_lo >= header && ld_offs_t->_hi < (sizetype->_lo * elemsize + header)) { 594 // The load is known to be within bounds. It receives its value from ac. 595 return ac; 596 } 597 // The load is known to be out-of-bounds. 598 } 599 // The load could be out-of-bounds. It must not be hoisted but must remain 600 // dependent on the runtime range check. This is achieved by returning null. 601 } else if (mem->is_Proj() && mem->in(0) != nullptr && mem->in(0)->is_ArrayCopy()) { 602 ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy(); 603 604 if (ac->is_arraycopy_validated() || 605 ac->is_copyof_validated() || 606 ac->is_copyofrange_validated()) { 607 Node* ld_addp = in(MemNode::Address); 608 if (ld_addp->is_AddP()) { 609 Node* ld_base = ld_addp->in(AddPNode::Address); 610 Node* ld_offs = ld_addp->in(AddPNode::Offset); 611 612 Node* dest = ac->in(ArrayCopyNode::Dest); 613 614 if (dest == ld_base) { 615 const TypeX* ld_offs_t = phase->type(ld_offs)->isa_intptr_t(); 616 assert(!ld_offs_t->empty(), "dead reference should be checked already"); 617 // Take into account vector or unsafe access size 618 jlong ld_size_in_bytes = (jlong)memory_size(); 619 jlong offset_hi = ld_offs_t->_hi + ld_size_in_bytes - 1; 620 offset_hi = MIN2(offset_hi, (jlong)(TypeX::MAX->_hi)); // Take care for overflow in 32-bit VM 621 if (ac->modifies(ld_offs_t->_lo, (intptr_t)offset_hi, phase, can_see_stored_value)) { 622 return ac; 623 } 624 if (!can_see_stored_value) { 625 mem = ac->in(TypeFunc::Memory); 626 return ac; 627 } 628 } 629 } 630 } 631 } 632 return nullptr; 633 } 634 635 ArrayCopyNode* MemNode::find_array_copy_clone(Node* ld_alloc, Node* mem) const { 636 if (mem->is_Proj() && mem->in(0) != nullptr && (mem->in(0)->Opcode() == Op_MemBarStoreStore || 637 mem->in(0)->Opcode() == Op_MemBarCPUOrder)) { 638 if (ld_alloc != nullptr) { 639 // Check if there is an array copy for a clone 640 Node* mb = mem->in(0); 641 ArrayCopyNode* ac = nullptr; 642 if (mb->in(0) != nullptr && mb->in(0)->is_Proj() && 643 mb->in(0)->in(0) != nullptr && mb->in(0)->in(0)->is_ArrayCopy()) { 644 ac = mb->in(0)->in(0)->as_ArrayCopy(); 645 } else { 646 // Step over GC barrier when ReduceInitialCardMarks is disabled 647 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 648 Node* control_proj_ac = bs->step_over_gc_barrier(mb->in(0)); 649 650 if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) { 651 ac = control_proj_ac->in(0)->as_ArrayCopy(); 652 } 653 } 654 655 if (ac != nullptr && ac->is_clonebasic()) { 656 AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest)); 657 if (alloc != nullptr && alloc == ld_alloc) { 658 return ac; 659 } 660 } 661 } 662 } 663 return nullptr; 664 } 665 666 // The logic for reordering loads and stores uses four steps: 667 // (a) Walk carefully past stores and initializations which we 668 // can prove are independent of this load. 669 // (b) Observe that the next memory state makes an exact match 670 // with self (load or store), and locate the relevant store. 671 // (c) Ensure that, if we were to wire self directly to the store, 672 // the optimizer would fold it up somehow. 673 // (d) Do the rewiring, and return, depending on some other part of 674 // the optimizer to fold up the load. 675 // This routine handles steps (a) and (b). Steps (c) and (d) are 676 // specific to loads and stores, so they are handled by the callers. 677 // (Currently, only LoadNode::Ideal has steps (c), (d). More later.) 678 // 679 Node* MemNode::find_previous_store(PhaseValues* phase) { 680 Node* ctrl = in(MemNode::Control); 681 Node* adr = in(MemNode::Address); 682 intptr_t offset = 0; 683 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); 684 AllocateNode* alloc = AllocateNode::Ideal_allocation(base); 685 686 if (offset == Type::OffsetBot) 687 return nullptr; // cannot unalias unless there are precise offsets 688 689 const bool adr_maybe_raw = check_if_adr_maybe_raw(adr); 690 const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr(); 691 692 intptr_t size_in_bytes = memory_size(); 693 694 Node* mem = in(MemNode::Memory); // start searching here... 695 696 int cnt = 50; // Cycle limiter 697 for (;;) { // While we can dance past unrelated stores... 698 if (--cnt < 0) break; // Caught in cycle or a complicated dance? 699 700 Node* prev = mem; 701 if (mem->is_Store()) { 702 Node* st_adr = mem->in(MemNode::Address); 703 intptr_t st_offset = 0; 704 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset); 705 if (st_base == nullptr) 706 break; // inscrutable pointer 707 708 // For raw accesses it's not enough to prove that constant offsets don't intersect. 709 // We need the bases to be the equal in order for the offset check to make sense. 710 if ((adr_maybe_raw || check_if_adr_maybe_raw(st_adr)) && st_base != base) { 711 break; 712 } 713 714 if (st_offset != offset && st_offset != Type::OffsetBot) { 715 const int MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize); 716 assert(mem->as_Store()->memory_size() <= MAX_STORE, ""); 717 if (st_offset >= offset + size_in_bytes || 718 st_offset <= offset - MAX_STORE || 719 st_offset <= offset - mem->as_Store()->memory_size()) { 720 // Success: The offsets are provably independent. 721 // (You may ask, why not just test st_offset != offset and be done? 722 // The answer is that stores of different sizes can co-exist 723 // in the same sequence of RawMem effects. We sometimes initialize 724 // a whole 'tile' of array elements with a single jint or jlong.) 725 mem = mem->in(MemNode::Memory); 726 continue; // (a) advance through independent store memory 727 } 728 } 729 if (st_base != base && 730 detect_ptr_independence(base, alloc, 731 st_base, 732 AllocateNode::Ideal_allocation(st_base), 733 phase)) { 734 // Success: The bases are provably independent. 735 mem = mem->in(MemNode::Memory); 736 continue; // (a) advance through independent store memory 737 } 738 739 // (b) At this point, if the bases or offsets do not agree, we lose, 740 // since we have not managed to prove 'this' and 'mem' independent. 741 if (st_base == base && st_offset == offset) { 742 return mem; // let caller handle steps (c), (d) 743 } 744 745 } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) { 746 InitializeNode* st_init = mem->in(0)->as_Initialize(); 747 AllocateNode* st_alloc = st_init->allocation(); 748 if (st_alloc == nullptr) { 749 break; // something degenerated 750 } 751 bool known_identical = false; 752 bool known_independent = false; 753 if (alloc == st_alloc) { 754 known_identical = true; 755 } else if (alloc != nullptr) { 756 known_independent = true; 757 } else if (all_controls_dominate(this, st_alloc)) { 758 known_independent = true; 759 } 760 761 if (known_independent) { 762 // The bases are provably independent: Either they are 763 // manifestly distinct allocations, or else the control 764 // of this load dominates the store's allocation. 765 int alias_idx = phase->C->get_alias_index(adr_type()); 766 if (alias_idx == Compile::AliasIdxRaw) { 767 mem = st_alloc->in(TypeFunc::Memory); 768 } else { 769 mem = st_init->memory(alias_idx); 770 } 771 continue; // (a) advance through independent store memory 772 } 773 774 // (b) at this point, if we are not looking at a store initializing 775 // the same allocation we are loading from, we lose. 776 if (known_identical) { 777 // From caller, can_see_stored_value will consult find_captured_store. 778 return mem; // let caller handle steps (c), (d) 779 } 780 781 } else if (find_previous_arraycopy(phase, alloc, mem, false) != nullptr) { 782 if (prev != mem) { 783 // Found an arraycopy but it doesn't affect that load 784 continue; 785 } 786 // Found an arraycopy that may affect that load 787 return mem; 788 } else if (addr_t != nullptr && addr_t->is_known_instance_field()) { 789 // Can't use optimize_simple_memory_chain() since it needs PhaseGVN. 790 if (mem->is_Proj() && mem->in(0)->is_Call()) { 791 // ArrayCopyNodes processed here as well. 792 CallNode *call = mem->in(0)->as_Call(); 793 if (!call->may_modify(addr_t, phase)) { 794 mem = call->in(TypeFunc::Memory); 795 continue; // (a) advance through independent call memory 796 } 797 } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) { 798 ArrayCopyNode* ac = nullptr; 799 if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase, ac)) { 800 break; 801 } 802 mem = mem->in(0)->in(TypeFunc::Memory); 803 continue; // (a) advance through independent MemBar memory 804 } else if (mem->is_ClearArray()) { 805 if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) { 806 // (the call updated 'mem' value) 807 continue; // (a) advance through independent allocation memory 808 } else { 809 // Can not bypass initialization of the instance 810 // we are looking for. 811 return mem; 812 } 813 } else if (mem->is_MergeMem()) { 814 int alias_idx = phase->C->get_alias_index(adr_type()); 815 mem = mem->as_MergeMem()->memory_at(alias_idx); 816 continue; // (a) advance through independent MergeMem memory 817 } 818 } 819 820 // Unless there is an explicit 'continue', we must bail out here, 821 // because 'mem' is an inscrutable memory state (e.g., a call). 822 break; 823 } 824 825 return nullptr; // bail out 826 } 827 828 //----------------------calculate_adr_type------------------------------------- 829 // Helper function. Notices when the given type of address hits top or bottom. 830 // Also, asserts a cross-check of the type against the expected address type. 831 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) { 832 if (t == Type::TOP) return nullptr; // does not touch memory any more? 833 #ifdef ASSERT 834 if (!VerifyAliases || VMError::is_error_reported() || Node::in_dump()) cross_check = nullptr; 835 #endif 836 const TypePtr* tp = t->isa_ptr(); 837 if (tp == nullptr) { 838 assert(cross_check == nullptr || cross_check == TypePtr::BOTTOM, "expected memory type must be wide"); 839 return TypePtr::BOTTOM; // touches lots of memory 840 } else { 841 #ifdef ASSERT 842 // %%%% [phh] We don't check the alias index if cross_check is 843 // TypeRawPtr::BOTTOM. Needs to be investigated. 844 if (cross_check != nullptr && 845 cross_check != TypePtr::BOTTOM && 846 cross_check != TypeRawPtr::BOTTOM) { 847 // Recheck the alias index, to see if it has changed (due to a bug). 848 Compile* C = Compile::current(); 849 assert(C->get_alias_index(cross_check) == C->get_alias_index(tp), 850 "must stay in the original alias category"); 851 // The type of the address must be contained in the adr_type, 852 // disregarding "null"-ness. 853 // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.) 854 const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr(); 855 assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(), 856 "real address must not escape from expected memory type"); 857 } 858 #endif 859 return tp; 860 } 861 } 862 863 uint8_t MemNode::barrier_data(const Node* n) { 864 if (n->is_LoadStore()) { 865 return n->as_LoadStore()->barrier_data(); 866 } else if (n->is_Mem()) { 867 return n->as_Mem()->barrier_data(); 868 } 869 return 0; 870 } 871 872 //============================================================================= 873 // Should LoadNode::Ideal() attempt to remove control edges? 874 bool LoadNode::can_remove_control() const { 875 return !has_pinned_control_dependency(); 876 } 877 uint LoadNode::size_of() const { return sizeof(*this); } 878 bool LoadNode::cmp(const Node &n) const { 879 LoadNode& load = (LoadNode &)n; 880 return Type::equals(_type, load._type) && 881 _control_dependency == load._control_dependency && 882 _mo == load._mo; 883 } 884 const Type *LoadNode::bottom_type() const { return _type; } 885 uint LoadNode::ideal_reg() const { 886 return _type->ideal_reg(); 887 } 888 889 #ifndef PRODUCT 890 void LoadNode::dump_spec(outputStream *st) const { 891 MemNode::dump_spec(st); 892 if( !Verbose && !WizardMode ) { 893 // standard dump does this in Verbose and WizardMode 894 st->print(" #"); _type->dump_on(st); 895 } 896 if (!depends_only_on_test()) { 897 st->print(" (does not depend only on test, "); 898 if (control_dependency() == UnknownControl) { 899 st->print("unknown control"); 900 } else if (control_dependency() == Pinned) { 901 st->print("pinned"); 902 } else if (adr_type() == TypeRawPtr::BOTTOM) { 903 st->print("raw access"); 904 } else { 905 st->print("unknown reason"); 906 } 907 st->print(")"); 908 } 909 } 910 #endif 911 912 #ifdef ASSERT 913 //----------------------------is_immutable_value------------------------------- 914 // Helper function to allow a raw load without control edge for some cases 915 bool LoadNode::is_immutable_value(Node* adr) { 916 if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() && 917 adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal) { 918 919 jlong offset = adr->in(AddPNode::Offset)->find_intptr_t_con(-1); 920 int offsets[] = { 921 in_bytes(JavaThread::osthread_offset()), 922 in_bytes(JavaThread::threadObj_offset()), 923 in_bytes(JavaThread::vthread_offset()), 924 in_bytes(JavaThread::scopedValueCache_offset()), 925 }; 926 927 for (size_t i = 0; i < sizeof offsets / sizeof offsets[0]; i++) { 928 if (offset == offsets[i]) { 929 return true; 930 } 931 } 932 } 933 934 return false; 935 } 936 #endif 937 938 //----------------------------LoadNode::make----------------------------------- 939 // Polymorphic factory method: 940 Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, BasicType bt, MemOrd mo, 941 ControlDependency control_dependency, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) { 942 Compile* C = gvn.C; 943 944 // sanity check the alias category against the created node type 945 assert(!(adr_type->isa_oopptr() && 946 adr_type->offset() == oopDesc::klass_offset_in_bytes()), 947 "use LoadKlassNode instead"); 948 assert(!(adr_type->isa_aryptr() && 949 adr_type->offset() == arrayOopDesc::length_offset_in_bytes()), 950 "use LoadRangeNode instead"); 951 // Check control edge of raw loads 952 assert( ctl != nullptr || C->get_alias_index(adr_type) != Compile::AliasIdxRaw || 953 // oop will be recorded in oop map if load crosses safepoint 954 rt->isa_oopptr() || is_immutable_value(adr), 955 "raw memory operations should have control edge"); 956 LoadNode* load = nullptr; 957 switch (bt) { 958 case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 959 case T_BYTE: load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 960 case T_INT: load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 961 case T_CHAR: load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 962 case T_SHORT: load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 963 case T_LONG: load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic_access); break; 964 case T_FLOAT: load = new LoadFNode (ctl, mem, adr, adr_type, rt, mo, control_dependency); break; 965 case T_DOUBLE: load = new LoadDNode (ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic_access); break; 966 case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency); break; 967 case T_OBJECT: 968 case T_NARROWOOP: 969 #ifdef _LP64 970 if (adr->bottom_type()->is_ptr_to_narrowoop()) { 971 load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency); 972 } else 973 #endif 974 { 975 assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop"); 976 load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency); 977 } 978 break; 979 default: 980 ShouldNotReachHere(); 981 break; 982 } 983 assert(load != nullptr, "LoadNode should have been created"); 984 if (unaligned) { 985 load->set_unaligned_access(); 986 } 987 if (mismatched) { 988 load->set_mismatched_access(); 989 } 990 if (unsafe) { 991 load->set_unsafe_access(); 992 } 993 load->set_barrier_data(barrier_data); 994 if (load->Opcode() == Op_LoadN) { 995 Node* ld = gvn.transform(load); 996 return new DecodeNNode(ld, ld->bottom_type()->make_ptr()); 997 } 998 999 return load; 1000 } 1001 1002 //------------------------------hash------------------------------------------- 1003 uint LoadNode::hash() const { 1004 // unroll addition of interesting fields 1005 return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address); 1006 } 1007 1008 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) { 1009 if ((atp != nullptr) && (atp->index() >= Compile::AliasIdxRaw)) { 1010 bool non_volatile = (atp->field() != nullptr) && !atp->field()->is_volatile(); 1011 bool is_stable_ary = FoldStableValues && 1012 (tp != nullptr) && (tp->isa_aryptr() != nullptr) && 1013 tp->isa_aryptr()->is_stable(); 1014 1015 return (eliminate_boxing && non_volatile) || is_stable_ary; 1016 } 1017 1018 return false; 1019 } 1020 1021 LoadNode* LoadNode::pin_array_access_node() const { 1022 const TypePtr* adr_type = this->adr_type(); 1023 if (adr_type != nullptr && adr_type->isa_aryptr()) { 1024 return clone_pinned(); 1025 } 1026 return nullptr; 1027 } 1028 1029 // Is the value loaded previously stored by an arraycopy? If so return 1030 // a load node that reads from the source array so we may be able to 1031 // optimize out the ArrayCopy node later. 1032 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const { 1033 Node* ld_adr = in(MemNode::Address); 1034 intptr_t ld_off = 0; 1035 AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off); 1036 Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true); 1037 if (ac != nullptr) { 1038 assert(ac->is_ArrayCopy(), "what kind of node can this be?"); 1039 1040 Node* mem = ac->in(TypeFunc::Memory); 1041 Node* ctl = ac->in(0); 1042 Node* src = ac->in(ArrayCopyNode::Src); 1043 1044 if (!ac->as_ArrayCopy()->is_clonebasic() && !phase->type(src)->isa_aryptr()) { 1045 return nullptr; 1046 } 1047 1048 // load depends on the tests that validate the arraycopy 1049 LoadNode* ld = clone_pinned(); 1050 Node* addp = in(MemNode::Address)->clone(); 1051 if (ac->as_ArrayCopy()->is_clonebasic()) { 1052 assert(ld_alloc != nullptr, "need an alloc"); 1053 assert(addp->is_AddP(), "address must be addp"); 1054 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1055 assert(bs->step_over_gc_barrier(addp->in(AddPNode::Base)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern"); 1056 assert(bs->step_over_gc_barrier(addp->in(AddPNode::Address)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern"); 1057 addp->set_req(AddPNode::Base, src); 1058 addp->set_req(AddPNode::Address, src); 1059 } else { 1060 assert(ac->as_ArrayCopy()->is_arraycopy_validated() || 1061 ac->as_ArrayCopy()->is_copyof_validated() || 1062 ac->as_ArrayCopy()->is_copyofrange_validated(), "only supported cases"); 1063 assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be"); 1064 addp->set_req(AddPNode::Base, src); 1065 addp->set_req(AddPNode::Address, src); 1066 1067 const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr(); 1068 BasicType ary_elem = ary_t->isa_aryptr()->elem()->array_element_basic_type(); 1069 if (is_reference_type(ary_elem, true)) ary_elem = T_OBJECT; 1070 1071 uint header = arrayOopDesc::base_offset_in_bytes(ary_elem); 1072 uint shift = exact_log2(type2aelembytes(ary_elem)); 1073 1074 Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos))); 1075 #ifdef _LP64 1076 diff = phase->transform(new ConvI2LNode(diff)); 1077 #endif 1078 diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift))); 1079 1080 Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff)); 1081 addp->set_req(AddPNode::Offset, offset); 1082 } 1083 addp = phase->transform(addp); 1084 #ifdef ASSERT 1085 const TypePtr* adr_type = phase->type(addp)->is_ptr(); 1086 ld->_adr_type = adr_type; 1087 #endif 1088 ld->set_req(MemNode::Address, addp); 1089 ld->set_req(0, ctl); 1090 ld->set_req(MemNode::Memory, mem); 1091 return ld; 1092 } 1093 return nullptr; 1094 } 1095 1096 1097 //---------------------------can_see_stored_value------------------------------ 1098 // This routine exists to make sure this set of tests is done the same 1099 // everywhere. We need to make a coordinated change: first LoadNode::Ideal 1100 // will change the graph shape in a way which makes memory alive twice at the 1101 // same time (uses the Oracle model of aliasing), then some 1102 // LoadXNode::Identity will fold things back to the equivalence-class model 1103 // of aliasing. 1104 Node* MemNode::can_see_stored_value(Node* st, PhaseValues* phase) const { 1105 Node* ld_adr = in(MemNode::Address); 1106 intptr_t ld_off = 0; 1107 Node* ld_base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ld_off); 1108 Node* ld_alloc = AllocateNode::Ideal_allocation(ld_base); 1109 const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr(); 1110 Compile::AliasType* atp = (tp != nullptr) ? phase->C->alias_type(tp) : nullptr; 1111 // This is more general than load from boxing objects. 1112 if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) { 1113 uint alias_idx = atp->index(); 1114 Node* result = nullptr; 1115 Node* current = st; 1116 // Skip through chains of MemBarNodes checking the MergeMems for 1117 // new states for the slice of this load. Stop once any other 1118 // kind of node is encountered. Loads from final memory can skip 1119 // through any kind of MemBar but normal loads shouldn't skip 1120 // through MemBarAcquire since the could allow them to move out of 1121 // a synchronized region. It is not safe to step over MemBarCPUOrder, 1122 // because alias info above them may be inaccurate (e.g., due to 1123 // mixed/mismatched unsafe accesses). 1124 bool is_final_mem = !atp->is_rewritable(); 1125 while (current->is_Proj()) { 1126 int opc = current->in(0)->Opcode(); 1127 if ((is_final_mem && (opc == Op_MemBarAcquire || 1128 opc == Op_MemBarAcquireLock || 1129 opc == Op_LoadFence)) || 1130 opc == Op_MemBarRelease || 1131 opc == Op_StoreFence || 1132 opc == Op_MemBarReleaseLock || 1133 opc == Op_MemBarStoreStore || 1134 opc == Op_StoreStoreFence) { 1135 Node* mem = current->in(0)->in(TypeFunc::Memory); 1136 if (mem->is_MergeMem()) { 1137 MergeMemNode* merge = mem->as_MergeMem(); 1138 Node* new_st = merge->memory_at(alias_idx); 1139 if (new_st == merge->base_memory()) { 1140 // Keep searching 1141 current = new_st; 1142 continue; 1143 } 1144 // Save the new memory state for the slice and fall through 1145 // to exit. 1146 result = new_st; 1147 } 1148 } 1149 break; 1150 } 1151 if (result != nullptr) { 1152 st = result; 1153 } 1154 } 1155 1156 // Loop around twice in the case Load -> Initialize -> Store. 1157 // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.) 1158 for (int trip = 0; trip <= 1; trip++) { 1159 1160 if (st->is_Store()) { 1161 Node* st_adr = st->in(MemNode::Address); 1162 if (st_adr != ld_adr) { 1163 // Try harder before giving up. Unify base pointers with casts (e.g., raw/non-raw pointers). 1164 intptr_t st_off = 0; 1165 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_off); 1166 if (ld_base == nullptr) return nullptr; 1167 if (st_base == nullptr) return nullptr; 1168 if (!ld_base->eqv_uncast(st_base, /*keep_deps=*/true)) return nullptr; 1169 if (ld_off != st_off) return nullptr; 1170 if (ld_off == Type::OffsetBot) return nullptr; 1171 // Same base, same offset. 1172 // Possible improvement for arrays: check index value instead of absolute offset. 1173 1174 // At this point we have proven something like this setup: 1175 // B = << base >> 1176 // L = LoadQ(AddP(Check/CastPP(B), #Off)) 1177 // S = StoreQ(AddP( B , #Off), V) 1178 // (Actually, we haven't yet proven the Q's are the same.) 1179 // In other words, we are loading from a casted version of 1180 // the same pointer-and-offset that we stored to. 1181 // Casted version may carry a dependency and it is respected. 1182 // Thus, we are able to replace L by V. 1183 } 1184 // Now prove that we have a LoadQ matched to a StoreQ, for some Q. 1185 if (store_Opcode() != st->Opcode()) { 1186 return nullptr; 1187 } 1188 // LoadVector/StoreVector needs additional check to ensure the types match. 1189 if (st->is_StoreVector()) { 1190 const TypeVect* in_vt = st->as_StoreVector()->vect_type(); 1191 const TypeVect* out_vt = as_LoadVector()->vect_type(); 1192 if (in_vt != out_vt) { 1193 return nullptr; 1194 } 1195 } 1196 return st->in(MemNode::ValueIn); 1197 } 1198 1199 // A load from a freshly-created object always returns zero. 1200 // (This can happen after LoadNode::Ideal resets the load's memory input 1201 // to find_captured_store, which returned InitializeNode::zero_memory.) 1202 if (st->is_Proj() && st->in(0)->is_Allocate() && 1203 (st->in(0) == ld_alloc) && 1204 (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) { 1205 // return a zero value for the load's basic type 1206 // (This is one of the few places where a generic PhaseTransform 1207 // can create new nodes. Think of it as lazily manifesting 1208 // virtually pre-existing constants.) 1209 if (memory_type() != T_VOID) { 1210 if (ReduceBulkZeroing || find_array_copy_clone(ld_alloc, in(MemNode::Memory)) == nullptr) { 1211 // If ReduceBulkZeroing is disabled, we need to check if the allocation does not belong to an 1212 // ArrayCopyNode clone. If it does, then we cannot assume zero since the initialization is done 1213 // by the ArrayCopyNode. 1214 return phase->zerocon(memory_type()); 1215 } 1216 } else { 1217 // TODO: materialize all-zero vector constant 1218 assert(!isa_Load() || as_Load()->type()->isa_vect(), ""); 1219 } 1220 } 1221 1222 // A load from an initialization barrier can match a captured store. 1223 if (st->is_Proj() && st->in(0)->is_Initialize()) { 1224 InitializeNode* init = st->in(0)->as_Initialize(); 1225 AllocateNode* alloc = init->allocation(); 1226 if ((alloc != nullptr) && (alloc == ld_alloc)) { 1227 // examine a captured store value 1228 st = init->find_captured_store(ld_off, memory_size(), phase); 1229 if (st != nullptr) { 1230 continue; // take one more trip around 1231 } 1232 } 1233 } 1234 1235 // Load boxed value from result of valueOf() call is input parameter. 1236 if (this->is_Load() && ld_adr->is_AddP() && 1237 (tp != nullptr) && tp->is_ptr_to_boxed_value()) { 1238 intptr_t ignore = 0; 1239 Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore); 1240 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1241 base = bs->step_over_gc_barrier(base); 1242 if (base != nullptr && base->is_Proj() && 1243 base->as_Proj()->_con == TypeFunc::Parms && 1244 base->in(0)->is_CallStaticJava() && 1245 base->in(0)->as_CallStaticJava()->is_boxing_method()) { 1246 return base->in(0)->in(TypeFunc::Parms); 1247 } 1248 } 1249 1250 break; 1251 } 1252 1253 return nullptr; 1254 } 1255 1256 //----------------------is_instance_field_load_with_local_phi------------------ 1257 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) { 1258 if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl && 1259 in(Address)->is_AddP() ) { 1260 const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr(); 1261 // Only instances and boxed values. 1262 if( t_oop != nullptr && 1263 (t_oop->is_ptr_to_boxed_value() || 1264 t_oop->is_known_instance_field()) && 1265 t_oop->offset() != Type::OffsetBot && 1266 t_oop->offset() != Type::OffsetTop) { 1267 return true; 1268 } 1269 } 1270 return false; 1271 } 1272 1273 //------------------------------Identity--------------------------------------- 1274 // Loads are identity if previous store is to same address 1275 Node* LoadNode::Identity(PhaseGVN* phase) { 1276 // If the previous store-maker is the right kind of Store, and the store is 1277 // to the same address, then we are equal to the value stored. 1278 Node* mem = in(Memory); 1279 Node* value = can_see_stored_value(mem, phase); 1280 if( value ) { 1281 // byte, short & char stores truncate naturally. 1282 // A load has to load the truncated value which requires 1283 // some sort of masking operation and that requires an 1284 // Ideal call instead of an Identity call. 1285 if (memory_size() < BytesPerInt) { 1286 // If the input to the store does not fit with the load's result type, 1287 // it must be truncated via an Ideal call. 1288 if (!phase->type(value)->higher_equal(phase->type(this))) 1289 return this; 1290 } 1291 // (This works even when value is a Con, but LoadNode::Value 1292 // usually runs first, producing the singleton type of the Con.) 1293 if (!has_pinned_control_dependency() || value->is_Con()) { 1294 return value; 1295 } else { 1296 return this; 1297 } 1298 } 1299 1300 if (has_pinned_control_dependency()) { 1301 return this; 1302 } 1303 // Search for an existing data phi which was generated before for the same 1304 // instance's field to avoid infinite generation of phis in a loop. 1305 Node *region = mem->in(0); 1306 if (is_instance_field_load_with_local_phi(region)) { 1307 const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr(); 1308 int this_index = phase->C->get_alias_index(addr_t); 1309 int this_offset = addr_t->offset(); 1310 int this_iid = addr_t->instance_id(); 1311 if (!addr_t->is_known_instance() && 1312 addr_t->is_ptr_to_boxed_value()) { 1313 // Use _idx of address base (could be Phi node) for boxed values. 1314 intptr_t ignore = 0; 1315 Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore); 1316 if (base == nullptr) { 1317 return this; 1318 } 1319 this_iid = base->_idx; 1320 } 1321 const Type* this_type = bottom_type(); 1322 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 1323 Node* phi = region->fast_out(i); 1324 if (phi->is_Phi() && phi != mem && 1325 phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) { 1326 return phi; 1327 } 1328 } 1329 } 1330 1331 return this; 1332 } 1333 1334 // Construct an equivalent unsigned load. 1335 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) { 1336 BasicType bt = T_ILLEGAL; 1337 const Type* rt = nullptr; 1338 switch (Opcode()) { 1339 case Op_LoadUB: return this; 1340 case Op_LoadUS: return this; 1341 case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break; 1342 case Op_LoadS: bt = T_CHAR; rt = TypeInt::CHAR; break; 1343 default: 1344 assert(false, "no unsigned variant: %s", Name()); 1345 return nullptr; 1346 } 1347 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), 1348 raw_adr_type(), rt, bt, _mo, _control_dependency, 1349 false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access()); 1350 } 1351 1352 // Construct an equivalent signed load. 1353 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) { 1354 BasicType bt = T_ILLEGAL; 1355 const Type* rt = nullptr; 1356 switch (Opcode()) { 1357 case Op_LoadUB: bt = T_BYTE; rt = TypeInt::BYTE; break; 1358 case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break; 1359 case Op_LoadB: // fall through 1360 case Op_LoadS: // fall through 1361 case Op_LoadI: // fall through 1362 case Op_LoadL: return this; 1363 default: 1364 assert(false, "no signed variant: %s", Name()); 1365 return nullptr; 1366 } 1367 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), 1368 raw_adr_type(), rt, bt, _mo, _control_dependency, 1369 false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access()); 1370 } 1371 1372 bool LoadNode::has_reinterpret_variant(const Type* rt) { 1373 BasicType bt = rt->basic_type(); 1374 switch (Opcode()) { 1375 case Op_LoadI: return (bt == T_FLOAT); 1376 case Op_LoadL: return (bt == T_DOUBLE); 1377 case Op_LoadF: return (bt == T_INT); 1378 case Op_LoadD: return (bt == T_LONG); 1379 1380 default: return false; 1381 } 1382 } 1383 1384 Node* LoadNode::convert_to_reinterpret_load(PhaseGVN& gvn, const Type* rt) { 1385 BasicType bt = rt->basic_type(); 1386 assert(has_reinterpret_variant(rt), "no reinterpret variant: %s %s", Name(), type2name(bt)); 1387 bool is_mismatched = is_mismatched_access(); 1388 const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr(); 1389 if (raw_type == nullptr) { 1390 is_mismatched = true; // conservatively match all non-raw accesses as mismatched 1391 } 1392 const int op = Opcode(); 1393 bool require_atomic_access = (op == Op_LoadL && ((LoadLNode*)this)->require_atomic_access()) || 1394 (op == Op_LoadD && ((LoadDNode*)this)->require_atomic_access()); 1395 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), 1396 raw_adr_type(), rt, bt, _mo, _control_dependency, 1397 require_atomic_access, is_unaligned_access(), is_mismatched); 1398 } 1399 1400 bool StoreNode::has_reinterpret_variant(const Type* vt) { 1401 BasicType bt = vt->basic_type(); 1402 switch (Opcode()) { 1403 case Op_StoreI: return (bt == T_FLOAT); 1404 case Op_StoreL: return (bt == T_DOUBLE); 1405 case Op_StoreF: return (bt == T_INT); 1406 case Op_StoreD: return (bt == T_LONG); 1407 1408 default: return false; 1409 } 1410 } 1411 1412 Node* StoreNode::convert_to_reinterpret_store(PhaseGVN& gvn, Node* val, const Type* vt) { 1413 BasicType bt = vt->basic_type(); 1414 assert(has_reinterpret_variant(vt), "no reinterpret variant: %s %s", Name(), type2name(bt)); 1415 const int op = Opcode(); 1416 bool require_atomic_access = (op == Op_StoreL && ((StoreLNode*)this)->require_atomic_access()) || 1417 (op == Op_StoreD && ((StoreDNode*)this)->require_atomic_access()); 1418 StoreNode* st = StoreNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), 1419 raw_adr_type(), val, bt, _mo, require_atomic_access); 1420 1421 bool is_mismatched = is_mismatched_access(); 1422 const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr(); 1423 if (raw_type == nullptr) { 1424 is_mismatched = true; // conservatively match all non-raw accesses as mismatched 1425 } 1426 if (is_mismatched) { 1427 st->set_mismatched_access(); 1428 } 1429 return st; 1430 } 1431 1432 // We're loading from an object which has autobox behaviour. 1433 // If this object is result of a valueOf call we'll have a phi 1434 // merging a newly allocated object and a load from the cache. 1435 // We want to replace this load with the original incoming 1436 // argument to the valueOf call. 1437 Node* LoadNode::eliminate_autobox(PhaseIterGVN* igvn) { 1438 assert(igvn->C->eliminate_boxing(), "sanity"); 1439 intptr_t ignore = 0; 1440 Node* base = AddPNode::Ideal_base_and_offset(in(Address), igvn, ignore); 1441 if ((base == nullptr) || base->is_Phi()) { 1442 // Push the loads from the phi that comes from valueOf up 1443 // through it to allow elimination of the loads and the recovery 1444 // of the original value. It is done in split_through_phi(). 1445 return nullptr; 1446 } else if (base->is_Load() || 1447 (base->is_DecodeN() && base->in(1)->is_Load())) { 1448 // Eliminate the load of boxed value for integer types from the cache 1449 // array by deriving the value from the index into the array. 1450 // Capture the offset of the load and then reverse the computation. 1451 1452 // Get LoadN node which loads a boxing object from 'cache' array. 1453 if (base->is_DecodeN()) { 1454 base = base->in(1); 1455 } 1456 if (!base->in(Address)->is_AddP()) { 1457 return nullptr; // Complex address 1458 } 1459 AddPNode* address = base->in(Address)->as_AddP(); 1460 Node* cache_base = address->in(AddPNode::Base); 1461 if ((cache_base != nullptr) && cache_base->is_DecodeN()) { 1462 // Get ConP node which is static 'cache' field. 1463 cache_base = cache_base->in(1); 1464 } 1465 if ((cache_base != nullptr) && cache_base->is_Con()) { 1466 const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr(); 1467 if ((base_type != nullptr) && base_type->is_autobox_cache()) { 1468 Node* elements[4]; 1469 int shift = exact_log2(type2aelembytes(T_OBJECT)); 1470 int count = address->unpack_offsets(elements, ARRAY_SIZE(elements)); 1471 if (count > 0 && elements[0]->is_Con() && 1472 (count == 1 || 1473 (count == 2 && elements[1]->Opcode() == Op_LShiftX && 1474 elements[1]->in(2) == igvn->intcon(shift)))) { 1475 ciObjArray* array = base_type->const_oop()->as_obj_array(); 1476 // Fetch the box object cache[0] at the base of the array and get its value 1477 ciInstance* box = array->obj_at(0)->as_instance(); 1478 ciInstanceKlass* ik = box->klass()->as_instance_klass(); 1479 assert(ik->is_box_klass(), "sanity"); 1480 assert(ik->nof_nonstatic_fields() == 1, "change following code"); 1481 if (ik->nof_nonstatic_fields() == 1) { 1482 // This should be true nonstatic_field_at requires calling 1483 // nof_nonstatic_fields so check it anyway 1484 ciConstant c = box->field_value(ik->nonstatic_field_at(0)); 1485 BasicType bt = c.basic_type(); 1486 // Only integer types have boxing cache. 1487 assert(bt == T_BOOLEAN || bt == T_CHAR || 1488 bt == T_BYTE || bt == T_SHORT || 1489 bt == T_INT || bt == T_LONG, "wrong type = %s", type2name(bt)); 1490 jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int(); 1491 if (cache_low != (int)cache_low) { 1492 return nullptr; // should not happen since cache is array indexed by value 1493 } 1494 jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift); 1495 if (offset != (int)offset) { 1496 return nullptr; // should not happen since cache is array indexed by value 1497 } 1498 // Add up all the offsets making of the address of the load 1499 Node* result = elements[0]; 1500 for (int i = 1; i < count; i++) { 1501 result = igvn->transform(new AddXNode(result, elements[i])); 1502 } 1503 // Remove the constant offset from the address and then 1504 result = igvn->transform(new AddXNode(result, igvn->MakeConX(-(int)offset))); 1505 // remove the scaling of the offset to recover the original index. 1506 if (result->Opcode() == Op_LShiftX && result->in(2) == igvn->intcon(shift)) { 1507 // Peel the shift off directly but wrap it in a dummy node 1508 // since Ideal can't return existing nodes 1509 igvn->_worklist.push(result); // remove dead node later 1510 result = new RShiftXNode(result->in(1), igvn->intcon(0)); 1511 } else if (result->is_Add() && result->in(2)->is_Con() && 1512 result->in(1)->Opcode() == Op_LShiftX && 1513 result->in(1)->in(2) == igvn->intcon(shift)) { 1514 // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z) 1515 // but for boxing cache access we know that X<<Z will not overflow 1516 // (there is range check) so we do this optimizatrion by hand here. 1517 igvn->_worklist.push(result); // remove dead node later 1518 Node* add_con = new RShiftXNode(result->in(2), igvn->intcon(shift)); 1519 result = new AddXNode(result->in(1)->in(1), igvn->transform(add_con)); 1520 } else { 1521 result = new RShiftXNode(result, igvn->intcon(shift)); 1522 } 1523 #ifdef _LP64 1524 if (bt != T_LONG) { 1525 result = new ConvL2INode(igvn->transform(result)); 1526 } 1527 #else 1528 if (bt == T_LONG) { 1529 result = new ConvI2LNode(igvn->transform(result)); 1530 } 1531 #endif 1532 // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair). 1533 // Need to preserve unboxing load type if it is unsigned. 1534 switch(this->Opcode()) { 1535 case Op_LoadUB: 1536 result = new AndINode(igvn->transform(result), igvn->intcon(0xFF)); 1537 break; 1538 case Op_LoadUS: 1539 result = new AndINode(igvn->transform(result), igvn->intcon(0xFFFF)); 1540 break; 1541 } 1542 return result; 1543 } 1544 } 1545 } 1546 } 1547 } 1548 return nullptr; 1549 } 1550 1551 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) { 1552 Node* region = phi->in(0); 1553 if (region == nullptr) { 1554 return false; // Wait stable graph 1555 } 1556 uint cnt = phi->req(); 1557 for (uint i = 1; i < cnt; i++) { 1558 Node* rc = region->in(i); 1559 if (rc == nullptr || phase->type(rc) == Type::TOP) 1560 return false; // Wait stable graph 1561 Node* in = phi->in(i); 1562 if (in == nullptr || phase->type(in) == Type::TOP) 1563 return false; // Wait stable graph 1564 } 1565 return true; 1566 } 1567 1568 //------------------------------split_through_phi------------------------------ 1569 // Check whether a call to 'split_through_phi' would split this load through the 1570 // Phi *base*. This method is essentially a copy of the validations performed 1571 // by 'split_through_phi'. The first use of this method was in EA code as part 1572 // of simplification of allocation merges. 1573 // Some differences from original method (split_through_phi): 1574 // - If base->is_CastPP(): base = base->in(1) 1575 bool LoadNode::can_split_through_phi_base(PhaseGVN* phase) { 1576 Node* mem = in(Memory); 1577 Node* address = in(Address); 1578 intptr_t ignore = 0; 1579 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore); 1580 1581 if (base->is_CastPP()) { 1582 base = base->in(1); 1583 } 1584 1585 if (req() > 3 || base == nullptr || !base->is_Phi()) { 1586 return false; 1587 } 1588 1589 if (!mem->is_Phi()) { 1590 if (!MemNode::all_controls_dominate(mem, base->in(0))) { 1591 return false; 1592 } 1593 } else if (base->in(0) != mem->in(0)) { 1594 if (!MemNode::all_controls_dominate(mem, base->in(0))) { 1595 return false; 1596 } 1597 } 1598 1599 return true; 1600 } 1601 1602 //------------------------------split_through_phi------------------------------ 1603 // Split instance or boxed field load through Phi. 1604 Node* LoadNode::split_through_phi(PhaseGVN* phase, bool ignore_missing_instance_id) { 1605 if (req() > 3) { 1606 assert(is_LoadVector() && Opcode() != Op_LoadVector, "load has too many inputs"); 1607 // LoadVector subclasses such as LoadVectorMasked have extra inputs that the logic below doesn't take into account 1608 return nullptr; 1609 } 1610 Node* mem = in(Memory); 1611 Node* address = in(Address); 1612 const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr(); 1613 1614 assert((t_oop != nullptr) && 1615 (ignore_missing_instance_id || 1616 t_oop->is_known_instance_field() || 1617 t_oop->is_ptr_to_boxed_value()), "invalid conditions"); 1618 1619 Compile* C = phase->C; 1620 intptr_t ignore = 0; 1621 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore); 1622 bool base_is_phi = (base != nullptr) && base->is_Phi(); 1623 bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() && 1624 (base != nullptr) && (base == address->in(AddPNode::Base)) && 1625 phase->type(base)->higher_equal(TypePtr::NOTNULL); 1626 1627 if (!((mem->is_Phi() || base_is_phi) && 1628 (ignore_missing_instance_id || load_boxed_values || t_oop->is_known_instance_field()))) { 1629 return nullptr; // Neither memory or base are Phi 1630 } 1631 1632 if (mem->is_Phi()) { 1633 if (!stable_phi(mem->as_Phi(), phase)) { 1634 return nullptr; // Wait stable graph 1635 } 1636 uint cnt = mem->req(); 1637 // Check for loop invariant memory. 1638 if (cnt == 3) { 1639 for (uint i = 1; i < cnt; i++) { 1640 Node* in = mem->in(i); 1641 Node* m = optimize_memory_chain(in, t_oop, this, phase); 1642 if (m == mem) { 1643 if (i == 1) { 1644 // if the first edge was a loop, check second edge too. 1645 // If both are replaceable - we are in an infinite loop 1646 Node *n = optimize_memory_chain(mem->in(2), t_oop, this, phase); 1647 if (n == mem) { 1648 break; 1649 } 1650 } 1651 set_req(Memory, mem->in(cnt - i)); 1652 return this; // made change 1653 } 1654 } 1655 } 1656 } 1657 if (base_is_phi) { 1658 if (!stable_phi(base->as_Phi(), phase)) { 1659 return nullptr; // Wait stable graph 1660 } 1661 uint cnt = base->req(); 1662 // Check for loop invariant memory. 1663 if (cnt == 3) { 1664 for (uint i = 1; i < cnt; i++) { 1665 if (base->in(i) == base) { 1666 return nullptr; // Wait stable graph 1667 } 1668 } 1669 } 1670 } 1671 1672 // Split through Phi (see original code in loopopts.cpp). 1673 assert(ignore_missing_instance_id || C->have_alias_type(t_oop), "instance should have alias type"); 1674 1675 // Do nothing here if Identity will find a value 1676 // (to avoid infinite chain of value phis generation). 1677 if (this != Identity(phase)) { 1678 return nullptr; 1679 } 1680 1681 // Select Region to split through. 1682 Node* region; 1683 DomResult dom_result = DomResult::Dominate; 1684 if (!base_is_phi) { 1685 assert(mem->is_Phi(), "sanity"); 1686 region = mem->in(0); 1687 // Skip if the region dominates some control edge of the address. 1688 // We will check `dom_result` later. 1689 dom_result = MemNode::maybe_all_controls_dominate(address, region); 1690 } else if (!mem->is_Phi()) { 1691 assert(base_is_phi, "sanity"); 1692 region = base->in(0); 1693 // Skip if the region dominates some control edge of the memory. 1694 // We will check `dom_result` later. 1695 dom_result = MemNode::maybe_all_controls_dominate(mem, region); 1696 } else if (base->in(0) != mem->in(0)) { 1697 assert(base_is_phi && mem->is_Phi(), "sanity"); 1698 dom_result = MemNode::maybe_all_controls_dominate(mem, base->in(0)); 1699 if (dom_result == DomResult::Dominate) { 1700 region = base->in(0); 1701 } else { 1702 dom_result = MemNode::maybe_all_controls_dominate(address, mem->in(0)); 1703 if (dom_result == DomResult::Dominate) { 1704 region = mem->in(0); 1705 } 1706 // Otherwise we encountered a complex graph. 1707 } 1708 } else { 1709 assert(base->in(0) == mem->in(0), "sanity"); 1710 region = mem->in(0); 1711 } 1712 1713 PhaseIterGVN* igvn = phase->is_IterGVN(); 1714 if (dom_result != DomResult::Dominate) { 1715 if (dom_result == DomResult::EncounteredDeadCode) { 1716 // There is some dead code which eventually will be removed in IGVN. 1717 // Once this is the case, we get an unambiguous dominance result. 1718 // Push the node to the worklist again until the dead code is removed. 1719 igvn->_worklist.push(this); 1720 } 1721 return nullptr; 1722 } 1723 1724 Node* phi = nullptr; 1725 const Type* this_type = this->bottom_type(); 1726 if (t_oop != nullptr && (t_oop->is_known_instance_field() || load_boxed_values)) { 1727 int this_index = C->get_alias_index(t_oop); 1728 int this_offset = t_oop->offset(); 1729 int this_iid = t_oop->is_known_instance_field() ? t_oop->instance_id() : base->_idx; 1730 phi = new PhiNode(region, this_type, nullptr, mem->_idx, this_iid, this_index, this_offset); 1731 } else if (ignore_missing_instance_id) { 1732 phi = new PhiNode(region, this_type, nullptr, mem->_idx); 1733 } else { 1734 return nullptr; 1735 } 1736 1737 for (uint i = 1; i < region->req(); i++) { 1738 Node* x; 1739 Node* the_clone = nullptr; 1740 Node* in = region->in(i); 1741 if (region->is_CountedLoop() && region->as_Loop()->is_strip_mined() && i == LoopNode::EntryControl && 1742 in != nullptr && in->is_OuterStripMinedLoop()) { 1743 // No node should go in the outer strip mined loop 1744 in = in->in(LoopNode::EntryControl); 1745 } 1746 if (in == nullptr || in == C->top()) { 1747 x = C->top(); // Dead path? Use a dead data op 1748 } else { 1749 x = this->clone(); // Else clone up the data op 1750 the_clone = x; // Remember for possible deletion. 1751 // Alter data node to use pre-phi inputs 1752 if (this->in(0) == region) { 1753 x->set_req(0, in); 1754 } else { 1755 x->set_req(0, nullptr); 1756 } 1757 if (mem->is_Phi() && (mem->in(0) == region)) { 1758 x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone. 1759 } 1760 if (address->is_Phi() && address->in(0) == region) { 1761 x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone 1762 } 1763 if (base_is_phi && (base->in(0) == region)) { 1764 Node* base_x = base->in(i); // Clone address for loads from boxed objects. 1765 Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset))); 1766 x->set_req(Address, adr_x); 1767 } 1768 } 1769 // Check for a 'win' on some paths 1770 const Type *t = x->Value(igvn); 1771 1772 bool singleton = t->singleton(); 1773 1774 // See comments in PhaseIdealLoop::split_thru_phi(). 1775 if (singleton && t == Type::TOP) { 1776 singleton &= region->is_Loop() && (i != LoopNode::EntryControl); 1777 } 1778 1779 if (singleton) { 1780 x = igvn->makecon(t); 1781 } else { 1782 // We now call Identity to try to simplify the cloned node. 1783 // Note that some Identity methods call phase->type(this). 1784 // Make sure that the type array is big enough for 1785 // our new node, even though we may throw the node away. 1786 // (This tweaking with igvn only works because x is a new node.) 1787 igvn->set_type(x, t); 1788 // If x is a TypeNode, capture any more-precise type permanently into Node 1789 // otherwise it will be not updated during igvn->transform since 1790 // igvn->type(x) is set to x->Value() already. 1791 x->raise_bottom_type(t); 1792 Node* y = x->Identity(igvn); 1793 if (y != x) { 1794 x = y; 1795 } else { 1796 y = igvn->hash_find_insert(x); 1797 if (y) { 1798 x = y; 1799 } else { 1800 // Else x is a new node we are keeping 1801 // We do not need register_new_node_with_optimizer 1802 // because set_type has already been called. 1803 igvn->_worklist.push(x); 1804 } 1805 } 1806 } 1807 if (x != the_clone && the_clone != nullptr) { 1808 igvn->remove_dead_node(the_clone); 1809 } 1810 phi->set_req(i, x); 1811 } 1812 // Record Phi 1813 igvn->register_new_node_with_optimizer(phi); 1814 return phi; 1815 } 1816 1817 AllocateNode* LoadNode::is_new_object_mark_load() const { 1818 if (Opcode() == Op_LoadX) { 1819 Node* address = in(MemNode::Address); 1820 AllocateNode* alloc = AllocateNode::Ideal_allocation(address); 1821 Node* mem = in(MemNode::Memory); 1822 if (alloc != nullptr && mem->is_Proj() && 1823 mem->in(0) != nullptr && 1824 mem->in(0) == alloc->initialization() && 1825 alloc->initialization()->proj_out_or_null(0) != nullptr) { 1826 return alloc; 1827 } 1828 } 1829 return nullptr; 1830 } 1831 1832 1833 //------------------------------Ideal------------------------------------------ 1834 // If the load is from Field memory and the pointer is non-null, it might be possible to 1835 // zero out the control input. 1836 // If the offset is constant and the base is an object allocation, 1837 // try to hook me up to the exact initializing store. 1838 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) { 1839 if (has_pinned_control_dependency()) { 1840 return nullptr; 1841 } 1842 Node* p = MemNode::Ideal_common(phase, can_reshape); 1843 if (p) return (p == NodeSentinel) ? nullptr : p; 1844 1845 Node* ctrl = in(MemNode::Control); 1846 Node* address = in(MemNode::Address); 1847 bool progress = false; 1848 1849 bool addr_mark = ((phase->type(address)->isa_oopptr() || phase->type(address)->isa_narrowoop()) && 1850 phase->type(address)->is_ptr()->offset() == oopDesc::mark_offset_in_bytes()); 1851 1852 // Skip up past a SafePoint control. Cannot do this for Stores because 1853 // pointer stores & cardmarks must stay on the same side of a SafePoint. 1854 if( ctrl != nullptr && ctrl->Opcode() == Op_SafePoint && 1855 phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw && 1856 !addr_mark && 1857 (depends_only_on_test() || has_unknown_control_dependency())) { 1858 ctrl = ctrl->in(0); 1859 set_req(MemNode::Control,ctrl); 1860 progress = true; 1861 } 1862 1863 intptr_t ignore = 0; 1864 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore); 1865 if (base != nullptr 1866 && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) { 1867 // Check for useless control edge in some common special cases 1868 if (in(MemNode::Control) != nullptr 1869 && can_remove_control() 1870 && phase->type(base)->higher_equal(TypePtr::NOTNULL) 1871 && all_controls_dominate(base, phase->C->start())) { 1872 // A method-invariant, non-null address (constant or 'this' argument). 1873 set_req(MemNode::Control, nullptr); 1874 progress = true; 1875 } 1876 } 1877 1878 Node* mem = in(MemNode::Memory); 1879 const TypePtr *addr_t = phase->type(address)->isa_ptr(); 1880 1881 if (can_reshape && (addr_t != nullptr)) { 1882 // try to optimize our memory input 1883 Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase); 1884 if (opt_mem != mem) { 1885 set_req_X(MemNode::Memory, opt_mem, phase); 1886 if (phase->type( opt_mem ) == Type::TOP) return nullptr; 1887 return this; 1888 } 1889 const TypeOopPtr *t_oop = addr_t->isa_oopptr(); 1890 if ((t_oop != nullptr) && 1891 (t_oop->is_known_instance_field() || 1892 t_oop->is_ptr_to_boxed_value())) { 1893 PhaseIterGVN *igvn = phase->is_IterGVN(); 1894 assert(igvn != nullptr, "must be PhaseIterGVN when can_reshape is true"); 1895 if (igvn->_worklist.member(opt_mem)) { 1896 // Delay this transformation until memory Phi is processed. 1897 igvn->_worklist.push(this); 1898 return nullptr; 1899 } 1900 // Split instance field load through Phi. 1901 Node* result = split_through_phi(phase); 1902 if (result != nullptr) return result; 1903 1904 if (t_oop->is_ptr_to_boxed_value()) { 1905 Node* result = eliminate_autobox(igvn); 1906 if (result != nullptr) return result; 1907 } 1908 } 1909 } 1910 1911 // Is there a dominating load that loads the same value? Leave 1912 // anything that is not a load of a field/array element (like 1913 // barriers etc.) alone 1914 if (in(0) != nullptr && !adr_type()->isa_rawptr() && can_reshape) { 1915 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) { 1916 Node *use = mem->fast_out(i); 1917 if (use != this && 1918 use->Opcode() == Opcode() && 1919 use->in(0) != nullptr && 1920 use->in(0) != in(0) && 1921 use->in(Address) == in(Address)) { 1922 Node* ctl = in(0); 1923 for (int i = 0; i < 10 && ctl != nullptr; i++) { 1924 ctl = IfNode::up_one_dom(ctl); 1925 if (ctl == use->in(0)) { 1926 set_req(0, use->in(0)); 1927 return this; 1928 } 1929 } 1930 } 1931 } 1932 } 1933 1934 // Check for prior store with a different base or offset; make Load 1935 // independent. Skip through any number of them. Bail out if the stores 1936 // are in an endless dead cycle and report no progress. This is a key 1937 // transform for Reflection. However, if after skipping through the Stores 1938 // we can't then fold up against a prior store do NOT do the transform as 1939 // this amounts to using the 'Oracle' model of aliasing. It leaves the same 1940 // array memory alive twice: once for the hoisted Load and again after the 1941 // bypassed Store. This situation only works if EVERYBODY who does 1942 // anti-dependence work knows how to bypass. I.e. we need all 1943 // anti-dependence checks to ask the same Oracle. Right now, that Oracle is 1944 // the alias index stuff. So instead, peek through Stores and IFF we can 1945 // fold up, do so. 1946 Node* prev_mem = find_previous_store(phase); 1947 if (prev_mem != nullptr) { 1948 Node* value = can_see_arraycopy_value(prev_mem, phase); 1949 if (value != nullptr) { 1950 return value; 1951 } 1952 } 1953 // Steps (a), (b): Walk past independent stores to find an exact match. 1954 if (prev_mem != nullptr && prev_mem != in(MemNode::Memory)) { 1955 // (c) See if we can fold up on the spot, but don't fold up here. 1956 // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or 1957 // just return a prior value, which is done by Identity calls. 1958 if (can_see_stored_value(prev_mem, phase)) { 1959 // Make ready for step (d): 1960 set_req_X(MemNode::Memory, prev_mem, phase); 1961 return this; 1962 } 1963 } 1964 1965 return progress ? this : nullptr; 1966 } 1967 1968 // Helper to recognize certain Klass fields which are invariant across 1969 // some group of array types (e.g., int[] or all T[] where T < Object). 1970 const Type* 1971 LoadNode::load_array_final_field(const TypeKlassPtr *tkls, 1972 ciKlass* klass) const { 1973 assert(!UseCompactObjectHeaders || tkls->offset() != in_bytes(Klass::prototype_header_offset()), 1974 "must not happen"); 1975 if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) { 1976 // The field is Klass::_modifier_flags. Return its (constant) value. 1977 // (Folds up the 2nd indirection in aClassConstant.getModifiers().) 1978 assert(Opcode() == Op_LoadUS, "must load an unsigned short from _modifier_flags"); 1979 return TypeInt::make(klass->modifier_flags()); 1980 } 1981 if (tkls->offset() == in_bytes(Klass::access_flags_offset())) { 1982 // The field is Klass::_access_flags. Return its (constant) value. 1983 // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).) 1984 assert(Opcode() == Op_LoadUS, "must load an unsigned short from _access_flags"); 1985 return TypeInt::make(klass->access_flags()); 1986 } 1987 if (tkls->offset() == in_bytes(Klass::misc_flags_offset())) { 1988 // The field is Klass::_misc_flags. Return its (constant) value. 1989 // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).) 1990 assert(Opcode() == Op_LoadUB, "must load an unsigned byte from _misc_flags"); 1991 return TypeInt::make(klass->misc_flags()); 1992 } 1993 if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) { 1994 // The field is Klass::_layout_helper. Return its constant value if known. 1995 assert(Opcode() == Op_LoadI, "must load an int from _layout_helper"); 1996 return TypeInt::make(klass->layout_helper()); 1997 } 1998 1999 // No match. 2000 return nullptr; 2001 } 2002 2003 //------------------------------Value----------------------------------------- 2004 const Type* LoadNode::Value(PhaseGVN* phase) const { 2005 // Either input is TOP ==> the result is TOP 2006 Node* mem = in(MemNode::Memory); 2007 const Type *t1 = phase->type(mem); 2008 if (t1 == Type::TOP) return Type::TOP; 2009 Node* adr = in(MemNode::Address); 2010 const TypePtr* tp = phase->type(adr)->isa_ptr(); 2011 if (tp == nullptr || tp->empty()) return Type::TOP; 2012 int off = tp->offset(); 2013 assert(off != Type::OffsetTop, "case covered by TypePtr::empty"); 2014 Compile* C = phase->C; 2015 2016 // If we are loading from a freshly-allocated object, produce a zero, 2017 // if the load is provably beyond the header of the object. 2018 // (Also allow a variable load from a fresh array to produce zero.) 2019 const TypeOopPtr* tinst = tp->isa_oopptr(); 2020 bool is_instance = (tinst != nullptr) && tinst->is_known_instance_field(); 2021 Node* value = can_see_stored_value(mem, phase); 2022 if (value != nullptr && value->is_Con()) { 2023 assert(value->bottom_type()->higher_equal(_type), "sanity"); 2024 return value->bottom_type(); 2025 } 2026 2027 // Try to guess loaded type from pointer type 2028 if (tp->isa_aryptr()) { 2029 const TypeAryPtr* ary = tp->is_aryptr(); 2030 const Type* t = ary->elem(); 2031 2032 // Determine whether the reference is beyond the header or not, by comparing 2033 // the offset against the offset of the start of the array's data. 2034 // Different array types begin at slightly different offsets (12 vs. 16). 2035 // We choose T_BYTE as an example base type that is least restrictive 2036 // as to alignment, which will therefore produce the smallest 2037 // possible base offset. 2038 const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE); 2039 const bool off_beyond_header = (off >= min_base_off); 2040 2041 // Try to constant-fold a stable array element. 2042 if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) { 2043 // Make sure the reference is not into the header and the offset is constant 2044 ciObject* aobj = ary->const_oop(); 2045 if (aobj != nullptr && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) { 2046 int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0); 2047 const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off, 2048 stable_dimension, 2049 memory_type(), is_unsigned()); 2050 if (con_type != nullptr) { 2051 return con_type; 2052 } 2053 } 2054 } 2055 2056 // Don't do this for integer types. There is only potential profit if 2057 // the element type t is lower than _type; that is, for int types, if _type is 2058 // more restrictive than t. This only happens here if one is short and the other 2059 // char (both 16 bits), and in those cases we've made an intentional decision 2060 // to use one kind of load over the other. See AndINode::Ideal and 4965907. 2061 // Also, do not try to narrow the type for a LoadKlass, regardless of offset. 2062 // 2063 // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8)) 2064 // where the _gvn.type of the AddP is wider than 8. This occurs when an earlier 2065 // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been 2066 // subsumed by p1. If p1 is on the worklist but has not yet been re-transformed, 2067 // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any. 2068 // In fact, that could have been the original type of p1, and p1 could have 2069 // had an original form like p1:(AddP x x (LShiftL quux 3)), where the 2070 // expression (LShiftL quux 3) independently optimized to the constant 8. 2071 if ((t->isa_int() == nullptr) && (t->isa_long() == nullptr) 2072 && (_type->isa_vect() == nullptr) 2073 && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) { 2074 // t might actually be lower than _type, if _type is a unique 2075 // concrete subclass of abstract class t. 2076 if (off_beyond_header || off == Type::OffsetBot) { // is the offset beyond the header? 2077 const Type* jt = t->join_speculative(_type); 2078 // In any case, do not allow the join, per se, to empty out the type. 2079 if (jt->empty() && !t->empty()) { 2080 // This can happen if a interface-typed array narrows to a class type. 2081 jt = _type; 2082 } 2083 #ifdef ASSERT 2084 if (phase->C->eliminate_boxing() && adr->is_AddP()) { 2085 // The pointers in the autobox arrays are always non-null 2086 Node* base = adr->in(AddPNode::Base); 2087 if ((base != nullptr) && base->is_DecodeN()) { 2088 // Get LoadN node which loads IntegerCache.cache field 2089 base = base->in(1); 2090 } 2091 if ((base != nullptr) && base->is_Con()) { 2092 const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr(); 2093 if ((base_type != nullptr) && base_type->is_autobox_cache()) { 2094 // It could be narrow oop 2095 assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity"); 2096 } 2097 } 2098 } 2099 #endif 2100 return jt; 2101 } 2102 } 2103 } else if (tp->base() == Type::InstPtr) { 2104 assert( off != Type::OffsetBot || 2105 // arrays can be cast to Objects 2106 !tp->isa_instptr() || 2107 tp->is_instptr()->instance_klass()->is_java_lang_Object() || 2108 // unsafe field access may not have a constant offset 2109 C->has_unsafe_access(), 2110 "Field accesses must be precise" ); 2111 // For oop loads, we expect the _type to be precise. 2112 2113 // Optimize loads from constant fields. 2114 const TypeInstPtr* tinst = tp->is_instptr(); 2115 ciObject* const_oop = tinst->const_oop(); 2116 if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != nullptr && const_oop->is_instance()) { 2117 const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), memory_type()); 2118 if (con_type != nullptr) { 2119 return con_type; 2120 } 2121 } 2122 } else if (tp->base() == Type::KlassPtr || tp->base() == Type::InstKlassPtr || tp->base() == Type::AryKlassPtr) { 2123 assert(off != Type::OffsetBot || 2124 !tp->isa_instklassptr() || 2125 // arrays can be cast to Objects 2126 tp->isa_instklassptr()->instance_klass()->is_java_lang_Object() || 2127 // also allow array-loading from the primary supertype 2128 // array during subtype checks 2129 Opcode() == Op_LoadKlass, 2130 "Field accesses must be precise"); 2131 // For klass/static loads, we expect the _type to be precise 2132 } else if (tp->base() == Type::RawPtr && adr->is_Load() && off == 0) { 2133 /* With mirrors being an indirect in the Klass* 2134 * the VM is now using two loads. LoadKlass(LoadP(LoadP(Klass, mirror_offset), zero_offset)) 2135 * The LoadP from the Klass has a RawPtr type (see LibraryCallKit::load_mirror_from_klass). 2136 * 2137 * So check the type and klass of the node before the LoadP. 2138 */ 2139 Node* adr2 = adr->in(MemNode::Address); 2140 const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr(); 2141 if (tkls != nullptr && !StressReflectiveCode) { 2142 if (tkls->is_loaded() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::java_mirror_offset())) { 2143 ciKlass* klass = tkls->exact_klass(); 2144 assert(adr->Opcode() == Op_LoadP, "must load an oop from _java_mirror"); 2145 assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror"); 2146 return TypeInstPtr::make(klass->java_mirror()); 2147 } 2148 } 2149 } 2150 2151 const TypeKlassPtr *tkls = tp->isa_klassptr(); 2152 if (tkls != nullptr) { 2153 if (tkls->is_loaded() && tkls->klass_is_exact()) { 2154 ciKlass* klass = tkls->exact_klass(); 2155 // We are loading a field from a Klass metaobject whose identity 2156 // is known at compile time (the type is "exact" or "precise"). 2157 // Check for fields we know are maintained as constants by the VM. 2158 if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) { 2159 // The field is Klass::_super_check_offset. Return its (constant) value. 2160 // (Folds up type checking code.) 2161 assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset"); 2162 return TypeInt::make(klass->super_check_offset()); 2163 } 2164 if (UseCompactObjectHeaders) { 2165 if (tkls->offset() == in_bytes(Klass::prototype_header_offset())) { 2166 // The field is Klass::_prototype_header. Return its (constant) value. 2167 assert(this->Opcode() == Op_LoadX, "must load a proper type from _prototype_header"); 2168 return TypeX::make(klass->prototype_header()); 2169 } 2170 } 2171 // Compute index into primary_supers array 2172 juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*); 2173 // Check for overflowing; use unsigned compare to handle the negative case. 2174 if( depth < ciKlass::primary_super_limit() ) { 2175 // The field is an element of Klass::_primary_supers. Return its (constant) value. 2176 // (Folds up type checking code.) 2177 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers"); 2178 ciKlass *ss = klass->super_of_depth(depth); 2179 return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR; 2180 } 2181 const Type* aift = load_array_final_field(tkls, klass); 2182 if (aift != nullptr) return aift; 2183 } 2184 2185 // We can still check if we are loading from the primary_supers array at a 2186 // shallow enough depth. Even though the klass is not exact, entries less 2187 // than or equal to its super depth are correct. 2188 if (tkls->is_loaded()) { 2189 ciKlass* klass = nullptr; 2190 if (tkls->isa_instklassptr()) { 2191 klass = tkls->is_instklassptr()->instance_klass(); 2192 } else { 2193 int dims; 2194 const Type* inner = tkls->is_aryklassptr()->base_element_type(dims); 2195 if (inner->isa_instklassptr()) { 2196 klass = inner->is_instklassptr()->instance_klass(); 2197 klass = ciObjArrayKlass::make(klass, dims); 2198 } 2199 } 2200 if (klass != nullptr) { 2201 // Compute index into primary_supers array 2202 juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*); 2203 // Check for overflowing; use unsigned compare to handle the negative case. 2204 if (depth < ciKlass::primary_super_limit() && 2205 depth <= klass->super_depth()) { // allow self-depth checks to handle self-check case 2206 // The field is an element of Klass::_primary_supers. Return its (constant) value. 2207 // (Folds up type checking code.) 2208 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers"); 2209 ciKlass *ss = klass->super_of_depth(depth); 2210 return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR; 2211 } 2212 } 2213 } 2214 2215 // If the type is enough to determine that the thing is not an array, 2216 // we can give the layout_helper a positive interval type. 2217 // This will help short-circuit some reflective code. 2218 if (tkls->offset() == in_bytes(Klass::layout_helper_offset()) && 2219 tkls->isa_instklassptr() && // not directly typed as an array 2220 !tkls->is_instklassptr()->instance_klass()->is_java_lang_Object() // not the supertype of all T[] and specifically not Serializable & Cloneable 2221 ) { 2222 // Note: When interfaces are reliable, we can narrow the interface 2223 // test to (klass != Serializable && klass != Cloneable). 2224 assert(Opcode() == Op_LoadI, "must load an int from _layout_helper"); 2225 jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false); 2226 // The key property of this type is that it folds up tests 2227 // for array-ness, since it proves that the layout_helper is positive. 2228 // Thus, a generic value like the basic object layout helper works fine. 2229 return TypeInt::make(min_size, max_jint, Type::WidenMin); 2230 } 2231 } 2232 2233 bool is_vect = (_type->isa_vect() != nullptr); 2234 if (is_instance && !is_vect) { 2235 // If we have an instance type and our memory input is the 2236 // programs's initial memory state, there is no matching store, 2237 // so just return a zero of the appropriate type - 2238 // except if it is vectorized - then we have no zero constant. 2239 Node *mem = in(MemNode::Memory); 2240 if (mem->is_Parm() && mem->in(0)->is_Start()) { 2241 assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm"); 2242 return Type::get_zero_type(_type->basic_type()); 2243 } 2244 } 2245 2246 if (!UseCompactObjectHeaders) { 2247 Node* alloc = is_new_object_mark_load(); 2248 if (alloc != nullptr) { 2249 return TypeX::make(markWord::prototype().value()); 2250 } 2251 } 2252 2253 return _type; 2254 } 2255 2256 //------------------------------match_edge------------------------------------- 2257 // Do we Match on this edge index or not? Match only the address. 2258 uint LoadNode::match_edge(uint idx) const { 2259 return idx == MemNode::Address; 2260 } 2261 2262 //--------------------------LoadBNode::Ideal-------------------------------------- 2263 // 2264 // If the previous store is to the same address as this load, 2265 // and the value stored was larger than a byte, replace this load 2266 // with the value stored truncated to a byte. If no truncation is 2267 // needed, the replacement is done in LoadNode::Identity(). 2268 // 2269 Node* LoadBNode::Ideal(PhaseGVN* phase, bool can_reshape) { 2270 Node* mem = in(MemNode::Memory); 2271 Node* value = can_see_stored_value(mem,phase); 2272 if (value != nullptr) { 2273 Node* narrow = Compile::narrow_value(T_BYTE, value, _type, phase, false); 2274 if (narrow != value) { 2275 return narrow; 2276 } 2277 } 2278 // Identity call will handle the case where truncation is not needed. 2279 return LoadNode::Ideal(phase, can_reshape); 2280 } 2281 2282 const Type* LoadBNode::Value(PhaseGVN* phase) const { 2283 Node* mem = in(MemNode::Memory); 2284 Node* value = can_see_stored_value(mem,phase); 2285 if (value != nullptr && value->is_Con() && 2286 !value->bottom_type()->higher_equal(_type)) { 2287 // If the input to the store does not fit with the load's result type, 2288 // it must be truncated. We can't delay until Ideal call since 2289 // a singleton Value is needed for split_thru_phi optimization. 2290 int con = value->get_int(); 2291 return TypeInt::make((con << 24) >> 24); 2292 } 2293 return LoadNode::Value(phase); 2294 } 2295 2296 //--------------------------LoadUBNode::Ideal------------------------------------- 2297 // 2298 // If the previous store is to the same address as this load, 2299 // and the value stored was larger than a byte, replace this load 2300 // with the value stored truncated to a byte. If no truncation is 2301 // needed, the replacement is done in LoadNode::Identity(). 2302 // 2303 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) { 2304 Node* mem = in(MemNode::Memory); 2305 Node* value = can_see_stored_value(mem, phase); 2306 if (value != nullptr) { 2307 Node* narrow = Compile::narrow_value(T_BOOLEAN, value, _type, phase, false); 2308 if (narrow != value) { 2309 return narrow; 2310 } 2311 } 2312 // Identity call will handle the case where truncation is not needed. 2313 return LoadNode::Ideal(phase, can_reshape); 2314 } 2315 2316 const Type* LoadUBNode::Value(PhaseGVN* phase) const { 2317 Node* mem = in(MemNode::Memory); 2318 Node* value = can_see_stored_value(mem,phase); 2319 if (value != nullptr && value->is_Con() && 2320 !value->bottom_type()->higher_equal(_type)) { 2321 // If the input to the store does not fit with the load's result type, 2322 // it must be truncated. We can't delay until Ideal call since 2323 // a singleton Value is needed for split_thru_phi optimization. 2324 int con = value->get_int(); 2325 return TypeInt::make(con & 0xFF); 2326 } 2327 return LoadNode::Value(phase); 2328 } 2329 2330 //--------------------------LoadUSNode::Ideal------------------------------------- 2331 // 2332 // If the previous store is to the same address as this load, 2333 // and the value stored was larger than a char, replace this load 2334 // with the value stored truncated to a char. If no truncation is 2335 // needed, the replacement is done in LoadNode::Identity(). 2336 // 2337 Node* LoadUSNode::Ideal(PhaseGVN* phase, bool can_reshape) { 2338 Node* mem = in(MemNode::Memory); 2339 Node* value = can_see_stored_value(mem,phase); 2340 if (value != nullptr) { 2341 Node* narrow = Compile::narrow_value(T_CHAR, value, _type, phase, false); 2342 if (narrow != value) { 2343 return narrow; 2344 } 2345 } 2346 // Identity call will handle the case where truncation is not needed. 2347 return LoadNode::Ideal(phase, can_reshape); 2348 } 2349 2350 const Type* LoadUSNode::Value(PhaseGVN* phase) const { 2351 Node* mem = in(MemNode::Memory); 2352 Node* value = can_see_stored_value(mem,phase); 2353 if (value != nullptr && value->is_Con() && 2354 !value->bottom_type()->higher_equal(_type)) { 2355 // If the input to the store does not fit with the load's result type, 2356 // it must be truncated. We can't delay until Ideal call since 2357 // a singleton Value is needed for split_thru_phi optimization. 2358 int con = value->get_int(); 2359 return TypeInt::make(con & 0xFFFF); 2360 } 2361 return LoadNode::Value(phase); 2362 } 2363 2364 //--------------------------LoadSNode::Ideal-------------------------------------- 2365 // 2366 // If the previous store is to the same address as this load, 2367 // and the value stored was larger than a short, replace this load 2368 // with the value stored truncated to a short. If no truncation is 2369 // needed, the replacement is done in LoadNode::Identity(). 2370 // 2371 Node* LoadSNode::Ideal(PhaseGVN* phase, bool can_reshape) { 2372 Node* mem = in(MemNode::Memory); 2373 Node* value = can_see_stored_value(mem,phase); 2374 if (value != nullptr) { 2375 Node* narrow = Compile::narrow_value(T_SHORT, value, _type, phase, false); 2376 if (narrow != value) { 2377 return narrow; 2378 } 2379 } 2380 // Identity call will handle the case where truncation is not needed. 2381 return LoadNode::Ideal(phase, can_reshape); 2382 } 2383 2384 const Type* LoadSNode::Value(PhaseGVN* phase) const { 2385 Node* mem = in(MemNode::Memory); 2386 Node* value = can_see_stored_value(mem,phase); 2387 if (value != nullptr && value->is_Con() && 2388 !value->bottom_type()->higher_equal(_type)) { 2389 // If the input to the store does not fit with the load's result type, 2390 // it must be truncated. We can't delay until Ideal call since 2391 // a singleton Value is needed for split_thru_phi optimization. 2392 int con = value->get_int(); 2393 return TypeInt::make((con << 16) >> 16); 2394 } 2395 return LoadNode::Value(phase); 2396 } 2397 2398 //============================================================================= 2399 //----------------------------LoadKlassNode::make------------------------------ 2400 // Polymorphic factory method: 2401 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) { 2402 // sanity check the alias category against the created node type 2403 const TypePtr *adr_type = adr->bottom_type()->isa_ptr(); 2404 assert(adr_type != nullptr, "expecting TypeKlassPtr"); 2405 #ifdef _LP64 2406 if (adr_type->is_ptr_to_narrowklass()) { 2407 assert(UseCompressedClassPointers, "no compressed klasses"); 2408 Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered)); 2409 return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr()); 2410 } 2411 #endif 2412 assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop"); 2413 return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered); 2414 } 2415 2416 //------------------------------Value------------------------------------------ 2417 const Type* LoadKlassNode::Value(PhaseGVN* phase) const { 2418 return klass_value_common(phase); 2419 } 2420 2421 // In most cases, LoadKlassNode does not have the control input set. If the control 2422 // input is set, it must not be removed (by LoadNode::Ideal()). 2423 bool LoadKlassNode::can_remove_control() const { 2424 return false; 2425 } 2426 2427 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const { 2428 // Either input is TOP ==> the result is TOP 2429 const Type *t1 = phase->type( in(MemNode::Memory) ); 2430 if (t1 == Type::TOP) return Type::TOP; 2431 Node *adr = in(MemNode::Address); 2432 const Type *t2 = phase->type( adr ); 2433 if (t2 == Type::TOP) return Type::TOP; 2434 const TypePtr *tp = t2->is_ptr(); 2435 if (TypePtr::above_centerline(tp->ptr()) || 2436 tp->ptr() == TypePtr::Null) return Type::TOP; 2437 2438 // Return a more precise klass, if possible 2439 const TypeInstPtr *tinst = tp->isa_instptr(); 2440 if (tinst != nullptr) { 2441 ciInstanceKlass* ik = tinst->instance_klass(); 2442 int offset = tinst->offset(); 2443 if (ik == phase->C->env()->Class_klass() 2444 && (offset == java_lang_Class::klass_offset() || 2445 offset == java_lang_Class::array_klass_offset())) { 2446 // We are loading a special hidden field from a Class mirror object, 2447 // the field which points to the VM's Klass metaobject. 2448 ciType* t = tinst->java_mirror_type(); 2449 // java_mirror_type returns non-null for compile-time Class constants. 2450 if (t != nullptr) { 2451 // constant oop => constant klass 2452 if (offset == java_lang_Class::array_klass_offset()) { 2453 if (t->is_void()) { 2454 // We cannot create a void array. Since void is a primitive type return null 2455 // klass. Users of this result need to do a null check on the returned klass. 2456 return TypePtr::NULL_PTR; 2457 } 2458 return TypeKlassPtr::make(ciArrayKlass::make(t), Type::trust_interfaces); 2459 } 2460 if (!t->is_klass()) { 2461 // a primitive Class (e.g., int.class) has null for a klass field 2462 return TypePtr::NULL_PTR; 2463 } 2464 // (Folds up the 1st indirection in aClassConstant.getModifiers().) 2465 return TypeKlassPtr::make(t->as_klass(), Type::trust_interfaces); 2466 } 2467 // non-constant mirror, so we can't tell what's going on 2468 } 2469 if (!tinst->is_loaded()) 2470 return _type; // Bail out if not loaded 2471 if (offset == oopDesc::klass_offset_in_bytes()) { 2472 return tinst->as_klass_type(true); 2473 } 2474 } 2475 2476 // Check for loading klass from an array 2477 const TypeAryPtr *tary = tp->isa_aryptr(); 2478 if (tary != nullptr && 2479 tary->offset() == oopDesc::klass_offset_in_bytes()) { 2480 return tary->as_klass_type(true); 2481 } 2482 2483 // Check for loading klass from an array klass 2484 const TypeKlassPtr *tkls = tp->isa_klassptr(); 2485 if (tkls != nullptr && !StressReflectiveCode) { 2486 if (!tkls->is_loaded()) 2487 return _type; // Bail out if not loaded 2488 if (tkls->isa_aryklassptr() && tkls->is_aryklassptr()->elem()->isa_klassptr() && 2489 tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) { 2490 // // Always returning precise element type is incorrect, 2491 // // e.g., element type could be object and array may contain strings 2492 // return TypeKlassPtr::make(TypePtr::Constant, elem, 0); 2493 2494 // The array's TypeKlassPtr was declared 'precise' or 'not precise' 2495 // according to the element type's subclassing. 2496 return tkls->is_aryklassptr()->elem()->isa_klassptr()->cast_to_exactness(tkls->klass_is_exact()); 2497 } 2498 if (tkls->isa_instklassptr() != nullptr && tkls->klass_is_exact() && 2499 tkls->offset() == in_bytes(Klass::super_offset())) { 2500 ciKlass* sup = tkls->is_instklassptr()->instance_klass()->super(); 2501 // The field is Klass::_super. Return its (constant) value. 2502 // (Folds up the 2nd indirection in aClassConstant.getSuperClass().) 2503 return sup ? TypeKlassPtr::make(sup, Type::trust_interfaces) : TypePtr::NULL_PTR; 2504 } 2505 } 2506 2507 if (tkls != nullptr && !UseSecondarySupersCache 2508 && tkls->offset() == in_bytes(Klass::secondary_super_cache_offset())) { 2509 // Treat Klass::_secondary_super_cache as a constant when the cache is disabled. 2510 return TypePtr::NULL_PTR; 2511 } 2512 2513 // Bailout case 2514 return LoadNode::Value(phase); 2515 } 2516 2517 //------------------------------Identity--------------------------------------- 2518 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k. 2519 // Also feed through the klass in Allocate(...klass...)._klass. 2520 Node* LoadKlassNode::Identity(PhaseGVN* phase) { 2521 return klass_identity_common(phase); 2522 } 2523 2524 Node* LoadNode::klass_identity_common(PhaseGVN* phase) { 2525 Node* x = LoadNode::Identity(phase); 2526 if (x != this) return x; 2527 2528 // Take apart the address into an oop and offset. 2529 // Return 'this' if we cannot. 2530 Node* adr = in(MemNode::Address); 2531 intptr_t offset = 0; 2532 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); 2533 if (base == nullptr) return this; 2534 const TypeOopPtr* toop = phase->type(adr)->isa_oopptr(); 2535 if (toop == nullptr) return this; 2536 2537 // Step over potential GC barrier for OopHandle resolve 2538 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 2539 if (bs->is_gc_barrier_node(base)) { 2540 base = bs->step_over_gc_barrier(base); 2541 } 2542 2543 // We can fetch the klass directly through an AllocateNode. 2544 // This works even if the klass is not constant (clone or newArray). 2545 if (offset == oopDesc::klass_offset_in_bytes()) { 2546 Node* allocated_klass = AllocateNode::Ideal_klass(base, phase); 2547 if (allocated_klass != nullptr) { 2548 return allocated_klass; 2549 } 2550 } 2551 2552 // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*. 2553 // See inline_native_Class_query for occurrences of these patterns. 2554 // Java Example: x.getClass().isAssignableFrom(y) 2555 // 2556 // This improves reflective code, often making the Class 2557 // mirror go completely dead. (Current exception: Class 2558 // mirrors may appear in debug info, but we could clean them out by 2559 // introducing a new debug info operator for Klass.java_mirror). 2560 2561 if (toop->isa_instptr() && toop->is_instptr()->instance_klass() == phase->C->env()->Class_klass() 2562 && offset == java_lang_Class::klass_offset()) { 2563 if (base->is_Load()) { 2564 Node* base2 = base->in(MemNode::Address); 2565 if (base2->is_Load()) { /* direct load of a load which is the OopHandle */ 2566 Node* adr2 = base2->in(MemNode::Address); 2567 const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr(); 2568 if (tkls != nullptr && !tkls->empty() 2569 && (tkls->isa_instklassptr() || tkls->isa_aryklassptr()) 2570 && adr2->is_AddP() 2571 ) { 2572 int mirror_field = in_bytes(Klass::java_mirror_offset()); 2573 if (tkls->offset() == mirror_field) { 2574 return adr2->in(AddPNode::Base); 2575 } 2576 } 2577 } 2578 } 2579 } 2580 2581 return this; 2582 } 2583 2584 LoadNode* LoadNode::clone_pinned() const { 2585 LoadNode* ld = clone()->as_Load(); 2586 ld->_control_dependency = UnknownControl; 2587 return ld; 2588 } 2589 2590 2591 //------------------------------Value------------------------------------------ 2592 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const { 2593 const Type *t = klass_value_common(phase); 2594 if (t == Type::TOP) 2595 return t; 2596 2597 return t->make_narrowklass(); 2598 } 2599 2600 //------------------------------Identity--------------------------------------- 2601 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k. 2602 // Also feed through the klass in Allocate(...klass...)._klass. 2603 Node* LoadNKlassNode::Identity(PhaseGVN* phase) { 2604 Node *x = klass_identity_common(phase); 2605 2606 const Type *t = phase->type( x ); 2607 if( t == Type::TOP ) return x; 2608 if( t->isa_narrowklass()) return x; 2609 assert (!t->isa_narrowoop(), "no narrow oop here"); 2610 2611 return phase->transform(new EncodePKlassNode(x, t->make_narrowklass())); 2612 } 2613 2614 //------------------------------Value----------------------------------------- 2615 const Type* LoadRangeNode::Value(PhaseGVN* phase) const { 2616 // Either input is TOP ==> the result is TOP 2617 const Type *t1 = phase->type( in(MemNode::Memory) ); 2618 if( t1 == Type::TOP ) return Type::TOP; 2619 Node *adr = in(MemNode::Address); 2620 const Type *t2 = phase->type( adr ); 2621 if( t2 == Type::TOP ) return Type::TOP; 2622 const TypePtr *tp = t2->is_ptr(); 2623 if (TypePtr::above_centerline(tp->ptr())) return Type::TOP; 2624 const TypeAryPtr *tap = tp->isa_aryptr(); 2625 if( !tap ) return _type; 2626 return tap->size(); 2627 } 2628 2629 //-------------------------------Ideal--------------------------------------- 2630 // Feed through the length in AllocateArray(...length...)._length. 2631 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) { 2632 Node* p = MemNode::Ideal_common(phase, can_reshape); 2633 if (p) return (p == NodeSentinel) ? nullptr : p; 2634 2635 // Take apart the address into an oop and offset. 2636 // Return 'this' if we cannot. 2637 Node* adr = in(MemNode::Address); 2638 intptr_t offset = 0; 2639 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); 2640 if (base == nullptr) return nullptr; 2641 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr(); 2642 if (tary == nullptr) return nullptr; 2643 2644 // We can fetch the length directly through an AllocateArrayNode. 2645 // This works even if the length is not constant (clone or newArray). 2646 if (offset == arrayOopDesc::length_offset_in_bytes()) { 2647 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base); 2648 if (alloc != nullptr) { 2649 Node* allocated_length = alloc->Ideal_length(); 2650 Node* len = alloc->make_ideal_length(tary, phase); 2651 if (allocated_length != len) { 2652 // New CastII improves on this. 2653 return len; 2654 } 2655 } 2656 } 2657 2658 return nullptr; 2659 } 2660 2661 //------------------------------Identity--------------------------------------- 2662 // Feed through the length in AllocateArray(...length...)._length. 2663 Node* LoadRangeNode::Identity(PhaseGVN* phase) { 2664 Node* x = LoadINode::Identity(phase); 2665 if (x != this) return x; 2666 2667 // Take apart the address into an oop and offset. 2668 // Return 'this' if we cannot. 2669 Node* adr = in(MemNode::Address); 2670 intptr_t offset = 0; 2671 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); 2672 if (base == nullptr) return this; 2673 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr(); 2674 if (tary == nullptr) return this; 2675 2676 // We can fetch the length directly through an AllocateArrayNode. 2677 // This works even if the length is not constant (clone or newArray). 2678 if (offset == arrayOopDesc::length_offset_in_bytes()) { 2679 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base); 2680 if (alloc != nullptr) { 2681 Node* allocated_length = alloc->Ideal_length(); 2682 // Do not allow make_ideal_length to allocate a CastII node. 2683 Node* len = alloc->make_ideal_length(tary, phase, false); 2684 if (allocated_length == len) { 2685 // Return allocated_length only if it would not be improved by a CastII. 2686 return allocated_length; 2687 } 2688 } 2689 } 2690 2691 return this; 2692 2693 } 2694 2695 //============================================================================= 2696 //---------------------------StoreNode::make----------------------------------- 2697 // Polymorphic factory method: 2698 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo, bool require_atomic_access) { 2699 assert((mo == unordered || mo == release), "unexpected"); 2700 Compile* C = gvn.C; 2701 assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw || 2702 ctl != nullptr, "raw memory operations should have control edge"); 2703 2704 switch (bt) { 2705 case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case 2706 case T_BYTE: return new StoreBNode(ctl, mem, adr, adr_type, val, mo); 2707 case T_INT: return new StoreINode(ctl, mem, adr, adr_type, val, mo); 2708 case T_CHAR: 2709 case T_SHORT: return new StoreCNode(ctl, mem, adr, adr_type, val, mo); 2710 case T_LONG: return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access); 2711 case T_FLOAT: return new StoreFNode(ctl, mem, adr, adr_type, val, mo); 2712 case T_DOUBLE: return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access); 2713 case T_METADATA: 2714 case T_ADDRESS: 2715 case T_OBJECT: 2716 #ifdef _LP64 2717 if (adr->bottom_type()->is_ptr_to_narrowoop()) { 2718 val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop())); 2719 return new StoreNNode(ctl, mem, adr, adr_type, val, mo); 2720 } else if (adr->bottom_type()->is_ptr_to_narrowklass() || 2721 (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() && 2722 adr->bottom_type()->isa_rawptr())) { 2723 val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass())); 2724 return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo); 2725 } 2726 #endif 2727 { 2728 return new StorePNode(ctl, mem, adr, adr_type, val, mo); 2729 } 2730 default: 2731 ShouldNotReachHere(); 2732 return (StoreNode*)nullptr; 2733 } 2734 } 2735 2736 //--------------------------bottom_type---------------------------------------- 2737 const Type *StoreNode::bottom_type() const { 2738 return Type::MEMORY; 2739 } 2740 2741 //------------------------------hash------------------------------------------- 2742 uint StoreNode::hash() const { 2743 // unroll addition of interesting fields 2744 //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn); 2745 2746 // Since they are not commoned, do not hash them: 2747 return NO_HASH; 2748 } 2749 2750 // Link together multiple stores (B/S/C/I) into a longer one. 2751 // 2752 // Example: _store = StoreB[i+3] 2753 // 2754 // RangeCheck[i+0] RangeCheck[i+0] 2755 // StoreB[i+0] 2756 // RangeCheck[i+3] RangeCheck[i+3] 2757 // StoreB[i+1] --> pass: fail: 2758 // StoreB[i+2] StoreI[i+0] StoreB[i+0] 2759 // StoreB[i+3] 2760 // 2761 // The 4 StoreB are merged into a single StoreI node. We have to be careful with RangeCheck[i+1]: before 2762 // the optimization, if this RangeCheck[i+1] fails, then we execute only StoreB[i+0], and then trap. After 2763 // the optimization, the new StoreI[i+0] is on the passing path of RangeCheck[i+3], and StoreB[i+0] on the 2764 // failing path. 2765 // 2766 // Note: For normal array stores, every store at first has a RangeCheck. But they can be removed with: 2767 // - RCE (RangeCheck Elimination): the RangeChecks in the loop are hoisted out and before the loop, 2768 // and possibly no RangeChecks remain between the stores. 2769 // - RangeCheck smearing: the earlier RangeChecks are adjusted such that they cover later RangeChecks, 2770 // and those later RangeChecks can be removed. Example: 2771 // 2772 // RangeCheck[i+0] RangeCheck[i+0] <- before first store 2773 // StoreB[i+0] StoreB[i+0] <- first store 2774 // RangeCheck[i+1] --> smeared --> RangeCheck[i+3] <- only RC between first and last store 2775 // StoreB[i+1] StoreB[i+1] <- second store 2776 // RangeCheck[i+2] --> removed 2777 // StoreB[i+2] StoreB[i+2] 2778 // RangeCheck[i+3] --> removed 2779 // StoreB[i+3] StoreB[i+3] <- last store 2780 // 2781 // Thus, it is a common pattern that between the first and last store in a chain 2782 // of adjacent stores there remains exactly one RangeCheck, located between the 2783 // first and the second store (e.g. RangeCheck[i+3]). 2784 // 2785 class MergePrimitiveStores : public StackObj { 2786 private: 2787 PhaseGVN* const _phase; 2788 StoreNode* const _store; 2789 2790 NOT_PRODUCT( const CHeapBitMap &_trace_tags; ) 2791 2792 public: 2793 MergePrimitiveStores(PhaseGVN* phase, StoreNode* store) : 2794 _phase(phase), _store(store) 2795 NOT_PRODUCT( COMMA _trace_tags(Compile::current()->directive()->trace_merge_stores_tags()) ) 2796 {} 2797 2798 StoreNode* run(); 2799 2800 private: 2801 bool is_compatible_store(const StoreNode* other_store) const; 2802 bool is_adjacent_pair(const StoreNode* use_store, const StoreNode* def_store) const; 2803 bool is_adjacent_input_pair(const Node* n1, const Node* n2, const int memory_size) const; 2804 static bool is_con_RShift(const Node* n, Node const*& base_out, jint& shift_out); 2805 enum CFGStatus { SuccessNoRangeCheck, SuccessWithRangeCheck, Failure }; 2806 static CFGStatus cfg_status_for_pair(const StoreNode* use_store, const StoreNode* def_store); 2807 2808 class Status { 2809 private: 2810 StoreNode* _found_store; 2811 bool _found_range_check; 2812 2813 Status(StoreNode* found_store, bool found_range_check) 2814 : _found_store(found_store), _found_range_check(found_range_check) {} 2815 2816 public: 2817 StoreNode* found_store() const { return _found_store; } 2818 bool found_range_check() const { return _found_range_check; } 2819 static Status make_failure() { return Status(nullptr, false); } 2820 2821 static Status make(StoreNode* found_store, const CFGStatus cfg_status) { 2822 if (cfg_status == CFGStatus::Failure) { 2823 return Status::make_failure(); 2824 } 2825 return Status(found_store, cfg_status == CFGStatus::SuccessWithRangeCheck); 2826 } 2827 2828 #ifndef PRODUCT 2829 void print_on(outputStream* st) const { 2830 if (_found_store == nullptr) { 2831 st->print_cr("None"); 2832 } else { 2833 st->print_cr("Found[%d %s, %s]", _found_store->_idx, _found_store->Name(), 2834 _found_range_check ? "RC" : "no-RC"); 2835 } 2836 } 2837 #endif 2838 }; 2839 2840 Status find_adjacent_use_store(const StoreNode* def_store) const; 2841 Status find_adjacent_def_store(const StoreNode* use_store) const; 2842 Status find_use_store(const StoreNode* def_store) const; 2843 Status find_def_store(const StoreNode* use_store) const; 2844 Status find_use_store_unidirectional(const StoreNode* def_store) const; 2845 Status find_def_store_unidirectional(const StoreNode* use_store) const; 2846 2847 void collect_merge_list(Node_List& merge_list) const; 2848 Node* make_merged_input_value(const Node_List& merge_list); 2849 StoreNode* make_merged_store(const Node_List& merge_list, Node* merged_input_value); 2850 2851 #ifndef PRODUCT 2852 // Access to TraceMergeStores tags 2853 bool is_trace(TraceMergeStores::Tag tag) const { 2854 return _trace_tags.at(tag); 2855 } 2856 2857 bool is_trace_basic() const { 2858 return is_trace(TraceMergeStores::Tag::BASIC); 2859 } 2860 2861 bool is_trace_pointer_parsing() const { 2862 return is_trace(TraceMergeStores::Tag::POINTER_PARSING); 2863 } 2864 2865 bool is_trace_pointer_aliasing() const { 2866 return is_trace(TraceMergeStores::Tag::POINTER_ALIASING); 2867 } 2868 2869 bool is_trace_pointer_adjacency() const { 2870 return is_trace(TraceMergeStores::Tag::POINTER_ADJACENCY); 2871 } 2872 2873 bool is_trace_success() const { 2874 return is_trace(TraceMergeStores::Tag::SUCCESS); 2875 } 2876 #endif 2877 2878 NOT_PRODUCT( void trace(const Node_List& merge_list, const Node* merged_input_value, const StoreNode* merged_store) const; ) 2879 }; 2880 2881 StoreNode* MergePrimitiveStores::run() { 2882 // Check for B/S/C/I 2883 int opc = _store->Opcode(); 2884 if (opc != Op_StoreB && opc != Op_StoreC && opc != Op_StoreI) { 2885 return nullptr; 2886 } 2887 2888 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] MergePrimitiveStores::run: "); _store->dump(); }) 2889 2890 // The _store must be the "last" store in a chain. If we find a use we could merge with 2891 // then that use or a store further down is the "last" store. 2892 Status status_use = find_adjacent_use_store(_store); 2893 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] expect no use: "); status_use.print_on(tty); }) 2894 if (status_use.found_store() != nullptr) { 2895 return nullptr; 2896 } 2897 2898 // Check if we can merge with at least one def, so that we have at least 2 stores to merge. 2899 Status status_def = find_adjacent_def_store(_store); 2900 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] expect def: "); status_def.print_on(tty); }) 2901 if (status_def.found_store() == nullptr) { 2902 return nullptr; 2903 } 2904 2905 ResourceMark rm; 2906 Node_List merge_list; 2907 collect_merge_list(merge_list); 2908 2909 Node* merged_input_value = make_merged_input_value(merge_list); 2910 if (merged_input_value == nullptr) { return nullptr; } 2911 2912 StoreNode* merged_store = make_merged_store(merge_list, merged_input_value); 2913 2914 NOT_PRODUCT( if (is_trace_success()) { trace(merge_list, merged_input_value, merged_store); } ) 2915 2916 return merged_store; 2917 } 2918 2919 // Check compatibility between _store and other_store. 2920 bool MergePrimitiveStores::is_compatible_store(const StoreNode* other_store) const { 2921 int opc = _store->Opcode(); 2922 assert(opc == Op_StoreB || opc == Op_StoreC || opc == Op_StoreI, "precondition"); 2923 2924 if (other_store == nullptr || 2925 _store->Opcode() != other_store->Opcode()) { 2926 return false; 2927 } 2928 2929 return true; 2930 } 2931 2932 bool MergePrimitiveStores::is_adjacent_pair(const StoreNode* use_store, const StoreNode* def_store) const { 2933 if (!is_adjacent_input_pair(def_store->in(MemNode::ValueIn), 2934 use_store->in(MemNode::ValueIn), 2935 def_store->memory_size())) { 2936 return false; 2937 } 2938 2939 ResourceMark rm; 2940 #ifndef PRODUCT 2941 const TraceMemPointer trace(is_trace_pointer_parsing(), 2942 is_trace_pointer_aliasing(), 2943 is_trace_pointer_adjacency(), 2944 true); 2945 #endif 2946 const MemPointer pointer_use(use_store NOT_PRODUCT(COMMA trace)); 2947 const MemPointer pointer_def(def_store NOT_PRODUCT(COMMA trace)); 2948 return pointer_def.is_adjacent_to_and_before(pointer_use); 2949 } 2950 2951 bool MergePrimitiveStores::is_adjacent_input_pair(const Node* n1, const Node* n2, const int memory_size) const { 2952 // Pattern: [n1 = ConI, n2 = ConI] 2953 if (n1->Opcode() == Op_ConI) { 2954 return n2->Opcode() == Op_ConI; 2955 } 2956 2957 // Pattern: [n1 = base >> shift, n2 = base >> (shift + memory_size)] 2958 #ifndef VM_LITTLE_ENDIAN 2959 // Pattern: [n1 = base >> (shift + memory_size), n2 = base >> shift] 2960 // Swapping n1 with n2 gives same pattern as on little endian platforms. 2961 swap(n1, n2); 2962 #endif // !VM_LITTLE_ENDIAN 2963 Node const* base_n2; 2964 jint shift_n2; 2965 if (!is_con_RShift(n2, base_n2, shift_n2)) { 2966 return false; 2967 } 2968 if (n1->Opcode() == Op_ConvL2I) { 2969 // look through 2970 n1 = n1->in(1); 2971 } 2972 Node const* base_n1; 2973 jint shift_n1; 2974 if (n1 == base_n2) { 2975 // n1 = base = base >> 0 2976 base_n1 = n1; 2977 shift_n1 = 0; 2978 } else if (!is_con_RShift(n1, base_n1, shift_n1)) { 2979 return false; 2980 } 2981 int bits_per_store = memory_size * 8; 2982 if (base_n1 != base_n2 || 2983 shift_n1 + bits_per_store != shift_n2 || 2984 shift_n1 % bits_per_store != 0) { 2985 return false; 2986 } 2987 2988 // both load from same value with correct shift 2989 return true; 2990 } 2991 2992 // Detect pattern: n = base_out >> shift_out 2993 bool MergePrimitiveStores::is_con_RShift(const Node* n, Node const*& base_out, jint& shift_out) { 2994 assert(n != nullptr, "precondition"); 2995 2996 int opc = n->Opcode(); 2997 if (opc == Op_ConvL2I) { 2998 n = n->in(1); 2999 opc = n->Opcode(); 3000 } 3001 3002 if ((opc == Op_RShiftI || 3003 opc == Op_RShiftL || 3004 opc == Op_URShiftI || 3005 opc == Op_URShiftL) && 3006 n->in(2)->is_ConI()) { 3007 base_out = n->in(1); 3008 shift_out = n->in(2)->get_int(); 3009 // The shift must be positive: 3010 return shift_out >= 0; 3011 } 3012 return false; 3013 } 3014 3015 // Check if there is nothing between the two stores, except optionally a RangeCheck leading to an uncommon trap. 3016 MergePrimitiveStores::CFGStatus MergePrimitiveStores::cfg_status_for_pair(const StoreNode* use_store, const StoreNode* def_store) { 3017 assert(use_store->in(MemNode::Memory) == def_store, "use-def relationship"); 3018 3019 Node* ctrl_use = use_store->in(MemNode::Control); 3020 Node* ctrl_def = def_store->in(MemNode::Control); 3021 if (ctrl_use == nullptr || ctrl_def == nullptr) { 3022 return CFGStatus::Failure; 3023 } 3024 3025 if (ctrl_use == ctrl_def) { 3026 // Same ctrl -> no RangeCheck in between. 3027 // Check: use_store must be the only use of def_store. 3028 if (def_store->outcnt() > 1) { 3029 return CFGStatus::Failure; 3030 } 3031 return CFGStatus::SuccessNoRangeCheck; 3032 } 3033 3034 // Different ctrl -> could have RangeCheck in between. 3035 // Check: 1. def_store only has these uses: use_store and MergeMem for uncommon trap, and 3036 // 2. ctrl separated by RangeCheck. 3037 if (def_store->outcnt() != 2) { 3038 return CFGStatus::Failure; // Cannot have exactly these uses: use_store and MergeMem for uncommon trap. 3039 } 3040 int use_store_out_idx = def_store->raw_out(0) == use_store ? 0 : 1; 3041 Node* merge_mem = def_store->raw_out(1 - use_store_out_idx)->isa_MergeMem(); 3042 if (merge_mem == nullptr || 3043 merge_mem->outcnt() != 1) { 3044 return CFGStatus::Failure; // Does not have MergeMem for uncommon trap. 3045 } 3046 if (!ctrl_use->is_IfProj() || 3047 !ctrl_use->in(0)->is_RangeCheck() || 3048 ctrl_use->in(0)->outcnt() != 2) { 3049 return CFGStatus::Failure; // Not RangeCheck. 3050 } 3051 ProjNode* other_proj = ctrl_use->as_IfProj()->other_if_proj(); 3052 Node* trap = other_proj->is_uncommon_trap_proj(Deoptimization::Reason_range_check); 3053 if (trap != merge_mem->unique_out() || 3054 ctrl_use->in(0)->in(0) != ctrl_def) { 3055 return CFGStatus::Failure; // Not RangeCheck with merge_mem leading to uncommon trap. 3056 } 3057 3058 return CFGStatus::SuccessWithRangeCheck; 3059 } 3060 3061 MergePrimitiveStores::Status MergePrimitiveStores::find_adjacent_use_store(const StoreNode* def_store) const { 3062 Status status_use = find_use_store(def_store); 3063 StoreNode* use_store = status_use.found_store(); 3064 if (use_store != nullptr && !is_adjacent_pair(use_store, def_store)) { 3065 return Status::make_failure(); 3066 } 3067 return status_use; 3068 } 3069 3070 MergePrimitiveStores::Status MergePrimitiveStores::find_adjacent_def_store(const StoreNode* use_store) const { 3071 Status status_def = find_def_store(use_store); 3072 StoreNode* def_store = status_def.found_store(); 3073 if (def_store != nullptr && !is_adjacent_pair(use_store, def_store)) { 3074 return Status::make_failure(); 3075 } 3076 return status_def; 3077 } 3078 3079 MergePrimitiveStores::Status MergePrimitiveStores::find_use_store(const StoreNode* def_store) const { 3080 Status status_use = find_use_store_unidirectional(def_store); 3081 3082 #ifdef ASSERT 3083 StoreNode* use_store = status_use.found_store(); 3084 if (use_store != nullptr) { 3085 Status status_def = find_def_store_unidirectional(use_store); 3086 assert(status_def.found_store() == def_store && 3087 status_def.found_range_check() == status_use.found_range_check(), 3088 "find_use_store and find_def_store must be symmetric"); 3089 } 3090 #endif 3091 3092 return status_use; 3093 } 3094 3095 MergePrimitiveStores::Status MergePrimitiveStores::find_def_store(const StoreNode* use_store) const { 3096 Status status_def = find_def_store_unidirectional(use_store); 3097 3098 #ifdef ASSERT 3099 StoreNode* def_store = status_def.found_store(); 3100 if (def_store != nullptr) { 3101 Status status_use = find_use_store_unidirectional(def_store); 3102 assert(status_use.found_store() == use_store && 3103 status_use.found_range_check() == status_def.found_range_check(), 3104 "find_use_store and find_def_store must be symmetric"); 3105 } 3106 #endif 3107 3108 return status_def; 3109 } 3110 3111 MergePrimitiveStores::Status MergePrimitiveStores::find_use_store_unidirectional(const StoreNode* def_store) const { 3112 assert(is_compatible_store(def_store), "precondition: must be compatible with _store"); 3113 3114 for (DUIterator_Fast imax, i = def_store->fast_outs(imax); i < imax; i++) { 3115 StoreNode* use_store = def_store->fast_out(i)->isa_Store(); 3116 if (is_compatible_store(use_store)) { 3117 return Status::make(use_store, cfg_status_for_pair(use_store, def_store)); 3118 } 3119 } 3120 3121 return Status::make_failure(); 3122 } 3123 3124 MergePrimitiveStores::Status MergePrimitiveStores::find_def_store_unidirectional(const StoreNode* use_store) const { 3125 assert(is_compatible_store(use_store), "precondition: must be compatible with _store"); 3126 3127 StoreNode* def_store = use_store->in(MemNode::Memory)->isa_Store(); 3128 if (!is_compatible_store(def_store)) { 3129 return Status::make_failure(); 3130 } 3131 3132 return Status::make(def_store, cfg_status_for_pair(use_store, def_store)); 3133 } 3134 3135 void MergePrimitiveStores::collect_merge_list(Node_List& merge_list) const { 3136 // The merged store can be at most 8 bytes. 3137 const uint merge_list_max_size = 8 / _store->memory_size(); 3138 assert(merge_list_max_size >= 2 && 3139 merge_list_max_size <= 8 && 3140 is_power_of_2(merge_list_max_size), 3141 "must be 2, 4 or 8"); 3142 3143 // Traverse up the chain of adjacent def stores. 3144 StoreNode* current = _store; 3145 merge_list.push(current); 3146 while (current != nullptr && merge_list.size() < merge_list_max_size) { 3147 Status status = find_adjacent_def_store(current); 3148 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] find def: "); status.print_on(tty); }) 3149 3150 current = status.found_store(); 3151 if (current != nullptr) { 3152 merge_list.push(current); 3153 3154 // We can have at most one RangeCheck. 3155 if (status.found_range_check()) { 3156 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] found RangeCheck, stop traversal."); }) 3157 break; 3158 } 3159 } 3160 } 3161 3162 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] found:"); merge_list.dump(); }) 3163 3164 // Truncate the merge_list to a power of 2. 3165 const uint pow2size = round_down_power_of_2(merge_list.size()); 3166 assert(pow2size >= 2, "must be merging at least 2 stores"); 3167 while (merge_list.size() > pow2size) { merge_list.pop(); } 3168 3169 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] truncated:"); merge_list.dump(); }) 3170 } 3171 3172 // Merge the input values of the smaller stores to a single larger input value. 3173 Node* MergePrimitiveStores::make_merged_input_value(const Node_List& merge_list) { 3174 int new_memory_size = _store->memory_size() * merge_list.size(); 3175 Node* first = merge_list.at(merge_list.size()-1); 3176 Node* merged_input_value = nullptr; 3177 if (_store->in(MemNode::ValueIn)->Opcode() == Op_ConI) { 3178 // Pattern: [ConI, ConI, ...] -> new constant 3179 jlong con = 0; 3180 jlong bits_per_store = _store->memory_size() * 8; 3181 jlong mask = (((jlong)1) << bits_per_store) - 1; 3182 for (uint i = 0; i < merge_list.size(); i++) { 3183 jlong con_i = merge_list.at(i)->in(MemNode::ValueIn)->get_int(); 3184 #ifdef VM_LITTLE_ENDIAN 3185 con = con << bits_per_store; 3186 con = con | (mask & con_i); 3187 #else // VM_LITTLE_ENDIAN 3188 con_i = (mask & con_i) << (i * bits_per_store); 3189 con = con | con_i; 3190 #endif // VM_LITTLE_ENDIAN 3191 } 3192 merged_input_value = _phase->longcon(con); 3193 } else { 3194 // Pattern: [base >> 24, base >> 16, base >> 8, base] -> base 3195 // | | 3196 // _store first 3197 // 3198 Node* hi = _store->in(MemNode::ValueIn); 3199 Node* lo = first->in(MemNode::ValueIn); 3200 #ifndef VM_LITTLE_ENDIAN 3201 // `_store` and `first` are swapped in the diagram above 3202 swap(hi, lo); 3203 #endif // !VM_LITTLE_ENDIAN 3204 Node const* hi_base; 3205 jint hi_shift; 3206 merged_input_value = lo; 3207 bool is_true = is_con_RShift(hi, hi_base, hi_shift); 3208 assert(is_true, "must detect con RShift"); 3209 if (merged_input_value != hi_base && merged_input_value->Opcode() == Op_ConvL2I) { 3210 // look through 3211 merged_input_value = merged_input_value->in(1); 3212 } 3213 if (merged_input_value != hi_base) { 3214 // merged_input_value is not the base 3215 return nullptr; 3216 } 3217 } 3218 3219 if (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size <= 4) { 3220 // Example: 3221 // 3222 // long base = ...; 3223 // a[0] = (byte)(base >> 0); 3224 // a[1] = (byte)(base >> 8); 3225 // 3226 merged_input_value = _phase->transform(new ConvL2INode(merged_input_value)); 3227 } 3228 3229 assert((_phase->type(merged_input_value)->isa_int() != nullptr && new_memory_size <= 4) || 3230 (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size == 8), 3231 "merged_input_value is either int or long, and new_memory_size is small enough"); 3232 3233 return merged_input_value; 3234 } 3235 3236 // // 3237 // first_ctrl first_mem first_adr first_ctrl first_mem first_adr // 3238 // | | | | | | // 3239 // | | | | +---------------+ | // 3240 // | | | | | | | // 3241 // | | +---------+ | | +---------------+ // 3242 // | | | | | | | | // 3243 // +--------------+ | | v1 +------------------------------+ | | v1 // 3244 // | | | | | | | | | | | | // 3245 // RangeCheck first_store RangeCheck | | first_store // 3246 // | | | | | | | // 3247 // last_ctrl | +----> unc_trap last_ctrl | | +----> unc_trap // 3248 // | | ===> | | | // 3249 // +--------------+ | a2 v2 | | | // 3250 // | | | | | | | | // 3251 // | second_store | | | // 3252 // | | | | | [v1 v2 ... vn] // 3253 // ... ... | | | | // 3254 // | | | | | v // 3255 // +--------------+ | an vn +--------------+ | | merged_input_value // 3256 // | | | | | | | | // 3257 // last_store (= _store) merged_store // 3258 // // 3259 StoreNode* MergePrimitiveStores::make_merged_store(const Node_List& merge_list, Node* merged_input_value) { 3260 Node* first_store = merge_list.at(merge_list.size()-1); 3261 Node* last_ctrl = _store->in(MemNode::Control); // after (optional) RangeCheck 3262 Node* first_mem = first_store->in(MemNode::Memory); 3263 Node* first_adr = first_store->in(MemNode::Address); 3264 3265 const TypePtr* new_adr_type = _store->adr_type(); 3266 3267 int new_memory_size = _store->memory_size() * merge_list.size(); 3268 BasicType bt = T_ILLEGAL; 3269 switch (new_memory_size) { 3270 case 2: bt = T_SHORT; break; 3271 case 4: bt = T_INT; break; 3272 case 8: bt = T_LONG; break; 3273 } 3274 3275 StoreNode* merged_store = StoreNode::make(*_phase, last_ctrl, first_mem, first_adr, 3276 new_adr_type, merged_input_value, bt, MemNode::unordered); 3277 3278 // Marking the store mismatched is sufficient to prevent reordering, since array stores 3279 // are all on the same slice. Hence, we need no barriers. 3280 merged_store->set_mismatched_access(); 3281 3282 // Constants above may now also be be packed -> put candidate on worklist 3283 _phase->is_IterGVN()->_worklist.push(first_mem); 3284 3285 return merged_store; 3286 } 3287 3288 #ifndef PRODUCT 3289 void MergePrimitiveStores::trace(const Node_List& merge_list, const Node* merged_input_value, const StoreNode* merged_store) const { 3290 stringStream ss; 3291 ss.print_cr("[TraceMergeStores]: Replace"); 3292 for (int i = (int)merge_list.size() - 1; i >= 0; i--) { 3293 merge_list.at(i)->dump("\n", false, &ss); 3294 } 3295 ss.print_cr("[TraceMergeStores]: with"); 3296 merged_input_value->dump("\n", false, &ss); 3297 merged_store->dump("\n", false, &ss); 3298 tty->print("%s", ss.as_string()); 3299 } 3300 #endif 3301 3302 //------------------------------Ideal------------------------------------------ 3303 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x). 3304 // When a store immediately follows a relevant allocation/initialization, 3305 // try to capture it into the initialization, or hoist it above. 3306 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) { 3307 Node* p = MemNode::Ideal_common(phase, can_reshape); 3308 if (p) return (p == NodeSentinel) ? nullptr : p; 3309 3310 Node* mem = in(MemNode::Memory); 3311 Node* address = in(MemNode::Address); 3312 Node* value = in(MemNode::ValueIn); 3313 // Back-to-back stores to same address? Fold em up. Generally 3314 // unsafe if I have intervening uses. 3315 { 3316 Node* st = mem; 3317 // If Store 'st' has more than one use, we cannot fold 'st' away. 3318 // For example, 'st' might be the final state at a conditional 3319 // return. Or, 'st' might be used by some node which is live at 3320 // the same time 'st' is live, which might be unschedulable. So, 3321 // require exactly ONE user until such time as we clone 'mem' for 3322 // each of 'mem's uses (thus making the exactly-1-user-rule hold 3323 // true). 3324 while (st->is_Store() && st->outcnt() == 1) { 3325 // Looking at a dead closed cycle of memory? 3326 assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal"); 3327 assert(Opcode() == st->Opcode() || 3328 st->Opcode() == Op_StoreVector || 3329 Opcode() == Op_StoreVector || 3330 st->Opcode() == Op_StoreVectorScatter || 3331 Opcode() == Op_StoreVectorScatter || 3332 phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw || 3333 (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode 3334 (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy 3335 (is_mismatched_access() || st->as_Store()->is_mismatched_access()), 3336 "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]); 3337 3338 if (st->in(MemNode::Address)->eqv_uncast(address) && 3339 st->as_Store()->memory_size() <= this->memory_size()) { 3340 Node* use = st->raw_out(0); 3341 if (phase->is_IterGVN()) { 3342 phase->is_IterGVN()->rehash_node_delayed(use); 3343 } 3344 // It's OK to do this in the parser, since DU info is always accurate, 3345 // and the parser always refers to nodes via SafePointNode maps. 3346 use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase); 3347 return this; 3348 } 3349 st = st->in(MemNode::Memory); 3350 } 3351 } 3352 3353 3354 // Capture an unaliased, unconditional, simple store into an initializer. 3355 // Or, if it is independent of the allocation, hoist it above the allocation. 3356 if (ReduceFieldZeroing && /*can_reshape &&*/ 3357 mem->is_Proj() && mem->in(0)->is_Initialize()) { 3358 InitializeNode* init = mem->in(0)->as_Initialize(); 3359 intptr_t offset = init->can_capture_store(this, phase, can_reshape); 3360 if (offset > 0) { 3361 Node* moved = init->capture_store(this, offset, phase, can_reshape); 3362 // If the InitializeNode captured me, it made a raw copy of me, 3363 // and I need to disappear. 3364 if (moved != nullptr) { 3365 // %%% hack to ensure that Ideal returns a new node: 3366 mem = MergeMemNode::make(mem); 3367 return mem; // fold me away 3368 } 3369 } 3370 } 3371 3372 // Fold reinterpret cast into memory operation: 3373 // StoreX mem (MoveY2X v) => StoreY mem v 3374 if (value->is_Move()) { 3375 const Type* vt = value->in(1)->bottom_type(); 3376 if (has_reinterpret_variant(vt)) { 3377 if (phase->C->post_loop_opts_phase()) { 3378 return convert_to_reinterpret_store(*phase, value->in(1), vt); 3379 } else { 3380 phase->C->record_for_post_loop_opts_igvn(this); // attempt the transformation once loop opts are over 3381 } 3382 } 3383 } 3384 3385 if (MergeStores && UseUnalignedAccesses) { 3386 if (phase->C->post_loop_opts_phase()) { 3387 MergePrimitiveStores merge(phase, this); 3388 Node* progress = merge.run(); 3389 if (progress != nullptr) { return progress; } 3390 } else { 3391 phase->C->record_for_post_loop_opts_igvn(this); 3392 } 3393 } 3394 3395 return nullptr; // No further progress 3396 } 3397 3398 //------------------------------Value----------------------------------------- 3399 const Type* StoreNode::Value(PhaseGVN* phase) const { 3400 // Either input is TOP ==> the result is TOP 3401 const Type *t1 = phase->type( in(MemNode::Memory) ); 3402 if( t1 == Type::TOP ) return Type::TOP; 3403 const Type *t2 = phase->type( in(MemNode::Address) ); 3404 if( t2 == Type::TOP ) return Type::TOP; 3405 const Type *t3 = phase->type( in(MemNode::ValueIn) ); 3406 if( t3 == Type::TOP ) return Type::TOP; 3407 return Type::MEMORY; 3408 } 3409 3410 //------------------------------Identity--------------------------------------- 3411 // Remove redundant stores: 3412 // Store(m, p, Load(m, p)) changes to m. 3413 // Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x). 3414 Node* StoreNode::Identity(PhaseGVN* phase) { 3415 Node* mem = in(MemNode::Memory); 3416 Node* adr = in(MemNode::Address); 3417 Node* val = in(MemNode::ValueIn); 3418 3419 Node* result = this; 3420 3421 // Load then Store? Then the Store is useless 3422 if (val->is_Load() && 3423 val->in(MemNode::Address)->eqv_uncast(adr) && 3424 val->in(MemNode::Memory )->eqv_uncast(mem) && 3425 val->as_Load()->store_Opcode() == Opcode()) { 3426 // Ensure vector type is the same 3427 if (!is_StoreVector() || (mem->is_LoadVector() && as_StoreVector()->vect_type() == mem->as_LoadVector()->vect_type())) { 3428 result = mem; 3429 } 3430 } 3431 3432 // Two stores in a row of the same value? 3433 if (result == this && 3434 mem->is_Store() && 3435 mem->in(MemNode::Address)->eqv_uncast(adr) && 3436 mem->in(MemNode::ValueIn)->eqv_uncast(val) && 3437 mem->Opcode() == Opcode()) { 3438 if (!is_StoreVector()) { 3439 result = mem; 3440 } else { 3441 const StoreVectorNode* store_vector = as_StoreVector(); 3442 const StoreVectorNode* mem_vector = mem->as_StoreVector(); 3443 const Node* store_indices = store_vector->indices(); 3444 const Node* mem_indices = mem_vector->indices(); 3445 const Node* store_mask = store_vector->mask(); 3446 const Node* mem_mask = mem_vector->mask(); 3447 // Ensure types, indices, and masks match 3448 if (store_vector->vect_type() == mem_vector->vect_type() && 3449 ((store_indices == nullptr) == (mem_indices == nullptr) && 3450 (store_indices == nullptr || store_indices->eqv_uncast(mem_indices))) && 3451 ((store_mask == nullptr) == (mem_mask == nullptr) && 3452 (store_mask == nullptr || store_mask->eqv_uncast(mem_mask)))) { 3453 result = mem; 3454 } 3455 } 3456 } 3457 3458 // Store of zero anywhere into a freshly-allocated object? 3459 // Then the store is useless. 3460 // (It must already have been captured by the InitializeNode.) 3461 if (result == this && 3462 ReduceFieldZeroing && phase->type(val)->is_zero_type()) { 3463 // a newly allocated object is already all-zeroes everywhere 3464 if (mem->is_Proj() && mem->in(0)->is_Allocate()) { 3465 result = mem; 3466 } 3467 3468 if (result == this) { 3469 // the store may also apply to zero-bits in an earlier object 3470 Node* prev_mem = find_previous_store(phase); 3471 // Steps (a), (b): Walk past independent stores to find an exact match. 3472 if (prev_mem != nullptr) { 3473 Node* prev_val = can_see_stored_value(prev_mem, phase); 3474 if (prev_val != nullptr && prev_val == val) { 3475 // prev_val and val might differ by a cast; it would be good 3476 // to keep the more informative of the two. 3477 result = mem; 3478 } 3479 } 3480 } 3481 } 3482 3483 PhaseIterGVN* igvn = phase->is_IterGVN(); 3484 if (result != this && igvn != nullptr) { 3485 MemBarNode* trailing = trailing_membar(); 3486 if (trailing != nullptr) { 3487 #ifdef ASSERT 3488 const TypeOopPtr* t_oop = phase->type(in(Address))->isa_oopptr(); 3489 assert(t_oop == nullptr || t_oop->is_known_instance_field(), "only for non escaping objects"); 3490 #endif 3491 trailing->remove(igvn); 3492 } 3493 } 3494 3495 return result; 3496 } 3497 3498 //------------------------------match_edge------------------------------------- 3499 // Do we Match on this edge index or not? Match only memory & value 3500 uint StoreNode::match_edge(uint idx) const { 3501 return idx == MemNode::Address || idx == MemNode::ValueIn; 3502 } 3503 3504 //------------------------------cmp-------------------------------------------- 3505 // Do not common stores up together. They generally have to be split 3506 // back up anyways, so do not bother. 3507 bool StoreNode::cmp( const Node &n ) const { 3508 return (&n == this); // Always fail except on self 3509 } 3510 3511 //------------------------------Ideal_masked_input----------------------------- 3512 // Check for a useless mask before a partial-word store 3513 // (StoreB ... (AndI valIn conIa) ) 3514 // If (conIa & mask == mask) this simplifies to 3515 // (StoreB ... (valIn) ) 3516 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) { 3517 Node *val = in(MemNode::ValueIn); 3518 if( val->Opcode() == Op_AndI ) { 3519 const TypeInt *t = phase->type( val->in(2) )->isa_int(); 3520 if( t && t->is_con() && (t->get_con() & mask) == mask ) { 3521 set_req_X(MemNode::ValueIn, val->in(1), phase); 3522 return this; 3523 } 3524 } 3525 return nullptr; 3526 } 3527 3528 3529 //------------------------------Ideal_sign_extended_input---------------------- 3530 // Check for useless sign-extension before a partial-word store 3531 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) ) 3532 // If (conIL == conIR && conIR <= num_bits) this simplifies to 3533 // (StoreB ... (valIn) ) 3534 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) { 3535 Node *val = in(MemNode::ValueIn); 3536 if( val->Opcode() == Op_RShiftI ) { 3537 const TypeInt *t = phase->type( val->in(2) )->isa_int(); 3538 if( t && t->is_con() && (t->get_con() <= num_bits) ) { 3539 Node *shl = val->in(1); 3540 if( shl->Opcode() == Op_LShiftI ) { 3541 const TypeInt *t2 = phase->type( shl->in(2) )->isa_int(); 3542 if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) { 3543 set_req_X(MemNode::ValueIn, shl->in(1), phase); 3544 return this; 3545 } 3546 } 3547 } 3548 } 3549 return nullptr; 3550 } 3551 3552 //------------------------------value_never_loaded----------------------------------- 3553 // Determine whether there are any possible loads of the value stored. 3554 // For simplicity, we actually check if there are any loads from the 3555 // address stored to, not just for loads of the value stored by this node. 3556 // 3557 bool StoreNode::value_never_loaded(PhaseValues* phase) const { 3558 Node *adr = in(Address); 3559 const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr(); 3560 if (adr_oop == nullptr) 3561 return false; 3562 if (!adr_oop->is_known_instance_field()) 3563 return false; // if not a distinct instance, there may be aliases of the address 3564 for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) { 3565 Node *use = adr->fast_out(i); 3566 if (use->is_Load() || use->is_LoadStore()) { 3567 return false; 3568 } 3569 } 3570 return true; 3571 } 3572 3573 MemBarNode* StoreNode::trailing_membar() const { 3574 if (is_release()) { 3575 MemBarNode* trailing_mb = nullptr; 3576 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) { 3577 Node* u = fast_out(i); 3578 if (u->is_MemBar()) { 3579 if (u->as_MemBar()->trailing_store()) { 3580 assert(u->Opcode() == Op_MemBarVolatile, ""); 3581 assert(trailing_mb == nullptr, "only one"); 3582 trailing_mb = u->as_MemBar(); 3583 #ifdef ASSERT 3584 Node* leading = u->as_MemBar()->leading_membar(); 3585 assert(leading->Opcode() == Op_MemBarRelease, "incorrect membar"); 3586 assert(leading->as_MemBar()->leading_store(), "incorrect membar pair"); 3587 assert(leading->as_MemBar()->trailing_membar() == u, "incorrect membar pair"); 3588 #endif 3589 } else { 3590 assert(u->as_MemBar()->standalone(), ""); 3591 } 3592 } 3593 } 3594 return trailing_mb; 3595 } 3596 return nullptr; 3597 } 3598 3599 3600 //============================================================================= 3601 //------------------------------Ideal------------------------------------------ 3602 // If the store is from an AND mask that leaves the low bits untouched, then 3603 // we can skip the AND operation. If the store is from a sign-extension 3604 // (a left shift, then right shift) we can skip both. 3605 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){ 3606 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF); 3607 if( progress != nullptr ) return progress; 3608 3609 progress = StoreNode::Ideal_sign_extended_input(phase, 24); 3610 if( progress != nullptr ) return progress; 3611 3612 // Finally check the default case 3613 return StoreNode::Ideal(phase, can_reshape); 3614 } 3615 3616 //============================================================================= 3617 //------------------------------Ideal------------------------------------------ 3618 // If the store is from an AND mask that leaves the low bits untouched, then 3619 // we can skip the AND operation 3620 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){ 3621 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF); 3622 if( progress != nullptr ) return progress; 3623 3624 progress = StoreNode::Ideal_sign_extended_input(phase, 16); 3625 if( progress != nullptr ) return progress; 3626 3627 // Finally check the default case 3628 return StoreNode::Ideal(phase, can_reshape); 3629 } 3630 3631 //============================================================================= 3632 //----------------------------------SCMemProjNode------------------------------ 3633 const Type* SCMemProjNode::Value(PhaseGVN* phase) const 3634 { 3635 if (in(0) == nullptr || phase->type(in(0)) == Type::TOP) { 3636 return Type::TOP; 3637 } 3638 return bottom_type(); 3639 } 3640 3641 //============================================================================= 3642 //----------------------------------LoadStoreNode------------------------------ 3643 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required ) 3644 : Node(required), 3645 _type(rt), 3646 _adr_type(at), 3647 _barrier_data(0) 3648 { 3649 init_req(MemNode::Control, c ); 3650 init_req(MemNode::Memory , mem); 3651 init_req(MemNode::Address, adr); 3652 init_req(MemNode::ValueIn, val); 3653 init_class_id(Class_LoadStore); 3654 } 3655 3656 //------------------------------Value----------------------------------------- 3657 const Type* LoadStoreNode::Value(PhaseGVN* phase) const { 3658 // Either input is TOP ==> the result is TOP 3659 if (!in(MemNode::Control) || phase->type(in(MemNode::Control)) == Type::TOP) { 3660 return Type::TOP; 3661 } 3662 const Type* t = phase->type(in(MemNode::Memory)); 3663 if (t == Type::TOP) { 3664 return Type::TOP; 3665 } 3666 t = phase->type(in(MemNode::Address)); 3667 if (t == Type::TOP) { 3668 return Type::TOP; 3669 } 3670 t = phase->type(in(MemNode::ValueIn)); 3671 if (t == Type::TOP) { 3672 return Type::TOP; 3673 } 3674 return bottom_type(); 3675 } 3676 3677 uint LoadStoreNode::ideal_reg() const { 3678 return _type->ideal_reg(); 3679 } 3680 3681 // This method conservatively checks if the result of a LoadStoreNode is 3682 // used, that is, if it returns true, then it is definitely the case that 3683 // the result of the node is not needed. 3684 // For example, GetAndAdd can be matched into a lock_add instead of a 3685 // lock_xadd if the result of LoadStoreNode::result_not_used() is true 3686 bool LoadStoreNode::result_not_used() const { 3687 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) { 3688 Node *x = fast_out(i); 3689 if (x->Opcode() == Op_SCMemProj) { 3690 continue; 3691 } 3692 if (x->bottom_type() == TypeTuple::MEMBAR && 3693 !x->is_Call() && 3694 x->Opcode() != Op_Blackhole) { 3695 continue; 3696 } 3697 return false; 3698 } 3699 return true; 3700 } 3701 3702 MemBarNode* LoadStoreNode::trailing_membar() const { 3703 MemBarNode* trailing = nullptr; 3704 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) { 3705 Node* u = fast_out(i); 3706 if (u->is_MemBar()) { 3707 if (u->as_MemBar()->trailing_load_store()) { 3708 assert(u->Opcode() == Op_MemBarAcquire, ""); 3709 assert(trailing == nullptr, "only one"); 3710 trailing = u->as_MemBar(); 3711 #ifdef ASSERT 3712 Node* leading = trailing->leading_membar(); 3713 assert(support_IRIW_for_not_multiple_copy_atomic_cpu || leading->Opcode() == Op_MemBarRelease, "incorrect membar"); 3714 assert(leading->as_MemBar()->leading_load_store(), "incorrect membar pair"); 3715 assert(leading->as_MemBar()->trailing_membar() == trailing, "incorrect membar pair"); 3716 #endif 3717 } else { 3718 assert(u->as_MemBar()->standalone(), "wrong barrier kind"); 3719 } 3720 } 3721 } 3722 3723 return trailing; 3724 } 3725 3726 uint LoadStoreNode::size_of() const { return sizeof(*this); } 3727 3728 //============================================================================= 3729 //----------------------------------LoadStoreConditionalNode-------------------- 3730 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, nullptr, TypeInt::BOOL, 5) { 3731 init_req(ExpectedIn, ex ); 3732 } 3733 3734 const Type* LoadStoreConditionalNode::Value(PhaseGVN* phase) const { 3735 // Either input is TOP ==> the result is TOP 3736 const Type* t = phase->type(in(ExpectedIn)); 3737 if (t == Type::TOP) { 3738 return Type::TOP; 3739 } 3740 return LoadStoreNode::Value(phase); 3741 } 3742 3743 //============================================================================= 3744 //-------------------------------adr_type-------------------------------------- 3745 const TypePtr* ClearArrayNode::adr_type() const { 3746 Node *adr = in(3); 3747 if (adr == nullptr) return nullptr; // node is dead 3748 return MemNode::calculate_adr_type(adr->bottom_type()); 3749 } 3750 3751 //------------------------------match_edge------------------------------------- 3752 // Do we Match on this edge index or not? Do not match memory 3753 uint ClearArrayNode::match_edge(uint idx) const { 3754 return idx > 1; 3755 } 3756 3757 //------------------------------Identity--------------------------------------- 3758 // Clearing a zero length array does nothing 3759 Node* ClearArrayNode::Identity(PhaseGVN* phase) { 3760 return phase->type(in(2))->higher_equal(TypeX::ZERO) ? in(1) : this; 3761 } 3762 3763 //------------------------------Idealize--------------------------------------- 3764 // Clearing a short array is faster with stores 3765 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) { 3766 // Already know this is a large node, do not try to ideal it 3767 if (_is_large) return nullptr; 3768 3769 const int unit = BytesPerLong; 3770 const TypeX* t = phase->type(in(2))->isa_intptr_t(); 3771 if (!t) return nullptr; 3772 if (!t->is_con()) return nullptr; 3773 intptr_t raw_count = t->get_con(); 3774 intptr_t size = raw_count; 3775 if (!Matcher::init_array_count_is_in_bytes) size *= unit; 3776 // Clearing nothing uses the Identity call. 3777 // Negative clears are possible on dead ClearArrays 3778 // (see jck test stmt114.stmt11402.val). 3779 if (size <= 0 || size % unit != 0) return nullptr; 3780 intptr_t count = size / unit; 3781 // Length too long; communicate this to matchers and assemblers. 3782 // Assemblers are responsible to produce fast hardware clears for it. 3783 if (size > InitArrayShortSize) { 3784 return new ClearArrayNode(in(0), in(1), in(2), in(3), true); 3785 } else if (size > 2 && Matcher::match_rule_supported_vector(Op_ClearArray, 4, T_LONG)) { 3786 return nullptr; 3787 } 3788 if (!IdealizeClearArrayNode) return nullptr; 3789 Node *mem = in(1); 3790 if( phase->type(mem)==Type::TOP ) return nullptr; 3791 Node *adr = in(3); 3792 const Type* at = phase->type(adr); 3793 if( at==Type::TOP ) return nullptr; 3794 const TypePtr* atp = at->isa_ptr(); 3795 // adjust atp to be the correct array element address type 3796 if (atp == nullptr) atp = TypePtr::BOTTOM; 3797 else atp = atp->add_offset(Type::OffsetBot); 3798 // Get base for derived pointer purposes 3799 if( adr->Opcode() != Op_AddP ) Unimplemented(); 3800 Node *base = adr->in(1); 3801 3802 Node *zero = phase->makecon(TypeLong::ZERO); 3803 Node *off = phase->MakeConX(BytesPerLong); 3804 mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false); 3805 count--; 3806 while( count-- ) { 3807 mem = phase->transform(mem); 3808 adr = phase->transform(new AddPNode(base,adr,off)); 3809 mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false); 3810 } 3811 return mem; 3812 } 3813 3814 //----------------------------step_through---------------------------------- 3815 // Return allocation input memory edge if it is different instance 3816 // or itself if it is the one we are looking for. 3817 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseValues* phase) { 3818 Node* n = *np; 3819 assert(n->is_ClearArray(), "sanity"); 3820 intptr_t offset; 3821 AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset); 3822 // This method is called only before Allocate nodes are expanded 3823 // during macro nodes expansion. Before that ClearArray nodes are 3824 // only generated in PhaseMacroExpand::generate_arraycopy() (before 3825 // Allocate nodes are expanded) which follows allocations. 3826 assert(alloc != nullptr, "should have allocation"); 3827 if (alloc->_idx == instance_id) { 3828 // Can not bypass initialization of the instance we are looking for. 3829 return false; 3830 } 3831 // Otherwise skip it. 3832 InitializeNode* init = alloc->initialization(); 3833 if (init != nullptr) 3834 *np = init->in(TypeFunc::Memory); 3835 else 3836 *np = alloc->in(TypeFunc::Memory); 3837 return true; 3838 } 3839 3840 //----------------------------clear_memory------------------------------------- 3841 // Generate code to initialize object storage to zero. 3842 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest, 3843 intptr_t start_offset, 3844 Node* end_offset, 3845 PhaseGVN* phase) { 3846 intptr_t offset = start_offset; 3847 3848 int unit = BytesPerLong; 3849 if ((offset % unit) != 0) { 3850 Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset)); 3851 adr = phase->transform(adr); 3852 const TypePtr* atp = TypeRawPtr::BOTTOM; 3853 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered); 3854 mem = phase->transform(mem); 3855 offset += BytesPerInt; 3856 } 3857 assert((offset % unit) == 0, ""); 3858 3859 // Initialize the remaining stuff, if any, with a ClearArray. 3860 return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase); 3861 } 3862 3863 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest, 3864 Node* start_offset, 3865 Node* end_offset, 3866 PhaseGVN* phase) { 3867 if (start_offset == end_offset) { 3868 // nothing to do 3869 return mem; 3870 } 3871 3872 int unit = BytesPerLong; 3873 Node* zbase = start_offset; 3874 Node* zend = end_offset; 3875 3876 // Scale to the unit required by the CPU: 3877 if (!Matcher::init_array_count_is_in_bytes) { 3878 Node* shift = phase->intcon(exact_log2(unit)); 3879 zbase = phase->transform(new URShiftXNode(zbase, shift) ); 3880 zend = phase->transform(new URShiftXNode(zend, shift) ); 3881 } 3882 3883 // Bulk clear double-words 3884 Node* zsize = phase->transform(new SubXNode(zend, zbase) ); 3885 Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) ); 3886 mem = new ClearArrayNode(ctl, mem, zsize, adr, false); 3887 return phase->transform(mem); 3888 } 3889 3890 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest, 3891 intptr_t start_offset, 3892 intptr_t end_offset, 3893 PhaseGVN* phase) { 3894 if (start_offset == end_offset) { 3895 // nothing to do 3896 return mem; 3897 } 3898 3899 assert((end_offset % BytesPerInt) == 0, "odd end offset"); 3900 intptr_t done_offset = end_offset; 3901 if ((done_offset % BytesPerLong) != 0) { 3902 done_offset -= BytesPerInt; 3903 } 3904 if (done_offset > start_offset) { 3905 mem = clear_memory(ctl, mem, dest, 3906 start_offset, phase->MakeConX(done_offset), phase); 3907 } 3908 if (done_offset < end_offset) { // emit the final 32-bit store 3909 Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset)); 3910 adr = phase->transform(adr); 3911 const TypePtr* atp = TypeRawPtr::BOTTOM; 3912 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered); 3913 mem = phase->transform(mem); 3914 done_offset += BytesPerInt; 3915 } 3916 assert(done_offset == end_offset, ""); 3917 return mem; 3918 } 3919 3920 //============================================================================= 3921 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent) 3922 : MultiNode(TypeFunc::Parms + (precedent == nullptr? 0: 1)), 3923 _adr_type(C->get_adr_type(alias_idx)), _kind(Standalone) 3924 #ifdef ASSERT 3925 , _pair_idx(0) 3926 #endif 3927 { 3928 init_class_id(Class_MemBar); 3929 Node* top = C->top(); 3930 init_req(TypeFunc::I_O,top); 3931 init_req(TypeFunc::FramePtr,top); 3932 init_req(TypeFunc::ReturnAdr,top); 3933 if (precedent != nullptr) 3934 init_req(TypeFunc::Parms, precedent); 3935 } 3936 3937 //------------------------------cmp-------------------------------------------- 3938 uint MemBarNode::hash() const { return NO_HASH; } 3939 bool MemBarNode::cmp( const Node &n ) const { 3940 return (&n == this); // Always fail except on self 3941 } 3942 3943 //------------------------------make------------------------------------------- 3944 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) { 3945 switch (opcode) { 3946 case Op_MemBarAcquire: return new MemBarAcquireNode(C, atp, pn); 3947 case Op_LoadFence: return new LoadFenceNode(C, atp, pn); 3948 case Op_MemBarRelease: return new MemBarReleaseNode(C, atp, pn); 3949 case Op_StoreFence: return new StoreFenceNode(C, atp, pn); 3950 case Op_MemBarStoreStore: return new MemBarStoreStoreNode(C, atp, pn); 3951 case Op_StoreStoreFence: return new StoreStoreFenceNode(C, atp, pn); 3952 case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn); 3953 case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn); 3954 case Op_MemBarVolatile: return new MemBarVolatileNode(C, atp, pn); 3955 case Op_MemBarCPUOrder: return new MemBarCPUOrderNode(C, atp, pn); 3956 case Op_OnSpinWait: return new OnSpinWaitNode(C, atp, pn); 3957 case Op_Initialize: return new InitializeNode(C, atp, pn); 3958 default: ShouldNotReachHere(); return nullptr; 3959 } 3960 } 3961 3962 void MemBarNode::remove(PhaseIterGVN *igvn) { 3963 if (outcnt() != 2) { 3964 assert(Opcode() == Op_Initialize, "Only seen when there are no use of init memory"); 3965 assert(outcnt() == 1, "Only control then"); 3966 } 3967 if (trailing_store() || trailing_load_store()) { 3968 MemBarNode* leading = leading_membar(); 3969 if (leading != nullptr) { 3970 assert(leading->trailing_membar() == this, "inconsistent leading/trailing membars"); 3971 leading->remove(igvn); 3972 } 3973 } 3974 if (proj_out_or_null(TypeFunc::Memory) != nullptr) { 3975 igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory)); 3976 } 3977 if (proj_out_or_null(TypeFunc::Control) != nullptr) { 3978 igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control)); 3979 } 3980 } 3981 3982 //------------------------------Ideal------------------------------------------ 3983 // Return a node which is more "ideal" than the current node. Strip out 3984 // control copies 3985 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) { 3986 if (remove_dead_region(phase, can_reshape)) return this; 3987 // Don't bother trying to transform a dead node 3988 if (in(0) && in(0)->is_top()) { 3989 return nullptr; 3990 } 3991 3992 bool progress = false; 3993 // Eliminate volatile MemBars for scalar replaced objects. 3994 if (can_reshape && req() == (Precedent+1)) { 3995 bool eliminate = false; 3996 int opc = Opcode(); 3997 if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) { 3998 // Volatile field loads and stores. 3999 Node* my_mem = in(MemBarNode::Precedent); 4000 // The MembarAquire may keep an unused LoadNode alive through the Precedent edge 4001 if ((my_mem != nullptr) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) { 4002 // if the Precedent is a decodeN and its input (a Load) is used at more than one place, 4003 // replace this Precedent (decodeN) with the Load instead. 4004 if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1)) { 4005 Node* load_node = my_mem->in(1); 4006 set_req(MemBarNode::Precedent, load_node); 4007 phase->is_IterGVN()->_worklist.push(my_mem); 4008 my_mem = load_node; 4009 } else { 4010 assert(my_mem->unique_out() == this, "sanity"); 4011 assert(!trailing_load_store(), "load store node can't be eliminated"); 4012 del_req(Precedent); 4013 phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later 4014 my_mem = nullptr; 4015 } 4016 progress = true; 4017 } 4018 if (my_mem != nullptr && my_mem->is_Mem()) { 4019 const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr(); 4020 // Check for scalar replaced object reference. 4021 if( t_oop != nullptr && t_oop->is_known_instance_field() && 4022 t_oop->offset() != Type::OffsetBot && 4023 t_oop->offset() != Type::OffsetTop) { 4024 eliminate = true; 4025 } 4026 } 4027 } else if (opc == Op_MemBarRelease || (UseStoreStoreForCtor && opc == Op_MemBarStoreStore)) { 4028 // Final field stores. 4029 Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent)); 4030 if ((alloc != nullptr) && alloc->is_Allocate() && 4031 alloc->as_Allocate()->does_not_escape_thread()) { 4032 // The allocated object does not escape. 4033 eliminate = true; 4034 } 4035 } 4036 if (eliminate) { 4037 // Replace MemBar projections by its inputs. 4038 PhaseIterGVN* igvn = phase->is_IterGVN(); 4039 remove(igvn); 4040 // Must return either the original node (now dead) or a new node 4041 // (Do not return a top here, since that would break the uniqueness of top.) 4042 return new ConINode(TypeInt::ZERO); 4043 } 4044 } 4045 return progress ? this : nullptr; 4046 } 4047 4048 //------------------------------Value------------------------------------------ 4049 const Type* MemBarNode::Value(PhaseGVN* phase) const { 4050 if( !in(0) ) return Type::TOP; 4051 if( phase->type(in(0)) == Type::TOP ) 4052 return Type::TOP; 4053 return TypeTuple::MEMBAR; 4054 } 4055 4056 //------------------------------match------------------------------------------ 4057 // Construct projections for memory. 4058 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) { 4059 switch (proj->_con) { 4060 case TypeFunc::Control: 4061 case TypeFunc::Memory: 4062 return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj); 4063 } 4064 ShouldNotReachHere(); 4065 return nullptr; 4066 } 4067 4068 void MemBarNode::set_store_pair(MemBarNode* leading, MemBarNode* trailing) { 4069 trailing->_kind = TrailingStore; 4070 leading->_kind = LeadingStore; 4071 #ifdef ASSERT 4072 trailing->_pair_idx = leading->_idx; 4073 leading->_pair_idx = leading->_idx; 4074 #endif 4075 } 4076 4077 void MemBarNode::set_load_store_pair(MemBarNode* leading, MemBarNode* trailing) { 4078 trailing->_kind = TrailingLoadStore; 4079 leading->_kind = LeadingLoadStore; 4080 #ifdef ASSERT 4081 trailing->_pair_idx = leading->_idx; 4082 leading->_pair_idx = leading->_idx; 4083 #endif 4084 } 4085 4086 MemBarNode* MemBarNode::trailing_membar() const { 4087 ResourceMark rm; 4088 Node* trailing = (Node*)this; 4089 VectorSet seen; 4090 Node_Stack multis(0); 4091 do { 4092 Node* c = trailing; 4093 uint i = 0; 4094 do { 4095 trailing = nullptr; 4096 for (; i < c->outcnt(); i++) { 4097 Node* next = c->raw_out(i); 4098 if (next != c && next->is_CFG()) { 4099 if (c->is_MultiBranch()) { 4100 if (multis.node() == c) { 4101 multis.set_index(i+1); 4102 } else { 4103 multis.push(c, i+1); 4104 } 4105 } 4106 trailing = next; 4107 break; 4108 } 4109 } 4110 if (trailing != nullptr && !seen.test_set(trailing->_idx)) { 4111 break; 4112 } 4113 while (multis.size() > 0) { 4114 c = multis.node(); 4115 i = multis.index(); 4116 if (i < c->req()) { 4117 break; 4118 } 4119 multis.pop(); 4120 } 4121 } while (multis.size() > 0); 4122 } while (!trailing->is_MemBar() || !trailing->as_MemBar()->trailing()); 4123 4124 MemBarNode* mb = trailing->as_MemBar(); 4125 assert((mb->_kind == TrailingStore && _kind == LeadingStore) || 4126 (mb->_kind == TrailingLoadStore && _kind == LeadingLoadStore), "bad trailing membar"); 4127 assert(mb->_pair_idx == _pair_idx, "bad trailing membar"); 4128 return mb; 4129 } 4130 4131 MemBarNode* MemBarNode::leading_membar() const { 4132 ResourceMark rm; 4133 VectorSet seen; 4134 Node_Stack regions(0); 4135 Node* leading = in(0); 4136 while (leading != nullptr && (!leading->is_MemBar() || !leading->as_MemBar()->leading())) { 4137 while (leading == nullptr || leading->is_top() || seen.test_set(leading->_idx)) { 4138 leading = nullptr; 4139 while (regions.size() > 0 && leading == nullptr) { 4140 Node* r = regions.node(); 4141 uint i = regions.index(); 4142 if (i < r->req()) { 4143 leading = r->in(i); 4144 regions.set_index(i+1); 4145 } else { 4146 regions.pop(); 4147 } 4148 } 4149 if (leading == nullptr) { 4150 assert(regions.size() == 0, "all paths should have been tried"); 4151 return nullptr; 4152 } 4153 } 4154 if (leading->is_Region()) { 4155 regions.push(leading, 2); 4156 leading = leading->in(1); 4157 } else { 4158 leading = leading->in(0); 4159 } 4160 } 4161 #ifdef ASSERT 4162 Unique_Node_List wq; 4163 wq.push((Node*)this); 4164 uint found = 0; 4165 for (uint i = 0; i < wq.size(); i++) { 4166 Node* n = wq.at(i); 4167 if (n->is_Region()) { 4168 for (uint j = 1; j < n->req(); j++) { 4169 Node* in = n->in(j); 4170 if (in != nullptr && !in->is_top()) { 4171 wq.push(in); 4172 } 4173 } 4174 } else { 4175 if (n->is_MemBar() && n->as_MemBar()->leading()) { 4176 assert(n == leading, "consistency check failed"); 4177 found++; 4178 } else { 4179 Node* in = n->in(0); 4180 if (in != nullptr && !in->is_top()) { 4181 wq.push(in); 4182 } 4183 } 4184 } 4185 } 4186 assert(found == 1 || (found == 0 && leading == nullptr), "consistency check failed"); 4187 #endif 4188 if (leading == nullptr) { 4189 return nullptr; 4190 } 4191 MemBarNode* mb = leading->as_MemBar(); 4192 assert((mb->_kind == LeadingStore && _kind == TrailingStore) || 4193 (mb->_kind == LeadingLoadStore && _kind == TrailingLoadStore), "bad leading membar"); 4194 assert(mb->_pair_idx == _pair_idx, "bad leading membar"); 4195 return mb; 4196 } 4197 4198 4199 //===========================InitializeNode==================================== 4200 // SUMMARY: 4201 // This node acts as a memory barrier on raw memory, after some raw stores. 4202 // The 'cooked' oop value feeds from the Initialize, not the Allocation. 4203 // The Initialize can 'capture' suitably constrained stores as raw inits. 4204 // It can coalesce related raw stores into larger units (called 'tiles'). 4205 // It can avoid zeroing new storage for memory units which have raw inits. 4206 // At macro-expansion, it is marked 'complete', and does not optimize further. 4207 // 4208 // EXAMPLE: 4209 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine. 4210 // ctl = incoming control; mem* = incoming memory 4211 // (Note: A star * on a memory edge denotes I/O and other standard edges.) 4212 // First allocate uninitialized memory and fill in the header: 4213 // alloc = (Allocate ctl mem* 16 #short[].klass ...) 4214 // ctl := alloc.Control; mem* := alloc.Memory* 4215 // rawmem = alloc.Memory; rawoop = alloc.RawAddress 4216 // Then initialize to zero the non-header parts of the raw memory block: 4217 // init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress) 4218 // ctl := init.Control; mem.SLICE(#short[*]) := init.Memory 4219 // After the initialize node executes, the object is ready for service: 4220 // oop := (CheckCastPP init.Control alloc.RawAddress #short[]) 4221 // Suppose its body is immediately initialized as {1,2}: 4222 // store1 = (StoreC init.Control init.Memory (+ oop 12) 1) 4223 // store2 = (StoreC init.Control store1 (+ oop 14) 2) 4224 // mem.SLICE(#short[*]) := store2 4225 // 4226 // DETAILS: 4227 // An InitializeNode collects and isolates object initialization after 4228 // an AllocateNode and before the next possible safepoint. As a 4229 // memory barrier (MemBarNode), it keeps critical stores from drifting 4230 // down past any safepoint or any publication of the allocation. 4231 // Before this barrier, a newly-allocated object may have uninitialized bits. 4232 // After this barrier, it may be treated as a real oop, and GC is allowed. 4233 // 4234 // The semantics of the InitializeNode include an implicit zeroing of 4235 // the new object from object header to the end of the object. 4236 // (The object header and end are determined by the AllocateNode.) 4237 // 4238 // Certain stores may be added as direct inputs to the InitializeNode. 4239 // These stores must update raw memory, and they must be to addresses 4240 // derived from the raw address produced by AllocateNode, and with 4241 // a constant offset. They must be ordered by increasing offset. 4242 // The first one is at in(RawStores), the last at in(req()-1). 4243 // Unlike most memory operations, they are not linked in a chain, 4244 // but are displayed in parallel as users of the rawmem output of 4245 // the allocation. 4246 // 4247 // (See comments in InitializeNode::capture_store, which continue 4248 // the example given above.) 4249 // 4250 // When the associated Allocate is macro-expanded, the InitializeNode 4251 // may be rewritten to optimize collected stores. A ClearArrayNode 4252 // may also be created at that point to represent any required zeroing. 4253 // The InitializeNode is then marked 'complete', prohibiting further 4254 // capturing of nearby memory operations. 4255 // 4256 // During macro-expansion, all captured initializations which store 4257 // constant values of 32 bits or smaller are coalesced (if advantageous) 4258 // into larger 'tiles' 32 or 64 bits. This allows an object to be 4259 // initialized in fewer memory operations. Memory words which are 4260 // covered by neither tiles nor non-constant stores are pre-zeroed 4261 // by explicit stores of zero. (The code shape happens to do all 4262 // zeroing first, then all other stores, with both sequences occurring 4263 // in order of ascending offsets.) 4264 // 4265 // Alternatively, code may be inserted between an AllocateNode and its 4266 // InitializeNode, to perform arbitrary initialization of the new object. 4267 // E.g., the object copying intrinsics insert complex data transfers here. 4268 // The initialization must then be marked as 'complete' disable the 4269 // built-in zeroing semantics and the collection of initializing stores. 4270 // 4271 // While an InitializeNode is incomplete, reads from the memory state 4272 // produced by it are optimizable if they match the control edge and 4273 // new oop address associated with the allocation/initialization. 4274 // They return a stored value (if the offset matches) or else zero. 4275 // A write to the memory state, if it matches control and address, 4276 // and if it is to a constant offset, may be 'captured' by the 4277 // InitializeNode. It is cloned as a raw memory operation and rewired 4278 // inside the initialization, to the raw oop produced by the allocation. 4279 // Operations on addresses which are provably distinct (e.g., to 4280 // other AllocateNodes) are allowed to bypass the initialization. 4281 // 4282 // The effect of all this is to consolidate object initialization 4283 // (both arrays and non-arrays, both piecewise and bulk) into a 4284 // single location, where it can be optimized as a unit. 4285 // 4286 // Only stores with an offset less than TrackedInitializationLimit words 4287 // will be considered for capture by an InitializeNode. This puts a 4288 // reasonable limit on the complexity of optimized initializations. 4289 4290 //---------------------------InitializeNode------------------------------------ 4291 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop) 4292 : MemBarNode(C, adr_type, rawoop), 4293 _is_complete(Incomplete), _does_not_escape(false) 4294 { 4295 init_class_id(Class_Initialize); 4296 4297 assert(adr_type == Compile::AliasIdxRaw, "only valid atp"); 4298 assert(in(RawAddress) == rawoop, "proper init"); 4299 // Note: allocation() can be null, for secondary initialization barriers 4300 } 4301 4302 // Since this node is not matched, it will be processed by the 4303 // register allocator. Declare that there are no constraints 4304 // on the allocation of the RawAddress edge. 4305 const RegMask &InitializeNode::in_RegMask(uint idx) const { 4306 // This edge should be set to top, by the set_complete. But be conservative. 4307 if (idx == InitializeNode::RawAddress) 4308 return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]); 4309 return RegMask::Empty; 4310 } 4311 4312 Node* InitializeNode::memory(uint alias_idx) { 4313 Node* mem = in(Memory); 4314 if (mem->is_MergeMem()) { 4315 return mem->as_MergeMem()->memory_at(alias_idx); 4316 } else { 4317 // incoming raw memory is not split 4318 return mem; 4319 } 4320 } 4321 4322 bool InitializeNode::is_non_zero() { 4323 if (is_complete()) return false; 4324 remove_extra_zeroes(); 4325 return (req() > RawStores); 4326 } 4327 4328 void InitializeNode::set_complete(PhaseGVN* phase) { 4329 assert(!is_complete(), "caller responsibility"); 4330 _is_complete = Complete; 4331 4332 // After this node is complete, it contains a bunch of 4333 // raw-memory initializations. There is no need for 4334 // it to have anything to do with non-raw memory effects. 4335 // Therefore, tell all non-raw users to re-optimize themselves, 4336 // after skipping the memory effects of this initialization. 4337 PhaseIterGVN* igvn = phase->is_IterGVN(); 4338 if (igvn) igvn->add_users_to_worklist(this); 4339 } 4340 4341 // convenience function 4342 // return false if the init contains any stores already 4343 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) { 4344 InitializeNode* init = initialization(); 4345 if (init == nullptr || init->is_complete()) return false; 4346 init->remove_extra_zeroes(); 4347 // for now, if this allocation has already collected any inits, bail: 4348 if (init->is_non_zero()) return false; 4349 init->set_complete(phase); 4350 return true; 4351 } 4352 4353 void InitializeNode::remove_extra_zeroes() { 4354 if (req() == RawStores) return; 4355 Node* zmem = zero_memory(); 4356 uint fill = RawStores; 4357 for (uint i = fill; i < req(); i++) { 4358 Node* n = in(i); 4359 if (n->is_top() || n == zmem) continue; // skip 4360 if (fill < i) set_req(fill, n); // compact 4361 ++fill; 4362 } 4363 // delete any empty spaces created: 4364 while (fill < req()) { 4365 del_req(fill); 4366 } 4367 } 4368 4369 // Helper for remembering which stores go with which offsets. 4370 intptr_t InitializeNode::get_store_offset(Node* st, PhaseValues* phase) { 4371 if (!st->is_Store()) return -1; // can happen to dead code via subsume_node 4372 intptr_t offset = -1; 4373 Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address), 4374 phase, offset); 4375 if (base == nullptr) return -1; // something is dead, 4376 if (offset < 0) return -1; // dead, dead 4377 return offset; 4378 } 4379 4380 // Helper for proving that an initialization expression is 4381 // "simple enough" to be folded into an object initialization. 4382 // Attempts to prove that a store's initial value 'n' can be captured 4383 // within the initialization without creating a vicious cycle, such as: 4384 // { Foo p = new Foo(); p.next = p; } 4385 // True for constants and parameters and small combinations thereof. 4386 bool InitializeNode::detect_init_independence(Node* value, PhaseGVN* phase) { 4387 ResourceMark rm; 4388 Unique_Node_List worklist; 4389 worklist.push(value); 4390 4391 uint complexity_limit = 20; 4392 for (uint j = 0; j < worklist.size(); j++) { 4393 if (j >= complexity_limit) { 4394 return false; // Bail out if processed too many nodes 4395 } 4396 4397 Node* n = worklist.at(j); 4398 if (n == nullptr) continue; // (can this really happen?) 4399 if (n->is_Proj()) n = n->in(0); 4400 if (n == this) return false; // found a cycle 4401 if (n->is_Con()) continue; 4402 if (n->is_Start()) continue; // params, etc., are OK 4403 if (n->is_Root()) continue; // even better 4404 4405 // There cannot be any dependency if 'n' is a CFG node that dominates the current allocation 4406 if (n->is_CFG() && phase->is_dominator(n, allocation())) { 4407 continue; 4408 } 4409 4410 Node* ctl = n->in(0); 4411 if (ctl != nullptr && !ctl->is_top()) { 4412 if (ctl->is_Proj()) ctl = ctl->in(0); 4413 if (ctl == this) return false; 4414 4415 // If we already know that the enclosing memory op is pinned right after 4416 // the init, then any control flow that the store has picked up 4417 // must have preceded the init, or else be equal to the init. 4418 // Even after loop optimizations (which might change control edges) 4419 // a store is never pinned *before* the availability of its inputs. 4420 if (!MemNode::all_controls_dominate(n, this)) { 4421 return false; // failed to prove a good control 4422 } 4423 } 4424 4425 // Check data edges for possible dependencies on 'this'. 4426 for (uint i = 1; i < n->req(); i++) { 4427 Node* m = n->in(i); 4428 if (m == nullptr || m == n || m->is_top()) continue; 4429 4430 // Only process data inputs once 4431 worklist.push(m); 4432 } 4433 } 4434 4435 return true; 4436 } 4437 4438 // Here are all the checks a Store must pass before it can be moved into 4439 // an initialization. Returns zero if a check fails. 4440 // On success, returns the (constant) offset to which the store applies, 4441 // within the initialized memory. 4442 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseGVN* phase, bool can_reshape) { 4443 const int FAIL = 0; 4444 if (st->req() != MemNode::ValueIn + 1) 4445 return FAIL; // an inscrutable StoreNode (card mark?) 4446 Node* ctl = st->in(MemNode::Control); 4447 if (!(ctl != nullptr && ctl->is_Proj() && ctl->in(0) == this)) 4448 return FAIL; // must be unconditional after the initialization 4449 Node* mem = st->in(MemNode::Memory); 4450 if (!(mem->is_Proj() && mem->in(0) == this)) 4451 return FAIL; // must not be preceded by other stores 4452 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 4453 if ((st->Opcode() == Op_StoreP || st->Opcode() == Op_StoreN) && 4454 !bs->can_initialize_object(st)) { 4455 return FAIL; 4456 } 4457 Node* adr = st->in(MemNode::Address); 4458 intptr_t offset; 4459 AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset); 4460 if (alloc == nullptr) 4461 return FAIL; // inscrutable address 4462 if (alloc != allocation()) 4463 return FAIL; // wrong allocation! (store needs to float up) 4464 int size_in_bytes = st->memory_size(); 4465 if ((size_in_bytes != 0) && (offset % size_in_bytes) != 0) { 4466 return FAIL; // mismatched access 4467 } 4468 Node* val = st->in(MemNode::ValueIn); 4469 4470 if (!detect_init_independence(val, phase)) 4471 return FAIL; // stored value must be 'simple enough' 4472 4473 // The Store can be captured only if nothing after the allocation 4474 // and before the Store is using the memory location that the store 4475 // overwrites. 4476 bool failed = false; 4477 // If is_complete_with_arraycopy() is true the shape of the graph is 4478 // well defined and is safe so no need for extra checks. 4479 if (!is_complete_with_arraycopy()) { 4480 // We are going to look at each use of the memory state following 4481 // the allocation to make sure nothing reads the memory that the 4482 // Store writes. 4483 const TypePtr* t_adr = phase->type(adr)->isa_ptr(); 4484 int alias_idx = phase->C->get_alias_index(t_adr); 4485 ResourceMark rm; 4486 Unique_Node_List mems; 4487 mems.push(mem); 4488 Node* unique_merge = nullptr; 4489 for (uint next = 0; next < mems.size(); ++next) { 4490 Node *m = mems.at(next); 4491 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) { 4492 Node *n = m->fast_out(j); 4493 if (n->outcnt() == 0) { 4494 continue; 4495 } 4496 if (n == st) { 4497 continue; 4498 } else if (n->in(0) != nullptr && n->in(0) != ctl) { 4499 // If the control of this use is different from the control 4500 // of the Store which is right after the InitializeNode then 4501 // this node cannot be between the InitializeNode and the 4502 // Store. 4503 continue; 4504 } else if (n->is_MergeMem()) { 4505 if (n->as_MergeMem()->memory_at(alias_idx) == m) { 4506 // We can hit a MergeMemNode (that will likely go away 4507 // later) that is a direct use of the memory state 4508 // following the InitializeNode on the same slice as the 4509 // store node that we'd like to capture. We need to check 4510 // the uses of the MergeMemNode. 4511 mems.push(n); 4512 } 4513 } else if (n->is_Mem()) { 4514 Node* other_adr = n->in(MemNode::Address); 4515 if (other_adr == adr) { 4516 failed = true; 4517 break; 4518 } else { 4519 const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr(); 4520 if (other_t_adr != nullptr) { 4521 int other_alias_idx = phase->C->get_alias_index(other_t_adr); 4522 if (other_alias_idx == alias_idx) { 4523 // A load from the same memory slice as the store right 4524 // after the InitializeNode. We check the control of the 4525 // object/array that is loaded from. If it's the same as 4526 // the store control then we cannot capture the store. 4527 assert(!n->is_Store(), "2 stores to same slice on same control?"); 4528 Node* base = other_adr; 4529 assert(base->is_AddP(), "should be addp but is %s", base->Name()); 4530 base = base->in(AddPNode::Base); 4531 if (base != nullptr) { 4532 base = base->uncast(); 4533 if (base->is_Proj() && base->in(0) == alloc) { 4534 failed = true; 4535 break; 4536 } 4537 } 4538 } 4539 } 4540 } 4541 } else { 4542 failed = true; 4543 break; 4544 } 4545 } 4546 } 4547 } 4548 if (failed) { 4549 if (!can_reshape) { 4550 // We decided we couldn't capture the store during parsing. We 4551 // should try again during the next IGVN once the graph is 4552 // cleaner. 4553 phase->C->record_for_igvn(st); 4554 } 4555 return FAIL; 4556 } 4557 4558 return offset; // success 4559 } 4560 4561 // Find the captured store in(i) which corresponds to the range 4562 // [start..start+size) in the initialized object. 4563 // If there is one, return its index i. If there isn't, return the 4564 // negative of the index where it should be inserted. 4565 // Return 0 if the queried range overlaps an initialization boundary 4566 // or if dead code is encountered. 4567 // If size_in_bytes is zero, do not bother with overlap checks. 4568 int InitializeNode::captured_store_insertion_point(intptr_t start, 4569 int size_in_bytes, 4570 PhaseValues* phase) { 4571 const int FAIL = 0, MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize); 4572 4573 if (is_complete()) 4574 return FAIL; // arraycopy got here first; punt 4575 4576 assert(allocation() != nullptr, "must be present"); 4577 4578 // no negatives, no header fields: 4579 if (start < (intptr_t) allocation()->minimum_header_size()) return FAIL; 4580 4581 // after a certain size, we bail out on tracking all the stores: 4582 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize); 4583 if (start >= ti_limit) return FAIL; 4584 4585 for (uint i = InitializeNode::RawStores, limit = req(); ; ) { 4586 if (i >= limit) return -(int)i; // not found; here is where to put it 4587 4588 Node* st = in(i); 4589 intptr_t st_off = get_store_offset(st, phase); 4590 if (st_off < 0) { 4591 if (st != zero_memory()) { 4592 return FAIL; // bail out if there is dead garbage 4593 } 4594 } else if (st_off > start) { 4595 // ...we are done, since stores are ordered 4596 if (st_off < start + size_in_bytes) { 4597 return FAIL; // the next store overlaps 4598 } 4599 return -(int)i; // not found; here is where to put it 4600 } else if (st_off < start) { 4601 assert(st->as_Store()->memory_size() <= MAX_STORE, ""); 4602 if (size_in_bytes != 0 && 4603 start < st_off + MAX_STORE && 4604 start < st_off + st->as_Store()->memory_size()) { 4605 return FAIL; // the previous store overlaps 4606 } 4607 } else { 4608 if (size_in_bytes != 0 && 4609 st->as_Store()->memory_size() != size_in_bytes) { 4610 return FAIL; // mismatched store size 4611 } 4612 return i; 4613 } 4614 4615 ++i; 4616 } 4617 } 4618 4619 // Look for a captured store which initializes at the offset 'start' 4620 // with the given size. If there is no such store, and no other 4621 // initialization interferes, then return zero_memory (the memory 4622 // projection of the AllocateNode). 4623 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes, 4624 PhaseValues* phase) { 4625 assert(stores_are_sane(phase), ""); 4626 int i = captured_store_insertion_point(start, size_in_bytes, phase); 4627 if (i == 0) { 4628 return nullptr; // something is dead 4629 } else if (i < 0) { 4630 return zero_memory(); // just primordial zero bits here 4631 } else { 4632 Node* st = in(i); // here is the store at this position 4633 assert(get_store_offset(st->as_Store(), phase) == start, "sanity"); 4634 return st; 4635 } 4636 } 4637 4638 // Create, as a raw pointer, an address within my new object at 'offset'. 4639 Node* InitializeNode::make_raw_address(intptr_t offset, 4640 PhaseGVN* phase) { 4641 Node* addr = in(RawAddress); 4642 if (offset != 0) { 4643 Compile* C = phase->C; 4644 addr = phase->transform( new AddPNode(C->top(), addr, 4645 phase->MakeConX(offset)) ); 4646 } 4647 return addr; 4648 } 4649 4650 // Clone the given store, converting it into a raw store 4651 // initializing a field or element of my new object. 4652 // Caller is responsible for retiring the original store, 4653 // with subsume_node or the like. 4654 // 4655 // From the example above InitializeNode::InitializeNode, 4656 // here are the old stores to be captured: 4657 // store1 = (StoreC init.Control init.Memory (+ oop 12) 1) 4658 // store2 = (StoreC init.Control store1 (+ oop 14) 2) 4659 // 4660 // Here is the changed code; note the extra edges on init: 4661 // alloc = (Allocate ...) 4662 // rawoop = alloc.RawAddress 4663 // rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1) 4664 // rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2) 4665 // init = (Initialize alloc.Control alloc.Memory rawoop 4666 // rawstore1 rawstore2) 4667 // 4668 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start, 4669 PhaseGVN* phase, bool can_reshape) { 4670 assert(stores_are_sane(phase), ""); 4671 4672 if (start < 0) return nullptr; 4673 assert(can_capture_store(st, phase, can_reshape) == start, "sanity"); 4674 4675 Compile* C = phase->C; 4676 int size_in_bytes = st->memory_size(); 4677 int i = captured_store_insertion_point(start, size_in_bytes, phase); 4678 if (i == 0) return nullptr; // bail out 4679 Node* prev_mem = nullptr; // raw memory for the captured store 4680 if (i > 0) { 4681 prev_mem = in(i); // there is a pre-existing store under this one 4682 set_req(i, C->top()); // temporarily disconnect it 4683 // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect. 4684 } else { 4685 i = -i; // no pre-existing store 4686 prev_mem = zero_memory(); // a slice of the newly allocated object 4687 if (i > InitializeNode::RawStores && in(i-1) == prev_mem) 4688 set_req(--i, C->top()); // reuse this edge; it has been folded away 4689 else 4690 ins_req(i, C->top()); // build a new edge 4691 } 4692 Node* new_st = st->clone(); 4693 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 4694 new_st->set_req(MemNode::Control, in(Control)); 4695 new_st->set_req(MemNode::Memory, prev_mem); 4696 new_st->set_req(MemNode::Address, make_raw_address(start, phase)); 4697 bs->eliminate_gc_barrier_data(new_st); 4698 new_st = phase->transform(new_st); 4699 4700 // At this point, new_st might have swallowed a pre-existing store 4701 // at the same offset, or perhaps new_st might have disappeared, 4702 // if it redundantly stored the same value (or zero to fresh memory). 4703 4704 // In any case, wire it in: 4705 PhaseIterGVN* igvn = phase->is_IterGVN(); 4706 if (igvn) { 4707 igvn->rehash_node_delayed(this); 4708 } 4709 set_req(i, new_st); 4710 4711 // The caller may now kill the old guy. 4712 DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase)); 4713 assert(check_st == new_st || check_st == nullptr, "must be findable"); 4714 assert(!is_complete(), ""); 4715 return new_st; 4716 } 4717 4718 static bool store_constant(jlong* tiles, int num_tiles, 4719 intptr_t st_off, int st_size, 4720 jlong con) { 4721 if ((st_off & (st_size-1)) != 0) 4722 return false; // strange store offset (assume size==2**N) 4723 address addr = (address)tiles + st_off; 4724 assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob"); 4725 switch (st_size) { 4726 case sizeof(jbyte): *(jbyte*) addr = (jbyte) con; break; 4727 case sizeof(jchar): *(jchar*) addr = (jchar) con; break; 4728 case sizeof(jint): *(jint*) addr = (jint) con; break; 4729 case sizeof(jlong): *(jlong*) addr = (jlong) con; break; 4730 default: return false; // strange store size (detect size!=2**N here) 4731 } 4732 return true; // return success to caller 4733 } 4734 4735 // Coalesce subword constants into int constants and possibly 4736 // into long constants. The goal, if the CPU permits, 4737 // is to initialize the object with a small number of 64-bit tiles. 4738 // Also, convert floating-point constants to bit patterns. 4739 // Non-constants are not relevant to this pass. 4740 // 4741 // In terms of the running example on InitializeNode::InitializeNode 4742 // and InitializeNode::capture_store, here is the transformation 4743 // of rawstore1 and rawstore2 into rawstore12: 4744 // alloc = (Allocate ...) 4745 // rawoop = alloc.RawAddress 4746 // tile12 = 0x00010002 4747 // rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12) 4748 // init = (Initialize alloc.Control alloc.Memory rawoop rawstore12) 4749 // 4750 void 4751 InitializeNode::coalesce_subword_stores(intptr_t header_size, 4752 Node* size_in_bytes, 4753 PhaseGVN* phase) { 4754 Compile* C = phase->C; 4755 4756 assert(stores_are_sane(phase), ""); 4757 // Note: After this pass, they are not completely sane, 4758 // since there may be some overlaps. 4759 4760 int old_subword = 0, old_long = 0, new_int = 0, new_long = 0; 4761 4762 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize); 4763 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit); 4764 size_limit = MIN2(size_limit, ti_limit); 4765 size_limit = align_up(size_limit, BytesPerLong); 4766 int num_tiles = size_limit / BytesPerLong; 4767 4768 // allocate space for the tile map: 4769 const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small 4770 jlong tiles_buf[small_len]; 4771 Node* nodes_buf[small_len]; 4772 jlong inits_buf[small_len]; 4773 jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0] 4774 : NEW_RESOURCE_ARRAY(jlong, num_tiles)); 4775 Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0] 4776 : NEW_RESOURCE_ARRAY(Node*, num_tiles)); 4777 jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0] 4778 : NEW_RESOURCE_ARRAY(jlong, num_tiles)); 4779 // tiles: exact bitwise model of all primitive constants 4780 // nodes: last constant-storing node subsumed into the tiles model 4781 // inits: which bytes (in each tile) are touched by any initializations 4782 4783 //// Pass A: Fill in the tile model with any relevant stores. 4784 4785 Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles); 4786 Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles); 4787 Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles); 4788 Node* zmem = zero_memory(); // initially zero memory state 4789 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) { 4790 Node* st = in(i); 4791 intptr_t st_off = get_store_offset(st, phase); 4792 4793 // Figure out the store's offset and constant value: 4794 if (st_off < header_size) continue; //skip (ignore header) 4795 if (st->in(MemNode::Memory) != zmem) continue; //skip (odd store chain) 4796 int st_size = st->as_Store()->memory_size(); 4797 if (st_off + st_size > size_limit) break; 4798 4799 // Record which bytes are touched, whether by constant or not. 4800 if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1)) 4801 continue; // skip (strange store size) 4802 4803 const Type* val = phase->type(st->in(MemNode::ValueIn)); 4804 if (!val->singleton()) continue; //skip (non-con store) 4805 BasicType type = val->basic_type(); 4806 4807 jlong con = 0; 4808 switch (type) { 4809 case T_INT: con = val->is_int()->get_con(); break; 4810 case T_LONG: con = val->is_long()->get_con(); break; 4811 case T_FLOAT: con = jint_cast(val->getf()); break; 4812 case T_DOUBLE: con = jlong_cast(val->getd()); break; 4813 default: continue; //skip (odd store type) 4814 } 4815 4816 if (type == T_LONG && Matcher::isSimpleConstant64(con) && 4817 st->Opcode() == Op_StoreL) { 4818 continue; // This StoreL is already optimal. 4819 } 4820 4821 // Store down the constant. 4822 store_constant(tiles, num_tiles, st_off, st_size, con); 4823 4824 intptr_t j = st_off >> LogBytesPerLong; 4825 4826 if (type == T_INT && st_size == BytesPerInt 4827 && (st_off & BytesPerInt) == BytesPerInt) { 4828 jlong lcon = tiles[j]; 4829 if (!Matcher::isSimpleConstant64(lcon) && 4830 st->Opcode() == Op_StoreI) { 4831 // This StoreI is already optimal by itself. 4832 jint* intcon = (jint*) &tiles[j]; 4833 intcon[1] = 0; // undo the store_constant() 4834 4835 // If the previous store is also optimal by itself, back up and 4836 // undo the action of the previous loop iteration... if we can. 4837 // But if we can't, just let the previous half take care of itself. 4838 st = nodes[j]; 4839 st_off -= BytesPerInt; 4840 con = intcon[0]; 4841 if (con != 0 && st != nullptr && st->Opcode() == Op_StoreI) { 4842 assert(st_off >= header_size, "still ignoring header"); 4843 assert(get_store_offset(st, phase) == st_off, "must be"); 4844 assert(in(i-1) == zmem, "must be"); 4845 DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn))); 4846 assert(con == tcon->is_int()->get_con(), "must be"); 4847 // Undo the effects of the previous loop trip, which swallowed st: 4848 intcon[0] = 0; // undo store_constant() 4849 set_req(i-1, st); // undo set_req(i, zmem) 4850 nodes[j] = nullptr; // undo nodes[j] = st 4851 --old_subword; // undo ++old_subword 4852 } 4853 continue; // This StoreI is already optimal. 4854 } 4855 } 4856 4857 // This store is not needed. 4858 set_req(i, zmem); 4859 nodes[j] = st; // record for the moment 4860 if (st_size < BytesPerLong) // something has changed 4861 ++old_subword; // includes int/float, but who's counting... 4862 else ++old_long; 4863 } 4864 4865 if ((old_subword + old_long) == 0) 4866 return; // nothing more to do 4867 4868 //// Pass B: Convert any non-zero tiles into optimal constant stores. 4869 // Be sure to insert them before overlapping non-constant stores. 4870 // (E.g., byte[] x = { 1,2,y,4 } => x[int 0] = 0x01020004, x[2]=y.) 4871 for (int j = 0; j < num_tiles; j++) { 4872 jlong con = tiles[j]; 4873 jlong init = inits[j]; 4874 if (con == 0) continue; 4875 jint con0, con1; // split the constant, address-wise 4876 jint init0, init1; // split the init map, address-wise 4877 { union { jlong con; jint intcon[2]; } u; 4878 u.con = con; 4879 con0 = u.intcon[0]; 4880 con1 = u.intcon[1]; 4881 u.con = init; 4882 init0 = u.intcon[0]; 4883 init1 = u.intcon[1]; 4884 } 4885 4886 Node* old = nodes[j]; 4887 assert(old != nullptr, "need the prior store"); 4888 intptr_t offset = (j * BytesPerLong); 4889 4890 bool split = !Matcher::isSimpleConstant64(con); 4891 4892 if (offset < header_size) { 4893 assert(offset + BytesPerInt >= header_size, "second int counts"); 4894 assert(*(jint*)&tiles[j] == 0, "junk in header"); 4895 split = true; // only the second word counts 4896 // Example: int a[] = { 42 ... } 4897 } else if (con0 == 0 && init0 == -1) { 4898 split = true; // first word is covered by full inits 4899 // Example: int a[] = { ... foo(), 42 ... } 4900 } else if (con1 == 0 && init1 == -1) { 4901 split = true; // second word is covered by full inits 4902 // Example: int a[] = { ... 42, foo() ... } 4903 } 4904 4905 // Here's a case where init0 is neither 0 nor -1: 4906 // byte a[] = { ... 0,0,foo(),0, 0,0,0,42 ... } 4907 // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF. 4908 // In this case the tile is not split; it is (jlong)42. 4909 // The big tile is stored down, and then the foo() value is inserted. 4910 // (If there were foo(),foo() instead of foo(),0, init0 would be -1.) 4911 4912 Node* ctl = old->in(MemNode::Control); 4913 Node* adr = make_raw_address(offset, phase); 4914 const TypePtr* atp = TypeRawPtr::BOTTOM; 4915 4916 // One or two coalesced stores to plop down. 4917 Node* st[2]; 4918 intptr_t off[2]; 4919 int nst = 0; 4920 if (!split) { 4921 ++new_long; 4922 off[nst] = offset; 4923 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp, 4924 phase->longcon(con), T_LONG, MemNode::unordered); 4925 } else { 4926 // Omit either if it is a zero. 4927 if (con0 != 0) { 4928 ++new_int; 4929 off[nst] = offset; 4930 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp, 4931 phase->intcon(con0), T_INT, MemNode::unordered); 4932 } 4933 if (con1 != 0) { 4934 ++new_int; 4935 offset += BytesPerInt; 4936 adr = make_raw_address(offset, phase); 4937 off[nst] = offset; 4938 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp, 4939 phase->intcon(con1), T_INT, MemNode::unordered); 4940 } 4941 } 4942 4943 // Insert second store first, then the first before the second. 4944 // Insert each one just before any overlapping non-constant stores. 4945 while (nst > 0) { 4946 Node* st1 = st[--nst]; 4947 C->copy_node_notes_to(st1, old); 4948 st1 = phase->transform(st1); 4949 offset = off[nst]; 4950 assert(offset >= header_size, "do not smash header"); 4951 int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase); 4952 guarantee(ins_idx != 0, "must re-insert constant store"); 4953 if (ins_idx < 0) ins_idx = -ins_idx; // never overlap 4954 if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem) 4955 set_req(--ins_idx, st1); 4956 else 4957 ins_req(ins_idx, st1); 4958 } 4959 } 4960 4961 if (PrintCompilation && WizardMode) 4962 tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long", 4963 old_subword, old_long, new_int, new_long); 4964 if (C->log() != nullptr) 4965 C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'", 4966 old_subword, old_long, new_int, new_long); 4967 4968 // Clean up any remaining occurrences of zmem: 4969 remove_extra_zeroes(); 4970 } 4971 4972 // Explore forward from in(start) to find the first fully initialized 4973 // word, and return its offset. Skip groups of subword stores which 4974 // together initialize full words. If in(start) is itself part of a 4975 // fully initialized word, return the offset of in(start). If there 4976 // are no following full-word stores, or if something is fishy, return 4977 // a negative value. 4978 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) { 4979 int int_map = 0; 4980 intptr_t int_map_off = 0; 4981 const int FULL_MAP = right_n_bits(BytesPerInt); // the int_map we hope for 4982 4983 for (uint i = start, limit = req(); i < limit; i++) { 4984 Node* st = in(i); 4985 4986 intptr_t st_off = get_store_offset(st, phase); 4987 if (st_off < 0) break; // return conservative answer 4988 4989 int st_size = st->as_Store()->memory_size(); 4990 if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) { 4991 return st_off; // we found a complete word init 4992 } 4993 4994 // update the map: 4995 4996 intptr_t this_int_off = align_down(st_off, BytesPerInt); 4997 if (this_int_off != int_map_off) { 4998 // reset the map: 4999 int_map = 0; 5000 int_map_off = this_int_off; 5001 } 5002 5003 int subword_off = st_off - this_int_off; 5004 int_map |= right_n_bits(st_size) << subword_off; 5005 if ((int_map & FULL_MAP) == FULL_MAP) { 5006 return this_int_off; // we found a complete word init 5007 } 5008 5009 // Did this store hit or cross the word boundary? 5010 intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt); 5011 if (next_int_off == this_int_off + BytesPerInt) { 5012 // We passed the current int, without fully initializing it. 5013 int_map_off = next_int_off; 5014 int_map >>= BytesPerInt; 5015 } else if (next_int_off > this_int_off + BytesPerInt) { 5016 // We passed the current and next int. 5017 return this_int_off + BytesPerInt; 5018 } 5019 } 5020 5021 return -1; 5022 } 5023 5024 5025 // Called when the associated AllocateNode is expanded into CFG. 5026 // At this point, we may perform additional optimizations. 5027 // Linearize the stores by ascending offset, to make memory 5028 // activity as coherent as possible. 5029 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr, 5030 intptr_t header_size, 5031 Node* size_in_bytes, 5032 PhaseIterGVN* phase) { 5033 assert(!is_complete(), "not already complete"); 5034 assert(stores_are_sane(phase), ""); 5035 assert(allocation() != nullptr, "must be present"); 5036 5037 remove_extra_zeroes(); 5038 5039 if (ReduceFieldZeroing || ReduceBulkZeroing) 5040 // reduce instruction count for common initialization patterns 5041 coalesce_subword_stores(header_size, size_in_bytes, phase); 5042 5043 Node* zmem = zero_memory(); // initially zero memory state 5044 Node* inits = zmem; // accumulating a linearized chain of inits 5045 #ifdef ASSERT 5046 intptr_t first_offset = allocation()->minimum_header_size(); 5047 intptr_t last_init_off = first_offset; // previous init offset 5048 intptr_t last_init_end = first_offset; // previous init offset+size 5049 intptr_t last_tile_end = first_offset; // previous tile offset+size 5050 #endif 5051 intptr_t zeroes_done = header_size; 5052 5053 bool do_zeroing = true; // we might give up if inits are very sparse 5054 int big_init_gaps = 0; // how many large gaps have we seen? 5055 5056 if (UseTLAB && ZeroTLAB) do_zeroing = false; 5057 if (!ReduceFieldZeroing && !ReduceBulkZeroing) do_zeroing = false; 5058 5059 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) { 5060 Node* st = in(i); 5061 intptr_t st_off = get_store_offset(st, phase); 5062 if (st_off < 0) 5063 break; // unknown junk in the inits 5064 if (st->in(MemNode::Memory) != zmem) 5065 break; // complicated store chains somehow in list 5066 5067 int st_size = st->as_Store()->memory_size(); 5068 intptr_t next_init_off = st_off + st_size; 5069 5070 if (do_zeroing && zeroes_done < next_init_off) { 5071 // See if this store needs a zero before it or under it. 5072 intptr_t zeroes_needed = st_off; 5073 5074 if (st_size < BytesPerInt) { 5075 // Look for subword stores which only partially initialize words. 5076 // If we find some, we must lay down some word-level zeroes first, 5077 // underneath the subword stores. 5078 // 5079 // Examples: 5080 // byte[] a = { p,q,r,s } => a[0]=p,a[1]=q,a[2]=r,a[3]=s 5081 // byte[] a = { x,y,0,0 } => a[0..3] = 0, a[0]=x,a[1]=y 5082 // byte[] a = { 0,0,z,0 } => a[0..3] = 0, a[2]=z 5083 // 5084 // Note: coalesce_subword_stores may have already done this, 5085 // if it was prompted by constant non-zero subword initializers. 5086 // But this case can still arise with non-constant stores. 5087 5088 intptr_t next_full_store = find_next_fullword_store(i, phase); 5089 5090 // In the examples above: 5091 // in(i) p q r s x y z 5092 // st_off 12 13 14 15 12 13 14 5093 // st_size 1 1 1 1 1 1 1 5094 // next_full_s. 12 16 16 16 16 16 16 5095 // z's_done 12 16 16 16 12 16 12 5096 // z's_needed 12 16 16 16 16 16 16 5097 // zsize 0 0 0 0 4 0 4 5098 if (next_full_store < 0) { 5099 // Conservative tack: Zero to end of current word. 5100 zeroes_needed = align_up(zeroes_needed, BytesPerInt); 5101 } else { 5102 // Zero to beginning of next fully initialized word. 5103 // Or, don't zero at all, if we are already in that word. 5104 assert(next_full_store >= zeroes_needed, "must go forward"); 5105 assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary"); 5106 zeroes_needed = next_full_store; 5107 } 5108 } 5109 5110 if (zeroes_needed > zeroes_done) { 5111 intptr_t zsize = zeroes_needed - zeroes_done; 5112 // Do some incremental zeroing on rawmem, in parallel with inits. 5113 zeroes_done = align_down(zeroes_done, BytesPerInt); 5114 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr, 5115 zeroes_done, zeroes_needed, 5116 phase); 5117 zeroes_done = zeroes_needed; 5118 if (zsize > InitArrayShortSize && ++big_init_gaps > 2) 5119 do_zeroing = false; // leave the hole, next time 5120 } 5121 } 5122 5123 // Collect the store and move on: 5124 phase->replace_input_of(st, MemNode::Memory, inits); 5125 inits = st; // put it on the linearized chain 5126 set_req(i, zmem); // unhook from previous position 5127 5128 if (zeroes_done == st_off) 5129 zeroes_done = next_init_off; 5130 5131 assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any"); 5132 5133 #ifdef ASSERT 5134 // Various order invariants. Weaker than stores_are_sane because 5135 // a large constant tile can be filled in by smaller non-constant stores. 5136 assert(st_off >= last_init_off, "inits do not reverse"); 5137 last_init_off = st_off; 5138 const Type* val = nullptr; 5139 if (st_size >= BytesPerInt && 5140 (val = phase->type(st->in(MemNode::ValueIn)))->singleton() && 5141 (int)val->basic_type() < (int)T_OBJECT) { 5142 assert(st_off >= last_tile_end, "tiles do not overlap"); 5143 assert(st_off >= last_init_end, "tiles do not overwrite inits"); 5144 last_tile_end = MAX2(last_tile_end, next_init_off); 5145 } else { 5146 intptr_t st_tile_end = align_up(next_init_off, BytesPerLong); 5147 assert(st_tile_end >= last_tile_end, "inits stay with tiles"); 5148 assert(st_off >= last_init_end, "inits do not overlap"); 5149 last_init_end = next_init_off; // it's a non-tile 5150 } 5151 #endif //ASSERT 5152 } 5153 5154 remove_extra_zeroes(); // clear out all the zmems left over 5155 add_req(inits); 5156 5157 if (!(UseTLAB && ZeroTLAB)) { 5158 // If anything remains to be zeroed, zero it all now. 5159 zeroes_done = align_down(zeroes_done, BytesPerInt); 5160 // if it is the last unused 4 bytes of an instance, forget about it 5161 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint); 5162 if (zeroes_done + BytesPerLong >= size_limit) { 5163 AllocateNode* alloc = allocation(); 5164 assert(alloc != nullptr, "must be present"); 5165 if (alloc != nullptr && alloc->Opcode() == Op_Allocate) { 5166 Node* klass_node = alloc->in(AllocateNode::KlassNode); 5167 ciKlass* k = phase->type(klass_node)->is_instklassptr()->instance_klass(); 5168 if (zeroes_done == k->layout_helper()) 5169 zeroes_done = size_limit; 5170 } 5171 } 5172 if (zeroes_done < size_limit) { 5173 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr, 5174 zeroes_done, size_in_bytes, phase); 5175 } 5176 } 5177 5178 set_complete(phase); 5179 return rawmem; 5180 } 5181 5182 5183 #ifdef ASSERT 5184 bool InitializeNode::stores_are_sane(PhaseValues* phase) { 5185 if (is_complete()) 5186 return true; // stores could be anything at this point 5187 assert(allocation() != nullptr, "must be present"); 5188 intptr_t last_off = allocation()->minimum_header_size(); 5189 for (uint i = InitializeNode::RawStores; i < req(); i++) { 5190 Node* st = in(i); 5191 intptr_t st_off = get_store_offset(st, phase); 5192 if (st_off < 0) continue; // ignore dead garbage 5193 if (last_off > st_off) { 5194 tty->print_cr("*** bad store offset at %d: %zd > %zd", i, last_off, st_off); 5195 this->dump(2); 5196 assert(false, "ascending store offsets"); 5197 return false; 5198 } 5199 last_off = st_off + st->as_Store()->memory_size(); 5200 } 5201 return true; 5202 } 5203 #endif //ASSERT 5204 5205 5206 5207 5208 //============================MergeMemNode===================================== 5209 // 5210 // SEMANTICS OF MEMORY MERGES: A MergeMem is a memory state assembled from several 5211 // contributing store or call operations. Each contributor provides the memory 5212 // state for a particular "alias type" (see Compile::alias_type). For example, 5213 // if a MergeMem has an input X for alias category #6, then any memory reference 5214 // to alias category #6 may use X as its memory state input, as an exact equivalent 5215 // to using the MergeMem as a whole. 5216 // Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p) 5217 // 5218 // (Here, the <N> notation gives the index of the relevant adr_type.) 5219 // 5220 // In one special case (and more cases in the future), alias categories overlap. 5221 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory 5222 // states. Therefore, if a MergeMem has only one contributing input W for Bot, 5223 // it is exactly equivalent to that state W: 5224 // MergeMem(<Bot>: W) <==> W 5225 // 5226 // Usually, the merge has more than one input. In that case, where inputs 5227 // overlap (i.e., one is Bot), the narrower alias type determines the memory 5228 // state for that type, and the wider alias type (Bot) fills in everywhere else: 5229 // Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p) 5230 // Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p) 5231 // 5232 // A merge can take a "wide" memory state as one of its narrow inputs. 5233 // This simply means that the merge observes out only the relevant parts of 5234 // the wide input. That is, wide memory states arriving at narrow merge inputs 5235 // are implicitly "filtered" or "sliced" as necessary. (This is rare.) 5236 // 5237 // These rules imply that MergeMem nodes may cascade (via their <Bot> links), 5238 // and that memory slices "leak through": 5239 // MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y) 5240 // 5241 // But, in such a cascade, repeated memory slices can "block the leak": 5242 // MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y') 5243 // 5244 // In the last example, Y is not part of the combined memory state of the 5245 // outermost MergeMem. The system must, of course, prevent unschedulable 5246 // memory states from arising, so you can be sure that the state Y is somehow 5247 // a precursor to state Y'. 5248 // 5249 // 5250 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array 5251 // of each MergeMemNode array are exactly the numerical alias indexes, including 5252 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw. The functions 5253 // Compile::alias_type (and kin) produce and manage these indexes. 5254 // 5255 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node. 5256 // (Note that this provides quick access to the top node inside MergeMem methods, 5257 // without the need to reach out via TLS to Compile::current.) 5258 // 5259 // As a consequence of what was just described, a MergeMem that represents a full 5260 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state, 5261 // containing all alias categories. 5262 // 5263 // MergeMem nodes never (?) have control inputs, so in(0) is null. 5264 // 5265 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either 5266 // a memory state for the alias type <N>, or else the top node, meaning that 5267 // there is no particular input for that alias type. Note that the length of 5268 // a MergeMem is variable, and may be extended at any time to accommodate new 5269 // memory states at larger alias indexes. When merges grow, they are of course 5270 // filled with "top" in the unused in() positions. 5271 // 5272 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable. 5273 // (Top was chosen because it works smoothly with passes like GCM.) 5274 // 5275 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM. (It is 5276 // the type of random VM bits like TLS references.) Since it is always the 5277 // first non-Bot memory slice, some low-level loops use it to initialize an 5278 // index variable: for (i = AliasIdxRaw; i < req(); i++). 5279 // 5280 // 5281 // ACCESSORS: There is a special accessor MergeMemNode::base_memory which returns 5282 // the distinguished "wide" state. The accessor MergeMemNode::memory_at(N) returns 5283 // the memory state for alias type <N>, or (if there is no particular slice at <N>, 5284 // it returns the base memory. To prevent bugs, memory_at does not accept <Top> 5285 // or <Bot> indexes. The iterator MergeMemStream provides robust iteration over 5286 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited. 5287 // 5288 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't 5289 // really that different from the other memory inputs. An abbreviation called 5290 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy. 5291 // 5292 // 5293 // PARTIAL MEMORY STATES: During optimization, MergeMem nodes may arise that represent 5294 // partial memory states. When a Phi splits through a MergeMem, the copy of the Phi 5295 // that "emerges though" the base memory will be marked as excluding the alias types 5296 // of the other (narrow-memory) copies which "emerged through" the narrow edges: 5297 // 5298 // Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y)) 5299 // ==Ideal=> MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y)) 5300 // 5301 // This strange "subtraction" effect is necessary to ensure IGVN convergence. 5302 // (It is currently unimplemented.) As you can see, the resulting merge is 5303 // actually a disjoint union of memory states, rather than an overlay. 5304 // 5305 5306 //------------------------------MergeMemNode----------------------------------- 5307 Node* MergeMemNode::make_empty_memory() { 5308 Node* empty_memory = (Node*) Compile::current()->top(); 5309 assert(empty_memory->is_top(), "correct sentinel identity"); 5310 return empty_memory; 5311 } 5312 5313 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) { 5314 init_class_id(Class_MergeMem); 5315 // all inputs are nullified in Node::Node(int) 5316 // set_input(0, nullptr); // no control input 5317 5318 // Initialize the edges uniformly to top, for starters. 5319 Node* empty_mem = make_empty_memory(); 5320 for (uint i = Compile::AliasIdxTop; i < req(); i++) { 5321 init_req(i,empty_mem); 5322 } 5323 assert(empty_memory() == empty_mem, ""); 5324 5325 if( new_base != nullptr && new_base->is_MergeMem() ) { 5326 MergeMemNode* mdef = new_base->as_MergeMem(); 5327 assert(mdef->empty_memory() == empty_mem, "consistent sentinels"); 5328 for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) { 5329 mms.set_memory(mms.memory2()); 5330 } 5331 assert(base_memory() == mdef->base_memory(), ""); 5332 } else { 5333 set_base_memory(new_base); 5334 } 5335 } 5336 5337 // Make a new, untransformed MergeMem with the same base as 'mem'. 5338 // If mem is itself a MergeMem, populate the result with the same edges. 5339 MergeMemNode* MergeMemNode::make(Node* mem) { 5340 return new MergeMemNode(mem); 5341 } 5342 5343 //------------------------------cmp-------------------------------------------- 5344 uint MergeMemNode::hash() const { return NO_HASH; } 5345 bool MergeMemNode::cmp( const Node &n ) const { 5346 return (&n == this); // Always fail except on self 5347 } 5348 5349 //------------------------------Identity--------------------------------------- 5350 Node* MergeMemNode::Identity(PhaseGVN* phase) { 5351 // Identity if this merge point does not record any interesting memory 5352 // disambiguations. 5353 Node* base_mem = base_memory(); 5354 Node* empty_mem = empty_memory(); 5355 if (base_mem != empty_mem) { // Memory path is not dead? 5356 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5357 Node* mem = in(i); 5358 if (mem != empty_mem && mem != base_mem) { 5359 return this; // Many memory splits; no change 5360 } 5361 } 5362 } 5363 return base_mem; // No memory splits; ID on the one true input 5364 } 5365 5366 //------------------------------Ideal------------------------------------------ 5367 // This method is invoked recursively on chains of MergeMem nodes 5368 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) { 5369 // Remove chain'd MergeMems 5370 // 5371 // This is delicate, because the each "in(i)" (i >= Raw) is interpreted 5372 // relative to the "in(Bot)". Since we are patching both at the same time, 5373 // we have to be careful to read each "in(i)" relative to the old "in(Bot)", 5374 // but rewrite each "in(i)" relative to the new "in(Bot)". 5375 Node *progress = nullptr; 5376 5377 5378 Node* old_base = base_memory(); 5379 Node* empty_mem = empty_memory(); 5380 if (old_base == empty_mem) 5381 return nullptr; // Dead memory path. 5382 5383 MergeMemNode* old_mbase; 5384 if (old_base != nullptr && old_base->is_MergeMem()) 5385 old_mbase = old_base->as_MergeMem(); 5386 else 5387 old_mbase = nullptr; 5388 Node* new_base = old_base; 5389 5390 // simplify stacked MergeMems in base memory 5391 if (old_mbase) new_base = old_mbase->base_memory(); 5392 5393 // the base memory might contribute new slices beyond my req() 5394 if (old_mbase) grow_to_match(old_mbase); 5395 5396 // Note: We do not call verify_sparse on entry, because inputs 5397 // can normalize to the base_memory via subsume_node or similar 5398 // mechanisms. This method repairs that damage. 5399 5400 assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels"); 5401 5402 // Look at each slice. 5403 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5404 Node* old_in = in(i); 5405 // calculate the old memory value 5406 Node* old_mem = old_in; 5407 if (old_mem == empty_mem) old_mem = old_base; 5408 assert(old_mem == memory_at(i), ""); 5409 5410 // maybe update (reslice) the old memory value 5411 5412 // simplify stacked MergeMems 5413 Node* new_mem = old_mem; 5414 MergeMemNode* old_mmem; 5415 if (old_mem != nullptr && old_mem->is_MergeMem()) 5416 old_mmem = old_mem->as_MergeMem(); 5417 else 5418 old_mmem = nullptr; 5419 if (old_mmem == this) { 5420 // This can happen if loops break up and safepoints disappear. 5421 // A merge of BotPtr (default) with a RawPtr memory derived from a 5422 // safepoint can be rewritten to a merge of the same BotPtr with 5423 // the BotPtr phi coming into the loop. If that phi disappears 5424 // also, we can end up with a self-loop of the mergemem. 5425 // In general, if loops degenerate and memory effects disappear, 5426 // a mergemem can be left looking at itself. This simply means 5427 // that the mergemem's default should be used, since there is 5428 // no longer any apparent effect on this slice. 5429 // Note: If a memory slice is a MergeMem cycle, it is unreachable 5430 // from start. Update the input to TOP. 5431 new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base; 5432 } 5433 else if (old_mmem != nullptr) { 5434 new_mem = old_mmem->memory_at(i); 5435 } 5436 // else preceding memory was not a MergeMem 5437 5438 // maybe store down a new value 5439 Node* new_in = new_mem; 5440 if (new_in == new_base) new_in = empty_mem; 5441 5442 if (new_in != old_in) { 5443 // Warning: Do not combine this "if" with the previous "if" 5444 // A memory slice might have be be rewritten even if it is semantically 5445 // unchanged, if the base_memory value has changed. 5446 set_req_X(i, new_in, phase); 5447 progress = this; // Report progress 5448 } 5449 } 5450 5451 if (new_base != old_base) { 5452 set_req_X(Compile::AliasIdxBot, new_base, phase); 5453 // Don't use set_base_memory(new_base), because we need to update du. 5454 assert(base_memory() == new_base, ""); 5455 progress = this; 5456 } 5457 5458 if( base_memory() == this ) { 5459 // a self cycle indicates this memory path is dead 5460 set_req(Compile::AliasIdxBot, empty_mem); 5461 } 5462 5463 // Resolve external cycles by calling Ideal on a MergeMem base_memory 5464 // Recursion must occur after the self cycle check above 5465 if( base_memory()->is_MergeMem() ) { 5466 MergeMemNode *new_mbase = base_memory()->as_MergeMem(); 5467 Node *m = phase->transform(new_mbase); // Rollup any cycles 5468 if( m != nullptr && 5469 (m->is_top() || 5470 (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) { 5471 // propagate rollup of dead cycle to self 5472 set_req(Compile::AliasIdxBot, empty_mem); 5473 } 5474 } 5475 5476 if( base_memory() == empty_mem ) { 5477 progress = this; 5478 // Cut inputs during Parse phase only. 5479 // During Optimize phase a dead MergeMem node will be subsumed by Top. 5480 if( !can_reshape ) { 5481 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5482 if( in(i) != empty_mem ) { set_req(i, empty_mem); } 5483 } 5484 } 5485 } 5486 5487 if( !progress && base_memory()->is_Phi() && can_reshape ) { 5488 // Check if PhiNode::Ideal's "Split phis through memory merges" 5489 // transform should be attempted. Look for this->phi->this cycle. 5490 uint merge_width = req(); 5491 if (merge_width > Compile::AliasIdxRaw) { 5492 PhiNode* phi = base_memory()->as_Phi(); 5493 for( uint i = 1; i < phi->req(); ++i ) {// For all paths in 5494 if (phi->in(i) == this) { 5495 phase->is_IterGVN()->_worklist.push(phi); 5496 break; 5497 } 5498 } 5499 } 5500 } 5501 5502 assert(progress || verify_sparse(), "please, no dups of base"); 5503 return progress; 5504 } 5505 5506 //-------------------------set_base_memory------------------------------------- 5507 void MergeMemNode::set_base_memory(Node *new_base) { 5508 Node* empty_mem = empty_memory(); 5509 set_req(Compile::AliasIdxBot, new_base); 5510 assert(memory_at(req()) == new_base, "must set default memory"); 5511 // Clear out other occurrences of new_base: 5512 if (new_base != empty_mem) { 5513 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5514 if (in(i) == new_base) set_req(i, empty_mem); 5515 } 5516 } 5517 } 5518 5519 //------------------------------out_RegMask------------------------------------ 5520 const RegMask &MergeMemNode::out_RegMask() const { 5521 return RegMask::Empty; 5522 } 5523 5524 //------------------------------dump_spec-------------------------------------- 5525 #ifndef PRODUCT 5526 void MergeMemNode::dump_spec(outputStream *st) const { 5527 st->print(" {"); 5528 Node* base_mem = base_memory(); 5529 for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) { 5530 Node* mem = (in(i) != nullptr) ? memory_at(i) : base_mem; 5531 if (mem == base_mem) { st->print(" -"); continue; } 5532 st->print( " N%d:", mem->_idx ); 5533 Compile::current()->get_adr_type(i)->dump_on(st); 5534 } 5535 st->print(" }"); 5536 } 5537 #endif // !PRODUCT 5538 5539 5540 #ifdef ASSERT 5541 static bool might_be_same(Node* a, Node* b) { 5542 if (a == b) return true; 5543 if (!(a->is_Phi() || b->is_Phi())) return false; 5544 // phis shift around during optimization 5545 return true; // pretty stupid... 5546 } 5547 5548 // verify a narrow slice (either incoming or outgoing) 5549 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) { 5550 if (!VerifyAliases) return; // don't bother to verify unless requested 5551 if (VMError::is_error_reported()) return; // muzzle asserts when debugging an error 5552 if (Node::in_dump()) return; // muzzle asserts when printing 5553 assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel"); 5554 assert(n != nullptr, ""); 5555 // Elide intervening MergeMem's 5556 while (n->is_MergeMem()) { 5557 n = n->as_MergeMem()->memory_at(alias_idx); 5558 } 5559 Compile* C = Compile::current(); 5560 const TypePtr* n_adr_type = n->adr_type(); 5561 if (n == m->empty_memory()) { 5562 // Implicit copy of base_memory() 5563 } else if (n_adr_type != TypePtr::BOTTOM) { 5564 assert(n_adr_type != nullptr, "new memory must have a well-defined adr_type"); 5565 assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice"); 5566 } else { 5567 // A few places like make_runtime_call "know" that VM calls are narrow, 5568 // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM. 5569 bool expected_wide_mem = false; 5570 if (n == m->base_memory()) { 5571 expected_wide_mem = true; 5572 } else if (alias_idx == Compile::AliasIdxRaw || 5573 n == m->memory_at(Compile::AliasIdxRaw)) { 5574 expected_wide_mem = true; 5575 } else if (!C->alias_type(alias_idx)->is_rewritable()) { 5576 // memory can "leak through" calls on channels that 5577 // are write-once. Allow this also. 5578 expected_wide_mem = true; 5579 } 5580 assert(expected_wide_mem, "expected narrow slice replacement"); 5581 } 5582 } 5583 #else // !ASSERT 5584 #define verify_memory_slice(m,i,n) (void)(0) // PRODUCT version is no-op 5585 #endif 5586 5587 5588 //-----------------------------memory_at--------------------------------------- 5589 Node* MergeMemNode::memory_at(uint alias_idx) const { 5590 assert(alias_idx >= Compile::AliasIdxRaw || 5591 (alias_idx == Compile::AliasIdxBot && !Compile::current()->do_aliasing()), 5592 "must avoid base_memory and AliasIdxTop"); 5593 5594 // Otherwise, it is a narrow slice. 5595 Node* n = alias_idx < req() ? in(alias_idx) : empty_memory(); 5596 if (is_empty_memory(n)) { 5597 // the array is sparse; empty slots are the "top" node 5598 n = base_memory(); 5599 assert(Node::in_dump() 5600 || n == nullptr || n->bottom_type() == Type::TOP 5601 || n->adr_type() == nullptr // address is TOP 5602 || n->adr_type() == TypePtr::BOTTOM 5603 || n->adr_type() == TypeRawPtr::BOTTOM 5604 || !Compile::current()->do_aliasing(), 5605 "must be a wide memory"); 5606 // do_aliasing == false if we are organizing the memory states manually. 5607 // See verify_memory_slice for comments on TypeRawPtr::BOTTOM. 5608 } else { 5609 // make sure the stored slice is sane 5610 #ifdef ASSERT 5611 if (VMError::is_error_reported() || Node::in_dump()) { 5612 } else if (might_be_same(n, base_memory())) { 5613 // Give it a pass: It is a mostly harmless repetition of the base. 5614 // This can arise normally from node subsumption during optimization. 5615 } else { 5616 verify_memory_slice(this, alias_idx, n); 5617 } 5618 #endif 5619 } 5620 return n; 5621 } 5622 5623 //---------------------------set_memory_at------------------------------------- 5624 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) { 5625 verify_memory_slice(this, alias_idx, n); 5626 Node* empty_mem = empty_memory(); 5627 if (n == base_memory()) n = empty_mem; // collapse default 5628 uint need_req = alias_idx+1; 5629 if (req() < need_req) { 5630 if (n == empty_mem) return; // already the default, so do not grow me 5631 // grow the sparse array 5632 do { 5633 add_req(empty_mem); 5634 } while (req() < need_req); 5635 } 5636 set_req( alias_idx, n ); 5637 } 5638 5639 5640 5641 //--------------------------iteration_setup------------------------------------ 5642 void MergeMemNode::iteration_setup(const MergeMemNode* other) { 5643 if (other != nullptr) { 5644 grow_to_match(other); 5645 // invariant: the finite support of mm2 is within mm->req() 5646 #ifdef ASSERT 5647 for (uint i = req(); i < other->req(); i++) { 5648 assert(other->is_empty_memory(other->in(i)), "slice left uncovered"); 5649 } 5650 #endif 5651 } 5652 // Replace spurious copies of base_memory by top. 5653 Node* base_mem = base_memory(); 5654 if (base_mem != nullptr && !base_mem->is_top()) { 5655 for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) { 5656 if (in(i) == base_mem) 5657 set_req(i, empty_memory()); 5658 } 5659 } 5660 } 5661 5662 //---------------------------grow_to_match------------------------------------- 5663 void MergeMemNode::grow_to_match(const MergeMemNode* other) { 5664 Node* empty_mem = empty_memory(); 5665 assert(other->is_empty_memory(empty_mem), "consistent sentinels"); 5666 // look for the finite support of the other memory 5667 for (uint i = other->req(); --i >= req(); ) { 5668 if (other->in(i) != empty_mem) { 5669 uint new_len = i+1; 5670 while (req() < new_len) add_req(empty_mem); 5671 break; 5672 } 5673 } 5674 } 5675 5676 //---------------------------verify_sparse------------------------------------- 5677 #ifndef PRODUCT 5678 bool MergeMemNode::verify_sparse() const { 5679 assert(is_empty_memory(make_empty_memory()), "sane sentinel"); 5680 Node* base_mem = base_memory(); 5681 // The following can happen in degenerate cases, since empty==top. 5682 if (is_empty_memory(base_mem)) return true; 5683 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5684 assert(in(i) != nullptr, "sane slice"); 5685 if (in(i) == base_mem) return false; // should have been the sentinel value! 5686 } 5687 return true; 5688 } 5689 5690 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) { 5691 Node* n; 5692 n = mm->in(idx); 5693 if (mem == n) return true; // might be empty_memory() 5694 n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx); 5695 if (mem == n) return true; 5696 return false; 5697 } 5698 #endif // !PRODUCT