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