1 /*
  2  * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2014, Red Hat Inc. All rights reserved.
  4  * Copyright (c) 2020, 2022, Huawei Technologies Co., Ltd. All rights reserved.
  5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  6  *
  7  * This code is free software; you can redistribute it and/or modify it
  8  * under the terms of the GNU General Public License version 2 only, as
  9  * published by the Free Software Foundation.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  *
 25  */
 26 
 27 #include "precompiled.hpp"
 28 #include "c1/c1_LIR.hpp"
 29 #include "c1/c1_MacroAssembler.hpp"
 30 #include "c1/c1_Runtime1.hpp"
 31 #include "classfile/systemDictionary.hpp"
 32 #include "gc/shared/barrierSetAssembler.hpp"
 33 #include "gc/shared/collectedHeap.hpp"
 34 #include "interpreter/interpreter.hpp"
 35 #include "oops/arrayOop.hpp"
 36 #include "oops/markWord.hpp"
 37 #include "runtime/basicLock.hpp"
 38 #include "runtime/os.hpp"
 39 #include "runtime/sharedRuntime.hpp"
 40 #include "runtime/stubRoutines.hpp"
 41 
 42 void C1_MacroAssembler::float_cmp(bool is_float, int unordered_result,
 43                                   FloatRegister freg0, FloatRegister freg1,
 44                                   Register result) {
 45   if (is_float) {
 46     float_compare(result, freg0, freg1, unordered_result);
 47   } else {
 48     double_compare(result, freg0, freg1, unordered_result);
 49   }
 50 }
 51 
 52 int C1_MacroAssembler::lock_object(Register hdr, Register obj, Register disp_hdr, Register temp, Label& slow_case) {
 53   const int aligned_mask = BytesPerWord - 1;
 54   const int hdr_offset = oopDesc::mark_offset_in_bytes();
 55   assert_different_registers(hdr, obj, disp_hdr, temp, t0, t1);
 56   int null_check_offset = -1;
 57 
 58   verify_oop(obj);
 59 
 60   // save object being locked into the BasicObjectLock
 61   sd(obj, Address(disp_hdr, BasicObjectLock::obj_offset()));
 62 
 63   null_check_offset = offset();
 64 
 65   if (DiagnoseSyncOnValueBasedClasses != 0) {
 66     load_klass(hdr, obj);
 67     lbu(hdr, Address(hdr, Klass::misc_flags_offset()));
 68     test_bit(temp, hdr, exact_log2(KlassFlags::_misc_is_value_based_class));
 69     bnez(temp, slow_case, true /* is_far */);
 70   }
 71 
 72   if (LockingMode == LM_LIGHTWEIGHT) {
 73     lightweight_lock(disp_hdr, obj, hdr, temp, t1, slow_case);
 74   } else if (LockingMode == LM_LEGACY) {
 75     Label done;
 76     // Load object header
 77     ld(hdr, Address(obj, hdr_offset));
 78     // and mark it as unlocked
 79     ori(hdr, hdr, markWord::unlocked_value);
 80     // save unlocked object header into the displaced header location on the stack
 81     sd(hdr, Address(disp_hdr, 0));
 82     // test if object header is still the same (i.e. unlocked), and if so, store the
 83     // displaced header address in the object header - if it is not the same, get the
 84     // object header instead
 85     la(temp, Address(obj, hdr_offset));
 86     // if the object header was the same, we're done
 87     cmpxchgptr(hdr, disp_hdr, temp, t1, done, /*fallthough*/nullptr);
 88     // if the object header was not the same, it is now in the hdr register
 89     // => test if it is a stack pointer into the same stack (recursive locking), i.e.:
 90     //
 91     // 1) (hdr & aligned_mask) == 0
 92     // 2) sp <= hdr
 93     // 3) hdr <= sp + page_size
 94     //
 95     // these 3 tests can be done by evaluating the following expression:
 96     //
 97     // (hdr -sp) & (aligned_mask - page_size)
 98     //
 99     // assuming both the stack pointer and page_size have their least
100     // significant 2 bits cleared and page_size is a power of 2
101     sub(hdr, hdr, sp);
102     mv(temp, aligned_mask - (int)os::vm_page_size());
103     andr(hdr, hdr, temp);
104     // for recursive locking, the result is zero => save it in the displaced header
105     // location (null in the displaced hdr location indicates recursive locking)
106     sd(hdr, Address(disp_hdr, 0));
107     // otherwise we don't care about the result and handle locking via runtime call
108     bnez(hdr, slow_case, /* is_far */ true);
109 
110     // done
111     bind(done);
112     inc_held_monitor_count();
113   }
114 
115   return null_check_offset;
116 }
117 
118 void C1_MacroAssembler::unlock_object(Register hdr, Register obj, Register disp_hdr, Register temp, Label& slow_case) {
119   const int aligned_mask = BytesPerWord - 1;
120   const int hdr_offset = oopDesc::mark_offset_in_bytes();
121   assert_different_registers(hdr, obj, disp_hdr, temp, t0, t1);
122   Label done;
123 
124   if (LockingMode != LM_LIGHTWEIGHT) {
125     // load displaced header
126     ld(hdr, Address(disp_hdr, 0));
127     // if the loaded hdr is null we had recursive locking
128     // if we had recursive locking, we are done
129     beqz(hdr, done);
130   }
131 
132   // load object
133   ld(obj, Address(disp_hdr, BasicObjectLock::obj_offset()));
134   verify_oop(obj);
135 
136   if (LockingMode == LM_LIGHTWEIGHT) {
137     lightweight_unlock(obj, hdr, temp, t1, slow_case);
138   } else if (LockingMode == LM_LEGACY) {
139     // test if object header is pointing to the displaced header, and if so, restore
140     // the displaced header in the object - if the object header is not pointing to
141     // the displaced header, get the object header instead
142     // if the object header was not pointing to the displaced header,
143     // we do unlocking via runtime call
144     if (hdr_offset) {
145       la(temp, Address(obj, hdr_offset));
146       cmpxchgptr(disp_hdr, hdr, temp, t1, done, &slow_case);
147     } else {
148       cmpxchgptr(disp_hdr, hdr, obj, t1, done, &slow_case);
149     }
150 
151     // done
152     bind(done);
153     dec_held_monitor_count();
154   }
155 }
156 
157 // Defines obj, preserves var_size_in_bytes
158 void C1_MacroAssembler::try_allocate(Register obj, Register var_size_in_bytes, int con_size_in_bytes, Register tmp1, Register tmp2, Label& slow_case) {
159   if (UseTLAB) {
160     tlab_allocate(obj, var_size_in_bytes, con_size_in_bytes, tmp1, tmp2, slow_case, /* is_far */ true);
161   } else {
162     j(slow_case);
163   }
164 }
165 
166 void C1_MacroAssembler::initialize_header(Register obj, Register klass, Register len, Register tmp1, Register tmp2) {
167   assert_different_registers(obj, klass, len, tmp1, tmp2);
168   // This assumes that all prototype bits fitr in an int32_t
169   mv(tmp1, (int32_t)(intptr_t)markWord::prototype().value());
170   sd(tmp1, Address(obj, oopDesc::mark_offset_in_bytes()));
171 
172   if (UseCompressedClassPointers) { // Take care not to kill klass
173     encode_klass_not_null(tmp1, klass, tmp2);
174     sw(tmp1, Address(obj, oopDesc::klass_offset_in_bytes()));
175   } else {
176     sd(klass, Address(obj, oopDesc::klass_offset_in_bytes()));
177   }
178 
179   if (len->is_valid()) {
180     sw(len, Address(obj, arrayOopDesc::length_offset_in_bytes()));
181     int base_offset = arrayOopDesc::length_offset_in_bytes() + BytesPerInt;
182     if (!is_aligned(base_offset, BytesPerWord)) {
183       assert(is_aligned(base_offset, BytesPerInt), "must be 4-byte aligned");
184       // Clear gap/first 4 bytes following the length field.
185       sw(zr, Address(obj, base_offset));
186     }
187   } else if (UseCompressedClassPointers) {
188     store_klass_gap(obj, zr);
189   }
190 }
191 
192 // preserves obj, destroys len_in_bytes
193 void C1_MacroAssembler::initialize_body(Register obj, Register len_in_bytes, int hdr_size_in_bytes, Register tmp) {
194   assert(hdr_size_in_bytes >= 0, "header size must be positive or 0");
195   Label done;
196 
197   // len_in_bytes is positive and ptr sized
198   sub(len_in_bytes, len_in_bytes, hdr_size_in_bytes);
199   beqz(len_in_bytes, done);
200 
201   // Preserve obj
202   if (hdr_size_in_bytes) {
203     add(obj, obj, hdr_size_in_bytes);
204   }
205   zero_memory(obj, len_in_bytes, tmp);
206   if (hdr_size_in_bytes) {
207     sub(obj, obj, hdr_size_in_bytes);
208   }
209 
210   bind(done);
211 }
212 
213 void C1_MacroAssembler::allocate_object(Register obj, Register tmp1, Register tmp2, int header_size, int object_size, Register klass, Label& slow_case) {
214   assert_different_registers(obj, tmp1, tmp2);
215   assert(header_size >= 0 && object_size >= header_size, "illegal sizes");
216 
217   try_allocate(obj, noreg, object_size * BytesPerWord, tmp1, tmp2, slow_case);
218 
219   initialize_object(obj, klass, noreg, object_size * HeapWordSize, tmp1, tmp2, UseTLAB);
220 }
221 
222 void C1_MacroAssembler::initialize_object(Register obj, Register klass, Register var_size_in_bytes, int con_size_in_bytes, Register tmp1, Register tmp2, bool is_tlab_allocated) {
223   assert((con_size_in_bytes & MinObjAlignmentInBytesMask) == 0,
224          "con_size_in_bytes is not multiple of alignment");
225   const int hdr_size_in_bytes = instanceOopDesc::header_size() * HeapWordSize;
226 
227   initialize_header(obj, klass, noreg, tmp1, tmp2);
228 
229   if (!(UseTLAB && ZeroTLAB && is_tlab_allocated)) {
230     // clear rest of allocated space
231     const Register index = tmp2;
232     // 16: multiplier for threshold
233     const int threshold = 16 * BytesPerWord;    // approximate break even point for code size (see comments below)
234     if (var_size_in_bytes != noreg) {
235       mv(index, var_size_in_bytes);
236       initialize_body(obj, index, hdr_size_in_bytes, tmp1);
237     } else if (con_size_in_bytes <= threshold) {
238       // use explicit null stores
239       int i = hdr_size_in_bytes;
240       if (i < con_size_in_bytes && (con_size_in_bytes % (2 * BytesPerWord))) { // 2: multiplier for BytesPerWord
241         sd(zr, Address(obj, i));
242         i += BytesPerWord;
243       }
244       for (; i < con_size_in_bytes; i += BytesPerWord) {
245         sd(zr, Address(obj, i));
246       }
247     } else if (con_size_in_bytes > hdr_size_in_bytes) {
248       block_comment("zero memory");
249       // use loop to null out the fields
250       int words = (con_size_in_bytes - hdr_size_in_bytes) / BytesPerWord;
251       mv(index, words / 8); // 8: byte size
252 
253       const int unroll = 8; // Number of sd(zr) instructions we'll unroll
254       int remainder = words % unroll;
255       la(t0, Address(obj, hdr_size_in_bytes + remainder * BytesPerWord));
256 
257       Label entry_point, loop;
258       j(entry_point);
259 
260       bind(loop);
261       sub(index, index, 1);
262       for (int i = -unroll; i < 0; i++) {
263         if (-i == remainder) {
264           bind(entry_point);
265         }
266         sd(zr, Address(t0, i * wordSize));
267       }
268       if (remainder == 0) {
269         bind(entry_point);
270       }
271       add(t0, t0, unroll * wordSize);
272       bnez(index, loop);
273     }
274   }
275 
276   membar(MacroAssembler::StoreStore);
277 
278   if (CURRENT_ENV->dtrace_alloc_probes()) {
279     assert(obj == x10, "must be");
280     far_call(RuntimeAddress(Runtime1::entry_for(C1StubId::dtrace_object_alloc_id)));
281   }
282 
283   verify_oop(obj);
284 }
285 
286 void C1_MacroAssembler::allocate_array(Register obj, Register len, Register tmp1, Register tmp2, int base_offset_in_bytes, int f, Register klass, Label& slow_case, bool zero_array) {
287   assert_different_registers(obj, len, tmp1, tmp2, klass);
288 
289   // determine alignment mask
290   assert(!(BytesPerWord & 1), "must be multiple of 2 for masking code to work");
291 
292   // check for negative or excessive length
293   mv(t0, (int32_t)max_array_allocation_length);
294   bgeu(len, t0, slow_case, /* is_far */ true);
295 
296   const Register arr_size = tmp2; // okay to be the same
297   // align object end
298   mv(arr_size, (int32_t)base_offset_in_bytes + MinObjAlignmentInBytesMask);
299   shadd(arr_size, len, arr_size, t0, f);
300   andi(arr_size, arr_size, ~(uint)MinObjAlignmentInBytesMask);
301 
302   try_allocate(obj, arr_size, 0, tmp1, tmp2, slow_case);
303 
304   initialize_header(obj, klass, len, tmp1, tmp2);
305 
306   // Align-up to word boundary, because we clear the 4 bytes potentially
307   // following the length field in initialize_header().
308   int base_offset = align_up(base_offset_in_bytes, BytesPerWord);
309 
310   // clear rest of allocated space
311   const Register len_zero = len;
312   if (zero_array) {
313     initialize_body(obj, arr_size, base_offset, len_zero);
314   }
315 
316   membar(MacroAssembler::StoreStore);
317 
318   if (CURRENT_ENV->dtrace_alloc_probes()) {
319     assert(obj == x10, "must be");
320     far_call(RuntimeAddress(Runtime1::entry_for(C1StubId::dtrace_object_alloc_id)));
321   }
322 
323   verify_oop(obj);
324 }
325 
326 void C1_MacroAssembler::build_frame(int framesize, int bang_size_in_bytes) {
327   assert(bang_size_in_bytes >= framesize, "stack bang size incorrect");
328   // Make sure there is enough stack space for this method's activation.
329   // Note that we do this before creating a frame.
330   generate_stack_overflow_check(bang_size_in_bytes);
331   MacroAssembler::build_frame(framesize);
332 
333   // Insert nmethod entry barrier into frame.
334   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
335   bs->nmethod_entry_barrier(this, nullptr /* slow_path */, nullptr /* continuation */, nullptr /* guard */);
336 }
337 
338 void C1_MacroAssembler::remove_frame(int framesize) {
339   MacroAssembler::remove_frame(framesize);
340 }
341 
342 
343 void C1_MacroAssembler::verified_entry(bool breakAtEntry) {
344   // If we have to make this method not-entrant we'll overwrite its
345   // first instruction with a jump. For this action to be legal we
346   // must ensure that this first instruction is a J, JAL or NOP.
347   // Make it a NOP.
348   IncompressibleRegion ir(this);  // keep the nop as 4 bytes for patching.
349   assert_alignment(pc());
350   nop();  // 4 bytes
351 }
352 
353 void C1_MacroAssembler::load_parameter(int offset_in_words, Register reg) {
354   //  fp + -2: link
355   //     + -1: return address
356   //     +  0: argument with offset 0
357   //     +  1: argument with offset 1
358   //     +  2: ...
359   ld(reg, Address(fp, offset_in_words * BytesPerWord));
360 }
361 
362 #ifndef PRODUCT
363 
364 void C1_MacroAssembler::verify_stack_oop(int stack_offset) {
365   if (!VerifyOops) {
366     return;
367   }
368   verify_oop_addr(Address(sp, stack_offset));
369 }
370 
371 void C1_MacroAssembler::verify_not_null_oop(Register r) {
372   if (!VerifyOops) return;
373   Label not_null;
374   bnez(r, not_null);
375   stop("non-null oop required");
376   bind(not_null);
377   verify_oop(r);
378 }
379 
380 void C1_MacroAssembler::invalidate_registers(bool inv_x10, bool inv_x9, bool inv_x12, bool inv_x13, bool inv_x14, bool inv_x15) {
381 #ifdef ASSERT
382   static int nn;
383   if (inv_x10) { mv(x10, 0xDEAD); }
384   if (inv_x9)  { mv(x9, 0xDEAD);  }
385   if (inv_x12) { mv(x12, nn++);   }
386   if (inv_x13) { mv(x13, 0xDEAD); }
387   if (inv_x14) { mv(x14, 0xDEAD); }
388   if (inv_x15) { mv(x15, 0xDEAD); }
389 #endif // ASSERT
390 }
391 #endif // ifndef PRODUCT
392 
393 typedef void (C1_MacroAssembler::*c1_cond_branch_insn)(Register op1, Register op2, Label& label, bool is_far);
394 typedef void (C1_MacroAssembler::*c1_float_cond_branch_insn)(FloatRegister op1, FloatRegister op2,
395               Label& label, bool is_far, bool is_unordered);
396 
397 static c1_cond_branch_insn c1_cond_branch[] =
398 {
399   /* SHORT branches */
400   (c1_cond_branch_insn)&MacroAssembler::beq,
401   (c1_cond_branch_insn)&MacroAssembler::bne,
402   (c1_cond_branch_insn)&MacroAssembler::blt,
403   (c1_cond_branch_insn)&MacroAssembler::ble,
404   (c1_cond_branch_insn)&MacroAssembler::bge,
405   (c1_cond_branch_insn)&MacroAssembler::bgt,
406   (c1_cond_branch_insn)&MacroAssembler::bleu, // lir_cond_belowEqual
407   (c1_cond_branch_insn)&MacroAssembler::bgeu  // lir_cond_aboveEqual
408 };
409 
410 static c1_float_cond_branch_insn c1_float_cond_branch[] =
411 {
412   /* FLOAT branches */
413   (c1_float_cond_branch_insn)&MacroAssembler::float_beq,
414   (c1_float_cond_branch_insn)&MacroAssembler::float_bne,
415   (c1_float_cond_branch_insn)&MacroAssembler::float_blt,
416   (c1_float_cond_branch_insn)&MacroAssembler::float_ble,
417   (c1_float_cond_branch_insn)&MacroAssembler::float_bge,
418   (c1_float_cond_branch_insn)&MacroAssembler::float_bgt,
419   nullptr, // lir_cond_belowEqual
420   nullptr, // lir_cond_aboveEqual
421 
422   /* DOUBLE branches */
423   (c1_float_cond_branch_insn)&MacroAssembler::double_beq,
424   (c1_float_cond_branch_insn)&MacroAssembler::double_bne,
425   (c1_float_cond_branch_insn)&MacroAssembler::double_blt,
426   (c1_float_cond_branch_insn)&MacroAssembler::double_ble,
427   (c1_float_cond_branch_insn)&MacroAssembler::double_bge,
428   (c1_float_cond_branch_insn)&MacroAssembler::double_bgt,
429   nullptr, // lir_cond_belowEqual
430   nullptr  // lir_cond_aboveEqual
431 };
432 
433 void C1_MacroAssembler::c1_cmp_branch(int cmpFlag, Register op1, Register op2, Label& label,
434                                       BasicType type, bool is_far) {
435   if (type == T_OBJECT || type == T_ARRAY) {
436     assert(cmpFlag == lir_cond_equal || cmpFlag == lir_cond_notEqual, "Should be equal or notEqual");
437     if (cmpFlag == lir_cond_equal) {
438       beq(op1, op2, label, is_far);
439     } else {
440       bne(op1, op2, label, is_far);
441     }
442   } else {
443     assert(cmpFlag >= 0 && cmpFlag < (int)(sizeof(c1_cond_branch) / sizeof(c1_cond_branch[0])),
444            "invalid c1 conditional branch index");
445     (this->*c1_cond_branch[cmpFlag])(op1, op2, label, is_far);
446   }
447 }
448 
449 void C1_MacroAssembler::c1_float_cmp_branch(int cmpFlag, FloatRegister op1, FloatRegister op2, Label& label,
450                                             bool is_far, bool is_unordered) {
451   assert(cmpFlag >= 0 &&
452          cmpFlag < (int)(sizeof(c1_float_cond_branch) / sizeof(c1_float_cond_branch[0])),
453          "invalid c1 float conditional branch index");
454   (this->*c1_float_cond_branch[cmpFlag])(op1, op2, label, is_far, is_unordered);
455 }