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