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