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