6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26 #include "classfile/javaClasses.hpp"
27 #include "gc/shared/barrierSet.hpp"
28 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
29 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
30 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
31 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
32 #include "gc/shenandoah/shenandoahCardTable.hpp"
33 #include "gc/shenandoah/shenandoahForwarding.hpp"
34 #include "gc/shenandoah/shenandoahHeap.hpp"
35 #include "gc/shenandoah/shenandoahRuntime.hpp"
36 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
37 #include "opto/arraycopynode.hpp"
38 #include "opto/escape.hpp"
39 #include "opto/graphKit.hpp"
40 #include "opto/idealKit.hpp"
41 #include "opto/macro.hpp"
42 #include "opto/movenode.hpp"
43 #include "opto/narrowptrnode.hpp"
44 #include "opto/rootnode.hpp"
45 #include "opto/runtime.hpp"
46
47 ShenandoahBarrierSetC2* ShenandoahBarrierSetC2::bsc2() {
48 return reinterpret_cast<ShenandoahBarrierSetC2*>(BarrierSet::barrier_set()->barrier_set_c2());
49 }
50
51 ShenandoahBarrierSetC2State::ShenandoahBarrierSetC2State(Arena* comp_arena)
52 : _load_reference_barriers(new (comp_arena) GrowableArray<ShenandoahLoadReferenceBarrierNode*>(comp_arena, 8, 0, nullptr)) {
53 }
54
55 int ShenandoahBarrierSetC2State::load_reference_barriers_count() const {
56 return _load_reference_barriers->length();
57 }
58
59 ShenandoahLoadReferenceBarrierNode* ShenandoahBarrierSetC2State::load_reference_barrier(int idx) const {
60 return _load_reference_barriers->at(idx);
61 }
62
63 void ShenandoahBarrierSetC2State::add_load_reference_barrier(ShenandoahLoadReferenceBarrierNode * n) {
64 assert(!_load_reference_barriers->contains(n), "duplicate entry in barrier list");
65 _load_reference_barriers->append(n);
66 }
67
68 void ShenandoahBarrierSetC2State::remove_load_reference_barrier(ShenandoahLoadReferenceBarrierNode * n) {
69 if (_load_reference_barriers->contains(n)) {
70 _load_reference_barriers->remove(n);
71 }
72 }
73
74 #define __ kit->
75
76 bool ShenandoahBarrierSetC2::satb_can_remove_pre_barrier(GraphKit* kit, PhaseValues* phase, Node* adr,
77 BasicType bt, uint adr_idx) const {
78 intptr_t offset = 0;
79 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
80 AllocateNode* alloc = AllocateNode::Ideal_allocation(base);
81
82 if (offset == Type::OffsetBot) {
83 return false; // cannot unalias unless there are precise offsets
84 }
85
86 if (alloc == nullptr) {
87 return false; // No allocation found
88 }
89
90 intptr_t size_in_bytes = type2aelembytes(bt);
91
92 Node* mem = __ memory(adr_idx); // start searching here...
93
94 for (int cnt = 0; cnt < 50; cnt++) {
95
96 if (mem->is_Store()) {
97
98 Node* st_adr = mem->in(MemNode::Address);
99 intptr_t st_offset = 0;
100 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
101
102 if (st_base == nullptr) {
103 break; // inscrutable pointer
104 }
105
106 // Break we have found a store with same base and offset as ours so break
107 if (st_base == base && st_offset == offset) {
108 break;
109 }
110
111 if (st_offset != offset && st_offset != Type::OffsetBot) {
112 const int MAX_STORE = BytesPerLong;
113 if (st_offset >= offset + size_in_bytes ||
114 st_offset <= offset - MAX_STORE ||
115 st_offset <= offset - mem->as_Store()->memory_size()) {
116 // Success: The offsets are provably independent.
117 // (You may ask, why not just test st_offset != offset and be done?
118 // The answer is that stores of different sizes can co-exist
119 // in the same sequence of RawMem effects. We sometimes initialize
120 // a whole 'tile' of array elements with a single jint or jlong.)
121 mem = mem->in(MemNode::Memory);
122 continue; // advance through independent store memory
123 }
124 }
125
126 if (st_base != base
127 && MemNode::detect_ptr_independence(base, alloc, st_base,
128 AllocateNode::Ideal_allocation(st_base),
129 phase)) {
130 // Success: The bases are provably independent.
131 mem = mem->in(MemNode::Memory);
132 continue; // advance through independent store memory
133 }
134 } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
135
136 InitializeNode* st_init = mem->in(0)->as_Initialize();
137 AllocateNode* st_alloc = st_init->allocation();
138
139 // Make sure that we are looking at the same allocation site.
140 // The alloc variable is guaranteed to not be null here from earlier check.
141 if (alloc == st_alloc) {
142 // Check that the initialization is storing null so that no previous store
143 // has been moved up and directly write a reference
144 Node* captured_store = st_init->find_captured_store(offset,
145 type2aelembytes(T_OBJECT),
146 phase);
147 if (captured_store == nullptr || captured_store == st_init->zero_memory()) {
148 return true;
149 }
150 }
151 }
152
153 // Unless there is an explicit 'continue', we must bail out here,
154 // because 'mem' is an inscrutable memory state (e.g., a call).
155 break;
156 }
157
158 return false;
159 }
160
161 #undef __
162 #define __ ideal.
163
164 void ShenandoahBarrierSetC2::satb_write_barrier_pre(GraphKit* kit,
165 bool do_load,
166 Node* obj,
167 Node* adr,
168 uint alias_idx,
169 Node* val,
170 const TypeOopPtr* val_type,
171 Node* pre_val,
172 BasicType bt) const {
173 // Some sanity checks
174 // Note: val is unused in this routine.
175
176 if (do_load) {
177 // We need to generate the load of the previous value
178 assert(adr != nullptr, "where are loading from?");
179 assert(pre_val == nullptr, "loaded already?");
180 assert(val_type != nullptr, "need a type");
181
182 if (ReduceInitialCardMarks
183 && satb_can_remove_pre_barrier(kit, &kit->gvn(), adr, bt, alias_idx)) {
184 return;
185 }
186
187 } else {
188 // In this case both val_type and alias_idx are unused.
189 assert(pre_val != nullptr, "must be loaded already");
190 // Nothing to be done if pre_val is null.
191 if (pre_val->bottom_type() == TypePtr::NULL_PTR) return;
192 assert(pre_val->bottom_type()->basic_type() == T_OBJECT, "or we shouldn't be here");
193 }
194 assert(bt == T_OBJECT, "or we shouldn't be here");
195
196 IdealKit ideal(kit, true);
197
198 Node* tls = __ thread(); // ThreadLocalStorage
199
200 Node* no_base = __ top();
201 Node* zero = __ ConI(0);
202 Node* zeroX = __ ConX(0);
203
204 float likely = PROB_LIKELY(0.999);
205 float unlikely = PROB_UNLIKELY(0.999);
206
207 // Offsets into the thread
208 const int index_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset());
209 const int buffer_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
210
211 // Now the actual pointers into the thread
212 Node* buffer_adr = __ AddP(no_base, tls, __ ConX(buffer_offset));
213 Node* index_adr = __ AddP(no_base, tls, __ ConX(index_offset));
214
215 // Now some of the values
216 Node* marking;
217 Node* gc_state = __ AddP(no_base, tls, __ ConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset())));
218 Node* ld = __ load(__ ctrl(), gc_state, TypeInt::BYTE, T_BYTE, Compile::AliasIdxRaw);
219 marking = __ AndI(ld, __ ConI(ShenandoahHeap::MARKING));
220 assert(ShenandoahBarrierC2Support::is_gc_state_load(ld), "Should match the shape");
221
222 // if (!marking)
223 __ if_then(marking, BoolTest::ne, zero, unlikely); {
224 BasicType index_bt = TypeX_X->basic_type();
225 assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading Shenandoah SATBMarkQueue::_index with wrong size.");
226 Node* index = __ load(__ ctrl(), index_adr, TypeX_X, index_bt, Compile::AliasIdxRaw);
227
228 if (do_load) {
229 // load original value
230 // alias_idx correct??
231 pre_val = __ load(__ ctrl(), adr, val_type, bt, alias_idx);
232 }
233
234 // if (pre_val != nullptr)
235 __ if_then(pre_val, BoolTest::ne, kit->null()); {
236 Node* buffer = __ load(__ ctrl(), buffer_adr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);
237
238 // is the queue for this thread full?
239 __ if_then(index, BoolTest::ne, zeroX, likely); {
240
241 // decrement the index
242 Node* next_index = kit->gvn().transform(new SubXNode(index, __ ConX(sizeof(intptr_t))));
243
244 // Now get the buffer location we will log the previous value into and store it
245 Node *log_addr = __ AddP(no_base, buffer, next_index);
246 __ store(__ ctrl(), log_addr, pre_val, T_OBJECT, Compile::AliasIdxRaw, MemNode::unordered);
247 // update the index
248 __ store(__ ctrl(), index_adr, next_index, index_bt, Compile::AliasIdxRaw, MemNode::unordered);
249
250 } __ else_(); {
251
252 // logging buffer is full, call the runtime
253 const TypeFunc *tf = ShenandoahBarrierSetC2::write_barrier_pre_Type();
254 __ make_leaf_call(tf, CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre), "shenandoah_wb_pre", pre_val);
255 } __ end_if(); // (!index)
256 } __ end_if(); // (pre_val != nullptr)
257 } __ end_if(); // (!marking)
258
259 // Final sync IdealKit and GraphKit.
260 kit->final_sync(ideal);
261
262 if (ShenandoahSATBBarrier && adr != nullptr) {
263 Node* c = kit->control();
264 Node* call = c->in(1)->in(1)->in(1)->in(0);
265 assert(is_shenandoah_wb_pre_call(call), "shenandoah_wb_pre call expected");
266 call->add_req(adr);
267 }
268 }
269
270 bool ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(Node* call) {
271 return call->is_CallLeaf() &&
272 call->as_CallLeaf()->entry_point() == CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre);
273 }
274
275 bool ShenandoahBarrierSetC2::is_shenandoah_clone_call(Node* call) {
276 return call->is_CallLeaf() &&
277 call->as_CallLeaf()->entry_point() == CAST_FROM_FN_PTR(address, ShenandoahRuntime::clone_barrier);
278 }
279
280 bool ShenandoahBarrierSetC2::is_shenandoah_lrb_call(Node* call) {
281 if (!call->is_CallLeaf()) {
282 return false;
283 }
284
285 address entry_point = call->as_CallLeaf()->entry_point();
286 return (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong)) ||
287 (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow)) ||
288 (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak)) ||
289 (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow)) ||
290 (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom)) ||
291 (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom_narrow));
292 }
293
294 bool ShenandoahBarrierSetC2::is_shenandoah_marking_if(PhaseValues* phase, Node* n) {
295 if (n->Opcode() != Op_If) {
296 return false;
297 }
298
299 Node* bol = n->in(1);
300 assert(bol->is_Bool(), "");
301 Node* cmpx = bol->in(1);
302 if (bol->as_Bool()->_test._test == BoolTest::ne &&
303 cmpx->is_Cmp() && cmpx->in(2) == phase->intcon(0) &&
304 is_shenandoah_state_load(cmpx->in(1)->in(1)) &&
305 cmpx->in(1)->in(2)->is_Con() &&
306 cmpx->in(1)->in(2) == phase->intcon(ShenandoahHeap::MARKING)) {
307 return true;
308 }
309
310 return false;
311 }
312
313 bool ShenandoahBarrierSetC2::is_shenandoah_state_load(Node* n) {
314 if (!n->is_Load()) return false;
315 const int state_offset = in_bytes(ShenandoahThreadLocalData::gc_state_offset());
316 return n->in(2)->is_AddP() && n->in(2)->in(2)->Opcode() == Op_ThreadLocal
317 && n->in(2)->in(3)->is_Con()
318 && n->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == state_offset;
319 }
320
321 void ShenandoahBarrierSetC2::shenandoah_write_barrier_pre(GraphKit* kit,
322 bool do_load,
323 Node* obj,
324 Node* adr,
325 uint alias_idx,
326 Node* val,
327 const TypeOopPtr* val_type,
328 Node* pre_val,
329 BasicType bt) const {
330 if (ShenandoahSATBBarrier) {
331 IdealKit ideal(kit);
332 kit->sync_kit(ideal);
333
334 satb_write_barrier_pre(kit, do_load, obj, adr, alias_idx, val, val_type, pre_val, bt);
335
336 ideal.sync_kit(kit);
337 kit->final_sync(ideal);
338 }
339 }
340
341 // Helper that guards and inserts a pre-barrier.
342 void ShenandoahBarrierSetC2::insert_pre_barrier(GraphKit* kit, Node* base_oop, Node* offset,
343 Node* pre_val, bool need_mem_bar) const {
344 // We could be accessing the referent field of a reference object. If so, when Shenandoah
345 // is enabled, we need to log the value in the referent field in an SATB buffer.
346 // This routine performs some compile time filters and generates suitable
347 // runtime filters that guard the pre-barrier code.
348 // Also add memory barrier for non volatile load from the referent field
349 // to prevent commoning of loads across safepoint.
350
351 // Some compile time checks.
352
353 // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
354 const TypeX* otype = offset->find_intptr_t_type();
355 if (otype != nullptr && otype->is_con() &&
356 otype->get_con() != java_lang_ref_Reference::referent_offset()) {
357 // Constant offset but not the reference_offset so just return
358 return;
359 }
360
361 // We only need to generate the runtime guards for instances.
362 const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
363 if (btype != nullptr) {
364 if (btype->isa_aryptr()) {
365 // Array type so nothing to do
366 return;
367 }
368
369 const TypeInstPtr* itype = btype->isa_instptr();
370 if (itype != nullptr) {
371 // Can the klass of base_oop be statically determined to be
372 // _not_ a sub-class of Reference and _not_ Object?
373 ciKlass* klass = itype->instance_klass();
374 if (klass->is_loaded() &&
375 !klass->is_subtype_of(kit->env()->Reference_klass()) &&
376 !kit->env()->Object_klass()->is_subtype_of(klass)) {
377 return;
378 }
379 }
380 }
381
382 // The compile time filters did not reject base_oop/offset so
383 // we need to generate the following runtime filters
384 //
385 // if (offset == java_lang_ref_Reference::_reference_offset) {
386 // if (instance_of(base, java.lang.ref.Reference)) {
387 // pre_barrier(_, pre_val, ...);
388 // }
389 // }
390
391 float likely = PROB_LIKELY( 0.999);
392 float unlikely = PROB_UNLIKELY(0.999);
393
394 IdealKit ideal(kit);
395
396 Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset());
397
398 __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
399 // Update graphKit memory and control from IdealKit.
400 kit->sync_kit(ideal);
401
402 Node* ref_klass_con = kit->makecon(TypeKlassPtr::make(kit->env()->Reference_klass()));
403 Node* is_instof = kit->gen_instanceof(base_oop, ref_klass_con);
404
405 // Update IdealKit memory and control from graphKit.
406 __ sync_kit(kit);
407
408 Node* one = __ ConI(1);
409 // is_instof == 0 if base_oop == nullptr
410 __ if_then(is_instof, BoolTest::eq, one, unlikely); {
411
412 // Update graphKit from IdeakKit.
413 kit->sync_kit(ideal);
414
415 // Use the pre-barrier to record the value in the referent field
416 satb_write_barrier_pre(kit, false /* do_load */,
417 nullptr /* obj */, nullptr /* adr */, max_juint /* alias_idx */, nullptr /* val */, nullptr /* val_type */,
418 pre_val /* pre_val */,
419 T_OBJECT);
420 if (need_mem_bar) {
421 // Add memory barrier to prevent commoning reads from this field
422 // across safepoint since GC can change its value.
423 kit->insert_mem_bar(Op_MemBarCPUOrder);
424 }
425 // Update IdealKit from graphKit.
426 __ sync_kit(kit);
427
428 } __ end_if(); // _ref_type != ref_none
429 } __ end_if(); // offset == referent_offset
430
431 // Final sync IdealKit and GraphKit.
432 kit->final_sync(ideal);
433 }
434
435 void ShenandoahBarrierSetC2::post_barrier(GraphKit* kit,
436 Node* ctl,
437 Node* oop_store,
438 Node* obj,
439 Node* adr,
440 uint adr_idx,
441 Node* val,
442 BasicType bt,
443 bool use_precise) const {
444 assert(ShenandoahCardBarrier, "Should have been checked by caller");
445
446 // No store check needed if we're storing a null.
447 if (val != nullptr && val->is_Con()) {
448 // must be either an oop or null
449 const Type* t = val->bottom_type();
450 if (t == TypePtr::NULL_PTR || t == Type::TOP)
451 return;
452 }
453
454 if (ReduceInitialCardMarks && obj == kit->just_allocated_object(kit->control())) {
455 // We use card marks to track old to young references in Generational Shenandoah;
456 // see flag ShenandoahCardBarrier above.
457 // Objects are always allocated in the young generation and initialized
458 // before they are promoted. There's always a safepoint (e.g. at final mark)
459 // before an object is promoted from young to old. Promotion entails dirtying of
460 // the cards backing promoted objects, so they will be guaranteed to be scanned
461 // at the next remembered set scan of the old generation.
462 // Thus, we can safely skip card-marking of initializing stores on a
463 // freshly-allocated object. If any of the assumptions above change in
464 // the future, this code will need to be re-examined; see check in
465 // ShenandoahCardBarrier::on_slowpath_allocation_exit().
466 return;
467 }
468
469 if (!use_precise) {
470 // All card marks for a (non-array) instance are in one place:
471 adr = obj;
472 }
473 // (Else it's an array (or unknown), and we want more precise card marks.)
474 assert(adr != nullptr, "");
475
476 IdealKit ideal(kit, true);
477
478 Node* tls = __ thread(); // ThreadLocalStorage
479
480 // Convert the pointer to an int prior to doing math on it
481 Node* cast = __ CastPX(__ ctrl(), adr);
482
483 Node* curr_ct_holder_offset = __ ConX(in_bytes(ShenandoahThreadLocalData::card_table_offset()));
484 Node* curr_ct_holder_addr = __ AddP(__ top(), tls, curr_ct_holder_offset);
485 Node* curr_ct_base_addr = __ load( __ ctrl(), curr_ct_holder_addr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);
486
487 // Divide by card size
488 Node* card_offset = __ URShiftX( cast, __ ConI(CardTable::card_shift()) );
489
490 // Combine card table base and card offset
491 Node* card_adr = __ AddP(__ top(), curr_ct_base_addr, card_offset);
492
493 // Get the alias_index for raw card-mark memory
494 int adr_type = Compile::AliasIdxRaw;
495 Node* zero = __ ConI(0); // Dirty card value
496
497 if (UseCondCardMark) {
498 // The classic GC reference write barrier is typically implemented
499 // as a store into the global card mark table. Unfortunately
500 // unconditional stores can result in false sharing and excessive
501 // coherence traffic as well as false transactional aborts.
502 // UseCondCardMark enables MP "polite" conditional card mark
503 // stores. In theory we could relax the load from ctrl() to
504 // no_ctrl, but that doesn't buy much latitude.
505 Node* card_val = __ load( __ ctrl(), card_adr, TypeInt::BYTE, T_BYTE, adr_type);
506 __ if_then(card_val, BoolTest::ne, zero);
507 }
508
509 // Smash zero into card
510 __ store(__ ctrl(), card_adr, zero, T_BYTE, adr_type, MemNode::unordered);
511
512 if (UseCondCardMark) {
513 __ end_if();
514 }
515
516 // Final sync IdealKit and GraphKit.
517 kit->final_sync(ideal);
518 }
519
520 #undef __
521
522 const TypeFunc* ShenandoahBarrierSetC2::write_barrier_pre_Type() {
523 const Type **fields = TypeTuple::fields(1);
524 fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // original field value
525 const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
526
527 // create result type (range)
528 fields = TypeTuple::fields(0);
529 const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
530
531 return TypeFunc::make(domain, range);
532 }
533
534 const TypeFunc* ShenandoahBarrierSetC2::clone_barrier_Type() {
535 const Type **fields = TypeTuple::fields(1);
536 fields[TypeFunc::Parms+0] = TypeOopPtr::NOTNULL; // src oop
537 const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
538
539 // create result type (range)
540 fields = TypeTuple::fields(0);
541 const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
542
543 return TypeFunc::make(domain, range);
544 }
545
546 const TypeFunc* ShenandoahBarrierSetC2::load_reference_barrier_Type() {
547 const Type **fields = TypeTuple::fields(2);
548 fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM; // original field value
549 fields[TypeFunc::Parms+1] = TypeRawPtr::BOTTOM; // original load address
550
551 const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
552
553 // create result type (range)
554 fields = TypeTuple::fields(1);
555 fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM;
556 const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
557
558 return TypeFunc::make(domain, range);
559 }
560
561 Node* ShenandoahBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
562 DecoratorSet decorators = access.decorators();
563
564 const TypePtr* adr_type = access.addr().type();
565 Node* adr = access.addr().node();
566
567 bool no_keepalive = (decorators & AS_NO_KEEPALIVE) != 0;
568
569 if (!access.is_oop()) {
570 return BarrierSetC2::store_at_resolved(access, val);
571 }
572
573 if (no_keepalive) {
574 // No keep-alive means no need for the pre-barrier.
575 return BarrierSetC2::store_at_resolved(access, val);
576 }
577
578 if (access.is_parse_access()) {
579 C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
580 GraphKit* kit = parse_access.kit();
581
582 uint adr_idx = kit->C->get_alias_index(adr_type);
583 assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
584 shenandoah_write_barrier_pre(kit, true /* do_load */, /*kit->control(),*/ access.base(), adr, adr_idx, val.node(),
585 static_cast<const TypeOopPtr*>(val.type()), nullptr /* pre_val */, access.type());
586
587 Node* result = BarrierSetC2::store_at_resolved(access, val);
588
589 if (ShenandoahCardBarrier) {
590 const bool anonymous = (decorators & ON_UNKNOWN_OOP_REF) != 0;
591 const bool is_array = (decorators & IS_ARRAY) != 0;
592 const bool use_precise = is_array || anonymous;
593 post_barrier(kit, kit->control(), access.raw_access(), access.base(),
594 adr, adr_idx, val.node(), access.type(), use_precise);
595 }
596 return result;
597 } else {
598 assert(access.is_opt_access(), "only for optimization passes");
599 assert(((decorators & C2_TIGHTLY_COUPLED_ALLOC) != 0 || !ShenandoahSATBBarrier) && (decorators & C2_ARRAY_COPY) != 0, "unexpected caller of this code");
600 return BarrierSetC2::store_at_resolved(access, val);
601 }
602 }
603
604 Node* ShenandoahBarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
605 // 1: non-reference load, no additional barrier is needed
606 if (!access.is_oop()) {
607 return BarrierSetC2::load_at_resolved(access, val_type);
608 }
609
610 Node* load = BarrierSetC2::load_at_resolved(access, val_type);
611 DecoratorSet decorators = access.decorators();
612 BasicType type = access.type();
613
614 // 2: apply LRB if needed
615 if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
616 load = new ShenandoahLoadReferenceBarrierNode(nullptr, load, decorators);
617 if (access.is_parse_access()) {
618 load = static_cast<C2ParseAccess &>(access).kit()->gvn().transform(load);
619 } else {
620 load = static_cast<C2OptAccess &>(access).gvn().transform(load);
621 }
622 }
623
624 // 3: apply keep-alive barrier for java.lang.ref.Reference if needed
625 if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
626 Node* top = Compile::current()->top();
627 Node* adr = access.addr().node();
628 Node* offset = adr->is_AddP() ? adr->in(AddPNode::Offset) : top;
629 Node* obj = access.base();
630
631 bool unknown = (decorators & ON_UNKNOWN_OOP_REF) != 0;
632 bool on_weak_ref = (decorators & (ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF)) != 0;
633 bool keep_alive = (decorators & AS_NO_KEEPALIVE) == 0;
634
635 // If we are reading the value of the referent field of a Reference
636 // object (either by using Unsafe directly or through reflection)
637 // then, if SATB is enabled, we need to record the referent in an
638 // SATB log buffer using the pre-barrier mechanism.
639 // Also we need to add memory barrier to prevent commoning reads
640 // from this field across safepoint since GC can change its value.
641 if (!on_weak_ref || (unknown && (offset == top || obj == top)) || !keep_alive) {
642 return load;
643 }
644
645 assert(access.is_parse_access(), "entry not supported at optimization time");
646 C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
647 GraphKit* kit = parse_access.kit();
648 bool mismatched = (decorators & C2_MISMATCHED) != 0;
649 bool is_unordered = (decorators & MO_UNORDERED) != 0;
650 bool in_native = (decorators & IN_NATIVE) != 0;
651 bool need_cpu_mem_bar = !is_unordered || mismatched || in_native;
652
653 if (on_weak_ref) {
654 // Use the pre-barrier to record the value in the referent field
655 satb_write_barrier_pre(kit, false /* do_load */,
656 nullptr /* obj */, nullptr /* adr */, max_juint /* alias_idx */, nullptr /* val */, nullptr /* val_type */,
657 load /* pre_val */, T_OBJECT);
658 // Add memory barrier to prevent commoning reads from this field
659 // across safepoint since GC can change its value.
660 kit->insert_mem_bar(Op_MemBarCPUOrder);
661 } else if (unknown) {
662 // We do not require a mem bar inside pre_barrier if need_mem_bar
663 // is set: the barriers would be emitted by us.
664 insert_pre_barrier(kit, obj, offset, load, !need_cpu_mem_bar);
665 }
666 }
667
668 return load;
669 }
670
671 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
672 Node* new_val, const Type* value_type) const {
673 GraphKit* kit = access.kit();
674 if (access.is_oop()) {
675 shenandoah_write_barrier_pre(kit, false /* do_load */,
676 nullptr, nullptr, max_juint, nullptr, nullptr,
677 expected_val /* pre_val */, T_OBJECT);
678
679 MemNode::MemOrd mo = access.mem_node_mo();
680 Node* mem = access.memory();
681 Node* adr = access.addr().node();
682 const TypePtr* adr_type = access.addr().type();
683 Node* load_store = nullptr;
684
685 #ifdef _LP64
686 if (adr->bottom_type()->is_ptr_to_narrowoop()) {
687 Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
688 Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
689 if (ShenandoahCASBarrier) {
690 load_store = kit->gvn().transform(new ShenandoahCompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
691 } else {
692 load_store = kit->gvn().transform(new CompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
693 }
694 } else
695 #endif
696 {
697 if (ShenandoahCASBarrier) {
698 load_store = kit->gvn().transform(new ShenandoahCompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
699 } else {
700 load_store = kit->gvn().transform(new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
701 }
702 }
703
704 access.set_raw_access(load_store);
705 pin_atomic_op(access);
706
707 #ifdef _LP64
708 if (adr->bottom_type()->is_ptr_to_narrowoop()) {
709 load_store = kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
710 }
711 #endif
712 load_store = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(nullptr, load_store, access.decorators()));
713 if (ShenandoahCardBarrier) {
714 post_barrier(kit, kit->control(), access.raw_access(), access.base(),
715 access.addr().node(), access.alias_idx(), new_val, T_OBJECT, true);
716 }
717 return load_store;
718 }
719 return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
720 }
721
722 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
723 Node* new_val, const Type* value_type) const {
724 GraphKit* kit = access.kit();
725 if (access.is_oop()) {
726 shenandoah_write_barrier_pre(kit, false /* do_load */,
727 nullptr, nullptr, max_juint, nullptr, nullptr,
728 expected_val /* pre_val */, T_OBJECT);
729 DecoratorSet decorators = access.decorators();
730 MemNode::MemOrd mo = access.mem_node_mo();
731 Node* mem = access.memory();
732 bool is_weak_cas = (decorators & C2_WEAK_CMPXCHG) != 0;
733 Node* load_store = nullptr;
734 Node* adr = access.addr().node();
735 #ifdef _LP64
736 if (adr->bottom_type()->is_ptr_to_narrowoop()) {
737 Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
738 Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
739 if (ShenandoahCASBarrier) {
740 if (is_weak_cas) {
741 load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
742 } else {
743 load_store = kit->gvn().transform(new ShenandoahCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
744 }
745 } else {
746 if (is_weak_cas) {
747 load_store = kit->gvn().transform(new WeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
748 } else {
749 load_store = kit->gvn().transform(new CompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
750 }
751 }
752 } else
753 #endif
754 {
755 if (ShenandoahCASBarrier) {
756 if (is_weak_cas) {
757 load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
758 } else {
759 load_store = kit->gvn().transform(new ShenandoahCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
760 }
761 } else {
762 if (is_weak_cas) {
763 load_store = kit->gvn().transform(new WeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
764 } else {
765 load_store = kit->gvn().transform(new CompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
766 }
767 }
768 }
769 access.set_raw_access(load_store);
770 pin_atomic_op(access);
771 if (ShenandoahCardBarrier) {
772 post_barrier(kit, kit->control(), access.raw_access(), access.base(),
773 access.addr().node(), access.alias_idx(), new_val, T_OBJECT, true);
774 }
775 return load_store;
776 }
777 return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
778 }
779
780 Node* ShenandoahBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* val, const Type* value_type) const {
781 GraphKit* kit = access.kit();
782 Node* result = BarrierSetC2::atomic_xchg_at_resolved(access, val, value_type);
783 if (access.is_oop()) {
784 result = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(nullptr, result, access.decorators()));
785 shenandoah_write_barrier_pre(kit, false /* do_load */,
786 nullptr, nullptr, max_juint, nullptr, nullptr,
787 result /* pre_val */, T_OBJECT);
788 if (ShenandoahCardBarrier) {
789 post_barrier(kit, kit->control(), access.raw_access(), access.base(),
790 access.addr().node(), access.alias_idx(), val, T_OBJECT, true);
791 }
792 }
793 return result;
794 }
795
796
797 bool ShenandoahBarrierSetC2::is_gc_pre_barrier_node(Node* node) const {
798 return is_shenandoah_wb_pre_call(node);
799 }
800
801 bool ShenandoahBarrierSetC2::is_gc_barrier_node(Node* node) const {
802 return (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) ||
803 is_shenandoah_lrb_call(node) ||
804 is_shenandoah_wb_pre_call(node) ||
805 is_shenandoah_clone_call(node);
806 }
807
808 Node* ShenandoahBarrierSetC2::step_over_gc_barrier(Node* c) const {
809 if (c == nullptr) {
810 return c;
811 }
812 if (c->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
813 return c->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
814 }
815 return c;
816 }
817
818 bool ShenandoahBarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const {
819 return !ShenandoahBarrierC2Support::expand(C, igvn);
820 }
821
822 bool ShenandoahBarrierSetC2::optimize_loops(PhaseIdealLoop* phase, LoopOptsMode mode, VectorSet& visited, Node_Stack& nstack, Node_List& worklist) const {
823 if (mode == LoopOptsShenandoahExpand) {
824 assert(UseShenandoahGC, "only for shenandoah");
825 ShenandoahBarrierC2Support::pin_and_expand(phase);
826 return true;
827 }
828 return false;
829 }
830
831 bool ShenandoahBarrierSetC2::array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, bool is_clone_instance, ArrayCopyPhase phase) const {
832 bool is_oop = is_reference_type(type);
833 if (!is_oop) {
834 return false;
835 }
836 if (ShenandoahSATBBarrier && tightly_coupled_alloc) {
837 if (phase == Optimization) {
838 return false;
839 }
840 return !is_clone;
841 }
842 return true;
843 }
844
845 bool ShenandoahBarrierSetC2::clone_needs_barrier(Node* src, PhaseGVN& gvn) {
846 const TypeOopPtr* src_type = gvn.type(src)->is_oopptr();
847 if (src_type->isa_instptr() != nullptr) {
848 ciInstanceKlass* ik = src_type->is_instptr()->instance_klass();
849 if ((src_type->klass_is_exact() || !ik->has_subklass()) && !ik->has_injected_fields()) {
850 if (ik->has_object_fields()) {
851 return true;
852 } else {
853 if (!src_type->klass_is_exact()) {
854 Compile::current()->dependencies()->assert_leaf_type(ik);
855 }
856 }
857 } else {
858 return true;
859 }
860 } else if (src_type->isa_aryptr()) {
861 BasicType src_elem = src_type->isa_aryptr()->elem()->array_element_basic_type();
862 if (is_reference_type(src_elem, true)) {
863 return true;
864 }
865 } else {
866 return true;
867 }
868 return false;
869 }
870
871 void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
872 Node* ctrl = ac->in(TypeFunc::Control);
873 Node* mem = ac->in(TypeFunc::Memory);
874 Node* src_base = ac->in(ArrayCopyNode::Src);
875 Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
876 Node* dest_base = ac->in(ArrayCopyNode::Dest);
877 Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
878 Node* length = ac->in(ArrayCopyNode::Length);
879
880 Node* src = phase->basic_plus_adr(src_base, src_offset);
881 Node* dest = phase->basic_plus_adr(dest_base, dest_offset);
882
883 if (ShenandoahCloneBarrier && clone_needs_barrier(src, phase->igvn())) {
884 // Check if heap is has forwarded objects. If it does, we need to call into the special
885 // routine that would fix up source references before we can continue.
886
887 enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
888 Node* region = new RegionNode(PATH_LIMIT);
889 Node* mem_phi = new PhiNode(region, Type::MEMORY, TypeRawPtr::BOTTOM);
890
891 Node* thread = phase->transform_later(new ThreadLocalNode());
892 Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
893 Node* gc_state_addr = phase->transform_later(new AddPNode(phase->C->top(), thread, offset));
894
895 uint gc_state_idx = Compile::AliasIdxRaw;
896 const TypePtr* gc_state_adr_type = nullptr; // debug-mode-only argument
897 DEBUG_ONLY(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
898
899 Node* gc_state = phase->transform_later(new LoadBNode(ctrl, mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered));
900 Node* stable_and = phase->transform_later(new AndINode(gc_state, phase->igvn().intcon(ShenandoahHeap::HAS_FORWARDED)));
901 Node* stable_cmp = phase->transform_later(new CmpINode(stable_and, phase->igvn().zerocon(T_INT)));
902 Node* stable_test = phase->transform_later(new BoolNode(stable_cmp, BoolTest::ne));
903
904 IfNode* stable_iff = phase->transform_later(new IfNode(ctrl, stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN))->as_If();
905 Node* stable_ctrl = phase->transform_later(new IfFalseNode(stable_iff));
906 Node* unstable_ctrl = phase->transform_later(new IfTrueNode(stable_iff));
907
908 // Heap is stable, no need to do anything additional
909 region->init_req(_heap_stable, stable_ctrl);
910 mem_phi->init_req(_heap_stable, mem);
911
912 // Heap is unstable, call into clone barrier stub
913 Node* call = phase->make_leaf_call(unstable_ctrl, mem,
914 ShenandoahBarrierSetC2::clone_barrier_Type(),
915 CAST_FROM_FN_PTR(address, ShenandoahRuntime::clone_barrier),
916 "shenandoah_clone",
917 TypeRawPtr::BOTTOM,
918 src_base);
919 call = phase->transform_later(call);
920
921 ctrl = phase->transform_later(new ProjNode(call, TypeFunc::Control));
922 mem = phase->transform_later(new ProjNode(call, TypeFunc::Memory));
923 region->init_req(_heap_unstable, ctrl);
924 mem_phi->init_req(_heap_unstable, mem);
925
926 // Wire up the actual arraycopy stub now
927 ctrl = phase->transform_later(region);
928 mem = phase->transform_later(mem_phi);
929
930 const char* name = "arraycopy";
931 call = phase->make_leaf_call(ctrl, mem,
932 OptoRuntime::fast_arraycopy_Type(),
933 phase->basictype2arraycopy(T_LONG, nullptr, nullptr, true, name, true),
934 name, TypeRawPtr::BOTTOM,
935 src, dest, length
936 LP64_ONLY(COMMA phase->top()));
937 call = phase->transform_later(call);
938
939 // Hook up the whole thing into the graph
940 phase->igvn().replace_node(ac, call);
941 } else {
942 BarrierSetC2::clone_at_expansion(phase, ac);
943 }
944 }
945
946
947 // Support for macro expanded GC barriers
948 void ShenandoahBarrierSetC2::register_potential_barrier_node(Node* node) const {
949 if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
950 state()->add_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
951 }
952 }
953
954 void ShenandoahBarrierSetC2::unregister_potential_barrier_node(Node* node) const {
955 if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
956 state()->remove_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
957 }
958 }
959
960 void ShenandoahBarrierSetC2::eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const {
961 if (is_shenandoah_wb_pre_call(node)) {
962 shenandoah_eliminate_wb_pre(node, ¯o->igvn());
963 }
964 if (ShenandoahCardBarrier && node->Opcode() == Op_CastP2X) {
965 Node* shift = node->unique_out();
966 Node* addp = shift->unique_out();
967 for (DUIterator_Last jmin, j = addp->last_outs(jmin); j >= jmin; --j) {
968 Node* mem = addp->last_out(j);
969 if (UseCondCardMark && mem->is_Load()) {
970 assert(mem->Opcode() == Op_LoadB, "unexpected code shape");
971 // The load is checking if the card has been written so
972 // replace it with zero to fold the test.
973 macro->replace_node(mem, macro->intcon(0));
974 continue;
975 }
976 assert(mem->is_Store(), "store required");
977 macro->replace_node(mem, mem->in(MemNode::Memory));
978 }
979 }
980 }
981
982 void ShenandoahBarrierSetC2::shenandoah_eliminate_wb_pre(Node* call, PhaseIterGVN* igvn) const {
983 assert(UseShenandoahGC && is_shenandoah_wb_pre_call(call), "");
984 Node* c = call->as_Call()->proj_out(TypeFunc::Control);
985 c = c->unique_ctrl_out();
986 assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
987 c = c->unique_ctrl_out();
988 assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
989 Node* iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
990 assert(iff->is_If(), "expect test");
991 if (!is_shenandoah_marking_if(igvn, iff)) {
992 c = c->unique_ctrl_out();
993 assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
994 iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
995 assert(is_shenandoah_marking_if(igvn, iff), "expect marking test");
996 }
997 Node* cmpx = iff->in(1)->in(1);
998 igvn->replace_node(cmpx, igvn->makecon(TypeInt::CC_EQ));
999 igvn->rehash_node_delayed(call);
1000 call->del_req(call->req()-1);
1001 }
1002
1003 void ShenandoahBarrierSetC2::enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const {
1004 if (node->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(node)) {
1005 igvn->add_users_to_worklist(node);
1006 }
1007 }
1008
1009 void ShenandoahBarrierSetC2::eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const {
1010 for (uint i = 0; i < useful.size(); i++) {
1011 Node* n = useful.at(i);
1012 if (n->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(n)) {
1013 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1014 C->record_for_igvn(n->fast_out(i));
1015 }
1016 }
1017 }
1018
1019 for (int i = state()->load_reference_barriers_count() - 1; i >= 0; i--) {
1020 ShenandoahLoadReferenceBarrierNode* n = state()->load_reference_barrier(i);
1021 if (!useful.member(n)) {
1022 state()->remove_load_reference_barrier(n);
1023 }
1024 }
1025 }
1026
1027 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
1028 return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
1029 }
1030
1031 ShenandoahBarrierSetC2State* ShenandoahBarrierSetC2::state() const {
1032 return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());
1033 }
1034
1035 // If the BarrierSetC2 state has kept macro nodes in its compilation unit state to be
1036 // expanded later, then now is the time to do so.
1037 bool ShenandoahBarrierSetC2::expand_macro_nodes(PhaseMacroExpand* macro) const { return false; }
1038
1039 #ifdef ASSERT
1040 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
1041 if (ShenandoahVerifyOptoBarriers && phase == BarrierSetC2::BeforeMacroExpand) {
1042 ShenandoahBarrierC2Support::verify(Compile::current()->root());
1043 } else if (phase == BarrierSetC2::BeforeCodeGen) {
1044 // Verify Shenandoah pre-barriers
1045 const int gc_state_offset = in_bytes(ShenandoahThreadLocalData::gc_state_offset());
1046
1047 Unique_Node_List visited;
1048 Node_List worklist;
1049 // We're going to walk control flow backwards starting from the Root
1050 worklist.push(compile->root());
1051 while (worklist.size() > 0) {
1052 Node *x = worklist.pop();
1053 if (x == nullptr || x == compile->top()) {
1054 continue;
1055 }
1056
1057 if (visited.member(x)) {
1058 continue;
1059 } else {
1060 visited.push(x);
1061 }
1062
1063 if (x->is_Region()) {
1064 for (uint i = 1; i < x->req(); i++) {
1065 worklist.push(x->in(i));
1066 }
1067 } else {
1068 worklist.push(x->in(0));
1069 // We are looking for the pattern:
1070 // /->ThreadLocal
1071 // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
1072 // \->ConI(0)
1073 // We want to verify that the If and the LoadB have the same control
1074 // See GraphKit::g1_write_barrier_pre()
1075 if (x->is_If()) {
1076 IfNode *iff = x->as_If();
1077 if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
1078 CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
1079 if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
1080 && cmp->in(1)->is_Load()) {
1081 LoadNode *load = cmp->in(1)->as_Load();
1082 if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
1083 && load->in(2)->in(3)->is_Con()
1084 && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == gc_state_offset) {
1085
1086 Node *if_ctrl = iff->in(0);
1087 Node *load_ctrl = load->in(0);
1088
1089 if (if_ctrl != load_ctrl) {
1090 // Skip possible CProj->NeverBranch in infinite loops
1091 if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
1092 && if_ctrl->in(0)->is_NeverBranch()) {
1093 if_ctrl = if_ctrl->in(0)->in(0);
1094 }
1095 }
1096 assert(load_ctrl != nullptr && if_ctrl == load_ctrl, "controls must match");
1097 }
1098 }
1099 }
1100 }
1101 }
1102 }
1103 }
1104 }
1105 #endif
1106
1107 Node* ShenandoahBarrierSetC2::ideal_node(PhaseGVN* phase, Node* n, bool can_reshape) const {
1108 if (is_shenandoah_wb_pre_call(n)) {
1109 uint cnt = ShenandoahBarrierSetC2::write_barrier_pre_Type()->domain()->cnt();
1110 if (n->req() > cnt) {
1111 Node* addp = n->in(cnt);
1112 if (has_only_shenandoah_wb_pre_uses(addp)) {
1113 n->del_req(cnt);
1114 if (can_reshape) {
1115 phase->is_IterGVN()->_worklist.push(addp);
1116 }
1117 return n;
1118 }
1119 }
1120 }
1121 if (n->Opcode() == Op_CmpP) {
1122 Node* in1 = n->in(1);
1123 Node* in2 = n->in(2);
1124
1125 // If one input is null, then step over the strong LRB barriers on the other input
1126 if (in1->bottom_type() == TypePtr::NULL_PTR &&
1127 !((in2->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1128 !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in2)->decorators()))) {
1129 in2 = step_over_gc_barrier(in2);
1130 }
1131 if (in2->bottom_type() == TypePtr::NULL_PTR &&
1132 !((in1->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1133 !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in1)->decorators()))) {
1134 in1 = step_over_gc_barrier(in1);
1135 }
1136
1137 if (in1 != n->in(1)) {
1138 n->set_req_X(1, in1, phase);
1139 assert(in2 == n->in(2), "only one change");
1140 return n;
1141 }
1142 if (in2 != n->in(2)) {
1143 n->set_req_X(2, in2, phase);
1144 return n;
1145 }
1146 } else if (can_reshape &&
1147 n->Opcode() == Op_If &&
1148 ShenandoahBarrierC2Support::is_heap_stable_test(n) &&
1149 n->in(0) != nullptr &&
1150 n->outcnt() == 2) {
1151 Node* dom = n->in(0);
1152 Node* prev_dom = n;
1153 int op = n->Opcode();
1154 int dist = 16;
1155 // Search up the dominator tree for another heap stable test
1156 while (dom->Opcode() != op || // Not same opcode?
1157 !ShenandoahBarrierC2Support::is_heap_stable_test(dom) || // Not same input 1?
1158 prev_dom->in(0) != dom) { // One path of test does not dominate?
1159 if (dist < 0) return nullptr;
1160
1161 dist--;
1162 prev_dom = dom;
1163 dom = IfNode::up_one_dom(dom);
1164 if (!dom) return nullptr;
1165 }
1166
1167 // Check that we did not follow a loop back to ourselves
1168 if (n == dom) {
1169 return nullptr;
1170 }
1171
1172 return n->as_If()->dominated_by(prev_dom, phase->is_IterGVN(), false);
1173 }
1174
1175 return nullptr;
1176 }
1177
1178 bool ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(Node* n) {
1179 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1180 Node* u = n->fast_out(i);
1181 if (!is_shenandoah_wb_pre_call(u)) {
1182 return false;
1183 }
1184 }
1185 return n->outcnt() > 0;
1186 }
1187
1188 bool ShenandoahBarrierSetC2::final_graph_reshaping(Compile* compile, Node* n, uint opcode, Unique_Node_List& dead_nodes) const {
1189 switch (opcode) {
1190 case Op_CallLeaf:
1191 case Op_CallLeafNoFP: {
1192 assert (n->is_Call(), "");
1193 CallNode *call = n->as_Call();
1194 if (ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(call)) {
1195 uint cnt = ShenandoahBarrierSetC2::write_barrier_pre_Type()->domain()->cnt();
1196 if (call->req() > cnt) {
1197 assert(call->req() == cnt + 1, "only one extra input");
1198 Node *addp = call->in(cnt);
1199 assert(!ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(addp), "useless address computation?");
1200 call->del_req(cnt);
1201 }
1202 }
1203 return false;
1204 }
1205 case Op_ShenandoahCompareAndSwapP:
1206 case Op_ShenandoahCompareAndSwapN:
1207 case Op_ShenandoahWeakCompareAndSwapN:
1208 case Op_ShenandoahWeakCompareAndSwapP:
1209 case Op_ShenandoahCompareAndExchangeP:
1210 case Op_ShenandoahCompareAndExchangeN:
1211 return true;
1212 case Op_ShenandoahLoadReferenceBarrier:
1213 assert(false, "should have been expanded already");
1214 return true;
1215 default:
1216 return false;
1217 }
1218 }
1219
1220 bool ShenandoahBarrierSetC2::escape_add_to_con_graph(ConnectionGraph* conn_graph, PhaseGVN* gvn, Unique_Node_List* delayed_worklist, Node* n, uint opcode) const {
1221 switch (opcode) {
1222 case Op_ShenandoahCompareAndExchangeP:
1223 case Op_ShenandoahCompareAndExchangeN:
1224 conn_graph->add_objload_to_connection_graph(n, delayed_worklist);
1225 // fallthrough
1226 case Op_ShenandoahWeakCompareAndSwapP:
1227 case Op_ShenandoahWeakCompareAndSwapN:
1228 case Op_ShenandoahCompareAndSwapP:
1229 case Op_ShenandoahCompareAndSwapN:
1230 conn_graph->add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
1231 return true;
1232 case Op_StoreP: {
1233 Node* adr = n->in(MemNode::Address);
1234 const Type* adr_type = gvn->type(adr);
1235 // Pointer stores in Shenandoah barriers looks like unsafe access.
1236 // Ignore such stores to be able scalar replace non-escaping
1237 // allocations.
1238 if (adr_type->isa_rawptr() && adr->is_AddP()) {
1239 Node* base = conn_graph->get_addp_base(adr);
1240 if (base->Opcode() == Op_LoadP &&
1241 base->in(MemNode::Address)->is_AddP()) {
1242 adr = base->in(MemNode::Address);
1243 Node* tls = conn_graph->get_addp_base(adr);
1244 if (tls->Opcode() == Op_ThreadLocal) {
1245 int offs = (int) gvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
1246 const int buf_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
1247 if (offs == buf_offset) {
1248 return true; // Pre barrier previous oop value store.
1249 }
1250 }
1251 }
1252 }
1253 return false;
1254 }
1255 case Op_ShenandoahLoadReferenceBarrier:
1256 conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), delayed_worklist);
1257 return true;
1258 default:
1259 // Nothing
1260 break;
1261 }
1262 return false;
1263 }
1264
1265 bool ShenandoahBarrierSetC2::escape_add_final_edges(ConnectionGraph* conn_graph, PhaseGVN* gvn, Node* n, uint opcode) const {
1266 switch (opcode) {
1267 case Op_ShenandoahCompareAndExchangeP:
1268 case Op_ShenandoahCompareAndExchangeN: {
1269 Node *adr = n->in(MemNode::Address);
1270 conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, adr, nullptr);
1271 // fallthrough
1272 }
1273 case Op_ShenandoahCompareAndSwapP:
1274 case Op_ShenandoahCompareAndSwapN:
1275 case Op_ShenandoahWeakCompareAndSwapP:
1276 case Op_ShenandoahWeakCompareAndSwapN:
1277 return conn_graph->add_final_edges_unsafe_access(n, opcode);
1278 case Op_ShenandoahLoadReferenceBarrier:
1279 conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), nullptr);
1280 return true;
1281 default:
1282 // Nothing
1283 break;
1284 }
1285 return false;
1286 }
1287
1288 bool ShenandoahBarrierSetC2::escape_has_out_with_unsafe_object(Node* n) const {
1289 return n->has_out_with(Op_ShenandoahCompareAndExchangeP) || n->has_out_with(Op_ShenandoahCompareAndExchangeN) ||
1290 n->has_out_with(Op_ShenandoahCompareAndSwapP, Op_ShenandoahCompareAndSwapN, Op_ShenandoahWeakCompareAndSwapP, Op_ShenandoahWeakCompareAndSwapN);
1291
1292 }
1293
1294 bool ShenandoahBarrierSetC2::matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const {
1295 switch (opcode) {
1296 case Op_ShenandoahCompareAndExchangeP:
1297 case Op_ShenandoahCompareAndExchangeN:
1298 case Op_ShenandoahWeakCompareAndSwapP:
1299 case Op_ShenandoahWeakCompareAndSwapN:
1300 case Op_ShenandoahCompareAndSwapP:
1301 case Op_ShenandoahCompareAndSwapN: { // Convert trinary to binary-tree
1302 Node* newval = n->in(MemNode::ValueIn);
1303 Node* oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
1304 Node* pair = new BinaryNode(oldval, newval);
1305 n->set_req(MemNode::ValueIn,pair);
1306 n->del_req(LoadStoreConditionalNode::ExpectedIn);
1307 return true;
1308 }
1309 default:
1310 break;
1311 }
1312 return false;
1313 }
1314
1315 bool ShenandoahBarrierSetC2::matcher_is_store_load_barrier(Node* x, uint xop) const {
1316 return xop == Op_ShenandoahCompareAndExchangeP ||
1317 xop == Op_ShenandoahCompareAndExchangeN ||
1318 xop == Op_ShenandoahWeakCompareAndSwapP ||
1319 xop == Op_ShenandoahWeakCompareAndSwapN ||
1320 xop == Op_ShenandoahCompareAndSwapN ||
1321 xop == Op_ShenandoahCompareAndSwapP;
1322 }
|
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26 #include "classfile/javaClasses.inline.hpp"
27 #include "gc/shared/barrierSet.hpp"
28 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
29 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
30 #include "gc/shenandoah/shenandoahForwarding.hpp"
31 #include "gc/shenandoah/shenandoahHeap.hpp"
32 #include "gc/shenandoah/shenandoahRuntime.hpp"
33 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
34 #include "opto/arraycopynode.hpp"
35 #include "opto/escape.hpp"
36 #include "opto/graphKit.hpp"
37 #include "opto/idealKit.hpp"
38 #include "opto/macro.hpp"
39 #include "opto/narrowptrnode.hpp"
40 #include "opto/output.hpp"
41 #include "opto/rootnode.hpp"
42 #include "opto/runtime.hpp"
43
44 ShenandoahBarrierSetC2* ShenandoahBarrierSetC2::bsc2() {
45 return reinterpret_cast<ShenandoahBarrierSetC2*>(BarrierSet::barrier_set()->barrier_set_c2());
46 }
47
48 ShenandoahBarrierSetC2State::ShenandoahBarrierSetC2State(Arena* comp_arena) :
49 BarrierSetC2State(comp_arena),
50 _stubs(new (comp_arena) GrowableArray<ShenandoahBarrierStubC2*>(comp_arena, 8, 0, nullptr)),
51 _stubs_start_offset(0) {
52 }
53
54 static void set_barrier_data(C2Access& access, bool load, bool store) {
55 if (!access.is_oop()) {
56 return;
57 }
58
59 DecoratorSet decorators = access.decorators();
60 bool tightly_coupled = (decorators & C2_TIGHTLY_COUPLED_ALLOC) != 0;
61 bool in_heap = (decorators & IN_HEAP) != 0;
62 bool on_weak = (decorators & ON_WEAK_OOP_REF) != 0;
63 bool on_phantom = (decorators & ON_PHANTOM_OOP_REF) != 0;
64
65 if (tightly_coupled) {
66 access.set_barrier_data(ShenandoahBitElided);
67 return;
68 }
69
70 uint8_t barrier_data = 0;
71
72 if (load) {
73 if (ShenandoahLoadRefBarrier) {
74 if (on_phantom) {
75 barrier_data |= ShenandoahBitPhantom;
76 } else if (on_weak) {
77 barrier_data |= ShenandoahBitWeak;
78 } else {
79 barrier_data |= ShenandoahBitStrong;
80 }
81 }
82 }
83
84 if (store) {
85 if (ShenandoahSATBBarrier) {
86 barrier_data |= ShenandoahBitKeepAlive;
87 }
88 if (ShenandoahCardBarrier && in_heap) {
89 barrier_data |= ShenandoahBitCardMark;
90 }
91 }
92
93 if (!in_heap) {
94 barrier_data |= ShenandoahBitNative;
95 }
96
97 access.set_barrier_data(barrier_data);
98 }
99
100 Node* ShenandoahBarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
101 // 1: Non-reference load, no additional barrier is needed
102 if (!access.is_oop()) {
103 return BarrierSetC2::load_at_resolved(access, val_type);
104 }
105
106 // 2. Set barrier data for load
107 set_barrier_data(access, /* load = */ true, /* store = */ false);
108
109 // 3. Correction: If we are reading the value of the referent field of
110 // a Reference object, we need to record the referent resurrection.
111 DecoratorSet decorators = access.decorators();
112 bool on_weak = (decorators & ON_WEAK_OOP_REF) != 0;
113 bool on_phantom = (decorators & ON_PHANTOM_OOP_REF) != 0;
114 bool no_keepalive = (decorators & AS_NO_KEEPALIVE) != 0;
115 bool needs_keepalive = ((on_weak || on_phantom) && !no_keepalive);
116 if (needs_keepalive) {
117 uint8_t barriers = access.barrier_data() | (ShenandoahSATBBarrier ? ShenandoahBitKeepAlive : 0);
118 access.set_barrier_data(barriers);
119 }
120
121 return BarrierSetC2::load_at_resolved(access, val_type);
122 }
123
124 Node* ShenandoahBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
125 // 1: Non-reference store, no additional barrier is needed
126 if (!access.is_oop()) {
127 return BarrierSetC2::store_at_resolved(access, val);
128 }
129
130 // 2. Set barrier data for store
131 set_barrier_data(access, /* load = */ false, /* store = */ true);
132
133 // 3. Correction: avoid keep-alive barriers that should not do keep-alive.
134 DecoratorSet decorators = access.decorators();
135 bool no_keepalive = (decorators & AS_NO_KEEPALIVE) != 0;
136 if (no_keepalive) {
137 access.set_barrier_data(access.barrier_data() & ~ShenandoahBitKeepAlive);
138 }
139
140 return BarrierSetC2::store_at_resolved(access, val);
141 }
142
143 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
144 Node* new_val, const Type* value_type) const {
145 set_barrier_data(access, /* load = */ true, /* store = */ true);
146 return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
147 }
148
149 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
150 Node* new_val, const Type* value_type) const {
151 set_barrier_data(access, /* load = */ true, /* store = */ true);
152 return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
153 }
154
155 Node* ShenandoahBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* val, const Type* value_type) const {
156 set_barrier_data(access, /* load = */ true, /* store = */ true);
157 return BarrierSetC2::atomic_xchg_at_resolved(access, val, value_type);
158 }
159
160 void ShenandoahBarrierSetC2::refine_store(const Node* n) {
161 MemNode* store = n->as_Store();
162 const Node* newval = n->in(MemNode::ValueIn);
163 assert(newval != nullptr, "");
164 const Type* newval_bottom = newval->bottom_type();
165 TypePtr::PTR newval_type = newval_bottom->make_ptr()->ptr();
166 uint8_t barrier_data = store->barrier_data();
167 if (!newval_bottom->isa_oopptr() &&
168 !newval_bottom->isa_narrowoop() &&
169 newval_type != TypePtr::Null) {
170 // newval is neither an OOP nor null, so there is no barrier to refine.
171 assert(barrier_data == 0, "non-OOP stores should have no barrier data");
172 return;
173 }
174 if (barrier_data == 0) {
175 // No barrier to refine.
176 return;
177 }
178 if (newval_type == TypePtr::Null) {
179 barrier_data &= ~ShenandoahBitNotNull;
180 // Simply elide post-barrier if writing null.
181 barrier_data &= ~ShenandoahBitCardMark;
182 } else if (newval_type == TypePtr::NotNull) {
183 barrier_data |= ShenandoahBitNotNull;
184 }
185 store->set_barrier_data(barrier_data);
186 }
187
188 bool ShenandoahBarrierSetC2::can_remove_load_barrier(Node* n) {
189 // Check if all outs feed into nodes that do not expose the oops to the rest
190 // of the runtime system. In this case, we can elide the LRB barrier. We bail
191 // out with false at the first sight of trouble.
192
193 ResourceMark rm;
194 VectorSet visited;
195 Node_List worklist;
196 worklist.push(n);
197
198 while (worklist.size() > 0) {
199 Node* n = worklist.pop();
200 if (visited.test_set(n->_idx)) {
201 continue;
202 }
203
204 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
205 Node* out = n->fast_out(i);
206 switch (out->Opcode()) {
207 case Op_CmpN: {
208 if (out->in(1) == n &&
209 out->in(2)->Opcode() == Op_ConN &&
210 out->in(2)->get_narrowcon() == 0) {
211 // Null check, no oop is exposed.
212 break;
213 } else {
214 return false;
215 }
216 }
217 case Op_CmpP: {
218 if (out->in(1) == n &&
219 out->in(2)->Opcode() == Op_ConP &&
220 out->in(2)->get_ptr() == 0) {
221 // Null check, no oop is exposed.
222 break;
223 } else {
224 return false;
225 }
226 }
227 case Op_DecodeN:
228 case Op_CastPP: {
229 // Check if any other outs are escaping.
230 worklist.push(out);
231 break;
232 }
233 case Op_CallStaticJava: {
234 if (out->as_CallStaticJava()->is_uncommon_trap()) {
235 // Local feeds into uncommon trap. Deopt machinery handles barriers itself.
236 break;
237 } else {
238 return false;
239 }
240 }
241
242 default: {
243 // Paranoidly distrust any other nodes.
244 // TODO: Check if there are other patterns that benefit from this elision.
245 return false;
246 }
247 }
248 }
249 }
250
251 // Nothing troublesome found.
252 return true;
253 }
254
255 void ShenandoahBarrierSetC2::refine_load(Node* n) {
256 MemNode* load = n->as_Load();
257
258 uint8_t barrier_data = load->barrier_data();
259
260 // Do not touch weak LRBs at all: they are responsible for shielding from
261 // Reference.referent resurrection.
262 if ((barrier_data & (ShenandoahBitWeak | ShenandoahBitPhantom)) != 0) {
263 return;
264 }
265
266 if (can_remove_load_barrier(n)) {
267 barrier_data &= ~ShenandoahBitStrong;
268 barrier_data |= ShenandoahBitElided;
269 }
270
271 load->set_barrier_data(barrier_data);
272 }
273
274 void ShenandoahBarrierSetC2::final_refinement(Compile* C) const {
275 ResourceMark rm;
276 VectorSet visited;
277 Node_List worklist;
278 worklist.push(C->root());
279 while (worklist.size() > 0) {
280 Node* n = worklist.pop();
281 if (visited.test_set(n->_idx)) {
282 continue;
283 }
284
285 // Do another pass to catch new opportunities after post-expansion optimizations.
286 switch(n->Opcode()) {
287 case Op_StoreP:
288 case Op_StoreN: {
289 refine_store(n);
290 break;
291 }
292 case Op_LoadN:
293 case Op_LoadP: {
294 refine_load(n);
295 break;
296 }
297 }
298
299 // If there are no real barrier flags on the node, strip away additional fluff.
300 // Matcher does not care about this, and we would like to avoid invoking "barrier_data() != 0"
301 // rules when the only flags are the irrelevant fluff.
302 if (n->is_LoadStore()) {
303 LoadStoreNode* load_store = n->as_LoadStore();
304 uint8_t barrier_data = load_store->barrier_data();
305 if ((barrier_data & ShenandoahBitsReal) == 0) {
306 load_store->set_barrier_data(0);
307 }
308 } else if (n->is_Mem()) {
309 MemNode* mem = n->as_Mem();
310 uint8_t barrier_data = mem->barrier_data();
311 if ((barrier_data & ShenandoahBitsReal) == 0) {
312 mem->set_barrier_data(0);
313 }
314 }
315
316 for (uint j = 0; j < n->req(); j++) {
317 Node* in = n->in(j);
318 if (in != nullptr) {
319 worklist.push(in);
320 }
321 }
322 }
323 }
324
325 bool ShenandoahBarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const {
326 ResourceMark rm;
327 VectorSet visited;
328 Node_List worklist;
329 worklist.push(C->root());
330 while (worklist.size() > 0) {
331 Node* n = worklist.pop();
332 if (visited.test_set(n->_idx)) {
333 continue;
334 }
335 switch(n->Opcode()) {
336 case Op_StoreP:
337 case Op_StoreN: {
338 refine_store(n);
339 break;
340 }
341 case Op_LoadN:
342 case Op_LoadP: {
343 refine_load(n);
344 break;
345 }
346 }
347
348 for (uint j = 0; j < n->req(); j++) {
349 Node* in = n->in(j);
350 if (in != nullptr) {
351 worklist.push(in);
352 }
353 }
354 }
355 return false;
356 }
357
358 // Support for macro expanded GC barriers
359 void ShenandoahBarrierSetC2::eliminate_gc_barrier_data(Node* node) const {
360 if (node->is_LoadStore()) {
361 LoadStoreNode* loadstore = node->as_LoadStore();
362 loadstore->set_barrier_data(0);
363 } else if (node->is_Mem()) {
364 MemNode* mem = node->as_Mem();
365 mem->set_barrier_data(0);
366 }
367 }
368
369 void ShenandoahBarrierSetC2::eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const {
370 eliminate_gc_barrier_data(node);
371 }
372
373 void ShenandoahBarrierSetC2::elide_dominated_barrier(MachNode* mach) const {
374 mach->set_barrier_data(0);
375 }
376
377 void ShenandoahBarrierSetC2::analyze_dominating_barriers() const {
378 ResourceMark rm;
379 Compile* const C = Compile::current();
380 PhaseCFG* const cfg = C->cfg();
381
382 Node_List loads, stores, atomics;
383 Node_List load_dominators, store_dominators, atomic_dominators;
384
385 for (uint i = 0; i < cfg->number_of_blocks(); ++i) {
386 const Block* const block = cfg->get_block(i);
387 for (uint j = 0; j < block->number_of_nodes(); ++j) {
388 Node* const node = block->get_node(j);
389
390 // Everything that happens in allocations does not need barriers.
391 if (node->is_Phi() && is_allocation(node)) {
392 load_dominators.push(node);
393 store_dominators.push(node);
394 atomic_dominators.push(node);
395 continue;
396 }
397
398 if (!node->is_Mach()) {
399 continue;
400 }
401
402 MachNode* const mach = node->as_Mach();
403 switch (mach->ideal_Opcode()) {
404
405 // Dominating loads have already passed through LRB and their load
406 // locations got fixed. Subsequent barriers are no longer required.
407 // The only exception are weak loads that have to go through LRB
408 // to deal with dying referents.
409 case Op_LoadP:
410 case Op_LoadN: {
411 if ((mach->barrier_data() & ShenandoahBitStrong) != 0) {
412 loads.push(mach);
413 load_dominators.push(mach);
414 }
415 break;
416 }
417
418 // Dominating stores have recorded the old value in SATB, and made the
419 // card table update for a location. Subsequent barriers are no longer
420 // required.
421 case Op_StoreP:
422 case Op_StoreN: {
423 if (mach->barrier_data() != 0) {
424 stores.push(mach);
425 load_dominators.push(mach);
426 store_dominators.push(mach);
427 atomic_dominators.push(mach);
428 }
429 break;
430 }
431
432 // Dominating atomics have dealt with false positives, and made the card
433 // table updates for a location. Even though CAS barriers are conditional,
434 // they perform all needed barriers when memory access is successful.
435 // Therefore, subsequent barriers are no longer required.
436 case Op_CompareAndExchangeN:
437 case Op_CompareAndExchangeP:
438 case Op_CompareAndSwapN:
439 case Op_CompareAndSwapP:
440 case Op_GetAndSetP:
441 case Op_GetAndSetN: {
442 if (mach->barrier_data() != 0) {
443 atomics.push(mach);
444 load_dominators.push(mach);
445 store_dominators.push(mach);
446 atomic_dominators.push(mach);
447 }
448 break;
449 }
450
451 default:
452 break;
453 }
454 }
455 }
456
457 elide_dominated_barriers(loads, load_dominators);
458 elide_dominated_barriers(stores, store_dominators);
459 elide_dominated_barriers(atomics, atomic_dominators);
460 }
461
462 uint ShenandoahBarrierSetC2::estimated_barrier_size(const Node* node) const {
463 uint8_t bd = MemNode::barrier_data(node);
464 assert(bd != 0, "Checked by caller");
465 if ((bd & ShenandoahBitElided) != 0) {
466 return 0;
467 }
468 // GC state check is ~4 fast-path nodes: Cmp, Bool, If, If-Proj.
469 return 4;
470 }
471
472 bool ShenandoahBarrierSetC2::array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, bool is_clone_instance, ArrayCopyPhase phase) const {
473 bool is_oop = is_reference_type(type);
474 if (!is_oop) {
475 return false;
476 }
477 if (ShenandoahSATBBarrier && tightly_coupled_alloc) {
478 if (phase == Optimization) {
479 return false;
480 }
481 return !is_clone;
482 }
483 return true;
484 }
485
486 bool ShenandoahBarrierSetC2::clone_needs_barrier(const TypeOopPtr* src_type, bool& is_oop_array) {
487 if (!ShenandoahCloneBarrier) {
488 return false;
489 }
490
491 if (src_type->isa_instptr() != nullptr) {
492 // Instance: need barrier only if there is a possibility of having an oop anywhere in it.
493 ciInstanceKlass* ik = src_type->is_instptr()->instance_klass();
494 if ((src_type->klass_is_exact() || !ik->has_subklass()) &&
495 !ik->has_injected_fields() && !ik->has_object_fields()) {
496 if (!src_type->klass_is_exact()) {
497 // Class is *currently* the leaf in the hierarchy.
498 // Record the dependency so that we deopt if this does not hold in future.
499 Compile::current()->dependencies()->assert_leaf_type(ik);
500 }
501 return false;
502 }
503 } else if (src_type->isa_aryptr() != nullptr) {
504 // Array: need barrier only if array is oop-bearing.
505 BasicType src_elem = src_type->isa_aryptr()->elem()->array_element_basic_type();
506 if (is_reference_type(src_elem, true)) {
507 is_oop_array = true;
508 } else {
509 return false;
510 }
511 }
512
513 // Assume the worst.
514 return true;
515 }
516
517 void ShenandoahBarrierSetC2::clone(GraphKit* kit, Node* src_base, Node* dst_base, Node* size, bool is_array) const {
518 const TypeOopPtr* src_type = kit->gvn().type(src_base)->is_oopptr();
519
520 bool is_oop_array = false;
521 if (!clone_needs_barrier(src_type, is_oop_array)) {
522 // No barrier is needed? Just do what common BarrierSetC2 wants with it.
523 BarrierSetC2::clone(kit, src_base, dst_base, size, is_array);
524 return;
525 }
526
527 if (ShenandoahCloneRuntime || !is_array || !is_oop_array) {
528 // Looks like an instance? Prepare the instance clone. This would either
529 // be exploded into individual accesses or be left as runtime call.
530 // Common BarrierSetC2 prepares everything for both cases.
531 BarrierSetC2::clone(kit, src_base, dst_base, size, is_array);
532 return;
533 }
534
535 // We are cloning the oop array. Prepare to call the normal arraycopy stub
536 // after the expansion. Normal stub takes the number of actual type-sized
537 // elements to copy after the base, compute the count here.
538 Node* offset = kit->MakeConX(arrayOopDesc::base_offset_in_bytes(UseCompressedOops ? T_NARROWOOP : T_OBJECT));
539 size = kit->gvn().transform(new SubXNode(size, offset));
540 size = kit->gvn().transform(new URShiftXNode(size, kit->intcon(LogBytesPerHeapOop)));
541 ArrayCopyNode* ac = ArrayCopyNode::make(kit, false, src_base, offset, dst_base, offset, size, true, false);
542 ac->set_clone_array();
543 Node* n = kit->gvn().transform(ac);
544 if (n == ac) {
545 ac->set_adr_type(TypeRawPtr::BOTTOM);
546 kit->set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), TypeRawPtr::BOTTOM);
547 } else {
548 kit->set_all_memory(n);
549 }
550 }
551
552 void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
553 Node* const ctrl = ac->in(TypeFunc::Control);
554 Node* const mem = ac->in(TypeFunc::Memory);
555 Node* const src = ac->in(ArrayCopyNode::Src);
556 Node* const src_offset = ac->in(ArrayCopyNode::SrcPos);
557 Node* const dest = ac->in(ArrayCopyNode::Dest);
558 Node* const dest_offset = ac->in(ArrayCopyNode::DestPos);
559 Node* length = ac->in(ArrayCopyNode::Length);
560
561 const TypeOopPtr* src_type = phase->igvn().type(src)->is_oopptr();
562
563 bool is_oop_array = false;
564 if (!clone_needs_barrier(src_type, is_oop_array)) {
565 // No barrier is needed? Expand to normal HeapWord-sized arraycopy.
566 BarrierSetC2::clone_at_expansion(phase, ac);
567 return;
568 }
569
570 if (ShenandoahCloneRuntime || !ac->is_clone_array() || !is_oop_array) {
571 // Still looks like an instance? Likely a large instance or reflective
572 // clone with unknown length. Go to runtime and handle it there.
573 clone_in_runtime(phase, ac, CAST_FROM_FN_PTR(address, ShenandoahRuntime::clone_addr()), "ShenandoahRuntime::clone");
574 return;
575 }
576
577 // We are cloning the oop array. Call into normal oop array copy stubs.
578 // Those stubs would call BarrierSetAssembler to handle GC barriers.
579
580 // This is the full clone, so offsets should equal each other and be at array base.
581 assert(src_offset == dest_offset, "should be equal");
582 const jlong offset = src_offset->get_long();
583 const TypeAryPtr* const ary_ptr = src->get_ptr_type()->isa_aryptr();
584 BasicType bt = ary_ptr->elem()->array_element_basic_type();
585 assert(offset == arrayOopDesc::base_offset_in_bytes(bt), "should match");
586
587 const char* copyfunc_name = "arraycopy";
588 const address copyfunc_addr = phase->basictype2arraycopy(T_OBJECT, nullptr, nullptr, true, copyfunc_name, true);
589
590 Node* const call = phase->make_leaf_call(ctrl, mem,
591 OptoRuntime::fast_arraycopy_Type(),
592 copyfunc_addr, copyfunc_name,
593 TypeRawPtr::BOTTOM,
594 phase->basic_plus_adr(src, src_offset),
595 phase->basic_plus_adr(dest, dest_offset),
596 length,
597 phase->top()
598 );
599 phase->transform_later(call);
600
601 phase->igvn().replace_node(ac, call);
602 }
603
604 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
605 return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
606 }
607
608 ShenandoahBarrierSetC2State* ShenandoahBarrierSetC2::state() const {
609 return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());
610 }
611
612 void ShenandoahBarrierSetC2::print_barrier_data(outputStream* os, uint8_t data) {
613 os->print(" Node barriers: ");
614 if ((data & ShenandoahBitStrong) != 0) {
615 data &= ~ShenandoahBitStrong;
616 os->print("strong ");
617 }
618
619 if ((data & ShenandoahBitWeak) != 0) {
620 data &= ~ShenandoahBitWeak;
621 os->print("weak ");
622 }
623
624 if ((data & ShenandoahBitPhantom) != 0) {
625 data &= ~ShenandoahBitPhantom;
626 os->print("phantom ");
627 }
628
629 if ((data & ShenandoahBitElided) != 0) {
630 data &= ~ShenandoahBitElided;
631 os->print("elided ");
632 }
633
634 if ((data & ShenandoahBitKeepAlive) != 0) {
635 data &= ~ShenandoahBitKeepAlive;
636 os->print("keepalive ");
637 }
638
639 if ((data & ShenandoahBitCardMark) != 0) {
640 data &= ~ShenandoahBitCardMark;
641 os->print("cardmark ");
642 }
643
644 if ((data & ShenandoahBitNotNull) != 0) {
645 data &= ~ShenandoahBitNotNull;
646 os->print("not-null ");
647 }
648 os->cr();
649
650 if (data > 0) {
651 fatal("Unknown bit!");
652 }
653
654 os->print_cr(" GC configuration: %sLRB %sSATB %sCAS %sClone %sCard",
655 (ShenandoahLoadRefBarrier ? "+" : "-"),
656 (ShenandoahSATBBarrier ? "+" : "-"),
657 (ShenandoahCASBarrier ? "+" : "-"),
658 (ShenandoahCloneBarrier ? "+" : "-"),
659 (ShenandoahCardBarrier ? "+" : "-")
660 );
661 }
662
663 #ifdef ASSERT
664 void ShenandoahBarrierSetC2::verify_gc_barrier_assert(bool cond, const char* msg, uint8_t bd, Node* n) {
665 if (!cond) {
666 stringStream ss;
667 ss.print_cr("%s", msg);
668 ss.print_cr("-----------------");
669 print_barrier_data(&ss, bd);
670 ss.print_cr("-----------------");
671 n->dump_bfs(1, nullptr, "", &ss);
672 report_vm_error(__FILE__, __LINE__, ss.as_string());
673 }
674 }
675
676 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
677 if (!ShenandoahVerifyOptoBarriers) {
678 return;
679 }
680
681 // Final refinement might have removed the remaining auxiliary flags, making some accesses completely blank.
682 bool accept_blank = (phase == BeforeCodeGen);
683 bool expect_load_barriers = !accept_blank && ShenandoahLoadRefBarrier;
684 bool expect_store_barriers = !accept_blank && (ShenandoahSATBBarrier || ShenandoahCardBarrier);
685 bool expect_load_store_barriers = !accept_blank && ShenandoahCASBarrier;
686
687 Unique_Node_List wq;
688 Node_Stack phis(0);
689 VectorSet visited;
690
691 wq.push(compile->root());
692 for (uint next = 0; next < wq.size(); next++) {
693 Node *n = wq.at(next);
694 int opc = n->Opcode();
695
696 if (opc == Op_LoadP || opc == Op_LoadN) {
697 uint8_t bd = n->as_Load()->barrier_data();
698
699 const TypePtr* adr_type = n->as_Load()->adr_type();
700 if (adr_type->isa_oopptr() || adr_type->isa_narrowoop()) {
701 verify_gc_barrier_assert(!expect_load_barriers || (bd != 0), "Oop load should have barrier data", bd, n);
702
703 bool is_weak = ((bd & (ShenandoahBitWeak | ShenandoahBitPhantom)) != 0);
704 bool is_referent = adr_type->isa_instptr() &&
705 adr_type->is_instptr()->instance_klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) &&
706 adr_type->is_instptr()->offset() == java_lang_ref_Reference::referent_offset();
707
708 verify_gc_barrier_assert(!is_weak || is_referent, "Weak load only for Reference.referent", bd, n);
709 } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
710 // Some LoadP-s are used for T_ADDRESS loads from raw pointers. These are not oops.
711 // Some LoadP-s are used to load class data.
712 // TODO: Verify their barrier data.
713 } else {
714 verify_gc_barrier_assert(false, "Unclassified access type", bd, n);
715 }
716 } else if (opc == Op_StoreP || opc == Op_StoreN) {
717 uint8_t bd = n->as_Store()->barrier_data();
718 const TypePtr* adr_type = n->as_Store()->adr_type();
719 if (adr_type->isa_oopptr() || adr_type->isa_narrowoop()) {
720 // Reference.clear stores null
721 bool is_referent = adr_type->isa_instptr() &&
722 adr_type->is_instptr()->instance_klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) &&
723 adr_type->is_instptr()->offset() == java_lang_ref_Reference::referent_offset();
724
725 const TypePtr* val_type = n->as_Store()->in(MemNode::Memory)->adr_type();
726 if (!is_referent && (val_type->isa_oopptr() || val_type->isa_narrowoop())) {
727 verify_gc_barrier_assert(!expect_store_barriers || (bd != 0), "Oop store should have barrier data", bd, n);
728 }
729 } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
730 // Similar to LoadP-s, some of these accesses are raw, and some are handling oops.
731 // TODO: Verify their barrier data.
732 } else {
733 verify_gc_barrier_assert(false, "Unclassified access type", bd, n);
734 }
735 } else if (opc == Op_WeakCompareAndSwapP || opc == Op_WeakCompareAndSwapN ||
736 opc == Op_CompareAndExchangeP || opc == Op_CompareAndExchangeN ||
737 opc == Op_CompareAndSwapP || opc == Op_CompareAndSwapN ||
738 opc == Op_GetAndSetP || opc == Op_GetAndSetN) {
739 uint8_t bd = n->as_LoadStore()->barrier_data();
740 verify_gc_barrier_assert(!expect_load_store_barriers || (bd != 0), "Oop load-store should have barrier data", bd, n);
741 } else if (n->is_Mem()) {
742 uint8_t bd = MemNode::barrier_data(n); // FIXME: LOL HotSpot, why not n->as_Mem()? LoadStore is both is_Mem() and not as_Mem().
743 verify_gc_barrier_assert(bd == 0, "Other mem nodes should have no barrier data", bd, n);
744 }
745
746 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
747 Node* m = n->fast_out(i);
748 wq.push(m);
749 }
750 }
751 }
752 #endif
753
754 static ShenandoahBarrierSetC2State* barrier_set_state() {
755 return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());
756 }
757
758 int ShenandoahBarrierSetC2::estimate_stub_size() const {
759 GrowableArray<ShenandoahBarrierStubC2*>* const stubs = barrier_set_state()->stubs();
760 assert(stubs->is_empty(), "Lifecycle: no stubs were yet created");
761 return 0;
762 }
763
764 void ShenandoahBarrierSetC2::emit_stubs(CodeBuffer& cb) const {
765 MacroAssembler masm(&cb);
766 GrowableArray<ShenandoahBarrierStubC2*>* const stubs = barrier_set_state()->stubs();
767 barrier_set_state()->set_stubs_start_offset(masm.offset());
768
769 // Stub generation uses nested skipped counters that can double-count.
770 // Calculate the actual skipped amount by the real PC before/after stub generation.
771 // FIXME: This should be handled upstream.
772 int offset_before = masm.offset();
773 int skipped_before = masm.get_skipped();
774
775 for (int i = 0; i < stubs->length(); i++) {
776 // Make sure there is enough space in the code buffer
777 if (cb.insts()->maybe_expand_to_ensure_remaining(PhaseOutput::MAX_inst_size) && cb.blob() == nullptr) {
778 ciEnv::current()->record_failure("CodeCache is full");
779 return;
780 }
781
782 stubs->at(i)->emit_code(masm);
783 }
784
785 int offset_after = masm.offset();
786
787 // The real stubs section is coming up after this, so we have to account for alignment
788 // padding there. See CodeSection::alignment().
789 offset_after = align_up(offset_after, HeapWordSize);
790
791 masm.set_skipped(skipped_before + (offset_after - offset_before));
792
793 masm.flush();
794 }
795
796 void ShenandoahBarrierStubC2::register_stub() {
797 if (!Compile::current()->output()->in_scratch_emit_size()) {
798 barrier_set_state()->stubs()->append(this);
799 }
800 }
801
802 ShenandoahLoadBarrierStubC2* ShenandoahLoadBarrierStubC2::create(const MachNode* node, Register dst, Address src) {
803 auto* stub = new (Compile::current()->comp_arena()) ShenandoahLoadBarrierStubC2(node, dst, noreg, src);
804 stub->register_stub();
805 return stub;
806 }
807
808 ShenandoahLoadBarrierStubC2* ShenandoahLoadBarrierStubC2::create(const MachNode* node, Register dst, Register addr) {
809 auto* stub = new (Compile::current()->comp_arena()) ShenandoahLoadBarrierStubC2(node, dst, addr, Address());
810 stub->register_stub();
811 return stub;
812 }
813
814 ShenandoahStoreBarrierStubC2* ShenandoahStoreBarrierStubC2::create(const MachNode* node, Address dst, bool dst_narrow, Register src, bool src_narrow, Register tmp) {
815 auto* stub = new (Compile::current()->comp_arena()) ShenandoahStoreBarrierStubC2(node, noreg, dst, dst_narrow, src, src_narrow, tmp);
816 stub->register_stub();
817 return stub;
818 }
819
820 ShenandoahStoreBarrierStubC2* ShenandoahStoreBarrierStubC2::create(const MachNode* node, Register addr, bool dst_narrow) {
821 auto* stub = new (Compile::current()->comp_arena()) ShenandoahStoreBarrierStubC2(node, addr, Address(), dst_narrow, noreg, false, noreg);
822 stub->register_stub();
823 return stub;
824 }
825
826 ShenandoahCASBarrierStubC2* ShenandoahCASBarrierStubC2::create(const MachNode* node, Register addr, Register expected, Register new_val, Register result, bool narrow, bool cae, bool maybe_null, bool acquire, bool release, bool weak) {
827 auto* stub = new (Compile::current()->comp_arena()) ShenandoahCASBarrierStubC2(node, addr, Address(), expected, new_val, result, noreg, noreg, narrow, cae, maybe_null, acquire, release, weak);
828 stub->register_stub();
829 return stub;
830 }
831
832 ShenandoahCASBarrierStubC2* ShenandoahCASBarrierStubC2::create(const MachNode* node, Address addr, Register expected, Register new_val, Register result, Register tmp1, Register tmp2, bool narrow, bool cae) {
833 auto* stub = new (Compile::current()->comp_arena()) ShenandoahCASBarrierStubC2(node, noreg, addr, expected, new_val, result, tmp1, tmp2, narrow, cae, true, false, false, false);
834 stub->register_stub();
835 return stub;
836 }
837
838 bool ShenandoahBarrierSetC2State::needs_liveness_data(const MachNode* mach) const {
839 // Must ask all stubs!
840 return ShenandoahLoadBarrierStubC2::needs_barrier(mach) ||
841 ShenandoahStoreBarrierStubC2::needs_barrier(mach) ||
842 ShenandoahCASBarrierStubC2::needs_barrier(mach);
843 }
844
845 bool ShenandoahBarrierSetC2State::needs_livein_data() const {
846 return true;
847 }
|