1 /* 2 * Copyright (c) 2005, 2025, 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 "ci/ciFlatArrayKlass.hpp" 26 #include "ci/ciInstanceKlass.hpp" 27 #include "compiler/compileLog.hpp" 28 #include "gc/shared/collectedHeap.inline.hpp" 29 #include "gc/shared/tlab_globals.hpp" 30 #include "libadt/vectset.hpp" 31 #include "memory/universe.hpp" 32 #include "opto/addnode.hpp" 33 #include "opto/arraycopynode.hpp" 34 #include "opto/callnode.hpp" 35 #include "opto/castnode.hpp" 36 #include "opto/cfgnode.hpp" 37 #include "opto/compile.hpp" 38 #include "opto/convertnode.hpp" 39 #include "opto/graphKit.hpp" 40 #include "opto/inlinetypenode.hpp" 41 #include "opto/intrinsicnode.hpp" 42 #include "opto/locknode.hpp" 43 #include "opto/loopnode.hpp" 44 #include "opto/macro.hpp" 45 #include "opto/memnode.hpp" 46 #include "opto/narrowptrnode.hpp" 47 #include "opto/node.hpp" 48 #include "opto/opaquenode.hpp" 49 #include "opto/phaseX.hpp" 50 #include "opto/rootnode.hpp" 51 #include "opto/runtime.hpp" 52 #include "opto/subnode.hpp" 53 #include "opto/subtypenode.hpp" 54 #include "opto/type.hpp" 55 #include "prims/jvmtiExport.hpp" 56 #include "runtime/continuation.hpp" 57 #include "runtime/sharedRuntime.hpp" 58 #include "runtime/stubRoutines.hpp" 59 #include "utilities/globalDefinitions.hpp" 60 #include "utilities/macros.hpp" 61 #include "utilities/powerOfTwo.hpp" 62 #if INCLUDE_G1GC 63 #include "gc/g1/g1ThreadLocalData.hpp" 64 #endif // INCLUDE_G1GC 65 66 67 // 68 // Replace any references to "oldref" in inputs to "use" with "newref". 69 // Returns the number of replacements made. 70 // 71 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) { 72 int nreplacements = 0; 73 uint req = use->req(); 74 for (uint j = 0; j < use->len(); j++) { 75 Node *uin = use->in(j); 76 if (uin == oldref) { 77 if (j < req) 78 use->set_req(j, newref); 79 else 80 use->set_prec(j, newref); 81 nreplacements++; 82 } else if (j >= req && uin == nullptr) { 83 break; 84 } 85 } 86 return nreplacements; 87 } 88 89 90 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word) { 91 Node* cmp = word; 92 Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne)); 93 IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN ); 94 transform_later(iff); 95 96 // Fast path taken. 97 Node *fast_taken = transform_later(new IfFalseNode(iff)); 98 99 // Fast path not-taken, i.e. slow path 100 Node *slow_taken = transform_later(new IfTrueNode(iff)); 101 102 region->init_req(edge, fast_taken); // Capture fast-control 103 return slow_taken; 104 } 105 106 //--------------------copy_predefined_input_for_runtime_call-------------------- 107 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) { 108 // Set fixed predefined input arguments 109 call->init_req( TypeFunc::Control, ctrl ); 110 call->init_req( TypeFunc::I_O , oldcall->in( TypeFunc::I_O) ); 111 call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ????? 112 call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) ); 113 call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) ); 114 } 115 116 //------------------------------make_slow_call--------------------------------- 117 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type, 118 address slow_call, const char* leaf_name, Node* slow_path, 119 Node* parm0, Node* parm1, Node* parm2) { 120 121 // Slow-path call 122 CallNode *call = leaf_name 123 ? (CallNode*)new CallLeafNode ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM ) 124 : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM ); 125 126 // Slow path call has no side-effects, uses few values 127 copy_predefined_input_for_runtime_call(slow_path, oldcall, call ); 128 if (parm0 != nullptr) call->init_req(TypeFunc::Parms+0, parm0); 129 if (parm1 != nullptr) call->init_req(TypeFunc::Parms+1, parm1); 130 if (parm2 != nullptr) call->init_req(TypeFunc::Parms+2, parm2); 131 call->copy_call_debug_info(&_igvn, oldcall); 132 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON. 133 _igvn.replace_node(oldcall, call); 134 transform_later(call); 135 136 return call; 137 } 138 139 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) { 140 BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2(); 141 bs->eliminate_gc_barrier(&_igvn, p2x); 142 #ifndef PRODUCT 143 if (PrintOptoStatistics) { 144 Atomic::inc(&PhaseMacroExpand::_GC_barriers_removed_counter); 145 } 146 #endif 147 } 148 149 // Search for a memory operation for the specified memory slice. 150 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) { 151 Node *orig_mem = mem; 152 Node *alloc_mem = alloc->as_Allocate()->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false); 153 assert(alloc_mem != nullptr, "Allocation without a memory projection."); 154 const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr(); 155 while (true) { 156 if (mem == alloc_mem || mem == start_mem ) { 157 return mem; // hit one of our sentinels 158 } else if (mem->is_MergeMem()) { 159 mem = mem->as_MergeMem()->memory_at(alias_idx); 160 } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) { 161 Node *in = mem->in(0); 162 // we can safely skip over safepoints, calls, locks and membars because we 163 // already know that the object is safe to eliminate. 164 if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) { 165 return in; 166 } else if (in->is_Call()) { 167 CallNode *call = in->as_Call(); 168 if (call->may_modify(tinst, phase)) { 169 assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape"); 170 if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) { 171 return in; 172 } 173 } 174 mem = in->in(TypeFunc::Memory); 175 } else if (in->is_MemBar()) { 176 ArrayCopyNode* ac = nullptr; 177 if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) { 178 if (ac != nullptr) { 179 assert(ac->is_clonebasic(), "Only basic clone is a non escaping clone"); 180 return ac; 181 } 182 } 183 mem = in->in(TypeFunc::Memory); 184 } else { 185 #ifdef ASSERT 186 in->dump(); 187 mem->dump(); 188 assert(false, "unexpected projection"); 189 #endif 190 } 191 } else if (mem->is_Store()) { 192 const TypePtr* atype = mem->as_Store()->adr_type(); 193 int adr_idx = phase->C->get_alias_index(atype); 194 if (adr_idx == alias_idx) { 195 assert(atype->isa_oopptr(), "address type must be oopptr"); 196 int adr_offset = atype->flat_offset(); 197 uint adr_iid = atype->is_oopptr()->instance_id(); 198 // Array elements references have the same alias_idx 199 // but different offset and different instance_id. 200 if (adr_offset == offset && adr_iid == alloc->_idx) { 201 return mem; 202 } 203 } else { 204 assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw"); 205 } 206 mem = mem->in(MemNode::Memory); 207 } else if (mem->is_ClearArray()) { 208 if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) { 209 // Can not bypass initialization of the instance 210 // we are looking. 211 DEBUG_ONLY(intptr_t offset;) 212 assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity"); 213 InitializeNode* init = alloc->as_Allocate()->initialization(); 214 // We are looking for stored value, return Initialize node 215 // or memory edge from Allocate node. 216 if (init != nullptr) { 217 return init; 218 } else { 219 return alloc->in(TypeFunc::Memory); // It will produce zero value (see callers). 220 } 221 } 222 // Otherwise skip it (the call updated 'mem' value). 223 } else if (mem->Opcode() == Op_SCMemProj) { 224 mem = mem->in(0); 225 Node* adr = nullptr; 226 if (mem->is_LoadStore()) { 227 adr = mem->in(MemNode::Address); 228 } else { 229 assert(mem->Opcode() == Op_EncodeISOArray || 230 mem->Opcode() == Op_StrCompressedCopy, "sanity"); 231 adr = mem->in(3); // Destination array 232 } 233 const TypePtr* atype = adr->bottom_type()->is_ptr(); 234 int adr_idx = phase->C->get_alias_index(atype); 235 if (adr_idx == alias_idx) { 236 DEBUG_ONLY(mem->dump();) 237 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field"); 238 return nullptr; 239 } 240 mem = mem->in(MemNode::Memory); 241 } else if (mem->Opcode() == Op_StrInflatedCopy) { 242 Node* adr = mem->in(3); // Destination array 243 const TypePtr* atype = adr->bottom_type()->is_ptr(); 244 int adr_idx = phase->C->get_alias_index(atype); 245 if (adr_idx == alias_idx) { 246 DEBUG_ONLY(mem->dump();) 247 assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field"); 248 return nullptr; 249 } 250 mem = mem->in(MemNode::Memory); 251 } else { 252 return mem; 253 } 254 assert(mem != orig_mem, "dead memory loop"); 255 } 256 } 257 258 // Generate loads from source of the arraycopy for fields of 259 // destination needed at a deoptimization point 260 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) { 261 BasicType bt = ft; 262 const Type *type = ftype; 263 if (ft == T_NARROWOOP) { 264 bt = T_OBJECT; 265 type = ftype->make_oopptr(); 266 } 267 Node* res = nullptr; 268 if (ac->is_clonebasic()) { 269 assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination"); 270 Node* base = ac->in(ArrayCopyNode::Src); 271 Node* adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(offset))); 272 const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset); 273 MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem(); 274 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 275 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt); 276 } else { 277 if (ac->modifies(offset, offset, &_igvn, true)) { 278 assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result"); 279 uint shift = exact_log2(type2aelembytes(bt)); 280 Node* src_pos = ac->in(ArrayCopyNode::SrcPos); 281 Node* dest_pos = ac->in(ArrayCopyNode::DestPos); 282 const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int(); 283 const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int(); 284 285 Node* adr = nullptr; 286 Node* base = ac->in(ArrayCopyNode::Src); 287 const TypeAryPtr* adr_type = _igvn.type(base)->is_aryptr(); 288 if (adr_type->is_flat()) { 289 shift = adr_type->flat_log_elem_size(); 290 } 291 if (src_pos_t->is_con() && dest_pos_t->is_con()) { 292 intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset; 293 adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(off))); 294 adr_type = _igvn.type(adr)->is_aryptr(); 295 assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type"); 296 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) { 297 // Don't emit a new load from src if src == dst but try to get the value from memory instead 298 return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type, alloc); 299 } 300 } else { 301 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) { 302 // Non constant offset in the array: we can't statically 303 // determine the value 304 return nullptr; 305 } 306 Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos))); 307 #ifdef _LP64 308 diff = _igvn.transform(new ConvI2LNode(diff)); 309 #endif 310 diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift))); 311 312 Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff)); 313 adr = _igvn.transform(new AddPNode(base, base, off)); 314 // In the case of a flat inline type array, each field has its 315 // own slice so we need to extract the field being accessed from 316 // the address computation 317 adr_type = adr_type->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot)->is_aryptr(); 318 adr = _igvn.transform(new CastPPNode(ctl, adr, adr_type)); 319 } 320 MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem(); 321 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 322 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt); 323 } 324 } 325 if (res != nullptr) { 326 if (ftype->isa_narrowoop()) { 327 // PhaseMacroExpand::scalar_replacement adds DecodeN nodes 328 assert(res->isa_DecodeN(), "should be narrow oop"); 329 res = _igvn.transform(new EncodePNode(res, ftype)); 330 } 331 return res; 332 } 333 return nullptr; 334 } 335 336 // 337 // Given a Memory Phi, compute a value Phi containing the values from stores 338 // on the input paths. 339 // Note: this function is recursive, its depth is limited by the "level" argument 340 // Returns the computed Phi, or null if it cannot compute it. 341 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, AllocateNode *alloc, Node_Stack *value_phis, int level) { 342 assert(mem->is_Phi(), "sanity"); 343 int alias_idx = C->get_alias_index(adr_t); 344 int offset = adr_t->flat_offset(); 345 int instance_id = adr_t->instance_id(); 346 347 // Check if an appropriate value phi already exists. 348 Node* region = mem->in(0); 349 for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) { 350 Node* phi = region->fast_out(k); 351 if (phi->is_Phi() && phi != mem && 352 phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) { 353 return phi; 354 } 355 } 356 // Check if an appropriate new value phi already exists. 357 Node* new_phi = value_phis->find(mem->_idx); 358 if (new_phi != nullptr) 359 return new_phi; 360 361 if (level <= 0) { 362 return nullptr; // Give up: phi tree too deep 363 } 364 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory); 365 Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false); 366 assert(alloc_mem != nullptr, "Allocation without a memory projection."); 367 368 uint length = mem->req(); 369 GrowableArray <Node *> values(length, length, nullptr); 370 371 // create a new Phi for the value 372 PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset); 373 transform_later(phi); 374 value_phis->push(phi, mem->_idx); 375 376 for (uint j = 1; j < length; j++) { 377 Node *in = mem->in(j); 378 if (in == nullptr || in->is_top()) { 379 values.at_put(j, in); 380 } else { 381 Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn); 382 if (val == start_mem || val == alloc_mem) { 383 // hit a sentinel, return appropriate value 384 Node* init_value = alloc->in(AllocateNode::InitValue); 385 if (init_value != nullptr) { 386 if (val == start_mem) { 387 // TODO 8350865 Scalar replacement does not work well for flat arrays. 388 // Somehow we ended up with root mem and therefore walked past the alloc. Fix this. Triggered by TestGenerated::test15 389 // Don't we need field_value_by_offset? 390 return nullptr; 391 } 392 values.at_put(j, init_value); 393 } else { 394 assert(alloc->in(AllocateNode::RawInitValue) == nullptr, "init value may not be null"); 395 values.at_put(j, _igvn.zerocon(ft)); 396 } 397 continue; 398 } 399 if (val->is_Initialize()) { 400 val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn); 401 } 402 if (val == nullptr) { 403 return nullptr; // can't find a value on this path 404 } 405 if (val == mem) { 406 values.at_put(j, mem); 407 } else if (val->is_Store()) { 408 Node* n = val->in(MemNode::ValueIn); 409 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 410 n = bs->step_over_gc_barrier(n); 411 if (is_subword_type(ft)) { 412 n = Compile::narrow_value(ft, n, phi_type, &_igvn, true); 413 } 414 values.at_put(j, n); 415 } else if (val->is_Proj() && val->in(0) == alloc) { 416 Node* init_value = alloc->in(AllocateNode::InitValue); 417 if (init_value != nullptr) { 418 // TODO 8350865 Scalar replacement does not work well for flat arrays. 419 // Is this correct for non-all-zero init values? Don't we need field_value_by_offset? 420 values.at_put(j, init_value); 421 } else { 422 assert(alloc->in(AllocateNode::RawInitValue) == nullptr, "init value may not be null"); 423 values.at_put(j, _igvn.zerocon(ft)); 424 } 425 } else if (val->is_Phi()) { 426 val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1); 427 if (val == nullptr) { 428 return nullptr; 429 } 430 values.at_put(j, val); 431 } else if (val->Opcode() == Op_SCMemProj) { 432 assert(val->in(0)->is_LoadStore() || 433 val->in(0)->Opcode() == Op_EncodeISOArray || 434 val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity"); 435 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field"); 436 return nullptr; 437 } else if (val->is_ArrayCopy()) { 438 Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc); 439 if (res == nullptr) { 440 return nullptr; 441 } 442 values.at_put(j, res); 443 } else if (val->is_top()) { 444 // This indicates that this path into the phi is dead. Top will eventually also propagate into the Region. 445 // IGVN will clean this up later. 446 values.at_put(j, val); 447 } else { 448 DEBUG_ONLY( val->dump(); ) 449 assert(false, "unknown node on this path"); 450 return nullptr; // unknown node on this path 451 } 452 } 453 } 454 // Set Phi's inputs 455 for (uint j = 1; j < length; j++) { 456 if (values.at(j) == mem) { 457 phi->init_req(j, phi); 458 } else { 459 phi->init_req(j, values.at(j)); 460 } 461 } 462 return phi; 463 } 464 465 // Search the last value stored into the object's field. 466 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) { 467 assert(adr_t->is_known_instance_field(), "instance required"); 468 int instance_id = adr_t->instance_id(); 469 assert((uint)instance_id == alloc->_idx, "wrong allocation"); 470 471 int alias_idx = C->get_alias_index(adr_t); 472 int offset = adr_t->flat_offset(); 473 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory); 474 Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false); 475 assert(alloc_mem != nullptr, "Allocation without a memory projection."); 476 VectorSet visited; 477 478 bool done = sfpt_mem == alloc_mem; 479 Node *mem = sfpt_mem; 480 while (!done) { 481 if (visited.test_set(mem->_idx)) { 482 return nullptr; // found a loop, give up 483 } 484 mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn); 485 if (mem == start_mem || mem == alloc_mem) { 486 done = true; // hit a sentinel, return appropriate 0 value 487 } else if (mem->is_Initialize()) { 488 mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn); 489 if (mem == nullptr) { 490 done = true; // Something went wrong. 491 } else if (mem->is_Store()) { 492 const TypePtr* atype = mem->as_Store()->adr_type(); 493 assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice"); 494 done = true; 495 } 496 } else if (mem->is_Store()) { 497 const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr(); 498 assert(atype != nullptr, "address type must be oopptr"); 499 assert(C->get_alias_index(atype) == alias_idx && 500 atype->is_known_instance_field() && atype->flat_offset() == offset && 501 atype->instance_id() == instance_id, "store is correct memory slice"); 502 done = true; 503 } else if (mem->is_Phi()) { 504 // try to find a phi's unique input 505 Node *unique_input = nullptr; 506 Node *top = C->top(); 507 for (uint i = 1; i < mem->req(); i++) { 508 Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn); 509 if (n == nullptr || n == top || n == mem) { 510 continue; 511 } else if (unique_input == nullptr) { 512 unique_input = n; 513 } else if (unique_input != n) { 514 unique_input = top; 515 break; 516 } 517 } 518 if (unique_input != nullptr && unique_input != top) { 519 mem = unique_input; 520 } else { 521 done = true; 522 } 523 } else if (mem->is_ArrayCopy()) { 524 done = true; 525 } else { 526 DEBUG_ONLY( mem->dump(); ) 527 assert(false, "unexpected node"); 528 } 529 } 530 if (mem != nullptr) { 531 if (mem == start_mem || mem == alloc_mem) { 532 // hit a sentinel, return appropriate value 533 Node* init_value = alloc->in(AllocateNode::InitValue); 534 if (init_value != nullptr) { 535 if (adr_t->is_flat()) { 536 if (init_value->is_EncodeP()) { 537 init_value = init_value->in(1); 538 } 539 assert(adr_t->is_aryptr()->field_offset().get() != Type::OffsetBot, "Unknown offset"); 540 offset = adr_t->is_aryptr()->field_offset().get() + init_value->bottom_type()->inline_klass()->payload_offset(); 541 init_value = init_value->as_InlineType()->field_value_by_offset(offset, true); 542 if (ft == T_NARROWOOP) { 543 init_value = transform_later(new EncodePNode(init_value, init_value->bottom_type()->make_ptr())); 544 } 545 } 546 return init_value; 547 } 548 assert(alloc->in(AllocateNode::RawInitValue) == nullptr, "init value may not be null"); 549 return _igvn.zerocon(ft); 550 } else if (mem->is_Store()) { 551 Node* n = mem->in(MemNode::ValueIn); 552 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 553 n = bs->step_over_gc_barrier(n); 554 return n; 555 } else if (mem->is_Phi()) { 556 // attempt to produce a Phi reflecting the values on the input paths of the Phi 557 Node_Stack value_phis(8); 558 Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit); 559 if (phi != nullptr) { 560 return phi; 561 } else { 562 // Kill all new Phis 563 while(value_phis.is_nonempty()) { 564 Node* n = value_phis.node(); 565 _igvn.replace_node(n, C->top()); 566 value_phis.pop(); 567 } 568 } 569 } else if (mem->is_ArrayCopy()) { 570 Node* ctl = mem->in(0); 571 Node* m = mem->in(TypeFunc::Memory); 572 if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj()) { 573 // pin the loads in the uncommon trap path 574 ctl = sfpt_ctl; 575 m = sfpt_mem; 576 } 577 return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc); 578 } 579 } 580 // Something went wrong. 581 return nullptr; 582 } 583 584 // Search the last value stored into the inline type's fields (for flat arrays). 585 Node* PhaseMacroExpand::inline_type_from_mem(ciInlineKlass* vk, const TypeAryPtr* elem_adr_type, int elem_idx, int offset_in_element, bool null_free, AllocateNode* alloc, SafePointNode* sfpt) { 586 auto report_failure = [&](int field_offset_in_element) { 587 #ifndef PRODUCT 588 if (PrintEliminateAllocations) { 589 ciInlineKlass* elem_klass = elem_adr_type->elem()->inline_klass(); 590 int offset = field_offset_in_element + elem_klass->payload_offset(); 591 ciField* flattened_field = elem_klass->get_field_by_offset(offset, false); 592 assert(flattened_field != nullptr, "must have a field of type %s at offset %d", elem_klass->name()->as_utf8(), offset); 593 tty->print("=== At SafePoint node %d can't find value of field [%s] of array element [%d]", sfpt->_idx, flattened_field->name()->as_utf8(), elem_idx); 594 tty->print(", which prevents elimination of: "); 595 alloc->dump(); 596 } 597 #endif // PRODUCT 598 }; 599 600 // Create a new InlineTypeNode and retrieve the field values from memory 601 InlineTypeNode* vt = InlineTypeNode::make_uninitialized(_igvn, vk, false); 602 transform_later(vt); 603 if (null_free) { 604 vt->set_null_marker(_igvn); 605 } else { 606 int nm_offset_in_element = offset_in_element + vk->null_marker_offset_in_payload(); 607 const TypeAryPtr* nm_adr_type = elem_adr_type->with_field_offset(nm_offset_in_element); 608 Node* nm_value = value_from_mem(sfpt->memory(), sfpt->control(), T_BOOLEAN, TypeInt::BOOL, nm_adr_type, alloc); 609 if (nm_value != nullptr) { 610 vt->set_null_marker(_igvn, nm_value); 611 } else { 612 report_failure(nm_offset_in_element); 613 return nullptr; 614 } 615 } 616 617 for (int i = 0; i < vk->nof_declared_nonstatic_fields(); ++i) { 618 ciType* field_type = vt->field_type(i); 619 int field_offset_in_element = offset_in_element + vt->field_offset(i) - vk->payload_offset(); 620 Node* field_value = nullptr; 621 if (vt->field_is_flat(i)) { 622 field_value = inline_type_from_mem(field_type->as_inline_klass(), elem_adr_type, elem_idx, field_offset_in_element, vt->field_is_null_free(i), alloc, sfpt); 623 } else { 624 const Type* ft = Type::get_const_type(field_type); 625 BasicType bt = type2field[field_type->basic_type()]; 626 if (UseCompressedOops && !is_java_primitive(bt)) { 627 ft = ft->make_narrowoop(); 628 bt = T_NARROWOOP; 629 } 630 // Each inline type field has its own memory slice 631 const TypeAryPtr* field_adr_type = elem_adr_type->with_field_offset(field_offset_in_element); 632 field_value = value_from_mem(sfpt->memory(), sfpt->control(), bt, ft, field_adr_type, alloc); 633 if (field_value == nullptr) { 634 report_failure(field_offset_in_element); 635 } else if (ft->isa_narrowoop()) { 636 assert(UseCompressedOops, "unexpected narrow oop"); 637 if (field_value->is_EncodeP()) { 638 field_value = field_value->in(1); 639 } else if (!field_value->is_InlineType()) { 640 field_value = transform_later(new DecodeNNode(field_value, field_value->get_ptr_type())); 641 } 642 } 643 } 644 if (field_value != nullptr) { 645 vt->set_field_value(i, field_value); 646 } else { 647 return nullptr; 648 } 649 } 650 return vt; 651 } 652 653 // Check the possibility of scalar replacement. 654 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode *alloc, GrowableArray <SafePointNode *>* safepoints) { 655 // Scan the uses of the allocation to check for anything that would 656 // prevent us from eliminating it. 657 NOT_PRODUCT( const char* fail_eliminate = nullptr; ) 658 DEBUG_ONLY( Node* disq_node = nullptr; ) 659 bool can_eliminate = true; 660 bool reduce_merge_precheck = (safepoints == nullptr); 661 662 Unique_Node_List worklist; 663 Node* res = alloc->result_cast(); 664 const TypeOopPtr* res_type = nullptr; 665 if (res == nullptr) { 666 // All users were eliminated. 667 } else if (!res->is_CheckCastPP()) { 668 NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";) 669 can_eliminate = false; 670 } else { 671 worklist.push(res); 672 res_type = igvn->type(res)->isa_oopptr(); 673 if (res_type == nullptr) { 674 NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";) 675 can_eliminate = false; 676 } else if (!res_type->klass_is_exact()) { 677 NOT_PRODUCT(fail_eliminate = "Not an exact type.";) 678 can_eliminate = false; 679 } else if (res_type->isa_aryptr()) { 680 int length = alloc->in(AllocateNode::ALength)->find_int_con(-1); 681 if (length < 0) { 682 NOT_PRODUCT(fail_eliminate = "Array's size is not constant";) 683 can_eliminate = false; 684 } 685 } 686 } 687 688 while (can_eliminate && worklist.size() > 0) { 689 BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2(); 690 res = worklist.pop(); 691 for (DUIterator_Fast jmax, j = res->fast_outs(jmax); j < jmax && can_eliminate; j++) { 692 Node* use = res->fast_out(j); 693 694 if (use->is_AddP()) { 695 const TypePtr* addp_type = igvn->type(use)->is_ptr(); 696 int offset = addp_type->offset(); 697 698 if (offset == Type::OffsetTop || offset == Type::OffsetBot) { 699 NOT_PRODUCT(fail_eliminate = "Undefined field reference";) 700 can_eliminate = false; 701 break; 702 } 703 for (DUIterator_Fast kmax, k = use->fast_outs(kmax); 704 k < kmax && can_eliminate; k++) { 705 Node* n = use->fast_out(k); 706 if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) { 707 DEBUG_ONLY(disq_node = n;) 708 if (n->is_Load() || n->is_LoadStore()) { 709 NOT_PRODUCT(fail_eliminate = "Field load";) 710 } else { 711 NOT_PRODUCT(fail_eliminate = "Not store field reference";) 712 } 713 can_eliminate = false; 714 } 715 } 716 } else if (use->is_ArrayCopy() && 717 (use->as_ArrayCopy()->is_clonebasic() || 718 use->as_ArrayCopy()->is_arraycopy_validated() || 719 use->as_ArrayCopy()->is_copyof_validated() || 720 use->as_ArrayCopy()->is_copyofrange_validated()) && 721 use->in(ArrayCopyNode::Dest) == res) { 722 // ok to eliminate 723 } else if (use->is_SafePoint()) { 724 SafePointNode* sfpt = use->as_SafePoint(); 725 if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) { 726 // Object is passed as argument. 727 DEBUG_ONLY(disq_node = use;) 728 NOT_PRODUCT(fail_eliminate = "Object is passed as argument";) 729 can_eliminate = false; 730 } 731 Node* sfptMem = sfpt->memory(); 732 if (sfptMem == nullptr || sfptMem->is_top()) { 733 DEBUG_ONLY(disq_node = use;) 734 NOT_PRODUCT(fail_eliminate = "null or TOP memory";) 735 can_eliminate = false; 736 } else if (!reduce_merge_precheck) { 737 assert(!res->is_Phi() || !res->as_Phi()->can_be_inline_type(), "Inline type allocations should not have safepoint uses"); 738 safepoints->append_if_missing(sfpt); 739 } 740 } else if (use->is_InlineType() && use->as_InlineType()->get_oop() == res) { 741 // Look at uses 742 for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) { 743 Node* u = use->fast_out(k); 744 if (u->is_InlineType()) { 745 // Use in flat field can be eliminated 746 InlineTypeNode* vt = u->as_InlineType(); 747 for (uint i = 0; i < vt->field_count(); ++i) { 748 if (vt->field_value(i) == use && !vt->field_is_flat(i)) { 749 can_eliminate = false; // Use in non-flat field 750 break; 751 } 752 } 753 } else { 754 // Add other uses to the worklist to process individually 755 worklist.push(use); 756 } 757 } 758 } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) { 759 // Store to mark word of inline type larval buffer 760 assert(res_type->is_inlinetypeptr(), "Unexpected store to mark word"); 761 } else if (res_type->is_inlinetypeptr() && (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore)) { 762 // Inline type buffer allocations are followed by a membar 763 } else if (reduce_merge_precheck && 764 (use->is_Phi() || use->is_EncodeP() || 765 use->Opcode() == Op_MemBarRelease || 766 (UseStoreStoreForCtor && use->Opcode() == Op_MemBarStoreStore))) { 767 // Nothing to do 768 } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark 769 if (use->is_Phi()) { 770 if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) { 771 NOT_PRODUCT(fail_eliminate = "Object is return value";) 772 } else { 773 NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";) 774 } 775 DEBUG_ONLY(disq_node = use;) 776 } else { 777 if (use->Opcode() == Op_Return) { 778 NOT_PRODUCT(fail_eliminate = "Object is return value";) 779 } else { 780 NOT_PRODUCT(fail_eliminate = "Object is referenced by node";) 781 } 782 DEBUG_ONLY(disq_node = use;) 783 } 784 can_eliminate = false; 785 } else { 786 assert(use->Opcode() == Op_CastP2X, "should be"); 787 assert(!use->has_out_with(Op_OrL), "should have been removed because oop is never null"); 788 } 789 } 790 } 791 792 #ifndef PRODUCT 793 if (PrintEliminateAllocations && safepoints != nullptr) { 794 if (can_eliminate) { 795 tty->print("Scalar "); 796 if (res == nullptr) 797 alloc->dump(); 798 else 799 res->dump(); 800 } else { 801 tty->print("NotScalar (%s)", fail_eliminate); 802 if (res == nullptr) 803 alloc->dump(); 804 else 805 res->dump(); 806 #ifdef ASSERT 807 if (disq_node != nullptr) { 808 tty->print(" >>>> "); 809 disq_node->dump(); 810 } 811 #endif /*ASSERT*/ 812 } 813 } 814 815 if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) { 816 tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : ""); 817 DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();) 818 } 819 #endif 820 return can_eliminate; 821 } 822 823 void PhaseMacroExpand::undo_previous_scalarizations(GrowableArray <SafePointNode *> safepoints_done, AllocateNode* alloc) { 824 Node* res = alloc->result_cast(); 825 int nfields = 0; 826 assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result"); 827 828 if (res != nullptr) { 829 const TypeOopPtr* res_type = _igvn.type(res)->isa_oopptr(); 830 831 if (res_type->isa_instptr()) { 832 // find the fields of the class which will be needed for safepoint debug information 833 ciInstanceKlass* iklass = res_type->is_instptr()->instance_klass(); 834 nfields = iklass->nof_nonstatic_fields(); 835 } else { 836 // find the array's elements which will be needed for safepoint debug information 837 nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1); 838 assert(nfields >= 0, "must be an array klass."); 839 } 840 } 841 842 // rollback processed safepoints 843 while (safepoints_done.length() > 0) { 844 SafePointNode* sfpt_done = safepoints_done.pop(); 845 // remove any extra entries we added to the safepoint 846 uint last = sfpt_done->req() - 1; 847 for (int k = 0; k < nfields; k++) { 848 sfpt_done->del_req(last--); 849 } 850 JVMState *jvms = sfpt_done->jvms(); 851 jvms->set_endoff(sfpt_done->req()); 852 // Now make a pass over the debug information replacing any references 853 // to SafePointScalarObjectNode with the allocated object. 854 int start = jvms->debug_start(); 855 int end = jvms->debug_end(); 856 for (int i = start; i < end; i++) { 857 if (sfpt_done->in(i)->is_SafePointScalarObject()) { 858 SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject(); 859 if (scobj->first_index(jvms) == sfpt_done->req() && 860 scobj->n_fields() == (uint)nfields) { 861 assert(scobj->alloc() == alloc, "sanity"); 862 sfpt_done->set_req(i, res); 863 } 864 } 865 } 866 _igvn._worklist.push(sfpt_done); 867 } 868 } 869 870 void PhaseMacroExpand::process_field_value_at_safepoint(const Type* field_type, Node* field_val, SafePointNode* sfpt, Unique_Node_List* value_worklist) { 871 if (UseCompressedOops && field_type->isa_narrowoop()) { 872 // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation 873 // to be able scalar replace the allocation. 874 if (field_val->is_EncodeP()) { 875 field_val = field_val->in(1); 876 } else if (!field_val->is_InlineType()) { 877 field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type())); 878 } 879 } 880 881 // Keep track of inline types to scalarize them later 882 if (field_val->is_InlineType()) { 883 value_worklist->push(field_val); 884 } else if (field_val->is_Phi()) { 885 PhiNode* phi = field_val->as_Phi(); 886 // Eagerly replace inline type phis now since we could be removing an inline type allocation where we must 887 // scalarize all its fields in safepoints. 888 field_val = phi->try_push_inline_types_down(&_igvn, true); 889 if (field_val->is_InlineType()) { 890 value_worklist->push(field_val); 891 } 892 } 893 sfpt->add_req(field_val); 894 } 895 896 bool PhaseMacroExpand::add_array_elems_to_safepoint(AllocateNode* alloc, const TypeAryPtr* array_type, SafePointNode* sfpt, Unique_Node_List* value_worklist) { 897 const Type* elem_type = array_type->elem(); 898 BasicType basic_elem_type = elem_type->array_element_basic_type(); 899 900 intptr_t elem_size; 901 uint header_size; 902 if (array_type->is_flat()) { 903 elem_size = array_type->flat_elem_size(); 904 header_size = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT); 905 } else { 906 elem_size = type2aelembytes(basic_elem_type); 907 header_size = arrayOopDesc::base_offset_in_bytes(basic_elem_type); 908 } 909 910 int n_elems = alloc->in(AllocateNode::ALength)->get_int(); 911 for (int elem_idx = 0; elem_idx < n_elems; elem_idx++) { 912 intptr_t elem_offset = header_size + elem_idx * elem_size; 913 const TypeAryPtr* elem_adr_type = array_type->with_offset(elem_offset); 914 Node* elem_val; 915 if (array_type->is_flat()) { 916 ciInlineKlass* elem_klass = elem_type->inline_klass(); 917 assert(elem_klass->maybe_flat_in_array(), "must be flat in array"); 918 elem_val = inline_type_from_mem(elem_klass, elem_adr_type, elem_idx, 0, array_type->is_null_free(), alloc, sfpt); 919 } else { 920 elem_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, elem_type, elem_adr_type, alloc); 921 #ifndef PRODUCT 922 if (PrintEliminateAllocations && elem_val == nullptr) { 923 tty->print("=== At SafePoint node %d can't find value of array element [%d]", sfpt->_idx, elem_idx); 924 tty->print(", which prevents elimination of: "); 925 alloc->dump(); 926 } 927 #endif // PRODUCT 928 } 929 if (elem_val == nullptr) { 930 return false; 931 } 932 933 process_field_value_at_safepoint(elem_type, elem_val, sfpt, value_worklist); 934 } 935 936 return true; 937 } 938 939 // Recursively adds all flattened fields of a type 'iklass' inside 'base' to 'sfpt'. 940 // 'offset_minus_header' refers to the offset of the payload of 'iklass' inside 'base' minus the 941 // payload offset of 'iklass'. If 'base' is of type 'iklass' then 'offset_minus_header' == 0. 942 bool PhaseMacroExpand::add_inst_fields_to_safepoint(ciInstanceKlass* iklass, AllocateNode* alloc, Node* base, int offset_minus_header, SafePointNode* sfpt, Unique_Node_List* value_worklist) { 943 const TypeInstPtr* base_type = _igvn.type(base)->is_instptr(); 944 auto report_failure = [&](int offset) { 945 #ifndef PRODUCT 946 if (PrintEliminateAllocations) { 947 ciInstanceKlass* base_klass = base_type->instance_klass(); 948 ciField* flattened_field = base_klass->get_field_by_offset(offset, false); 949 assert(flattened_field != nullptr, "must have a field of type %s at offset %d", base_klass->name()->as_utf8(), offset); 950 tty->print("=== At SafePoint node %d can't find value of field: ", sfpt->_idx); 951 flattened_field->print(); 952 int field_idx = C->alias_type(flattened_field)->index(); 953 tty->print(" (alias_idx=%d)", field_idx); 954 tty->print(", which prevents elimination of: "); 955 base->dump(); 956 } 957 #endif // PRODUCT 958 }; 959 960 for (int i = 0; i < iklass->nof_declared_nonstatic_fields(); i++) { 961 ciField* field = iklass->declared_nonstatic_field_at(i); 962 if (field->is_flat()) { 963 ciInlineKlass* fvk = field->type()->as_inline_klass(); 964 int field_offset_minus_header = offset_minus_header + field->offset_in_bytes() - fvk->payload_offset(); 965 bool success = add_inst_fields_to_safepoint(fvk, alloc, base, field_offset_minus_header, sfpt, value_worklist); 966 if (!success) { 967 return false; 968 } 969 970 // The null marker of a field is added right after we scalarize that field 971 if (!field->is_null_free()) { 972 int nm_offset = offset_minus_header + field->null_marker_offset(); 973 Node* null_marker = value_from_mem(sfpt->memory(), sfpt->control(), T_BOOLEAN, TypeInt::BOOL, base_type->with_offset(nm_offset), alloc); 974 if (null_marker == nullptr) { 975 report_failure(nm_offset); 976 return false; 977 } 978 process_field_value_at_safepoint(TypeInt::BOOL, null_marker, sfpt, value_worklist); 979 } 980 981 continue; 982 } 983 984 int offset = offset_minus_header + field->offset_in_bytes(); 985 ciType* elem_type = field->type(); 986 BasicType basic_elem_type = field->layout_type(); 987 988 const Type* field_type; 989 if (is_reference_type(basic_elem_type)) { 990 if (!elem_type->is_loaded()) { 991 field_type = TypeInstPtr::BOTTOM; 992 } else { 993 field_type = TypeOopPtr::make_from_klass(elem_type->as_klass()); 994 } 995 if (UseCompressedOops) { 996 field_type = field_type->make_narrowoop(); 997 basic_elem_type = T_NARROWOOP; 998 } 999 } else { 1000 field_type = Type::get_const_basic_type(basic_elem_type); 1001 } 1002 1003 const TypeInstPtr* field_addr_type = base_type->add_offset(offset)->isa_instptr(); 1004 Node* field_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc); 1005 if (field_val == nullptr) { 1006 report_failure(offset); 1007 return false; 1008 } 1009 process_field_value_at_safepoint(field_type, field_val, sfpt, value_worklist); 1010 } 1011 1012 return true; 1013 } 1014 1015 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode* alloc, SafePointNode* sfpt, 1016 Unique_Node_List* value_worklist) { 1017 // Fields of scalar objs are referenced only at the end 1018 // of regular debuginfo at the last (youngest) JVMS. 1019 // Record relative start index. 1020 ciInstanceKlass* iklass = nullptr; 1021 const TypeOopPtr* res_type = nullptr; 1022 int nfields = 0; 1023 uint first_ind = (sfpt->req() - sfpt->jvms()->scloff()); 1024 Node* res = alloc->result_cast(); 1025 1026 assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result"); 1027 assert(sfpt->jvms() != nullptr, "missed JVMS"); 1028 uint before_sfpt_req = sfpt->req(); 1029 1030 if (res != nullptr) { // Could be null when there are no users 1031 res_type = _igvn.type(res)->isa_oopptr(); 1032 1033 if (res_type->isa_instptr()) { 1034 // find the fields of the class which will be needed for safepoint debug information 1035 iklass = res_type->is_instptr()->instance_klass(); 1036 nfields = iklass->nof_nonstatic_fields(); 1037 } else { 1038 // find the array's elements which will be needed for safepoint debug information 1039 nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1); 1040 assert(nfields >= 0, "must be an array klass."); 1041 } 1042 1043 if (res->bottom_type()->is_inlinetypeptr()) { 1044 // Nullable inline types have a null marker field which is added to the safepoint when scalarizing them (see 1045 // InlineTypeNode::make_scalar_in_safepoint()). When having circular inline types, we stop scalarizing at depth 1 1046 // to avoid an endless recursion. Therefore, we do not have a SafePointScalarObjectNode node here, yet. 1047 // We are about to create a SafePointScalarObjectNode as if this is a normal object. Add an additional int input 1048 // with value 1 which sets the null marker to true to indicate that the object is always non-null. This input is checked 1049 // later in PhaseOutput::filLocArray() for inline types. 1050 sfpt->add_req(_igvn.intcon(1)); 1051 } 1052 } 1053 1054 SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields); 1055 sobj->init_req(0, C->root()); 1056 transform_later(sobj); 1057 1058 if (res == nullptr) { 1059 sfpt->jvms()->set_endoff(sfpt->req()); 1060 return sobj; 1061 } 1062 1063 bool success; 1064 if (iklass == nullptr) { 1065 success = add_array_elems_to_safepoint(alloc, res_type->is_aryptr(), sfpt, value_worklist); 1066 } else { 1067 success = add_inst_fields_to_safepoint(iklass, alloc, res, 0, sfpt, value_worklist); 1068 } 1069 1070 // We weren't able to find a value for this field, remove all the fields added to the safepoint 1071 if (!success) { 1072 for (uint i = sfpt->req() - 1; i >= before_sfpt_req; i--) { 1073 sfpt->del_req(i); 1074 } 1075 _igvn._worklist.push(sfpt); 1076 return nullptr; 1077 } 1078 1079 sfpt->jvms()->set_endoff(sfpt->req()); 1080 return sobj; 1081 } 1082 1083 // Do scalar replacement. 1084 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) { 1085 GrowableArray <SafePointNode *> safepoints_done; 1086 Node* res = alloc->result_cast(); 1087 assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result"); 1088 const TypeOopPtr* res_type = nullptr; 1089 if (res != nullptr) { // Could be null when there are no users 1090 res_type = _igvn.type(res)->isa_oopptr(); 1091 } 1092 1093 // Process the safepoint uses 1094 Unique_Node_List value_worklist; 1095 while (safepoints.length() > 0) { 1096 SafePointNode* sfpt = safepoints.pop(); 1097 SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt, &value_worklist); 1098 1099 if (sobj == nullptr) { 1100 undo_previous_scalarizations(safepoints_done, alloc); 1101 return false; 1102 } 1103 1104 // Now make a pass over the debug information replacing any references 1105 // to the allocated object with "sobj" 1106 JVMState *jvms = sfpt->jvms(); 1107 sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn); 1108 _igvn._worklist.push(sfpt); 1109 1110 // keep it for rollback 1111 safepoints_done.append_if_missing(sfpt); 1112 } 1113 // Scalarize inline types that were added to the safepoint. 1114 // Don't allow linking a constant oop (if available) for flat array elements 1115 // because Deoptimization::reassign_flat_array_elements needs field values. 1116 bool allow_oop = (res_type != nullptr) && !res_type->is_flat(); 1117 for (uint i = 0; i < value_worklist.size(); ++i) { 1118 InlineTypeNode* vt = value_worklist.at(i)->as_InlineType(); 1119 vt->make_scalar_in_safepoints(&_igvn, allow_oop); 1120 } 1121 return true; 1122 } 1123 1124 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) { 1125 Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control); 1126 Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory); 1127 if (ctl_proj != nullptr) { 1128 igvn.replace_node(ctl_proj, n->in(0)); 1129 } 1130 if (mem_proj != nullptr) { 1131 igvn.replace_node(mem_proj, n->in(TypeFunc::Memory)); 1132 } 1133 } 1134 1135 // Process users of eliminated allocation. 1136 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) { 1137 Unique_Node_List worklist; 1138 Node* res = alloc->result_cast(); 1139 if (res != nullptr) { 1140 worklist.push(res); 1141 } 1142 while (worklist.size() > 0) { 1143 res = worklist.pop(); 1144 for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) { 1145 Node *use = res->last_out(j); 1146 uint oc1 = res->outcnt(); 1147 1148 if (use->is_AddP()) { 1149 for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) { 1150 Node *n = use->last_out(k); 1151 uint oc2 = use->outcnt(); 1152 if (n->is_Store()) { 1153 for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) { 1154 MemBarNode* mb = n->fast_out(p)->isa_MemBar(); 1155 if (mb != nullptr && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) { 1156 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations 1157 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object"); 1158 mb->remove(&_igvn); 1159 } 1160 } 1161 _igvn.replace_node(n, n->in(MemNode::Memory)); 1162 } else { 1163 eliminate_gc_barrier(n); 1164 } 1165 k -= (oc2 - use->outcnt()); 1166 } 1167 _igvn.remove_dead_node(use); 1168 } else if (use->is_ArrayCopy()) { 1169 // Disconnect ArrayCopy node 1170 ArrayCopyNode* ac = use->as_ArrayCopy(); 1171 if (ac->is_clonebasic()) { 1172 Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out(); 1173 disconnect_projections(ac, _igvn); 1174 assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation"); 1175 Node* membar_before = alloc->in(TypeFunc::Memory)->in(0); 1176 disconnect_projections(membar_before->as_MemBar(), _igvn); 1177 if (membar_after->is_MemBar()) { 1178 disconnect_projections(membar_after->as_MemBar(), _igvn); 1179 } 1180 } else { 1181 assert(ac->is_arraycopy_validated() || 1182 ac->is_copyof_validated() || 1183 ac->is_copyofrange_validated(), "unsupported"); 1184 CallProjections* callprojs = ac->extract_projections(true); 1185 1186 _igvn.replace_node(callprojs->fallthrough_ioproj, ac->in(TypeFunc::I_O)); 1187 _igvn.replace_node(callprojs->fallthrough_memproj, ac->in(TypeFunc::Memory)); 1188 _igvn.replace_node(callprojs->fallthrough_catchproj, ac->in(TypeFunc::Control)); 1189 1190 // Set control to top. IGVN will remove the remaining projections 1191 ac->set_req(0, top()); 1192 ac->replace_edge(res, top(), &_igvn); 1193 1194 // Disconnect src right away: it can help find new 1195 // opportunities for allocation elimination 1196 Node* src = ac->in(ArrayCopyNode::Src); 1197 ac->replace_edge(src, top(), &_igvn); 1198 // src can be top at this point if src and dest of the 1199 // arraycopy were the same 1200 if (src->outcnt() == 0 && !src->is_top()) { 1201 _igvn.remove_dead_node(src); 1202 } 1203 } 1204 _igvn._worklist.push(ac); 1205 } else if (use->is_InlineType()) { 1206 assert(use->as_InlineType()->get_oop() == res, "unexpected inline type ptr use"); 1207 // Cut off oop input and remove known instance id from type 1208 _igvn.rehash_node_delayed(use); 1209 use->as_InlineType()->set_oop(_igvn, _igvn.zerocon(T_OBJECT)); 1210 const TypeOopPtr* toop = _igvn.type(use)->is_oopptr()->cast_to_instance_id(TypeOopPtr::InstanceBot); 1211 _igvn.set_type(use, toop); 1212 use->as_InlineType()->set_type(toop); 1213 // Process users 1214 for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) { 1215 Node* u = use->fast_out(k); 1216 if (!u->is_InlineType()) { 1217 worklist.push(u); 1218 } 1219 } 1220 } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) { 1221 // Store to mark word of inline type larval buffer 1222 assert(inline_alloc, "Unexpected store to mark word"); 1223 _igvn.replace_node(use, use->in(MemNode::Memory)); 1224 } else if (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore) { 1225 // Inline type buffer allocations are followed by a membar 1226 assert(inline_alloc, "Unexpected MemBarRelease"); 1227 use->as_MemBar()->remove(&_igvn); 1228 } else { 1229 eliminate_gc_barrier(use); 1230 } 1231 j -= (oc1 - res->outcnt()); 1232 } 1233 assert(res->outcnt() == 0, "all uses of allocated objects must be deleted"); 1234 _igvn.remove_dead_node(res); 1235 } 1236 1237 // 1238 // Process other users of allocation's projections 1239 // 1240 if (_callprojs->resproj[0] != nullptr && _callprojs->resproj[0]->outcnt() != 0) { 1241 // First disconnect stores captured by Initialize node. 1242 // If Initialize node is eliminated first in the following code, 1243 // it will kill such stores and DUIterator_Last will assert. 1244 for (DUIterator_Fast jmax, j = _callprojs->resproj[0]->fast_outs(jmax); j < jmax; j++) { 1245 Node* use = _callprojs->resproj[0]->fast_out(j); 1246 if (use->is_AddP()) { 1247 // raw memory addresses used only by the initialization 1248 _igvn.replace_node(use, C->top()); 1249 --j; --jmax; 1250 } 1251 } 1252 for (DUIterator_Last jmin, j = _callprojs->resproj[0]->last_outs(jmin); j >= jmin; ) { 1253 Node* use = _callprojs->resproj[0]->last_out(j); 1254 uint oc1 = _callprojs->resproj[0]->outcnt(); 1255 if (use->is_Initialize()) { 1256 // Eliminate Initialize node. 1257 InitializeNode *init = use->as_Initialize(); 1258 assert(init->outcnt() <= 2, "only a control and memory projection expected"); 1259 Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control); 1260 if (ctrl_proj != nullptr) { 1261 _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control)); 1262 #ifdef ASSERT 1263 // If the InitializeNode has no memory out, it will die, and tmp will become null 1264 Node* tmp = init->in(TypeFunc::Control); 1265 assert(tmp == nullptr || tmp == _callprojs->fallthrough_catchproj, "allocation control projection"); 1266 #endif 1267 } 1268 Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory); 1269 if (mem_proj != nullptr) { 1270 Node *mem = init->in(TypeFunc::Memory); 1271 #ifdef ASSERT 1272 if (mem->is_MergeMem()) { 1273 assert(mem->in(TypeFunc::Memory) == _callprojs->fallthrough_memproj, "allocation memory projection"); 1274 } else { 1275 assert(mem == _callprojs->fallthrough_memproj, "allocation memory projection"); 1276 } 1277 #endif 1278 _igvn.replace_node(mem_proj, mem); 1279 } 1280 } else if (use->Opcode() == Op_MemBarStoreStore) { 1281 // Inline type buffer allocations are followed by a membar 1282 assert(inline_alloc, "Unexpected MemBarStoreStore"); 1283 use->as_MemBar()->remove(&_igvn); 1284 } else { 1285 assert(false, "only Initialize or AddP expected"); 1286 } 1287 j -= (oc1 - _callprojs->resproj[0]->outcnt()); 1288 } 1289 } 1290 if (_callprojs->fallthrough_catchproj != nullptr) { 1291 _igvn.replace_node(_callprojs->fallthrough_catchproj, alloc->in(TypeFunc::Control)); 1292 } 1293 if (_callprojs->fallthrough_memproj != nullptr) { 1294 _igvn.replace_node(_callprojs->fallthrough_memproj, alloc->in(TypeFunc::Memory)); 1295 } 1296 if (_callprojs->catchall_memproj != nullptr) { 1297 _igvn.replace_node(_callprojs->catchall_memproj, C->top()); 1298 } 1299 if (_callprojs->fallthrough_ioproj != nullptr) { 1300 _igvn.replace_node(_callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O)); 1301 } 1302 if (_callprojs->catchall_ioproj != nullptr) { 1303 _igvn.replace_node(_callprojs->catchall_ioproj, C->top()); 1304 } 1305 if (_callprojs->catchall_catchproj != nullptr) { 1306 _igvn.replace_node(_callprojs->catchall_catchproj, C->top()); 1307 } 1308 } 1309 1310 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) { 1311 // If reallocation fails during deoptimization we'll pop all 1312 // interpreter frames for this compiled frame and that won't play 1313 // nice with JVMTI popframe. 1314 // We avoid this issue by eager reallocation when the popframe request 1315 // is received. 1316 if (!EliminateAllocations) { 1317 return false; 1318 } 1319 Node* klass = alloc->in(AllocateNode::KlassNode); 1320 const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr(); 1321 1322 // Attempt to eliminate inline type buffer allocations 1323 // regardless of usage and escape/replaceable status. 1324 bool inline_alloc = tklass->isa_instklassptr() && 1325 tklass->is_instklassptr()->instance_klass()->is_inlinetype(); 1326 if (!alloc->_is_non_escaping && !inline_alloc) { 1327 return false; 1328 } 1329 // Eliminate boxing allocations which are not used 1330 // regardless scalar replaceable status. 1331 Node* res = alloc->result_cast(); 1332 bool boxing_alloc = (res == nullptr) && C->eliminate_boxing() && 1333 tklass->isa_instklassptr() && 1334 tklass->is_instklassptr()->instance_klass()->is_box_klass(); 1335 if (!alloc->_is_scalar_replaceable && !boxing_alloc && !inline_alloc) { 1336 return false; 1337 } 1338 1339 _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/); 1340 1341 GrowableArray <SafePointNode *> safepoints; 1342 if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) { 1343 return false; 1344 } 1345 1346 if (!alloc->_is_scalar_replaceable) { 1347 assert(res == nullptr || inline_alloc, "sanity"); 1348 // We can only eliminate allocation if all debug info references 1349 // are already replaced with SafePointScalarObject because 1350 // we can't search for a fields value without instance_id. 1351 if (safepoints.length() > 0) { 1352 return false; 1353 } 1354 } 1355 1356 if (!scalar_replacement(alloc, safepoints)) { 1357 return false; 1358 } 1359 1360 CompileLog* log = C->log(); 1361 if (log != nullptr) { 1362 log->head("eliminate_allocation type='%d'", 1363 log->identify(tklass->exact_klass())); 1364 JVMState* p = alloc->jvms(); 1365 while (p != nullptr) { 1366 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method())); 1367 p = p->caller(); 1368 } 1369 log->tail("eliminate_allocation"); 1370 } 1371 1372 process_users_of_allocation(alloc, inline_alloc); 1373 1374 #ifndef PRODUCT 1375 if (PrintEliminateAllocations) { 1376 if (alloc->is_AllocateArray()) 1377 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx); 1378 else 1379 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx); 1380 } 1381 #endif 1382 1383 return true; 1384 } 1385 1386 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) { 1387 // EA should remove all uses of non-escaping boxing node. 1388 if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) { 1389 return false; 1390 } 1391 1392 assert(boxing->result_cast() == nullptr, "unexpected boxing node result"); 1393 1394 _callprojs = boxing->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/); 1395 1396 const TypeTuple* r = boxing->tf()->range_sig(); 1397 assert(r->cnt() > TypeFunc::Parms, "sanity"); 1398 const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr(); 1399 assert(t != nullptr, "sanity"); 1400 1401 CompileLog* log = C->log(); 1402 if (log != nullptr) { 1403 log->head("eliminate_boxing type='%d'", 1404 log->identify(t->instance_klass())); 1405 JVMState* p = boxing->jvms(); 1406 while (p != nullptr) { 1407 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method())); 1408 p = p->caller(); 1409 } 1410 log->tail("eliminate_boxing"); 1411 } 1412 1413 process_users_of_allocation(boxing); 1414 1415 #ifndef PRODUCT 1416 if (PrintEliminateAllocations) { 1417 tty->print("++++ Eliminated: %d ", boxing->_idx); 1418 boxing->method()->print_short_name(tty); 1419 tty->cr(); 1420 } 1421 #endif 1422 1423 return true; 1424 } 1425 1426 1427 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) { 1428 Node* adr = basic_plus_adr(base, offset); 1429 const TypePtr* adr_type = adr->bottom_type()->is_ptr(); 1430 Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered); 1431 transform_later(value); 1432 return value; 1433 } 1434 1435 1436 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) { 1437 Node* adr = basic_plus_adr(base, offset); 1438 mem = StoreNode::make(_igvn, ctl, mem, adr, nullptr, value, bt, MemNode::unordered); 1439 transform_later(mem); 1440 return mem; 1441 } 1442 1443 //============================================================================= 1444 // 1445 // A L L O C A T I O N 1446 // 1447 // Allocation attempts to be fast in the case of frequent small objects. 1448 // It breaks down like this: 1449 // 1450 // 1) Size in doublewords is computed. This is a constant for objects and 1451 // variable for most arrays. Doubleword units are used to avoid size 1452 // overflow of huge doubleword arrays. We need doublewords in the end for 1453 // rounding. 1454 // 1455 // 2) Size is checked for being 'too large'. Too-large allocations will go 1456 // the slow path into the VM. The slow path can throw any required 1457 // exceptions, and does all the special checks for very large arrays. The 1458 // size test can constant-fold away for objects. For objects with 1459 // finalizers it constant-folds the otherway: you always go slow with 1460 // finalizers. 1461 // 1462 // 3) If NOT using TLABs, this is the contended loop-back point. 1463 // Load-Locked the heap top. If using TLABs normal-load the heap top. 1464 // 1465 // 4) Check that heap top + size*8 < max. If we fail go the slow ` route. 1466 // NOTE: "top+size*8" cannot wrap the 4Gig line! Here's why: for largish 1467 // "size*8" we always enter the VM, where "largish" is a constant picked small 1468 // enough that there's always space between the eden max and 4Gig (old space is 1469 // there so it's quite large) and large enough that the cost of entering the VM 1470 // is dwarfed by the cost to initialize the space. 1471 // 1472 // 5) If NOT using TLABs, Store-Conditional the adjusted heap top back 1473 // down. If contended, repeat at step 3. If using TLABs normal-store 1474 // adjusted heap top back down; there is no contention. 1475 // 1476 // 6) If !ZeroTLAB then Bulk-clear the object/array. Fill in klass & mark 1477 // fields. 1478 // 1479 // 7) Merge with the slow-path; cast the raw memory pointer to the correct 1480 // oop flavor. 1481 // 1482 //============================================================================= 1483 // FastAllocateSizeLimit value is in DOUBLEWORDS. 1484 // Allocations bigger than this always go the slow route. 1485 // This value must be small enough that allocation attempts that need to 1486 // trigger exceptions go the slow route. Also, it must be small enough so 1487 // that heap_top + size_in_bytes does not wrap around the 4Gig limit. 1488 //=============================================================================j// 1489 // %%% Here is an old comment from parseHelper.cpp; is it outdated? 1490 // The allocator will coalesce int->oop copies away. See comment in 1491 // coalesce.cpp about how this works. It depends critically on the exact 1492 // code shape produced here, so if you are changing this code shape 1493 // make sure the GC info for the heap-top is correct in and around the 1494 // slow-path call. 1495 // 1496 1497 void PhaseMacroExpand::expand_allocate_common( 1498 AllocateNode* alloc, // allocation node to be expanded 1499 Node* length, // array length for an array allocation 1500 Node* init_val, // value to initialize the array with 1501 const TypeFunc* slow_call_type, // Type of slow call 1502 address slow_call_address, // Address of slow call 1503 Node* valid_length_test // whether length is valid or not 1504 ) 1505 { 1506 Node* ctrl = alloc->in(TypeFunc::Control); 1507 Node* mem = alloc->in(TypeFunc::Memory); 1508 Node* i_o = alloc->in(TypeFunc::I_O); 1509 Node* size_in_bytes = alloc->in(AllocateNode::AllocSize); 1510 Node* klass_node = alloc->in(AllocateNode::KlassNode); 1511 Node* initial_slow_test = alloc->in(AllocateNode::InitialTest); 1512 assert(ctrl != nullptr, "must have control"); 1513 1514 // We need a Region and corresponding Phi's to merge the slow-path and fast-path results. 1515 // they will not be used if "always_slow" is set 1516 enum { slow_result_path = 1, fast_result_path = 2 }; 1517 Node *result_region = nullptr; 1518 Node *result_phi_rawmem = nullptr; 1519 Node *result_phi_rawoop = nullptr; 1520 Node *result_phi_i_o = nullptr; 1521 1522 // The initial slow comparison is a size check, the comparison 1523 // we want to do is a BoolTest::gt 1524 bool expand_fast_path = true; 1525 int tv = _igvn.find_int_con(initial_slow_test, -1); 1526 if (tv >= 0) { 1527 // InitialTest has constant result 1528 // 0 - can fit in TLAB 1529 // 1 - always too big or negative 1530 assert(tv <= 1, "0 or 1 if a constant"); 1531 expand_fast_path = (tv == 0); 1532 initial_slow_test = nullptr; 1533 } else { 1534 initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn); 1535 } 1536 1537 if (!UseTLAB) { 1538 // Force slow-path allocation 1539 expand_fast_path = false; 1540 initial_slow_test = nullptr; 1541 } 1542 1543 bool allocation_has_use = (alloc->result_cast() != nullptr); 1544 if (!allocation_has_use) { 1545 InitializeNode* init = alloc->initialization(); 1546 if (init != nullptr) { 1547 init->remove(&_igvn); 1548 } 1549 if (expand_fast_path && (initial_slow_test == nullptr)) { 1550 // Remove allocation node and return. 1551 // Size is a non-negative constant -> no initial check needed -> directly to fast path. 1552 // Also, no usages -> empty fast path -> no fall out to slow path -> nothing left. 1553 #ifndef PRODUCT 1554 if (PrintEliminateAllocations) { 1555 tty->print("NotUsed "); 1556 Node* res = alloc->proj_out_or_null(TypeFunc::Parms); 1557 if (res != nullptr) { 1558 res->dump(); 1559 } else { 1560 alloc->dump(); 1561 } 1562 } 1563 #endif 1564 yank_alloc_node(alloc); 1565 return; 1566 } 1567 } 1568 1569 enum { too_big_or_final_path = 1, need_gc_path = 2 }; 1570 Node *slow_region = nullptr; 1571 Node *toobig_false = ctrl; 1572 1573 // generate the initial test if necessary 1574 if (initial_slow_test != nullptr ) { 1575 assert (expand_fast_path, "Only need test if there is a fast path"); 1576 slow_region = new RegionNode(3); 1577 1578 // Now make the initial failure test. Usually a too-big test but 1579 // might be a TRUE for finalizers. 1580 IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN); 1581 transform_later(toobig_iff); 1582 // Plug the failing-too-big test into the slow-path region 1583 Node* toobig_true = new IfTrueNode(toobig_iff); 1584 transform_later(toobig_true); 1585 slow_region ->init_req( too_big_or_final_path, toobig_true ); 1586 toobig_false = new IfFalseNode(toobig_iff); 1587 transform_later(toobig_false); 1588 } else { 1589 // No initial test, just fall into next case 1590 assert(allocation_has_use || !expand_fast_path, "Should already have been handled"); 1591 toobig_false = ctrl; 1592 DEBUG_ONLY(slow_region = NodeSentinel); 1593 } 1594 1595 // If we are here there are several possibilities 1596 // - expand_fast_path is false - then only a slow path is expanded. That's it. 1597 // no_initial_check means a constant allocation. 1598 // - If check always evaluates to false -> expand_fast_path is false (see above) 1599 // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath) 1600 // if !allocation_has_use the fast path is empty 1601 // if !allocation_has_use && no_initial_check 1602 // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all. 1603 // removed by yank_alloc_node above. 1604 1605 Node *slow_mem = mem; // save the current memory state for slow path 1606 // generate the fast allocation code unless we know that the initial test will always go slow 1607 if (expand_fast_path) { 1608 // Fast path modifies only raw memory. 1609 if (mem->is_MergeMem()) { 1610 mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw); 1611 } 1612 1613 // allocate the Region and Phi nodes for the result 1614 result_region = new RegionNode(3); 1615 result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM); 1616 result_phi_i_o = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch 1617 1618 // Grab regular I/O before optional prefetch may change it. 1619 // Slow-path does no I/O so just set it to the original I/O. 1620 result_phi_i_o->init_req(slow_result_path, i_o); 1621 1622 // Name successful fast-path variables 1623 Node* fast_oop_ctrl; 1624 Node* fast_oop_rawmem; 1625 1626 if (allocation_has_use) { 1627 Node* needgc_ctrl = nullptr; 1628 result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM); 1629 1630 intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines; 1631 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1632 Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl, 1633 fast_oop_ctrl, fast_oop_rawmem, 1634 prefetch_lines); 1635 1636 if (initial_slow_test != nullptr) { 1637 // This completes all paths into the slow merge point 1638 slow_region->init_req(need_gc_path, needgc_ctrl); 1639 transform_later(slow_region); 1640 } else { 1641 // No initial slow path needed! 1642 // Just fall from the need-GC path straight into the VM call. 1643 slow_region = needgc_ctrl; 1644 } 1645 1646 InitializeNode* init = alloc->initialization(); 1647 fast_oop_rawmem = initialize_object(alloc, 1648 fast_oop_ctrl, fast_oop_rawmem, fast_oop, 1649 klass_node, length, size_in_bytes); 1650 expand_initialize_membar(alloc, init, fast_oop_ctrl, fast_oop_rawmem); 1651 expand_dtrace_alloc_probe(alloc, fast_oop, fast_oop_ctrl, fast_oop_rawmem); 1652 1653 result_phi_rawoop->init_req(fast_result_path, fast_oop); 1654 } else { 1655 assert (initial_slow_test != nullptr, "sanity"); 1656 fast_oop_ctrl = toobig_false; 1657 fast_oop_rawmem = mem; 1658 transform_later(slow_region); 1659 } 1660 1661 // Plug in the successful fast-path into the result merge point 1662 result_region ->init_req(fast_result_path, fast_oop_ctrl); 1663 result_phi_i_o ->init_req(fast_result_path, i_o); 1664 result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem); 1665 } else { 1666 slow_region = ctrl; 1667 result_phi_i_o = i_o; // Rename it to use in the following code. 1668 } 1669 1670 // Generate slow-path call 1671 CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address, 1672 OptoRuntime::stub_name(slow_call_address), 1673 TypePtr::BOTTOM); 1674 call->init_req(TypeFunc::Control, slow_region); 1675 call->init_req(TypeFunc::I_O, top()); // does no i/o 1676 call->init_req(TypeFunc::Memory, slow_mem); // may gc ptrs 1677 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr)); 1678 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr)); 1679 1680 call->init_req(TypeFunc::Parms+0, klass_node); 1681 if (length != nullptr) { 1682 call->init_req(TypeFunc::Parms+1, length); 1683 if (init_val != nullptr) { 1684 call->init_req(TypeFunc::Parms+2, init_val); 1685 } 1686 } else { 1687 // Let the runtime know if this is a larval allocation 1688 call->init_req(TypeFunc::Parms+1, _igvn.intcon(alloc->_larval)); 1689 } 1690 1691 // Copy debug information and adjust JVMState information, then replace 1692 // allocate node with the call 1693 call->copy_call_debug_info(&_igvn, alloc); 1694 // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify 1695 // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough 1696 // path dies). 1697 if (valid_length_test != nullptr) { 1698 call->add_req(valid_length_test); 1699 } 1700 if (expand_fast_path) { 1701 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON. 1702 } else { 1703 // Hook i_o projection to avoid its elimination during allocation 1704 // replacement (when only a slow call is generated). 1705 call->set_req(TypeFunc::I_O, result_phi_i_o); 1706 } 1707 _igvn.replace_node(alloc, call); 1708 transform_later(call); 1709 1710 // Identify the output projections from the allocate node and 1711 // adjust any references to them. 1712 // The control and io projections look like: 1713 // 1714 // v---Proj(ctrl) <-----+ v---CatchProj(ctrl) 1715 // Allocate Catch 1716 // ^---Proj(io) <-------+ ^---CatchProj(io) 1717 // 1718 // We are interested in the CatchProj nodes. 1719 // 1720 _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/); 1721 1722 // An allocate node has separate memory projections for the uses on 1723 // the control and i_o paths. Replace the control memory projection with 1724 // result_phi_rawmem (unless we are only generating a slow call when 1725 // both memory projections are combined) 1726 if (expand_fast_path && _callprojs->fallthrough_memproj != nullptr) { 1727 _igvn.replace_in_uses(_callprojs->fallthrough_memproj, result_phi_rawmem); 1728 } 1729 // Now change uses of catchall_memproj to use fallthrough_memproj and delete 1730 // catchall_memproj so we end up with a call that has only 1 memory projection. 1731 if (_callprojs->catchall_memproj != nullptr) { 1732 if (_callprojs->fallthrough_memproj == nullptr) { 1733 _callprojs->fallthrough_memproj = new ProjNode(call, TypeFunc::Memory); 1734 transform_later(_callprojs->fallthrough_memproj); 1735 } 1736 _igvn.replace_in_uses(_callprojs->catchall_memproj, _callprojs->fallthrough_memproj); 1737 _igvn.remove_dead_node(_callprojs->catchall_memproj); 1738 } 1739 1740 // An allocate node has separate i_o projections for the uses on the control 1741 // and i_o paths. Always replace the control i_o projection with result i_o 1742 // otherwise incoming i_o become dead when only a slow call is generated 1743 // (it is different from memory projections where both projections are 1744 // combined in such case). 1745 if (_callprojs->fallthrough_ioproj != nullptr) { 1746 _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, result_phi_i_o); 1747 } 1748 // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete 1749 // catchall_ioproj so we end up with a call that has only 1 i_o projection. 1750 if (_callprojs->catchall_ioproj != nullptr) { 1751 if (_callprojs->fallthrough_ioproj == nullptr) { 1752 _callprojs->fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O); 1753 transform_later(_callprojs->fallthrough_ioproj); 1754 } 1755 _igvn.replace_in_uses(_callprojs->catchall_ioproj, _callprojs->fallthrough_ioproj); 1756 _igvn.remove_dead_node(_callprojs->catchall_ioproj); 1757 } 1758 1759 // if we generated only a slow call, we are done 1760 if (!expand_fast_path) { 1761 // Now we can unhook i_o. 1762 if (result_phi_i_o->outcnt() > 1) { 1763 call->set_req(TypeFunc::I_O, top()); 1764 } else { 1765 assert(result_phi_i_o->unique_ctrl_out() == call, "sanity"); 1766 // Case of new array with negative size known during compilation. 1767 // AllocateArrayNode::Ideal() optimization disconnect unreachable 1768 // following code since call to runtime will throw exception. 1769 // As result there will be no users of i_o after the call. 1770 // Leave i_o attached to this call to avoid problems in preceding graph. 1771 } 1772 return; 1773 } 1774 1775 if (_callprojs->fallthrough_catchproj != nullptr) { 1776 ctrl = _callprojs->fallthrough_catchproj->clone(); 1777 transform_later(ctrl); 1778 _igvn.replace_node(_callprojs->fallthrough_catchproj, result_region); 1779 } else { 1780 ctrl = top(); 1781 } 1782 Node *slow_result; 1783 if (_callprojs->resproj[0] == nullptr) { 1784 // no uses of the allocation result 1785 slow_result = top(); 1786 } else { 1787 slow_result = _callprojs->resproj[0]->clone(); 1788 transform_later(slow_result); 1789 _igvn.replace_node(_callprojs->resproj[0], result_phi_rawoop); 1790 } 1791 1792 // Plug slow-path into result merge point 1793 result_region->init_req( slow_result_path, ctrl); 1794 transform_later(result_region); 1795 if (allocation_has_use) { 1796 result_phi_rawoop->init_req(slow_result_path, slow_result); 1797 transform_later(result_phi_rawoop); 1798 } 1799 result_phi_rawmem->init_req(slow_result_path, _callprojs->fallthrough_memproj); 1800 transform_later(result_phi_rawmem); 1801 transform_later(result_phi_i_o); 1802 // This completes all paths into the result merge point 1803 } 1804 1805 // Remove alloc node that has no uses. 1806 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) { 1807 Node* ctrl = alloc->in(TypeFunc::Control); 1808 Node* mem = alloc->in(TypeFunc::Memory); 1809 Node* i_o = alloc->in(TypeFunc::I_O); 1810 1811 _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/); 1812 if (_callprojs->resproj[0] != nullptr) { 1813 for (DUIterator_Fast imax, i = _callprojs->resproj[0]->fast_outs(imax); i < imax; i++) { 1814 Node* use = _callprojs->resproj[0]->fast_out(i); 1815 use->isa_MemBar()->remove(&_igvn); 1816 --imax; 1817 --i; // back up iterator 1818 } 1819 assert(_callprojs->resproj[0]->outcnt() == 0, "all uses must be deleted"); 1820 _igvn.remove_dead_node(_callprojs->resproj[0]); 1821 } 1822 if (_callprojs->fallthrough_catchproj != nullptr) { 1823 _igvn.replace_in_uses(_callprojs->fallthrough_catchproj, ctrl); 1824 _igvn.remove_dead_node(_callprojs->fallthrough_catchproj); 1825 } 1826 if (_callprojs->catchall_catchproj != nullptr) { 1827 _igvn.rehash_node_delayed(_callprojs->catchall_catchproj); 1828 _callprojs->catchall_catchproj->set_req(0, top()); 1829 } 1830 if (_callprojs->fallthrough_proj != nullptr) { 1831 Node* catchnode = _callprojs->fallthrough_proj->unique_ctrl_out(); 1832 _igvn.remove_dead_node(catchnode); 1833 _igvn.remove_dead_node(_callprojs->fallthrough_proj); 1834 } 1835 if (_callprojs->fallthrough_memproj != nullptr) { 1836 _igvn.replace_in_uses(_callprojs->fallthrough_memproj, mem); 1837 _igvn.remove_dead_node(_callprojs->fallthrough_memproj); 1838 } 1839 if (_callprojs->fallthrough_ioproj != nullptr) { 1840 _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, i_o); 1841 _igvn.remove_dead_node(_callprojs->fallthrough_ioproj); 1842 } 1843 if (_callprojs->catchall_memproj != nullptr) { 1844 _igvn.rehash_node_delayed(_callprojs->catchall_memproj); 1845 _callprojs->catchall_memproj->set_req(0, top()); 1846 } 1847 if (_callprojs->catchall_ioproj != nullptr) { 1848 _igvn.rehash_node_delayed(_callprojs->catchall_ioproj); 1849 _callprojs->catchall_ioproj->set_req(0, top()); 1850 } 1851 #ifndef PRODUCT 1852 if (PrintEliminateAllocations) { 1853 if (alloc->is_AllocateArray()) { 1854 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx); 1855 } else { 1856 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx); 1857 } 1858 } 1859 #endif 1860 _igvn.remove_dead_node(alloc); 1861 } 1862 1863 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init, 1864 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) { 1865 // If initialization is performed by an array copy, any required 1866 // MemBarStoreStore was already added. If the object does not 1867 // escape no need for a MemBarStoreStore. If the object does not 1868 // escape in its initializer and memory barrier (MemBarStoreStore or 1869 // stronger) is already added at exit of initializer, also no need 1870 // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore 1871 // so that stores that initialize this object can't be reordered 1872 // with a subsequent store that makes this object accessible by 1873 // other threads. 1874 // Other threads include java threads and JVM internal threads 1875 // (for example concurrent GC threads). Current concurrent GC 1876 // implementation: G1 will not scan newly created object, 1877 // so it's safe to skip storestore barrier when allocation does 1878 // not escape. 1879 if (!alloc->does_not_escape_thread() && 1880 !alloc->is_allocation_MemBar_redundant() && 1881 (init == nullptr || !init->is_complete_with_arraycopy())) { 1882 if (init == nullptr || init->req() < InitializeNode::RawStores) { 1883 // No InitializeNode or no stores captured by zeroing 1884 // elimination. Simply add the MemBarStoreStore after object 1885 // initialization. 1886 MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot); 1887 transform_later(mb); 1888 1889 mb->init_req(TypeFunc::Memory, fast_oop_rawmem); 1890 mb->init_req(TypeFunc::Control, fast_oop_ctrl); 1891 fast_oop_ctrl = new ProjNode(mb, TypeFunc::Control); 1892 transform_later(fast_oop_ctrl); 1893 fast_oop_rawmem = new ProjNode(mb, TypeFunc::Memory); 1894 transform_later(fast_oop_rawmem); 1895 } else { 1896 // Add the MemBarStoreStore after the InitializeNode so that 1897 // all stores performing the initialization that were moved 1898 // before the InitializeNode happen before the storestore 1899 // barrier. 1900 1901 Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control); 1902 Node* init_mem = init->proj_out_or_null(TypeFunc::Memory); 1903 1904 MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot); 1905 transform_later(mb); 1906 1907 Node* ctrl = new ProjNode(init, TypeFunc::Control); 1908 transform_later(ctrl); 1909 Node* mem = new ProjNode(init, TypeFunc::Memory); 1910 transform_later(mem); 1911 1912 // The MemBarStoreStore depends on control and memory coming 1913 // from the InitializeNode 1914 mb->init_req(TypeFunc::Memory, mem); 1915 mb->init_req(TypeFunc::Control, ctrl); 1916 1917 ctrl = new ProjNode(mb, TypeFunc::Control); 1918 transform_later(ctrl); 1919 mem = new ProjNode(mb, TypeFunc::Memory); 1920 transform_later(mem); 1921 1922 // All nodes that depended on the InitializeNode for control 1923 // and memory must now depend on the MemBarNode that itself 1924 // depends on the InitializeNode 1925 if (init_ctrl != nullptr) { 1926 _igvn.replace_node(init_ctrl, ctrl); 1927 } 1928 if (init_mem != nullptr) { 1929 _igvn.replace_node(init_mem, mem); 1930 } 1931 } 1932 } 1933 } 1934 1935 void PhaseMacroExpand::expand_dtrace_alloc_probe(AllocateNode* alloc, Node* oop, 1936 Node*& ctrl, Node*& rawmem) { 1937 if (C->env()->dtrace_alloc_probes()) { 1938 // Slow-path call 1939 int size = TypeFunc::Parms + 2; 1940 CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(), 1941 CAST_FROM_FN_PTR(address, 1942 static_cast<int (*)(JavaThread*, oopDesc*)>(SharedRuntime::dtrace_object_alloc)), 1943 "dtrace_object_alloc", 1944 TypeRawPtr::BOTTOM); 1945 1946 // Get base of thread-local storage area 1947 Node* thread = new ThreadLocalNode(); 1948 transform_later(thread); 1949 1950 call->init_req(TypeFunc::Parms + 0, thread); 1951 call->init_req(TypeFunc::Parms + 1, oop); 1952 call->init_req(TypeFunc::Control, ctrl); 1953 call->init_req(TypeFunc::I_O , top()); // does no i/o 1954 call->init_req(TypeFunc::Memory , rawmem); 1955 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr)); 1956 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr)); 1957 transform_later(call); 1958 ctrl = new ProjNode(call, TypeFunc::Control); 1959 transform_later(ctrl); 1960 rawmem = new ProjNode(call, TypeFunc::Memory); 1961 transform_later(rawmem); 1962 } 1963 } 1964 1965 // Helper for PhaseMacroExpand::expand_allocate_common. 1966 // Initializes the newly-allocated storage. 1967 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc, 1968 Node* control, Node* rawmem, Node* object, 1969 Node* klass_node, Node* length, 1970 Node* size_in_bytes) { 1971 InitializeNode* init = alloc->initialization(); 1972 // Store the klass & mark bits 1973 Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem); 1974 if (!mark_node->is_Con()) { 1975 transform_later(mark_node); 1976 } 1977 rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type()); 1978 1979 if (!UseCompactObjectHeaders) { 1980 rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA); 1981 } 1982 int header_size = alloc->minimum_header_size(); // conservatively small 1983 1984 // Array length 1985 if (length != nullptr) { // Arrays need length field 1986 rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT); 1987 // conservatively small header size: 1988 header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE); 1989 if (_igvn.type(klass_node)->isa_aryklassptr()) { // we know the exact header size in most cases: 1990 BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type(); 1991 if (is_reference_type(elem, true)) { 1992 elem = T_OBJECT; 1993 } 1994 header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem)); 1995 } 1996 } 1997 1998 // Clear the object body, if necessary. 1999 if (init == nullptr) { 2000 // The init has somehow disappeared; be cautious and clear everything. 2001 // 2002 // This can happen if a node is allocated but an uncommon trap occurs 2003 // immediately. In this case, the Initialize gets associated with the 2004 // trap, and may be placed in a different (outer) loop, if the Allocate 2005 // is in a loop. If (this is rare) the inner loop gets unrolled, then 2006 // there can be two Allocates to one Initialize. The answer in all these 2007 // edge cases is safety first. It is always safe to clear immediately 2008 // within an Allocate, and then (maybe or maybe not) clear some more later. 2009 if (!(UseTLAB && ZeroTLAB)) { 2010 rawmem = ClearArrayNode::clear_memory(control, rawmem, object, 2011 alloc->in(AllocateNode::InitValue), 2012 alloc->in(AllocateNode::RawInitValue), 2013 header_size, size_in_bytes, 2014 &_igvn); 2015 } 2016 } else { 2017 if (!init->is_complete()) { 2018 // Try to win by zeroing only what the init does not store. 2019 // We can also try to do some peephole optimizations, 2020 // such as combining some adjacent subword stores. 2021 rawmem = init->complete_stores(control, rawmem, object, 2022 header_size, size_in_bytes, &_igvn); 2023 } 2024 // We have no more use for this link, since the AllocateNode goes away: 2025 init->set_req(InitializeNode::RawAddress, top()); 2026 // (If we keep the link, it just confuses the register allocator, 2027 // who thinks he sees a real use of the address by the membar.) 2028 } 2029 2030 return rawmem; 2031 } 2032 2033 // Generate prefetch instructions for next allocations. 2034 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false, 2035 Node*& contended_phi_rawmem, 2036 Node* old_eden_top, Node* new_eden_top, 2037 intx lines) { 2038 enum { fall_in_path = 1, pf_path = 2 }; 2039 if( UseTLAB && AllocatePrefetchStyle == 2 ) { 2040 // Generate prefetch allocation with watermark check. 2041 // As an allocation hits the watermark, we will prefetch starting 2042 // at a "distance" away from watermark. 2043 2044 Node *pf_region = new RegionNode(3); 2045 Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY, 2046 TypeRawPtr::BOTTOM ); 2047 // I/O is used for Prefetch 2048 Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO ); 2049 2050 Node *thread = new ThreadLocalNode(); 2051 transform_later(thread); 2052 2053 Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread, 2054 _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) ); 2055 transform_later(eden_pf_adr); 2056 2057 Node *old_pf_wm = new LoadPNode(needgc_false, 2058 contended_phi_rawmem, eden_pf_adr, 2059 TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM, 2060 MemNode::unordered); 2061 transform_later(old_pf_wm); 2062 2063 // check against new_eden_top 2064 Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm ); 2065 transform_later(need_pf_cmp); 2066 Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge ); 2067 transform_later(need_pf_bol); 2068 IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol, 2069 PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN ); 2070 transform_later(need_pf_iff); 2071 2072 // true node, add prefetchdistance 2073 Node *need_pf_true = new IfTrueNode( need_pf_iff ); 2074 transform_later(need_pf_true); 2075 2076 Node *need_pf_false = new IfFalseNode( need_pf_iff ); 2077 transform_later(need_pf_false); 2078 2079 Node *new_pf_wmt = new AddPNode( top(), old_pf_wm, 2080 _igvn.MakeConX(AllocatePrefetchDistance) ); 2081 transform_later(new_pf_wmt ); 2082 new_pf_wmt->set_req(0, need_pf_true); 2083 2084 Node *store_new_wmt = new StorePNode(need_pf_true, 2085 contended_phi_rawmem, eden_pf_adr, 2086 TypeRawPtr::BOTTOM, new_pf_wmt, 2087 MemNode::unordered); 2088 transform_later(store_new_wmt); 2089 2090 // adding prefetches 2091 pf_phi_abio->init_req( fall_in_path, i_o ); 2092 2093 Node *prefetch_adr; 2094 Node *prefetch; 2095 uint step_size = AllocatePrefetchStepSize; 2096 uint distance = 0; 2097 2098 for ( intx i = 0; i < lines; i++ ) { 2099 prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt, 2100 _igvn.MakeConX(distance) ); 2101 transform_later(prefetch_adr); 2102 prefetch = new PrefetchAllocationNode( i_o, prefetch_adr ); 2103 transform_later(prefetch); 2104 distance += step_size; 2105 i_o = prefetch; 2106 } 2107 pf_phi_abio->set_req( pf_path, i_o ); 2108 2109 pf_region->init_req( fall_in_path, need_pf_false ); 2110 pf_region->init_req( pf_path, need_pf_true ); 2111 2112 pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem ); 2113 pf_phi_rawmem->init_req( pf_path, store_new_wmt ); 2114 2115 transform_later(pf_region); 2116 transform_later(pf_phi_rawmem); 2117 transform_later(pf_phi_abio); 2118 2119 needgc_false = pf_region; 2120 contended_phi_rawmem = pf_phi_rawmem; 2121 i_o = pf_phi_abio; 2122 } else if( UseTLAB && AllocatePrefetchStyle == 3 ) { 2123 // Insert a prefetch instruction for each allocation. 2124 // This code is used to generate 1 prefetch instruction per cache line. 2125 2126 // Generate several prefetch instructions. 2127 uint step_size = AllocatePrefetchStepSize; 2128 uint distance = AllocatePrefetchDistance; 2129 2130 // Next cache address. 2131 Node *cache_adr = new AddPNode(old_eden_top, old_eden_top, 2132 _igvn.MakeConX(step_size + distance)); 2133 transform_later(cache_adr); 2134 cache_adr = new CastP2XNode(needgc_false, cache_adr); 2135 transform_later(cache_adr); 2136 // Address is aligned to execute prefetch to the beginning of cache line size 2137 // (it is important when BIS instruction is used on SPARC as prefetch). 2138 Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1)); 2139 cache_adr = new AndXNode(cache_adr, mask); 2140 transform_later(cache_adr); 2141 cache_adr = new CastX2PNode(cache_adr); 2142 transform_later(cache_adr); 2143 2144 // Prefetch 2145 Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr ); 2146 prefetch->set_req(0, needgc_false); 2147 transform_later(prefetch); 2148 contended_phi_rawmem = prefetch; 2149 Node *prefetch_adr; 2150 distance = step_size; 2151 for ( intx i = 1; i < lines; i++ ) { 2152 prefetch_adr = new AddPNode( cache_adr, cache_adr, 2153 _igvn.MakeConX(distance) ); 2154 transform_later(prefetch_adr); 2155 prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr ); 2156 transform_later(prefetch); 2157 distance += step_size; 2158 contended_phi_rawmem = prefetch; 2159 } 2160 } else if( AllocatePrefetchStyle > 0 ) { 2161 // Insert a prefetch for each allocation only on the fast-path 2162 Node *prefetch_adr; 2163 Node *prefetch; 2164 // Generate several prefetch instructions. 2165 uint step_size = AllocatePrefetchStepSize; 2166 uint distance = AllocatePrefetchDistance; 2167 for ( intx i = 0; i < lines; i++ ) { 2168 prefetch_adr = new AddPNode( old_eden_top, new_eden_top, 2169 _igvn.MakeConX(distance) ); 2170 transform_later(prefetch_adr); 2171 prefetch = new PrefetchAllocationNode( i_o, prefetch_adr ); 2172 // Do not let it float too high, since if eden_top == eden_end, 2173 // both might be null. 2174 if( i == 0 ) { // Set control for first prefetch, next follows it 2175 prefetch->init_req(0, needgc_false); 2176 } 2177 transform_later(prefetch); 2178 distance += step_size; 2179 i_o = prefetch; 2180 } 2181 } 2182 return i_o; 2183 } 2184 2185 2186 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) { 2187 expand_allocate_common(alloc, nullptr, nullptr, 2188 OptoRuntime::new_instance_Type(), 2189 OptoRuntime::new_instance_Java(), nullptr); 2190 } 2191 2192 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) { 2193 Node* length = alloc->in(AllocateNode::ALength); 2194 Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest); 2195 InitializeNode* init = alloc->initialization(); 2196 Node* klass_node = alloc->in(AllocateNode::KlassNode); 2197 Node* init_value = alloc->in(AllocateNode::InitValue); 2198 const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr(); 2199 // TODO 8366668 Compute the VM type, is this even needed now that we set it earlier? Should we assert instead? 2200 if (ary_klass_t && ary_klass_t->klass_is_exact() && ary_klass_t->exact_klass()->is_obj_array_klass()) { 2201 ary_klass_t = ary_klass_t->get_vm_type(); 2202 klass_node = makecon(ary_klass_t); 2203 _igvn.replace_input_of(alloc, AllocateNode::KlassNode, klass_node); 2204 } 2205 const TypeFunc* slow_call_type; 2206 address slow_call_address; // Address of slow call 2207 if (init != nullptr && init->is_complete_with_arraycopy() && 2208 ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) { 2209 // Don't zero type array during slow allocation in VM since 2210 // it will be initialized later by arraycopy in compiled code. 2211 slow_call_address = OptoRuntime::new_array_nozero_Java(); 2212 slow_call_type = OptoRuntime::new_array_nozero_Type(); 2213 } else { 2214 slow_call_address = OptoRuntime::new_array_Java(); 2215 slow_call_type = OptoRuntime::new_array_Type(); 2216 2217 if (init_value == nullptr) { 2218 init_value = _igvn.zerocon(T_OBJECT); 2219 } else if (UseCompressedOops) { 2220 init_value = transform_later(new DecodeNNode(init_value, init_value->bottom_type()->make_ptr())); 2221 } 2222 } 2223 expand_allocate_common(alloc, length, init_value, 2224 slow_call_type, 2225 slow_call_address, valid_length_test); 2226 } 2227 2228 //-------------------mark_eliminated_box---------------------------------- 2229 // 2230 // During EA obj may point to several objects but after few ideal graph 2231 // transformations (CCP) it may point to only one non escaping object 2232 // (but still using phi), corresponding locks and unlocks will be marked 2233 // for elimination. Later obj could be replaced with a new node (new phi) 2234 // and which does not have escape information. And later after some graph 2235 // reshape other locks and unlocks (which were not marked for elimination 2236 // before) are connected to this new obj (phi) but they still will not be 2237 // marked for elimination since new obj has no escape information. 2238 // Mark all associated (same box and obj) lock and unlock nodes for 2239 // elimination if some of them marked already. 2240 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) { 2241 BoxLockNode* oldbox = box->as_BoxLock(); 2242 if (oldbox->is_eliminated()) { 2243 return; // This BoxLock node was processed already. 2244 } 2245 assert(!oldbox->is_unbalanced(), "this should not be called for unbalanced region"); 2246 // New implementation (EliminateNestedLocks) has separate BoxLock 2247 // node for each locked region so mark all associated locks/unlocks as 2248 // eliminated even if different objects are referenced in one locked region 2249 // (for example, OSR compilation of nested loop inside locked scope). 2250 if (EliminateNestedLocks || 2251 oldbox->as_BoxLock()->is_simple_lock_region(nullptr, obj, nullptr)) { 2252 // Box is used only in one lock region. Mark this box as eliminated. 2253 oldbox->set_local(); // This verifies correct state of BoxLock 2254 _igvn.hash_delete(oldbox); 2255 oldbox->set_eliminated(); // This changes box's hash value 2256 _igvn.hash_insert(oldbox); 2257 2258 for (uint i = 0; i < oldbox->outcnt(); i++) { 2259 Node* u = oldbox->raw_out(i); 2260 if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) { 2261 AbstractLockNode* alock = u->as_AbstractLock(); 2262 // Check lock's box since box could be referenced by Lock's debug info. 2263 if (alock->box_node() == oldbox) { 2264 // Mark eliminated all related locks and unlocks. 2265 #ifdef ASSERT 2266 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4"); 2267 #endif 2268 alock->set_non_esc_obj(); 2269 } 2270 } 2271 } 2272 return; 2273 } 2274 2275 // Create new "eliminated" BoxLock node and use it in monitor debug info 2276 // instead of oldbox for the same object. 2277 BoxLockNode* newbox = oldbox->clone()->as_BoxLock(); 2278 2279 // Note: BoxLock node is marked eliminated only here and it is used 2280 // to indicate that all associated lock and unlock nodes are marked 2281 // for elimination. 2282 newbox->set_local(); // This verifies correct state of BoxLock 2283 newbox->set_eliminated(); 2284 transform_later(newbox); 2285 2286 // Replace old box node with new box for all users of the same object. 2287 for (uint i = 0; i < oldbox->outcnt();) { 2288 bool next_edge = true; 2289 2290 Node* u = oldbox->raw_out(i); 2291 if (u->is_AbstractLock()) { 2292 AbstractLockNode* alock = u->as_AbstractLock(); 2293 if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) { 2294 // Replace Box and mark eliminated all related locks and unlocks. 2295 #ifdef ASSERT 2296 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5"); 2297 #endif 2298 alock->set_non_esc_obj(); 2299 _igvn.rehash_node_delayed(alock); 2300 alock->set_box_node(newbox); 2301 next_edge = false; 2302 } 2303 } 2304 if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) { 2305 FastLockNode* flock = u->as_FastLock(); 2306 assert(flock->box_node() == oldbox, "sanity"); 2307 _igvn.rehash_node_delayed(flock); 2308 flock->set_box_node(newbox); 2309 next_edge = false; 2310 } 2311 2312 // Replace old box in monitor debug info. 2313 if (u->is_SafePoint() && u->as_SafePoint()->jvms()) { 2314 SafePointNode* sfn = u->as_SafePoint(); 2315 JVMState* youngest_jvms = sfn->jvms(); 2316 int max_depth = youngest_jvms->depth(); 2317 for (int depth = 1; depth <= max_depth; depth++) { 2318 JVMState* jvms = youngest_jvms->of_depth(depth); 2319 int num_mon = jvms->nof_monitors(); 2320 // Loop over monitors 2321 for (int idx = 0; idx < num_mon; idx++) { 2322 Node* obj_node = sfn->monitor_obj(jvms, idx); 2323 Node* box_node = sfn->monitor_box(jvms, idx); 2324 if (box_node == oldbox && obj_node->eqv_uncast(obj)) { 2325 int j = jvms->monitor_box_offset(idx); 2326 _igvn.replace_input_of(u, j, newbox); 2327 next_edge = false; 2328 } 2329 } 2330 } 2331 } 2332 if (next_edge) i++; 2333 } 2334 } 2335 2336 //-----------------------mark_eliminated_locking_nodes----------------------- 2337 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) { 2338 if (!alock->is_balanced()) { 2339 return; // Can't do any more elimination for this locking region 2340 } 2341 if (EliminateNestedLocks) { 2342 if (alock->is_nested()) { 2343 assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity"); 2344 return; 2345 } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened 2346 // Only Lock node has JVMState needed here. 2347 // Not that preceding claim is documented anywhere else. 2348 if (alock->jvms() != nullptr) { 2349 if (alock->as_Lock()->is_nested_lock_region()) { 2350 // Mark eliminated related nested locks and unlocks. 2351 Node* obj = alock->obj_node(); 2352 BoxLockNode* box_node = alock->box_node()->as_BoxLock(); 2353 assert(!box_node->is_eliminated(), "should not be marked yet"); 2354 // Note: BoxLock node is marked eliminated only here 2355 // and it is used to indicate that all associated lock 2356 // and unlock nodes are marked for elimination. 2357 box_node->set_eliminated(); // Box's hash is always NO_HASH here 2358 for (uint i = 0; i < box_node->outcnt(); i++) { 2359 Node* u = box_node->raw_out(i); 2360 if (u->is_AbstractLock()) { 2361 alock = u->as_AbstractLock(); 2362 if (alock->box_node() == box_node) { 2363 // Verify that this Box is referenced only by related locks. 2364 assert(alock->obj_node()->eqv_uncast(obj), ""); 2365 // Mark all related locks and unlocks. 2366 #ifdef ASSERT 2367 alock->log_lock_optimization(C, "eliminate_lock_set_nested"); 2368 #endif 2369 alock->set_nested(); 2370 } 2371 } 2372 } 2373 } else { 2374 #ifdef ASSERT 2375 alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region"); 2376 if (C->log() != nullptr) 2377 alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output 2378 #endif 2379 } 2380 } 2381 return; 2382 } 2383 // Process locks for non escaping object 2384 assert(alock->is_non_esc_obj(), ""); 2385 } // EliminateNestedLocks 2386 2387 if (alock->is_non_esc_obj()) { // Lock is used for non escaping object 2388 // Look for all locks of this object and mark them and 2389 // corresponding BoxLock nodes as eliminated. 2390 Node* obj = alock->obj_node(); 2391 for (uint j = 0; j < obj->outcnt(); j++) { 2392 Node* o = obj->raw_out(j); 2393 if (o->is_AbstractLock() && 2394 o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) { 2395 alock = o->as_AbstractLock(); 2396 Node* box = alock->box_node(); 2397 // Replace old box node with new eliminated box for all users 2398 // of the same object and mark related locks as eliminated. 2399 mark_eliminated_box(box, obj); 2400 } 2401 } 2402 } 2403 } 2404 2405 // we have determined that this lock/unlock can be eliminated, we simply 2406 // eliminate the node without expanding it. 2407 // 2408 // Note: The membar's associated with the lock/unlock are currently not 2409 // eliminated. This should be investigated as a future enhancement. 2410 // 2411 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) { 2412 2413 if (!alock->is_eliminated()) { 2414 return false; 2415 } 2416 #ifdef ASSERT 2417 if (!alock->is_coarsened()) { 2418 // Check that new "eliminated" BoxLock node is created. 2419 BoxLockNode* oldbox = alock->box_node()->as_BoxLock(); 2420 assert(oldbox->is_eliminated(), "should be done already"); 2421 } 2422 #endif 2423 2424 alock->log_lock_optimization(C, "eliminate_lock"); 2425 2426 #ifndef PRODUCT 2427 if (PrintEliminateLocks) { 2428 tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string()); 2429 } 2430 #endif 2431 2432 Node* mem = alock->in(TypeFunc::Memory); 2433 Node* ctrl = alock->in(TypeFunc::Control); 2434 guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null"); 2435 2436 _callprojs = alock->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/); 2437 // There are 2 projections from the lock. The lock node will 2438 // be deleted when its last use is subsumed below. 2439 assert(alock->outcnt() == 2 && 2440 _callprojs->fallthrough_proj != nullptr && 2441 _callprojs->fallthrough_memproj != nullptr, 2442 "Unexpected projections from Lock/Unlock"); 2443 2444 Node* fallthroughproj = _callprojs->fallthrough_proj; 2445 Node* memproj_fallthrough = _callprojs->fallthrough_memproj; 2446 2447 // The memory projection from a lock/unlock is RawMem 2448 // The input to a Lock is merged memory, so extract its RawMem input 2449 // (unless the MergeMem has been optimized away.) 2450 if (alock->is_Lock()) { 2451 // Search for MemBarAcquireLock node and delete it also. 2452 MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar(); 2453 assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, ""); 2454 Node* ctrlproj = membar->proj_out(TypeFunc::Control); 2455 Node* memproj = membar->proj_out(TypeFunc::Memory); 2456 _igvn.replace_node(ctrlproj, fallthroughproj); 2457 _igvn.replace_node(memproj, memproj_fallthrough); 2458 2459 // Delete FastLock node also if this Lock node is unique user 2460 // (a loop peeling may clone a Lock node). 2461 Node* flock = alock->as_Lock()->fastlock_node(); 2462 if (flock->outcnt() == 1) { 2463 assert(flock->unique_out() == alock, "sanity"); 2464 _igvn.replace_node(flock, top()); 2465 } 2466 } 2467 2468 // Search for MemBarReleaseLock node and delete it also. 2469 if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) { 2470 MemBarNode* membar = ctrl->in(0)->as_MemBar(); 2471 assert(membar->Opcode() == Op_MemBarReleaseLock && 2472 mem->is_Proj() && membar == mem->in(0), ""); 2473 _igvn.replace_node(fallthroughproj, ctrl); 2474 _igvn.replace_node(memproj_fallthrough, mem); 2475 fallthroughproj = ctrl; 2476 memproj_fallthrough = mem; 2477 ctrl = membar->in(TypeFunc::Control); 2478 mem = membar->in(TypeFunc::Memory); 2479 } 2480 2481 _igvn.replace_node(fallthroughproj, ctrl); 2482 _igvn.replace_node(memproj_fallthrough, mem); 2483 return true; 2484 } 2485 2486 2487 //------------------------------expand_lock_node---------------------- 2488 void PhaseMacroExpand::expand_lock_node(LockNode *lock) { 2489 2490 Node* ctrl = lock->in(TypeFunc::Control); 2491 Node* mem = lock->in(TypeFunc::Memory); 2492 Node* obj = lock->obj_node(); 2493 Node* box = lock->box_node(); 2494 Node* flock = lock->fastlock_node(); 2495 2496 assert(!box->as_BoxLock()->is_eliminated(), "sanity"); 2497 2498 // Make the merge point 2499 Node *region; 2500 Node *mem_phi; 2501 Node *slow_path; 2502 2503 region = new RegionNode(3); 2504 // create a Phi for the memory state 2505 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM); 2506 2507 // Optimize test; set region slot 2 2508 slow_path = opt_bits_test(ctrl, region, 2, flock); 2509 mem_phi->init_req(2, mem); 2510 2511 // Make slow path call 2512 CallNode* call = make_slow_call(lock, OptoRuntime::complete_monitor_enter_Type(), 2513 OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path, 2514 obj, box, nullptr); 2515 2516 _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/); 2517 2518 // Slow path can only throw asynchronous exceptions, which are always 2519 // de-opted. So the compiler thinks the slow-call can never throw an 2520 // exception. If it DOES throw an exception we would need the debug 2521 // info removed first (since if it throws there is no monitor). 2522 assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr && 2523 _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock"); 2524 2525 // Capture slow path 2526 // disconnect fall-through projection from call and create a new one 2527 // hook up users of fall-through projection to region 2528 Node *slow_ctrl = _callprojs->fallthrough_proj->clone(); 2529 transform_later(slow_ctrl); 2530 _igvn.hash_delete(_callprojs->fallthrough_proj); 2531 _callprojs->fallthrough_proj->disconnect_inputs(C); 2532 region->init_req(1, slow_ctrl); 2533 // region inputs are now complete 2534 transform_later(region); 2535 _igvn.replace_node(_callprojs->fallthrough_proj, region); 2536 2537 Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory)); 2538 2539 mem_phi->init_req(1, memproj); 2540 2541 transform_later(mem_phi); 2542 2543 _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi); 2544 } 2545 2546 //------------------------------expand_unlock_node---------------------- 2547 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) { 2548 2549 Node* ctrl = unlock->in(TypeFunc::Control); 2550 Node* mem = unlock->in(TypeFunc::Memory); 2551 Node* obj = unlock->obj_node(); 2552 Node* box = unlock->box_node(); 2553 2554 assert(!box->as_BoxLock()->is_eliminated(), "sanity"); 2555 2556 // No need for a null check on unlock 2557 2558 // Make the merge point 2559 Node *region; 2560 Node *mem_phi; 2561 2562 region = new RegionNode(3); 2563 // create a Phi for the memory state 2564 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM); 2565 2566 FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box ); 2567 funlock = transform_later( funlock )->as_FastUnlock(); 2568 // Optimize test; set region slot 2 2569 Node *slow_path = opt_bits_test(ctrl, region, 2, funlock); 2570 Node *thread = transform_later(new ThreadLocalNode()); 2571 2572 CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(), 2573 CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C), 2574 "complete_monitor_unlocking_C", slow_path, obj, box, thread); 2575 2576 _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/); 2577 assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr && 2578 _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock"); 2579 2580 // No exceptions for unlocking 2581 // Capture slow path 2582 // disconnect fall-through projection from call and create a new one 2583 // hook up users of fall-through projection to region 2584 Node *slow_ctrl = _callprojs->fallthrough_proj->clone(); 2585 transform_later(slow_ctrl); 2586 _igvn.hash_delete(_callprojs->fallthrough_proj); 2587 _callprojs->fallthrough_proj->disconnect_inputs(C); 2588 region->init_req(1, slow_ctrl); 2589 // region inputs are now complete 2590 transform_later(region); 2591 _igvn.replace_node(_callprojs->fallthrough_proj, region); 2592 2593 Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) ); 2594 mem_phi->init_req(1, memproj ); 2595 mem_phi->init_req(2, mem); 2596 transform_later(mem_phi); 2597 2598 _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi); 2599 } 2600 2601 // An inline type might be returned from the call but we don't know its 2602 // type. Either we get a buffered inline type (and nothing needs to be done) 2603 // or one of the values being returned is the klass of the inline type 2604 // and we need to allocate an inline type instance of that type and 2605 // initialize it with other values being returned. In that case, we 2606 // first try a fast path allocation and initialize the value with the 2607 // inline klass's pack handler or we fall back to a runtime call. 2608 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) { 2609 assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call"); 2610 Node* ret = call->proj_out_or_null(TypeFunc::Parms); 2611 if (ret == nullptr) { 2612 return; 2613 } 2614 const TypeFunc* tf = call->_tf; 2615 const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc(); 2616 const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain); 2617 call->_tf = new_tf; 2618 // Make sure the change of type is applied before projections are processed by igvn 2619 _igvn.set_type(call, call->Value(&_igvn)); 2620 _igvn.set_type(ret, ret->Value(&_igvn)); 2621 2622 // Before any new projection is added: 2623 CallProjections* projs = call->extract_projections(true, true); 2624 2625 // Create temporary hook nodes that will be replaced below. 2626 // Add an input to prevent hook nodes from being dead. 2627 Node* ctl = new Node(call); 2628 Node* mem = new Node(ctl); 2629 Node* io = new Node(ctl); 2630 Node* ex_ctl = new Node(ctl); 2631 Node* ex_mem = new Node(ctl); 2632 Node* ex_io = new Node(ctl); 2633 Node* res = new Node(ctl); 2634 2635 // Allocate a new buffered inline type only if a new one is not returned 2636 Node* cast = transform_later(new CastP2XNode(ctl, res)); 2637 Node* mask = MakeConX(0x1); 2638 Node* masked = transform_later(new AndXNode(cast, mask)); 2639 Node* cmp = transform_later(new CmpXNode(masked, mask)); 2640 Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq)); 2641 IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN); 2642 transform_later(allocation_iff); 2643 Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff)); 2644 Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff)); 2645 Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM)); 2646 2647 // Try to allocate a new buffered inline instance either from TLAB or eden space 2648 Node* needgc_ctrl = nullptr; // needgc means slowcase, i.e. allocation failed 2649 CallLeafNoFPNode* handler_call; 2650 const bool alloc_in_place = UseTLAB; 2651 if (alloc_in_place) { 2652 Node* fast_oop_ctrl = nullptr; 2653 Node* fast_oop_rawmem = nullptr; 2654 Node* mask2 = MakeConX(-2); 2655 Node* masked2 = transform_later(new AndXNode(cast, mask2)); 2656 Node* rawklassptr = transform_later(new CastX2PNode(masked2)); 2657 Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeInstKlassPtr::OBJECT_OR_NULL)); 2658 Node* layout_val = make_load(nullptr, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT); 2659 Node* size_in_bytes = ConvI2X(layout_val); 2660 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 2661 Node* fast_oop = bs->obj_allocate(this, mem, allocation_ctl, size_in_bytes, io, needgc_ctrl, 2662 fast_oop_ctrl, fast_oop_rawmem, 2663 AllocateInstancePrefetchLines); 2664 // Allocation succeed, initialize buffered inline instance header firstly, 2665 // and then initialize its fields with an inline class specific handler 2666 Node* mark_word_node; 2667 if (UseCompactObjectHeaders) { 2668 // COH: We need to load the prototype from the klass at runtime since it encodes the klass pointer already. 2669 mark_word_node = make_load(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeRawPtr::BOTTOM, T_ADDRESS); 2670 } else { 2671 // Otherwise, use the static prototype. 2672 mark_word_node = makecon(TypeRawPtr::make((address)markWord::inline_type_prototype().value())); 2673 } 2674 2675 fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::mark_offset_in_bytes(), mark_word_node, T_ADDRESS); 2676 if (!UseCompactObjectHeaders) { 2677 // COH: Everything is encoded in the mark word, so nothing left to do. 2678 fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA); 2679 if (UseCompressedClassPointers) { 2680 fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT); 2681 } 2682 } 2683 Node* fixed_block = make_load(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()), TypeRawPtr::BOTTOM, T_ADDRESS); 2684 Node* pack_handler = make_load(fast_oop_ctrl, fast_oop_rawmem, fixed_block, in_bytes(InlineKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS); 2685 handler_call = new CallLeafNoFPNode(OptoRuntime::pack_inline_type_Type(), 2686 nullptr, 2687 "pack handler", 2688 TypeRawPtr::BOTTOM); 2689 handler_call->init_req(TypeFunc::Control, fast_oop_ctrl); 2690 handler_call->init_req(TypeFunc::Memory, fast_oop_rawmem); 2691 handler_call->init_req(TypeFunc::I_O, top()); 2692 handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr)); 2693 handler_call->init_req(TypeFunc::ReturnAdr, top()); 2694 handler_call->init_req(TypeFunc::Parms, pack_handler); 2695 handler_call->init_req(TypeFunc::Parms+1, fast_oop); 2696 } else { 2697 needgc_ctrl = allocation_ctl; 2698 } 2699 2700 // Allocation failed, fall back to a runtime call 2701 CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_inline_type_fields_Type(), 2702 StubRoutines::store_inline_type_fields_to_buf(), 2703 "store_inline_type_fields", 2704 TypePtr::BOTTOM); 2705 slow_call->init_req(TypeFunc::Control, needgc_ctrl); 2706 slow_call->init_req(TypeFunc::Memory, mem); 2707 slow_call->init_req(TypeFunc::I_O, io); 2708 slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr)); 2709 slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr)); 2710 slow_call->init_req(TypeFunc::Parms, res); 2711 2712 Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control)); 2713 Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory)); 2714 Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O)); 2715 Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms)); 2716 Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2)); 2717 Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci)); 2718 Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index, CatchProjNode::no_handler_bci)); 2719 2720 Node* ex_r = new RegionNode(3); 2721 Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM); 2722 Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO); 2723 ex_r->init_req(1, slow_excp); 2724 ex_mem_phi->init_req(1, slow_mem); 2725 ex_io_phi->init_req(1, slow_io); 2726 ex_r->init_req(2, ex_ctl); 2727 ex_mem_phi->init_req(2, ex_mem); 2728 ex_io_phi->init_req(2, ex_io); 2729 transform_later(ex_r); 2730 transform_later(ex_mem_phi); 2731 transform_later(ex_io_phi); 2732 2733 // We don't know how many values are returned. This assumes the 2734 // worst case, that all available registers are used. 2735 for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) { 2736 if (domain->field_at(i) == Type::HALF) { 2737 slow_call->init_req(i, top()); 2738 if (alloc_in_place) { 2739 handler_call->init_req(i+1, top()); 2740 } 2741 continue; 2742 } 2743 Node* proj = transform_later(new ProjNode(call, i)); 2744 slow_call->init_req(i, proj); 2745 if (alloc_in_place) { 2746 handler_call->init_req(i+1, proj); 2747 } 2748 } 2749 // We can safepoint at that new call 2750 slow_call->copy_call_debug_info(&_igvn, call); 2751 transform_later(slow_call); 2752 if (alloc_in_place) { 2753 transform_later(handler_call); 2754 } 2755 2756 Node* fast_ctl = nullptr; 2757 Node* fast_res = nullptr; 2758 MergeMemNode* fast_mem = nullptr; 2759 if (alloc_in_place) { 2760 fast_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control)); 2761 Node* rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory)); 2762 fast_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms)); 2763 fast_mem = MergeMemNode::make(mem); 2764 fast_mem->set_memory_at(Compile::AliasIdxRaw, rawmem); 2765 transform_later(fast_mem); 2766 } 2767 2768 Node* r = new RegionNode(alloc_in_place ? 4 : 3); 2769 Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM); 2770 Node* io_phi = new PhiNode(r, Type::ABIO); 2771 Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM); 2772 r->init_req(1, no_allocation_ctl); 2773 mem_phi->init_req(1, mem); 2774 io_phi->init_req(1, io); 2775 res_phi->init_req(1, no_allocation_res); 2776 r->init_req(2, slow_norm); 2777 mem_phi->init_req(2, slow_mem); 2778 io_phi->init_req(2, slow_io); 2779 res_phi->init_req(2, slow_res); 2780 if (alloc_in_place) { 2781 r->init_req(3, fast_ctl); 2782 mem_phi->init_req(3, fast_mem); 2783 io_phi->init_req(3, io); 2784 res_phi->init_req(3, fast_res); 2785 } 2786 transform_later(r); 2787 transform_later(mem_phi); 2788 transform_later(io_phi); 2789 transform_later(res_phi); 2790 2791 // Do not let stores that initialize this buffer be reordered with a subsequent 2792 // store that would make this buffer accessible by other threads. 2793 MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot); 2794 transform_later(mb); 2795 mb->init_req(TypeFunc::Memory, mem_phi); 2796 mb->init_req(TypeFunc::Control, r); 2797 r = new ProjNode(mb, TypeFunc::Control); 2798 transform_later(r); 2799 mem_phi = new ProjNode(mb, TypeFunc::Memory); 2800 transform_later(mem_phi); 2801 2802 assert(projs->nb_resproj == 1, "unexpected number of results"); 2803 _igvn.replace_in_uses(projs->fallthrough_catchproj, r); 2804 _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi); 2805 _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi); 2806 _igvn.replace_in_uses(projs->resproj[0], res_phi); 2807 _igvn.replace_in_uses(projs->catchall_catchproj, ex_r); 2808 _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi); 2809 _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi); 2810 // The CatchNode should not use the ex_io_phi. Re-connect it to the catchall_ioproj. 2811 Node* cn = projs->fallthrough_catchproj->in(0); 2812 _igvn.replace_input_of(cn, 1, projs->catchall_ioproj); 2813 2814 _igvn.replace_node(ctl, projs->fallthrough_catchproj); 2815 _igvn.replace_node(mem, projs->fallthrough_memproj); 2816 _igvn.replace_node(io, projs->fallthrough_ioproj); 2817 _igvn.replace_node(res, projs->resproj[0]); 2818 _igvn.replace_node(ex_ctl, projs->catchall_catchproj); 2819 _igvn.replace_node(ex_mem, projs->catchall_memproj); 2820 _igvn.replace_node(ex_io, projs->catchall_ioproj); 2821 } 2822 2823 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) { 2824 assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned"); 2825 Node* bol = check->unique_out(); 2826 Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass); 2827 Node* superklass = check->in(SubTypeCheckNode::SuperKlass); 2828 assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node"); 2829 2830 for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) { 2831 Node* iff = bol->last_out(i); 2832 assert(iff->is_If(), "where's the if?"); 2833 2834 if (iff->in(0)->is_top()) { 2835 _igvn.replace_input_of(iff, 1, C->top()); 2836 continue; 2837 } 2838 2839 Node* iftrue = iff->as_If()->proj_out(1); 2840 Node* iffalse = iff->as_If()->proj_out(0); 2841 Node* ctrl = iff->in(0); 2842 2843 Node* subklass = nullptr; 2844 if (_igvn.type(obj_or_subklass)->isa_klassptr()) { 2845 subklass = obj_or_subklass; 2846 } else { 2847 Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes()); 2848 subklass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT)); 2849 } 2850 2851 Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci()); 2852 2853 _igvn.replace_input_of(iff, 0, C->top()); 2854 _igvn.replace_node(iftrue, not_subtype_ctrl); 2855 _igvn.replace_node(iffalse, ctrl); 2856 } 2857 _igvn.replace_node(check, C->top()); 2858 } 2859 2860 // FlatArrayCheckNode (array1 array2 ...) is expanded into: 2861 // 2862 // long mark = array1.mark | array2.mark | ...; 2863 // long locked_bit = markWord::unlocked_value & array1.mark & array2.mark & ...; 2864 // if (locked_bit == 0) { 2865 // // One array is locked, load prototype header from the klass 2866 // mark = array1.klass.proto | array2.klass.proto | ... 2867 // } 2868 // if ((mark & markWord::flat_array_bit_in_place) == 0) { 2869 // ... 2870 // } 2871 void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) { 2872 bool array_inputs = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->isa_oopptr() != nullptr; 2873 if (array_inputs) { 2874 Node* mark = MakeConX(0); 2875 Node* locked_bit = MakeConX(markWord::unlocked_value); 2876 Node* mem = check->in(FlatArrayCheckNode::Memory); 2877 for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) { 2878 Node* ary = check->in(i); 2879 const TypeOopPtr* t = _igvn.type(ary)->isa_oopptr(); 2880 assert(t != nullptr, "Mixing array and klass inputs"); 2881 assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out"); 2882 Node* mark_adr = basic_plus_adr(ary, oopDesc::mark_offset_in_bytes()); 2883 Node* mark_load = _igvn.transform(LoadNode::make(_igvn, nullptr, mem, mark_adr, mark_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered)); 2884 mark = _igvn.transform(new OrXNode(mark, mark_load)); 2885 locked_bit = _igvn.transform(new AndXNode(locked_bit, mark_load)); 2886 } 2887 assert(!mark->is_Con(), "Should have been optimized out"); 2888 Node* cmp = _igvn.transform(new CmpXNode(locked_bit, MakeConX(0))); 2889 Node* is_unlocked = _igvn.transform(new BoolNode(cmp, BoolTest::ne)); 2890 2891 // BoolNode might be shared, replace each if user 2892 Node* old_bol = check->unique_out(); 2893 assert(old_bol->is_Bool() && old_bol->as_Bool()->_test._test == BoolTest::ne, "unexpected condition"); 2894 for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) { 2895 IfNode* old_iff = old_bol->last_out(i)->as_If(); 2896 Node* ctrl = old_iff->in(0); 2897 RegionNode* region = new RegionNode(3); 2898 Node* mark_phi = new PhiNode(region, TypeX_X); 2899 2900 // Check if array is unlocked 2901 IfNode* iff = _igvn.transform(new IfNode(ctrl, is_unlocked, PROB_MAX, COUNT_UNKNOWN))->as_If(); 2902 2903 // Unlocked: Use bits from mark word 2904 region->init_req(1, _igvn.transform(new IfTrueNode(iff))); 2905 mark_phi->init_req(1, mark); 2906 2907 // Locked: Load prototype header from klass 2908 ctrl = _igvn.transform(new IfFalseNode(iff)); 2909 Node* proto = MakeConX(0); 2910 for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) { 2911 Node* ary = check->in(i); 2912 // Make loads control dependent to make sure they are only executed if array is locked 2913 Node* klass_adr = basic_plus_adr(ary, oopDesc::klass_offset_in_bytes()); 2914 Node* klass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT)); 2915 Node* proto_adr = basic_plus_adr(klass, in_bytes(Klass::prototype_header_offset())); 2916 Node* proto_load = _igvn.transform(LoadNode::make(_igvn, ctrl, C->immutable_memory(), proto_adr, proto_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered)); 2917 proto = _igvn.transform(new OrXNode(proto, proto_load)); 2918 } 2919 region->init_req(2, ctrl); 2920 mark_phi->init_req(2, proto); 2921 2922 // Check if flat array bits are set 2923 Node* mask = MakeConX(markWord::flat_array_bit_in_place); 2924 Node* masked = _igvn.transform(new AndXNode(_igvn.transform(mark_phi), mask)); 2925 cmp = _igvn.transform(new CmpXNode(masked, MakeConX(0))); 2926 Node* is_not_flat = _igvn.transform(new BoolNode(cmp, BoolTest::eq)); 2927 2928 ctrl = _igvn.transform(region); 2929 iff = _igvn.transform(new IfNode(ctrl, is_not_flat, PROB_MAX, COUNT_UNKNOWN))->as_If(); 2930 _igvn.replace_node(old_iff, iff); 2931 } 2932 _igvn.replace_node(check, C->top()); 2933 } else { 2934 // Fall back to layout helper check 2935 Node* lhs = intcon(0); 2936 for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) { 2937 Node* array_or_klass = check->in(i); 2938 Node* klass = nullptr; 2939 const TypePtr* t = _igvn.type(array_or_klass)->is_ptr(); 2940 assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out"); 2941 if (t->isa_oopptr() != nullptr) { 2942 Node* klass_adr = basic_plus_adr(array_or_klass, oopDesc::klass_offset_in_bytes()); 2943 klass = transform_later(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT)); 2944 } else { 2945 assert(t->isa_klassptr(), "Unexpected input type"); 2946 klass = array_or_klass; 2947 } 2948 Node* lh_addr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset())); 2949 Node* lh_val = _igvn.transform(LoadNode::make(_igvn, nullptr, C->immutable_memory(), lh_addr, lh_addr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered)); 2950 lhs = _igvn.transform(new OrINode(lhs, lh_val)); 2951 } 2952 Node* masked = transform_later(new AndINode(lhs, intcon(Klass::_lh_array_tag_flat_value_bit_inplace))); 2953 Node* cmp = transform_later(new CmpINode(masked, intcon(0))); 2954 Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq)); 2955 Node* m2b = transform_later(new Conv2BNode(masked)); 2956 // The matcher expects the input to If nodes to be produced by a Bool(CmpI..) 2957 // pattern, but the input to other potential users (e.g. Phi) to be some 2958 // other pattern (e.g. a Conv2B node, possibly idealized as a CMoveI). 2959 Node* old_bol = check->unique_out(); 2960 for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) { 2961 Node* user = old_bol->last_out(i); 2962 for (uint j = 0; j < user->req(); j++) { 2963 Node* n = user->in(j); 2964 if (n == old_bol) { 2965 _igvn.replace_input_of(user, j, user->is_If() ? bol : m2b); 2966 } 2967 } 2968 } 2969 _igvn.replace_node(check, C->top()); 2970 } 2971 } 2972 2973 // Perform refining of strip mined loop nodes in the macro nodes list. 2974 void PhaseMacroExpand::refine_strip_mined_loop_macro_nodes() { 2975 for (int i = C->macro_count(); i > 0; i--) { 2976 Node* n = C->macro_node(i - 1); 2977 if (n->is_OuterStripMinedLoop()) { 2978 n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn); 2979 } 2980 } 2981 } 2982 2983 //---------------------------eliminate_macro_nodes---------------------- 2984 // Eliminate scalar replaced allocations and associated locks. 2985 void PhaseMacroExpand::eliminate_macro_nodes(bool eliminate_locks) { 2986 if (C->macro_count() == 0) { 2987 return; 2988 } 2989 2990 if (StressMacroElimination) { 2991 C->shuffle_macro_nodes(); 2992 } 2993 NOT_PRODUCT(int membar_before = count_MemBar(C);) 2994 2995 int iteration = 0; 2996 while (C->macro_count() > 0) { 2997 if (iteration++ > 100) { 2998 assert(false, "Too slow convergence of macro elimination"); 2999 break; 3000 } 3001 3002 // Postpone lock elimination to after EA when most allocations are eliminated 3003 // because they might block lock elimination if their escape state isn't 3004 // determined yet and we only got one chance at eliminating the lock. 3005 if (eliminate_locks) { 3006 // Before elimination may re-mark (change to Nested or NonEscObj) 3007 // all associated (same box and obj) lock and unlock nodes. 3008 int cnt = C->macro_count(); 3009 for (int i=0; i < cnt; i++) { 3010 Node *n = C->macro_node(i); 3011 if (n->is_AbstractLock()) { // Lock and Unlock nodes 3012 mark_eliminated_locking_nodes(n->as_AbstractLock()); 3013 } 3014 } 3015 // Re-marking may break consistency of Coarsened locks. 3016 if (!C->coarsened_locks_consistent()) { 3017 return; // recompile without Coarsened locks if broken 3018 } else { 3019 // After coarsened locks are eliminated locking regions 3020 // become unbalanced. We should not execute any more 3021 // locks elimination optimizations on them. 3022 C->mark_unbalanced_boxes(); 3023 } 3024 } 3025 3026 bool progress = false; 3027 for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once 3028 Node* n = C->macro_node(i - 1); 3029 bool success = false; 3030 DEBUG_ONLY(int old_macro_count = C->macro_count();) 3031 switch (n->class_id()) { 3032 case Node::Class_Allocate: 3033 case Node::Class_AllocateArray: 3034 success = eliminate_allocate_node(n->as_Allocate()); 3035 #ifndef PRODUCT 3036 if (success && PrintOptoStatistics) { 3037 Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter); 3038 } 3039 #endif 3040 break; 3041 case Node::Class_CallStaticJava: { 3042 CallStaticJavaNode* call = n->as_CallStaticJava(); 3043 if (!call->method()->is_method_handle_intrinsic()) { 3044 success = eliminate_boxing_node(n->as_CallStaticJava()); 3045 } 3046 break; 3047 } 3048 case Node::Class_Lock: 3049 case Node::Class_Unlock: 3050 if (eliminate_locks) { 3051 success = eliminate_locking_node(n->as_AbstractLock()); 3052 #ifndef PRODUCT 3053 if (success && PrintOptoStatistics) { 3054 Atomic::inc(&PhaseMacroExpand::_monitor_objects_removed_counter); 3055 } 3056 #endif 3057 } 3058 break; 3059 case Node::Class_ArrayCopy: 3060 break; 3061 case Node::Class_OuterStripMinedLoop: 3062 break; 3063 case Node::Class_SubTypeCheck: 3064 break; 3065 case Node::Class_Opaque1: 3066 break; 3067 case Node::Class_FlatArrayCheck: 3068 break; 3069 default: 3070 assert(n->Opcode() == Op_LoopLimit || 3071 n->Opcode() == Op_ModD || 3072 n->Opcode() == Op_ModF || 3073 n->is_OpaqueNotNull() || 3074 n->is_OpaqueInitializedAssertionPredicate() || 3075 n->Opcode() == Op_MaxL || 3076 n->Opcode() == Op_MinL || 3077 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n), 3078 "unknown node type in macro list"); 3079 } 3080 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count"); 3081 progress = progress || success; 3082 if (success) { 3083 C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n); 3084 } 3085 } 3086 3087 // Ensure the graph after PhaseMacroExpand::eliminate_macro_nodes is canonical (no igvn 3088 // transformation is pending). If an allocation is used only in safepoints, elimination of 3089 // other macro nodes can remove all these safepoints, allowing the allocation to be removed. 3090 // Hence after igvn we retry removing macro nodes if some progress that has been made in this 3091 // iteration. 3092 _igvn.set_delay_transform(false); 3093 _igvn.optimize(); 3094 if (C->failing()) { 3095 return; 3096 } 3097 _igvn.set_delay_transform(true); 3098 3099 if (!progress) { 3100 break; 3101 } 3102 } 3103 #ifndef PRODUCT 3104 if (PrintOptoStatistics) { 3105 int membar_after = count_MemBar(C); 3106 Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after); 3107 } 3108 #endif 3109 } 3110 3111 void PhaseMacroExpand::eliminate_opaque_looplimit_macro_nodes() { 3112 if (C->macro_count() == 0) { 3113 return; 3114 } 3115 refine_strip_mined_loop_macro_nodes(); 3116 // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations. 3117 bool progress = true; 3118 while (progress) { 3119 progress = false; 3120 for (int i = C->macro_count(); i > 0; i--) { 3121 Node* n = C->macro_node(i-1); 3122 bool success = false; 3123 DEBUG_ONLY(int old_macro_count = C->macro_count();) 3124 if (n->Opcode() == Op_LoopLimit) { 3125 // Remove it from macro list and put on IGVN worklist to optimize. 3126 C->remove_macro_node(n); 3127 _igvn._worklist.push(n); 3128 success = true; 3129 } else if (n->Opcode() == Op_CallStaticJava) { 3130 CallStaticJavaNode* call = n->as_CallStaticJava(); 3131 if (!call->method()->is_method_handle_intrinsic()) { 3132 // Remove it from macro list and put on IGVN worklist to optimize. 3133 C->remove_macro_node(n); 3134 _igvn._worklist.push(n); 3135 success = true; 3136 } 3137 } else if (n->is_Opaque1()) { 3138 _igvn.replace_node(n, n->in(1)); 3139 success = true; 3140 } else if (n->is_OpaqueNotNull()) { 3141 // Tests with OpaqueNotNull nodes are implicitly known to be true. Replace the node with true. In debug builds, 3142 // we leave the test in the graph to have an additional sanity check at runtime. If the test fails (i.e. a bug), 3143 // we will execute a Halt node. 3144 #ifdef ASSERT 3145 _igvn.replace_node(n, n->in(1)); 3146 #else 3147 _igvn.replace_node(n, _igvn.intcon(1)); 3148 #endif 3149 success = true; 3150 } else if (n->is_OpaqueInitializedAssertionPredicate()) { 3151 // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product 3152 // builds as they are useless. In debug builds we keep them as additional verification code. Even though 3153 // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to 3154 // enable folding of dead control paths within which cast nodes become top after due to impossible types - 3155 // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now. 3156 #ifdef ASSERT 3157 _igvn.replace_node(n, n->in(1)); 3158 #else 3159 _igvn.replace_node(n, _igvn.intcon(1)); 3160 #endif // ASSERT 3161 } else if (n->Opcode() == Op_OuterStripMinedLoop) { 3162 C->remove_macro_node(n); 3163 success = true; 3164 } else if (n->Opcode() == Op_MaxL) { 3165 // Since MaxL and MinL are not implemented in the backend, we expand them to 3166 // a CMoveL construct now. At least until here, the type could be computed 3167 // precisely. CMoveL is not so smart, but we can give it at least the best 3168 // type we know abouot n now. 3169 Node* repl = MaxNode::signed_max(n->in(1), n->in(2), _igvn.type(n), _igvn); 3170 _igvn.replace_node(n, repl); 3171 success = true; 3172 } else if (n->Opcode() == Op_MinL) { 3173 Node* repl = MaxNode::signed_min(n->in(1), n->in(2), _igvn.type(n), _igvn); 3174 _igvn.replace_node(n, repl); 3175 success = true; 3176 } 3177 assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list"); 3178 progress = progress || success; 3179 if (success) { 3180 C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n); 3181 } 3182 } 3183 } 3184 } 3185 3186 //------------------------------expand_macro_nodes---------------------- 3187 // Returns true if a failure occurred. 3188 bool PhaseMacroExpand::expand_macro_nodes() { 3189 if (StressMacroExpansion) { 3190 C->shuffle_macro_nodes(); 3191 } 3192 3193 // Clean up the graph so we're less likely to hit the maximum node 3194 // limit 3195 _igvn.set_delay_transform(false); 3196 _igvn.optimize(); 3197 if (C->failing()) return true; 3198 _igvn.set_delay_transform(true); 3199 3200 3201 // Because we run IGVN after each expansion, some macro nodes may go 3202 // dead and be removed from the list as we iterate over it. Move 3203 // Allocate nodes (processed in a second pass) at the beginning of 3204 // the list and then iterate from the last element of the list until 3205 // an Allocate node is seen. This is robust to random deletion in 3206 // the list due to nodes going dead. 3207 C->sort_macro_nodes(); 3208 3209 // expand arraycopy "macro" nodes first 3210 // For ReduceBulkZeroing, we must first process all arraycopy nodes 3211 // before the allocate nodes are expanded. 3212 while (C->macro_count() > 0) { 3213 int macro_count = C->macro_count(); 3214 Node * n = C->macro_node(macro_count-1); 3215 assert(n->is_macro(), "only macro nodes expected here"); 3216 if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) { 3217 // node is unreachable, so don't try to expand it 3218 C->remove_macro_node(n); 3219 continue; 3220 } 3221 if (n->is_Allocate()) { 3222 break; 3223 } 3224 // Make sure expansion will not cause node limit to be exceeded. 3225 // Worst case is a macro node gets expanded into about 200 nodes. 3226 // Allow 50% more for optimization. 3227 if (C->check_node_count(300, "out of nodes before macro expansion")) { 3228 return true; 3229 } 3230 3231 DEBUG_ONLY(int old_macro_count = C->macro_count();) 3232 switch (n->class_id()) { 3233 case Node::Class_Lock: 3234 expand_lock_node(n->as_Lock()); 3235 break; 3236 case Node::Class_Unlock: 3237 expand_unlock_node(n->as_Unlock()); 3238 break; 3239 case Node::Class_ArrayCopy: 3240 expand_arraycopy_node(n->as_ArrayCopy()); 3241 break; 3242 case Node::Class_SubTypeCheck: 3243 expand_subtypecheck_node(n->as_SubTypeCheck()); 3244 break; 3245 case Node::Class_CallStaticJava: 3246 expand_mh_intrinsic_return(n->as_CallStaticJava()); 3247 C->remove_macro_node(n); 3248 break; 3249 case Node::Class_FlatArrayCheck: 3250 expand_flatarraycheck_node(n->as_FlatArrayCheck()); 3251 break; 3252 default: 3253 switch (n->Opcode()) { 3254 case Op_ModD: 3255 case Op_ModF: { 3256 CallNode* mod_macro = n->as_Call(); 3257 CallNode* call = new CallLeafPureNode(mod_macro->tf(), mod_macro->entry_point(), 3258 mod_macro->_name, TypeRawPtr::BOTTOM); 3259 call->init_req(TypeFunc::Control, mod_macro->in(TypeFunc::Control)); 3260 call->init_req(TypeFunc::I_O, C->top()); 3261 call->init_req(TypeFunc::Memory, C->top()); 3262 call->init_req(TypeFunc::ReturnAdr, C->top()); 3263 call->init_req(TypeFunc::FramePtr, C->top()); 3264 for (unsigned int i = 0; i < mod_macro->tf()->domain_cc()->cnt() - TypeFunc::Parms; i++) { 3265 call->init_req(TypeFunc::Parms + i, mod_macro->in(TypeFunc::Parms + i)); 3266 } 3267 _igvn.replace_node(mod_macro, call); 3268 transform_later(call); 3269 break; 3270 } 3271 default: 3272 assert(false, "unknown node type in macro list"); 3273 } 3274 } 3275 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list"); 3276 if (C->failing()) return true; 3277 C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n); 3278 3279 // Clean up the graph so we're less likely to hit the maximum node 3280 // limit 3281 _igvn.set_delay_transform(false); 3282 _igvn.optimize(); 3283 if (C->failing()) return true; 3284 _igvn.set_delay_transform(true); 3285 } 3286 3287 // All nodes except Allocate nodes are expanded now. There could be 3288 // new optimization opportunities (such as folding newly created 3289 // load from a just allocated object). Run IGVN. 3290 3291 // expand "macro" nodes 3292 // nodes are removed from the macro list as they are processed 3293 while (C->macro_count() > 0) { 3294 int macro_count = C->macro_count(); 3295 Node * n = C->macro_node(macro_count-1); 3296 assert(n->is_macro(), "only macro nodes expected here"); 3297 if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) { 3298 // node is unreachable, so don't try to expand it 3299 C->remove_macro_node(n); 3300 continue; 3301 } 3302 // Make sure expansion will not cause node limit to be exceeded. 3303 // Worst case is a macro node gets expanded into about 200 nodes. 3304 // Allow 50% more for optimization. 3305 if (C->check_node_count(300, "out of nodes before macro expansion")) { 3306 return true; 3307 } 3308 switch (n->class_id()) { 3309 case Node::Class_Allocate: 3310 expand_allocate(n->as_Allocate()); 3311 break; 3312 case Node::Class_AllocateArray: 3313 expand_allocate_array(n->as_AllocateArray()); 3314 break; 3315 default: 3316 assert(false, "unknown node type in macro list"); 3317 } 3318 assert(C->macro_count() < macro_count, "must have deleted a node from macro list"); 3319 if (C->failing()) return true; 3320 C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n); 3321 3322 // Clean up the graph so we're less likely to hit the maximum node 3323 // limit 3324 _igvn.set_delay_transform(false); 3325 _igvn.optimize(); 3326 if (C->failing()) return true; 3327 _igvn.set_delay_transform(true); 3328 } 3329 3330 _igvn.set_delay_transform(false); 3331 return false; 3332 } 3333 3334 #ifndef PRODUCT 3335 int PhaseMacroExpand::_objs_scalar_replaced_counter = 0; 3336 int PhaseMacroExpand::_monitor_objects_removed_counter = 0; 3337 int PhaseMacroExpand::_GC_barriers_removed_counter = 0; 3338 int PhaseMacroExpand::_memory_barriers_removed_counter = 0; 3339 3340 void PhaseMacroExpand::print_statistics() { 3341 tty->print("Objects scalar replaced = %d, ", Atomic::load(&_objs_scalar_replaced_counter)); 3342 tty->print("Monitor objects removed = %d, ", Atomic::load(&_monitor_objects_removed_counter)); 3343 tty->print("GC barriers removed = %d, ", Atomic::load(&_GC_barriers_removed_counter)); 3344 tty->print_cr("Memory barriers removed = %d", Atomic::load(&_memory_barriers_removed_counter)); 3345 } 3346 3347 int PhaseMacroExpand::count_MemBar(Compile *C) { 3348 if (!PrintOptoStatistics) { 3349 return 0; 3350 } 3351 Unique_Node_List ideal_nodes; 3352 int total = 0; 3353 ideal_nodes.map(C->live_nodes(), nullptr); 3354 ideal_nodes.push(C->root()); 3355 for (uint next = 0; next < ideal_nodes.size(); ++next) { 3356 Node* n = ideal_nodes.at(next); 3357 if (n->is_MemBar()) { 3358 total++; 3359 } 3360 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 3361 Node* m = n->fast_out(i); 3362 ideal_nodes.push(m); 3363 } 3364 } 3365 return total; 3366 } 3367 #endif