1 /*
2  * Copyright (c) 2013, Red Hat Inc.
3  * Copyright (c) 1997, 2012, Oracle and/or its affiliates.
4  * 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 <sys/types.h>
28 
29 #include "precompiled.hpp"
30 #include "asm/assembler.hpp"
31 #include "asm/assembler.inline.hpp"
32 #include "interpreter/interpreter.hpp"
33 
34 #include "compiler/disassembler.hpp"
35 #include "memory/resourceArea.hpp"
36 #include "runtime/biasedLocking.hpp"
37 #include "runtime/interfaceSupport.hpp"
38 #include "runtime/sharedRuntime.hpp"
39 
40 // #include "gc_interface/collectedHeap.inline.hpp"
41 // #include "interpreter/interpreter.hpp"
42 // #include "memory/cardTableModRefBS.hpp"
43 // #include "prims/methodHandles.hpp"
44 // #include "runtime/biasedLocking.hpp"
45 // #include "runtime/interfaceSupport.hpp"
46 // #include "runtime/objectMonitor.hpp"
47 // #include "runtime/os.hpp"
48 // #include "runtime/sharedRuntime.hpp"
49 // #include "runtime/stubRoutines.hpp"
50 
51 #if INCLUDE_ALL_GCS
52 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
53 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
54 #include "gc_implementation/g1/heapRegion.hpp"
55 #endif
56 
57 #ifdef COMPILER2
58 #include "opto/node.hpp"
59 #include "opto/compile.hpp"
60 #endif
61 
62 #ifdef PRODUCT
63 #define BLOCK_COMMENT(str) /* nothing */
64 #define STOP(error) stop(error)
65 #else
66 #define BLOCK_COMMENT(str) block_comment(str)
67 #define STOP(error) block_comment(error); stop(error)
68 #endif
69 
70 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
71 
72 // Patch any kind of instruction; there may be several instructions.
73 // Return the total length (in bytes) of the instructions.
pd_patch_instruction_size(address branch,address target)74 int MacroAssembler::pd_patch_instruction_size(address branch, address target) {
75   int instructions = 1;
76   assert((uint64_t)target < (1ul << 48), "48-bit overflow in address constant");
77   long offset = (target - branch) >> 2;
78   unsigned insn = *(unsigned*)branch;
79   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b111011) == 0b011000) {
80     // Load register (literal)
81     Instruction_aarch64::spatch(branch, 23, 5, offset);
82   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
83     // Unconditional branch (immediate)
84     Instruction_aarch64::spatch(branch, 25, 0, offset);
85   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
86     // Conditional branch (immediate)
87     Instruction_aarch64::spatch(branch, 23, 5, offset);
88   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
89     // Compare & branch (immediate)
90     Instruction_aarch64::spatch(branch, 23, 5, offset);
91   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
92     // Test & branch (immediate)
93     Instruction_aarch64::spatch(branch, 18, 5, offset);
94   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
95     // PC-rel. addressing
96     offset = target-branch;
97     int shift = Instruction_aarch64::extract(insn, 31, 31);
98     if (shift) {
99       u_int64_t dest = (u_int64_t)target;
100       uint64_t pc_page = (uint64_t)branch >> 12;
101       uint64_t adr_page = (uint64_t)target >> 12;
102       unsigned offset_lo = dest & 0xfff;
103       offset = adr_page - pc_page;
104 
105       // We handle 4 types of PC relative addressing
106       //   1 - adrp    Rx, target_page
107       //       ldr/str Ry, [Rx, #offset_in_page]
108       //   2 - adrp    Rx, target_page
109       //       add     Ry, Rx, #offset_in_page
110       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
111       //       movk    Rx, #imm16<<32
112       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
113       // In the first 3 cases we must check that Rx is the same in the adrp and the
114       // subsequent ldr/str, add or movk instruction. Otherwise we could accidentally end
115       // up treating a type 4 relocation as a type 1, 2 or 3 just because it happened
116       // to be followed by a random unrelated ldr/str, add or movk instruction.
117       //
118       unsigned insn2 = ((unsigned*)branch)[1];
119       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
120                 Instruction_aarch64::extract(insn, 4, 0) ==
121                         Instruction_aarch64::extract(insn2, 9, 5)) {
122         // Load/store register (unsigned immediate)
123         unsigned size = Instruction_aarch64::extract(insn2, 31, 30);
124         Instruction_aarch64::patch(branch + sizeof (unsigned),
125                                     21, 10, offset_lo >> size);
126         guarantee(((dest >> size) << size) == dest, "misaligned target");
127         instructions = 2;
128       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
129                 Instruction_aarch64::extract(insn, 4, 0) ==
130                         Instruction_aarch64::extract(insn2, 4, 0)) {
131         // add (immediate)
132         Instruction_aarch64::patch(branch + sizeof (unsigned),
133                                    21, 10, offset_lo);
134         instructions = 2;
135       } else if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110 &&
136                    Instruction_aarch64::extract(insn, 4, 0) ==
137                      Instruction_aarch64::extract(insn2, 4, 0)) {
138         // movk #imm16<<32
139         Instruction_aarch64::patch(branch + 4, 20, 5, (uint64_t)target >> 32);
140         long dest = ((long)target & 0xffffffffL) | ((long)branch & 0xffff00000000L);
141         long pc_page = (long)branch >> 12;
142         long adr_page = (long)dest >> 12;
143         offset = adr_page - pc_page;
144         instructions = 2;
145       }
146     }
147     int offset_lo = offset & 3;
148     offset >>= 2;
149     Instruction_aarch64::spatch(branch, 23, 5, offset);
150     Instruction_aarch64::patch(branch, 30, 29, offset_lo);
151   } else if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010100) {
152     u_int64_t dest = (u_int64_t)target;
153     // Move wide constant
154     assert(nativeInstruction_at(branch+4)->is_movk(), "wrong insns in patch");
155     assert(nativeInstruction_at(branch+8)->is_movk(), "wrong insns in patch");
156     Instruction_aarch64::patch(branch, 20, 5, dest & 0xffff);
157     Instruction_aarch64::patch(branch+4, 20, 5, (dest >>= 16) & 0xffff);
158     Instruction_aarch64::patch(branch+8, 20, 5, (dest >>= 16) & 0xffff);
159     assert(target_addr_for_insn(branch) == target, "should be");
160     instructions = 3;
161   } else if (Instruction_aarch64::extract(insn, 31, 22) == 0b1011100101 &&
162              Instruction_aarch64::extract(insn, 4, 0) == 0b11111) {
163     // nothing to do
164     assert(target == 0, "did not expect to relocate target for polling page load");
165   } else {
166     ShouldNotReachHere();
167   }
168   return instructions * NativeInstruction::instruction_size;
169 }
170 
patch_oop(address insn_addr,address o)171 int MacroAssembler::patch_oop(address insn_addr, address o) {
172   int instructions;
173   unsigned insn = *(unsigned*)insn_addr;
174   assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
175 
176   // OOPs are either narrow (32 bits) or wide (48 bits).  We encode
177   // narrow OOPs by setting the upper 16 bits in the first
178   // instruction.
179   if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010101) {
180     // Move narrow OOP
181     narrowOop n = oopDesc::encode_heap_oop((oop)o);
182     Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
183     Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
184     instructions = 2;
185   } else {
186     // Move wide OOP
187     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
188     uintptr_t dest = (uintptr_t)o;
189     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
190     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
191     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
192     instructions = 3;
193   }
194   return instructions * NativeInstruction::instruction_size;
195 }
196 
target_addr_for_insn(address insn_addr,unsigned insn)197 address MacroAssembler::target_addr_for_insn(address insn_addr, unsigned insn) {
198   long offset = 0;
199   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b011011) == 0b00011000) {
200     // Load register (literal)
201     offset = Instruction_aarch64::sextract(insn, 23, 5);
202     return address(((uint64_t)insn_addr + (offset << 2)));
203   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
204     // Unconditional branch (immediate)
205     offset = Instruction_aarch64::sextract(insn, 25, 0);
206   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
207     // Conditional branch (immediate)
208     offset = Instruction_aarch64::sextract(insn, 23, 5);
209   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
210     // Compare & branch (immediate)
211     offset = Instruction_aarch64::sextract(insn, 23, 5);
212    } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
213     // Test & branch (immediate)
214     offset = Instruction_aarch64::sextract(insn, 18, 5);
215   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
216     // PC-rel. addressing
217     offset = Instruction_aarch64::extract(insn, 30, 29);
218     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
219     int shift = Instruction_aarch64::extract(insn, 31, 31) ? 12 : 0;
220     if (shift) {
221       offset <<= shift;
222       uint64_t target_page = ((uint64_t)insn_addr) + offset;
223       target_page &= ((uint64_t)-1) << shift;
224       // Return the target address for the following sequences
225       //   1 - adrp    Rx, target_page
226       //       ldr/str Ry, [Rx, #offset_in_page]
227       //   2 - adrp    Rx, target_page
228       //       add     Ry, Rx, #offset_in_page
229       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
230       //       movk    Rx, #imm12<<32
231       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
232       //
233       // In the first two cases  we check that the register is the same and
234       // return the target_page + the offset within the page.
235       // Otherwise we assume it is a page aligned relocation and return
236       // the target page only.
237       //
238       unsigned insn2 = ((unsigned*)insn_addr)[1];
239       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
240                 Instruction_aarch64::extract(insn, 4, 0) ==
241                         Instruction_aarch64::extract(insn2, 9, 5)) {
242         // Load/store register (unsigned immediate)
243         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
244         unsigned int size = Instruction_aarch64::extract(insn2, 31, 30);
245         return address(target_page + (byte_offset << size));
246       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
247                 Instruction_aarch64::extract(insn, 4, 0) ==
248                         Instruction_aarch64::extract(insn2, 4, 0)) {
249         // add (immediate)
250         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
251         return address(target_page + byte_offset);
252       } else {
253         if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110  &&
254                Instruction_aarch64::extract(insn, 4, 0) ==
255                  Instruction_aarch64::extract(insn2, 4, 0)) {
256           target_page = (target_page & 0xffffffff) |
257                          ((uint64_t)Instruction_aarch64::extract(insn2, 20, 5) << 32);
258         }
259         return (address)target_page;
260       }
261     } else {
262       ShouldNotReachHere();
263     }
264   } else if (Instruction_aarch64::extract(insn, 31, 23) == 0b110100101) {
265     u_int32_t *insns = (u_int32_t *)insn_addr;
266     // Move wide constant: movz, movk, movk.  See movptr().
267     assert(nativeInstruction_at(insns+1)->is_movk(), "wrong insns in patch");
268     assert(nativeInstruction_at(insns+2)->is_movk(), "wrong insns in patch");
269     return address(u_int64_t(Instruction_aarch64::extract(insns[0], 20, 5))
270                    + (u_int64_t(Instruction_aarch64::extract(insns[1], 20, 5)) << 16)
271                    + (u_int64_t(Instruction_aarch64::extract(insns[2], 20, 5)) << 32));
272   } else if (Instruction_aarch64::extract(insn, 31, 22) == 0b1011100101 &&
273              Instruction_aarch64::extract(insn, 4, 0) == 0b11111) {
274     return 0;
275   } else {
276     ShouldNotReachHere();
277   }
278   return address(((uint64_t)insn_addr + (offset << 2)));
279 }
280 
serialize_memory(Register thread,Register tmp)281 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
282   dsb(Assembler::SY);
283 }
284 
285 
reset_last_Java_frame(bool clear_fp)286 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
287   // we must set sp to zero to clear frame
288   str(zr, Address(rthread, JavaThread::last_Java_sp_offset()));
289 
290   // must clear fp, so that compiled frames are not confused; it is
291   // possible that we need it only for debugging
292   if (clear_fp) {
293     str(zr, Address(rthread, JavaThread::last_Java_fp_offset()));
294   }
295 
296   // Always clear the pc because it could have been set by make_walkable()
297   str(zr, Address(rthread, JavaThread::last_Java_pc_offset()));
298 }
299 
300 // Calls to C land
301 //
302 // When entering C land, the rfp, & resp of the last Java frame have to be recorded
303 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
304 // has to be reset to 0. This is required to allow proper stack traversal.
set_last_Java_frame(Register last_java_sp,Register last_java_fp,Register last_java_pc,Register scratch)305 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
306                                          Register last_java_fp,
307                                          Register last_java_pc,
308                                          Register scratch) {
309 
310   if (last_java_pc->is_valid()) {
311       str(last_java_pc, Address(rthread,
312                                 JavaThread::frame_anchor_offset()
313                                 + JavaFrameAnchor::last_Java_pc_offset()));
314     }
315 
316   // determine last_java_sp register
317   if (last_java_sp == sp) {
318     mov(scratch, sp);
319     last_java_sp = scratch;
320   } else if (!last_java_sp->is_valid()) {
321     last_java_sp = esp;
322   }
323 
324   str(last_java_sp, Address(rthread, JavaThread::last_Java_sp_offset()));
325 
326   // last_java_fp is optional
327   if (last_java_fp->is_valid()) {
328     str(last_java_fp, Address(rthread, JavaThread::last_Java_fp_offset()));
329   }
330 }
331 
set_last_Java_frame(Register last_java_sp,Register last_java_fp,address last_java_pc,Register scratch)332 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
333                                          Register last_java_fp,
334                                          address  last_java_pc,
335                                          Register scratch) {
336   if (last_java_pc != NULL) {
337     adr(scratch, last_java_pc);
338   } else {
339     // FIXME: This is almost never correct.  We should delete all
340     // cases of set_last_Java_frame with last_java_pc=NULL and use the
341     // correct return address instead.
342     adr(scratch, pc());
343   }
344 
345   str(scratch, Address(rthread,
346                        JavaThread::frame_anchor_offset()
347                        + JavaFrameAnchor::last_Java_pc_offset()));
348 
349   set_last_Java_frame(last_java_sp, last_java_fp, noreg, scratch);
350 }
351 
set_last_Java_frame(Register last_java_sp,Register last_java_fp,Label & L,Register scratch)352 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
353                                          Register last_java_fp,
354                                          Label &L,
355                                          Register scratch) {
356   if (L.is_bound()) {
357     set_last_Java_frame(last_java_sp, last_java_fp, target(L), scratch);
358   } else {
359     InstructionMark im(this);
360     L.add_patch_at(code(), locator());
361     set_last_Java_frame(last_java_sp, last_java_fp, (address)NULL, scratch);
362   }
363 }
364 
far_call(Address entry,CodeBuffer * cbuf,Register tmp)365 void MacroAssembler::far_call(Address entry, CodeBuffer *cbuf, Register tmp) {
366   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
367   assert(CodeCache::find_blob(entry.target()) != NULL,
368          "destination of far call not found in code cache");
369   if (far_branches()) {
370     unsigned long offset;
371     // We can use ADRP here because we know that the total size of
372     // the code cache cannot exceed 2Gb.
373     adrp(tmp, entry, offset);
374     add(tmp, tmp, offset);
375     if (cbuf) cbuf->set_insts_mark();
376     blr(tmp);
377   } else {
378     if (cbuf) cbuf->set_insts_mark();
379     bl(entry);
380   }
381 }
382 
far_jump(Address entry,CodeBuffer * cbuf,Register tmp)383 void MacroAssembler::far_jump(Address entry, CodeBuffer *cbuf, Register tmp) {
384   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
385   assert(CodeCache::find_blob(entry.target()) != NULL,
386          "destination of far call not found in code cache");
387   if (far_branches()) {
388     unsigned long offset;
389     // We can use ADRP here because we know that the total size of
390     // the code cache cannot exceed 2Gb.
391     adrp(tmp, entry, offset);
392     add(tmp, tmp, offset);
393     if (cbuf) cbuf->set_insts_mark();
394     br(tmp);
395   } else {
396     if (cbuf) cbuf->set_insts_mark();
397     b(entry);
398   }
399 }
400 
biased_locking_enter(Register lock_reg,Register obj_reg,Register swap_reg,Register tmp_reg,bool swap_reg_contains_mark,Label & done,Label * slow_case,BiasedLockingCounters * counters)401 int MacroAssembler::biased_locking_enter(Register lock_reg,
402                                          Register obj_reg,
403                                          Register swap_reg,
404                                          Register tmp_reg,
405                                          bool swap_reg_contains_mark,
406                                          Label& done,
407                                          Label* slow_case,
408                                          BiasedLockingCounters* counters) {
409   assert(UseBiasedLocking, "why call this otherwise?");
410   assert_different_registers(lock_reg, obj_reg, swap_reg);
411 
412   if (PrintBiasedLockingStatistics && counters == NULL)
413     counters = BiasedLocking::counters();
414 
415   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg, rscratch1, rscratch2, noreg);
416   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
417   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
418   Address klass_addr     (obj_reg, oopDesc::klass_offset_in_bytes());
419   Address saved_mark_addr(lock_reg, 0);
420 
421   // Biased locking
422   // See whether the lock is currently biased toward our thread and
423   // whether the epoch is still valid
424   // Note that the runtime guarantees sufficient alignment of JavaThread
425   // pointers to allow age to be placed into low bits
426   // First check to see whether biasing is even enabled for this object
427   Label cas_label;
428   int null_check_offset = -1;
429   if (!swap_reg_contains_mark) {
430     null_check_offset = offset();
431     ldr(swap_reg, mark_addr);
432   }
433   andr(tmp_reg, swap_reg, markOopDesc::biased_lock_mask_in_place);
434   cmp(tmp_reg, markOopDesc::biased_lock_pattern);
435   br(Assembler::NE, cas_label);
436   // The bias pattern is present in the object's header. Need to check
437   // whether the bias owner and the epoch are both still current.
438   load_prototype_header(tmp_reg, obj_reg);
439   orr(tmp_reg, tmp_reg, rthread);
440   eor(tmp_reg, swap_reg, tmp_reg);
441   andr(tmp_reg, tmp_reg, ~((int) markOopDesc::age_mask_in_place));
442   if (counters != NULL) {
443     Label around;
444     cbnz(tmp_reg, around);
445     atomic_incw(Address((address)counters->biased_lock_entry_count_addr()), tmp_reg, rscratch1, rscratch2);
446     b(done);
447     bind(around);
448   } else {
449     cbz(tmp_reg, done);
450   }
451 
452   Label try_revoke_bias;
453   Label try_rebias;
454 
455   // At this point we know that the header has the bias pattern and
456   // that we are not the bias owner in the current epoch. We need to
457   // figure out more details about the state of the header in order to
458   // know what operations can be legally performed on the object's
459   // header.
460 
461   // If the low three bits in the xor result aren't clear, that means
462   // the prototype header is no longer biased and we have to revoke
463   // the bias on this object.
464   andr(rscratch1, tmp_reg, markOopDesc::biased_lock_mask_in_place);
465   cbnz(rscratch1, try_revoke_bias);
466 
467   // Biasing is still enabled for this data type. See whether the
468   // epoch of the current bias is still valid, meaning that the epoch
469   // bits of the mark word are equal to the epoch bits of the
470   // prototype header. (Note that the prototype header's epoch bits
471   // only change at a safepoint.) If not, attempt to rebias the object
472   // toward the current thread. Note that we must be absolutely sure
473   // that the current epoch is invalid in order to do this because
474   // otherwise the manipulations it performs on the mark word are
475   // illegal.
476   andr(rscratch1, tmp_reg, markOopDesc::epoch_mask_in_place);
477   cbnz(rscratch1, try_rebias);
478 
479   // The epoch of the current bias is still valid but we know nothing
480   // about the owner; it might be set or it might be clear. Try to
481   // acquire the bias of the object using an atomic operation. If this
482   // fails we will go in to the runtime to revoke the object's bias.
483   // Note that we first construct the presumed unbiased header so we
484   // don't accidentally blow away another thread's valid bias.
485   {
486     Label here;
487     mov(rscratch1, markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
488     andr(swap_reg, swap_reg, rscratch1);
489     orr(tmp_reg, swap_reg, rthread);
490     cmpxchgptr(swap_reg, tmp_reg, obj_reg, rscratch1, here, slow_case);
491     // If the biasing toward our thread failed, this means that
492     // another thread succeeded in biasing it toward itself and we
493     // need to revoke that bias. The revocation will occur in the
494     // interpreter runtime in the slow case.
495     bind(here);
496     if (counters != NULL) {
497       atomic_incw(Address((address)counters->anonymously_biased_lock_entry_count_addr()),
498                   tmp_reg, rscratch1, rscratch2);
499     }
500   }
501   b(done);
502 
503   bind(try_rebias);
504   // At this point we know the epoch has expired, meaning that the
505   // current "bias owner", if any, is actually invalid. Under these
506   // circumstances _only_, we are allowed to use the current header's
507   // value as the comparison value when doing the cas to acquire the
508   // bias in the current epoch. In other words, we allow transfer of
509   // the bias from one thread to another directly in this situation.
510   //
511   // FIXME: due to a lack of registers we currently blow away the age
512   // bits in this situation. Should attempt to preserve them.
513   {
514     Label here;
515     load_prototype_header(tmp_reg, obj_reg);
516     orr(tmp_reg, rthread, tmp_reg);
517     cmpxchgptr(swap_reg, tmp_reg, obj_reg, rscratch1, here, slow_case);
518     // If the biasing toward our thread failed, then another thread
519     // succeeded in biasing it toward itself and we need to revoke that
520     // bias. The revocation will occur in the runtime in the slow case.
521     bind(here);
522     if (counters != NULL) {
523       atomic_incw(Address((address)counters->rebiased_lock_entry_count_addr()),
524                   tmp_reg, rscratch1, rscratch2);
525     }
526   }
527   b(done);
528 
529   bind(try_revoke_bias);
530   // The prototype mark in the klass doesn't have the bias bit set any
531   // more, indicating that objects of this data type are not supposed
532   // to be biased any more. We are going to try to reset the mark of
533   // this object to the prototype value and fall through to the
534   // CAS-based locking scheme. Note that if our CAS fails, it means
535   // that another thread raced us for the privilege of revoking the
536   // bias of this particular object, so it's okay to continue in the
537   // normal locking code.
538   //
539   // FIXME: due to a lack of registers we currently blow away the age
540   // bits in this situation. Should attempt to preserve them.
541   {
542     Label here, nope;
543     load_prototype_header(tmp_reg, obj_reg);
544     cmpxchgptr(swap_reg, tmp_reg, obj_reg, rscratch1, here, &nope);
545     bind(here);
546 
547     // Fall through to the normal CAS-based lock, because no matter what
548     // the result of the above CAS, some thread must have succeeded in
549     // removing the bias bit from the object's header.
550     if (counters != NULL) {
551       atomic_incw(Address((address)counters->revoked_lock_entry_count_addr()), tmp_reg,
552                   rscratch1, rscratch2);
553     }
554     bind(nope);
555   }
556 
557   bind(cas_label);
558 
559   return null_check_offset;
560 }
561 
biased_locking_exit(Register obj_reg,Register temp_reg,Label & done)562 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
563   assert(UseBiasedLocking, "why call this otherwise?");
564 
565   // Check for biased locking unlock case, which is a no-op
566   // Note: we do not have to check the thread ID for two reasons.
567   // First, the interpreter checks for IllegalMonitorStateException at
568   // a higher level. Second, if the bias was revoked while we held the
569   // lock, the object could not be rebiased toward another thread, so
570   // the bias bit would be clear.
571   ldr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
572   andr(temp_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
573   cmp(temp_reg, markOopDesc::biased_lock_pattern);
574   br(Assembler::EQ, done);
575 }
576 
577 
578 // added to make this compile
579 
580 REGISTER_DEFINITION(Register, noreg);
581 
pass_arg0(MacroAssembler * masm,Register arg)582 static void pass_arg0(MacroAssembler* masm, Register arg) {
583   if (c_rarg0 != arg ) {
584     masm->mov(c_rarg0, arg);
585   }
586 }
587 
pass_arg1(MacroAssembler * masm,Register arg)588 static void pass_arg1(MacroAssembler* masm, Register arg) {
589   if (c_rarg1 != arg ) {
590     masm->mov(c_rarg1, arg);
591   }
592 }
593 
pass_arg2(MacroAssembler * masm,Register arg)594 static void pass_arg2(MacroAssembler* masm, Register arg) {
595   if (c_rarg2 != arg ) {
596     masm->mov(c_rarg2, arg);
597   }
598 }
599 
pass_arg3(MacroAssembler * masm,Register arg)600 static void pass_arg3(MacroAssembler* masm, Register arg) {
601   if (c_rarg3 != arg ) {
602     masm->mov(c_rarg3, arg);
603   }
604 }
605 
call_VM_base(Register oop_result,Register java_thread,Register last_java_sp,address entry_point,int number_of_arguments,bool check_exceptions)606 void MacroAssembler::call_VM_base(Register oop_result,
607                                   Register java_thread,
608                                   Register last_java_sp,
609                                   address  entry_point,
610                                   int      number_of_arguments,
611                                   bool     check_exceptions) {
612    // determine java_thread register
613   if (!java_thread->is_valid()) {
614     java_thread = rthread;
615   }
616 
617   // determine last_java_sp register
618   if (!last_java_sp->is_valid()) {
619     last_java_sp = esp;
620   }
621 
622   // debugging support
623   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
624   assert(java_thread == rthread, "unexpected register");
625 #ifdef ASSERT
626   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
627   // if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
628 #endif // ASSERT
629 
630   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
631   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
632 
633   // push java thread (becomes first argument of C function)
634 
635   mov(c_rarg0, java_thread);
636 
637   // set last Java frame before call
638   assert(last_java_sp != rfp, "can't use rfp");
639 
640   Label l;
641   set_last_Java_frame(last_java_sp, rfp, l, rscratch1);
642 
643   // do the call, remove parameters
644   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments, &l);
645 
646   // lr could be poisoned with PAC signature during throw_pending_exception
647   // if it was tail-call optimized by compiler, since lr is not callee-saved
648   // reload it with proper value
649   adr(lr, l);
650 
651   // reset last Java frame
652   // Only interpreter should have to clear fp
653   reset_last_Java_frame(true);
654 
655    // C++ interp handles this in the interpreter
656   check_and_handle_popframe(java_thread);
657   check_and_handle_earlyret(java_thread);
658 
659   if (check_exceptions) {
660     // check for pending exceptions (java_thread is set upon return)
661     ldr(rscratch1, Address(java_thread, in_bytes(Thread::pending_exception_offset())));
662     Label ok;
663     cbz(rscratch1, ok);
664     lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
665     br(rscratch1);
666     bind(ok);
667   }
668 
669   // get oop result if there is one and reset the value in the thread
670   if (oop_result->is_valid()) {
671     get_vm_result(oop_result, java_thread);
672   }
673 }
674 
call_VM_helper(Register oop_result,address entry_point,int number_of_arguments,bool check_exceptions)675 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
676   call_VM_base(oop_result, noreg, noreg, entry_point, number_of_arguments, check_exceptions);
677 }
678 
679 // Maybe emit a call via a trampoline.  If the code cache is small
680 // trampolines won't be emitted.
681 
trampoline_call(Address entry,CodeBuffer * cbuf)682 address MacroAssembler::trampoline_call(Address entry, CodeBuffer *cbuf) {
683   assert(entry.rspec().type() == relocInfo::runtime_call_type
684          || entry.rspec().type() == relocInfo::opt_virtual_call_type
685          || entry.rspec().type() == relocInfo::static_call_type
686          || entry.rspec().type() == relocInfo::virtual_call_type, "wrong reloc type");
687 
688   unsigned int start_offset = offset();
689 #ifdef COMPILER2
690   // We need a trampoline if branches are far.
691   if (far_branches()) {
692     // We don't want to emit a trampoline if C2 is generating dummy
693     // code during its branch shortening phase.
694     CompileTask* task = ciEnv::current()->task();
695     bool in_scratch_emit_size =
696       ((task != NULL) && is_c2_compile(task->comp_level())
697        && Compile::current()->in_scratch_emit_size());
698     if (! in_scratch_emit_size) {
699       address stub = emit_trampoline_stub(start_offset, entry.target());
700       if (stub == NULL) {
701         return NULL; // CodeCache is full
702       }
703     }
704   }
705 #endif
706 
707   if (cbuf) cbuf->set_insts_mark();
708   relocate(entry.rspec());
709 #ifdef COMPILER2
710   if (!far_branches()) {
711     bl(entry.target());
712   } else {
713     bl(pc());
714   }
715 #else
716     bl(entry.target());
717 #endif
718   // just need to return a non-null address
719   return pc();
720 }
721 
722 
723 // Emit a trampoline stub for a call to a target which is too far away.
724 //
725 // code sequences:
726 //
727 // call-site:
728 //   branch-and-link to <destination> or <trampoline stub>
729 //
730 // Related trampoline stub for this call site in the stub section:
731 //   load the call target from the constant pool
732 //   branch (LR still points to the call site above)
733 
emit_trampoline_stub(int insts_call_instruction_offset,address dest)734 address MacroAssembler::emit_trampoline_stub(int insts_call_instruction_offset,
735                                              address dest) {
736 #ifdef COMPILER2
737   address stub = start_a_stub(Compile::MAX_stubs_size/2);
738   if (stub == NULL) {
739     return NULL;  // CodeBuffer::expand failed
740   }
741 
742   // Create a trampoline stub relocation which relates this trampoline stub
743   // with the call instruction at insts_call_instruction_offset in the
744   // instructions code-section.
745   align(wordSize);
746   relocate(trampoline_stub_Relocation::spec(code()->insts()->start()
747                                             + insts_call_instruction_offset));
748   const int stub_start_offset = offset();
749 
750   // Now, create the trampoline stub's code:
751   // - load the call
752   // - call
753   Label target;
754   ldr(rscratch1, target);
755   br(rscratch1);
756   bind(target);
757   assert(offset() - stub_start_offset == NativeCallTrampolineStub::data_offset,
758          "should be");
759   emit_int64((int64_t)dest);
760 
761   const address stub_start_addr = addr_at(stub_start_offset);
762 
763   assert(is_NativeCallTrampolineStub_at(stub_start_addr), "doesn't look like a trampoline");
764 
765   end_a_stub();
766   return stub;
767 #else
768   ShouldNotReachHere();
769   return NULL;
770 #endif
771 }
772 
c2bool(Register x)773 void MacroAssembler::c2bool(Register x) {
774   // implements x == 0 ? 0 : 1
775   // note: must only look at least-significant byte of x
776   //       since C-style booleans are stored in one byte
777   //       only! (was bug)
778   tst(x, 0xff);
779   cset(x, Assembler::NE);
780 }
781 
ic_call(address entry)782 address MacroAssembler::ic_call(address entry) {
783   RelocationHolder rh = virtual_call_Relocation::spec(pc());
784   // address const_ptr = long_constant((jlong)Universe::non_oop_word());
785   // unsigned long offset;
786   // ldr_constant(rscratch2, const_ptr);
787   movptr(rscratch2, (uintptr_t)Universe::non_oop_word());
788   return trampoline_call(Address(entry, rh));
789 }
790 
791 // Implementation of call_VM versions
792 
call_VM(Register oop_result,address entry_point,bool check_exceptions)793 void MacroAssembler::call_VM(Register oop_result,
794                              address entry_point,
795                              bool check_exceptions) {
796   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
797 }
798 
call_VM(Register oop_result,address entry_point,Register arg_1,bool check_exceptions)799 void MacroAssembler::call_VM(Register oop_result,
800                              address entry_point,
801                              Register arg_1,
802                              bool check_exceptions) {
803   pass_arg1(this, arg_1);
804   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
805 }
806 
call_VM(Register oop_result,address entry_point,Register arg_1,Register arg_2,bool check_exceptions)807 void MacroAssembler::call_VM(Register oop_result,
808                              address entry_point,
809                              Register arg_1,
810                              Register arg_2,
811                              bool check_exceptions) {
812   assert(arg_1 != c_rarg2, "smashed arg");
813   pass_arg2(this, arg_2);
814   pass_arg1(this, arg_1);
815   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
816 }
817 
call_VM(Register oop_result,address entry_point,Register arg_1,Register arg_2,Register arg_3,bool check_exceptions)818 void MacroAssembler::call_VM(Register oop_result,
819                              address entry_point,
820                              Register arg_1,
821                              Register arg_2,
822                              Register arg_3,
823                              bool check_exceptions) {
824   assert(arg_1 != c_rarg3, "smashed arg");
825   assert(arg_2 != c_rarg3, "smashed arg");
826   pass_arg3(this, arg_3);
827 
828   assert(arg_1 != c_rarg2, "smashed arg");
829   pass_arg2(this, arg_2);
830 
831   pass_arg1(this, arg_1);
832   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
833 }
834 
call_VM(Register oop_result,Register last_java_sp,address entry_point,int number_of_arguments,bool check_exceptions)835 void MacroAssembler::call_VM(Register oop_result,
836                              Register last_java_sp,
837                              address entry_point,
838                              int number_of_arguments,
839                              bool check_exceptions) {
840   call_VM_base(oop_result, rthread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
841 }
842 
call_VM(Register oop_result,Register last_java_sp,address entry_point,Register arg_1,bool check_exceptions)843 void MacroAssembler::call_VM(Register oop_result,
844                              Register last_java_sp,
845                              address entry_point,
846                              Register arg_1,
847                              bool check_exceptions) {
848   pass_arg1(this, arg_1);
849   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
850 }
851 
call_VM(Register oop_result,Register last_java_sp,address entry_point,Register arg_1,Register arg_2,bool check_exceptions)852 void MacroAssembler::call_VM(Register oop_result,
853                              Register last_java_sp,
854                              address entry_point,
855                              Register arg_1,
856                              Register arg_2,
857                              bool check_exceptions) {
858 
859   assert(arg_1 != c_rarg2, "smashed arg");
860   pass_arg2(this, arg_2);
861   pass_arg1(this, arg_1);
862   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
863 }
864 
call_VM(Register oop_result,Register last_java_sp,address entry_point,Register arg_1,Register arg_2,Register arg_3,bool check_exceptions)865 void MacroAssembler::call_VM(Register oop_result,
866                              Register last_java_sp,
867                              address entry_point,
868                              Register arg_1,
869                              Register arg_2,
870                              Register arg_3,
871                              bool check_exceptions) {
872   assert(arg_1 != c_rarg3, "smashed arg");
873   assert(arg_2 != c_rarg3, "smashed arg");
874   pass_arg3(this, arg_3);
875   assert(arg_1 != c_rarg2, "smashed arg");
876   pass_arg2(this, arg_2);
877   pass_arg1(this, arg_1);
878   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
879 }
880 
881 
get_vm_result(Register oop_result,Register java_thread)882 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
883   ldr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
884   str(zr, Address(java_thread, JavaThread::vm_result_offset()));
885   verify_oop(oop_result, "broken oop in call_VM_base");
886 }
887 
get_vm_result_2(Register metadata_result,Register java_thread)888 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
889   ldr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
890   str(zr, Address(java_thread, JavaThread::vm_result_2_offset()));
891 }
892 
align(int modulus)893 void MacroAssembler::align(int modulus) {
894   while (offset() % modulus != 0) nop();
895 }
896 
897 // these are no-ops overridden by InterpreterMacroAssembler
898 
check_and_handle_earlyret(Register java_thread)899 void MacroAssembler::check_and_handle_earlyret(Register java_thread) { }
900 
check_and_handle_popframe(Register java_thread)901 void MacroAssembler::check_and_handle_popframe(Register java_thread) { }
902 
903 
delayed_value_impl(intptr_t * delayed_value_addr,Register tmp,int offset)904 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
905                                                       Register tmp,
906                                                       int offset) {
907   intptr_t value = *delayed_value_addr;
908   if (value != 0)
909     return RegisterOrConstant(value + offset);
910 
911   // load indirectly to solve generation ordering problem
912   ldr(tmp, ExternalAddress((address) delayed_value_addr));
913 
914   if (offset != 0)
915     add(tmp, tmp, offset);
916 
917   return RegisterOrConstant(tmp);
918 }
919 
920 // Look up the method for a megamorphic invokeinterface call.
921 // The target method is determined by <intf_klass, itable_index>.
922 // The receiver klass is in recv_klass.
923 // On success, the result will be in method_result, and execution falls through.
924 // On failure, execution transfers to the given label.
lookup_interface_method(Register recv_klass,Register intf_klass,RegisterOrConstant itable_index,Register method_result,Register scan_temp,Label & L_no_such_interface,bool return_method)925 void MacroAssembler::lookup_interface_method(Register recv_klass,
926                                              Register intf_klass,
927                                              RegisterOrConstant itable_index,
928                                              Register method_result,
929                                              Register scan_temp,
930                                              Label& L_no_such_interface,
931                                              bool return_method) {
932   assert_different_registers(recv_klass, intf_klass, scan_temp);
933   assert_different_registers(method_result, intf_klass, scan_temp);
934   assert(recv_klass != method_result || !return_method,
935          "recv_klass can be destroyed when method isn't needed");
936 
937   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
938          "caller must use same register for non-constant itable index as for method");
939 
940   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
941   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
942   int itentry_off = itableMethodEntry::method_offset_in_bytes();
943   int scan_step   = itableOffsetEntry::size() * wordSize;
944   int vte_size    = vtableEntry::size() * wordSize;
945   assert(vte_size == wordSize, "else adjust times_vte_scale");
946 
947   ldrw(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
948 
949   // %%% Could store the aligned, prescaled offset in the klassoop.
950   // lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
951   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
952   add(scan_temp, scan_temp, vtable_base);
953   if (HeapWordsPerLong > 1) {
954     // Round up to align_object_offset boundary
955     // see code for instanceKlass::start_of_itable!
956     round_to(scan_temp, BytesPerLong);
957   }
958 
959   if (return_method) {
960     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
961     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
962     // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
963     lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
964     if (itentry_off)
965       add(recv_klass, recv_klass, itentry_off);
966   }
967 
968   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
969   //   if (scan->interface() == intf) {
970   //     result = (klass + scan->offset() + itable_index);
971   //   }
972   // }
973   Label search, found_method;
974 
975   for (int peel = 1; peel >= 0; peel--) {
976     ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
977     cmp(intf_klass, method_result);
978 
979     if (peel) {
980       br(Assembler::EQ, found_method);
981     } else {
982       br(Assembler::NE, search);
983       // (invert the test to fall through to found_method...)
984     }
985 
986     if (!peel)  break;
987 
988     bind(search);
989 
990     // Check that the previous entry is non-null.  A null entry means that
991     // the receiver class doesn't implement the interface, and wasn't the
992     // same as when the caller was compiled.
993     cbz(method_result, L_no_such_interface);
994     add(scan_temp, scan_temp, scan_step);
995   }
996 
997   bind(found_method);
998 
999   if (return_method) {
1000     // Got a hit.
1001     ldrw(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
1002     ldr(method_result, Address(recv_klass, scan_temp, Address::uxtw(0)));
1003   }
1004 }
1005 
1006 // virtual method calling
lookup_virtual_method(Register recv_klass,RegisterOrConstant vtable_index,Register method_result)1007 void MacroAssembler::lookup_virtual_method(Register recv_klass,
1008                                            RegisterOrConstant vtable_index,
1009                                            Register method_result) {
1010   const int base = InstanceKlass::vtable_start_offset() * wordSize;
1011   assert(vtableEntry::size() * wordSize == 8,
1012          "adjust the scaling in the code below");
1013   int vtable_offset_in_bytes = base + vtableEntry::method_offset_in_bytes();
1014 
1015   if (vtable_index.is_register()) {
1016     lea(method_result, Address(recv_klass,
1017                                vtable_index.as_register(),
1018                                Address::lsl(LogBytesPerWord)));
1019     ldr(method_result, Address(method_result, vtable_offset_in_bytes));
1020   } else {
1021     vtable_offset_in_bytes += vtable_index.as_constant() * wordSize;
1022     ldr(method_result,
1023         form_address(rscratch1, recv_klass, vtable_offset_in_bytes, 0));
1024   }
1025 }
1026 
check_klass_subtype(Register sub_klass,Register super_klass,Register temp_reg,Label & L_success)1027 void MacroAssembler::check_klass_subtype(Register sub_klass,
1028                            Register super_klass,
1029                            Register temp_reg,
1030                            Label& L_success) {
1031   Label L_failure;
1032   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
1033   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
1034   bind(L_failure);
1035 }
1036 
1037 
check_klass_subtype_fast_path(Register sub_klass,Register super_klass,Register temp_reg,Label * L_success,Label * L_failure,Label * L_slow_path,RegisterOrConstant super_check_offset)1038 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
1039                                                    Register super_klass,
1040                                                    Register temp_reg,
1041                                                    Label* L_success,
1042                                                    Label* L_failure,
1043                                                    Label* L_slow_path,
1044                                         RegisterOrConstant super_check_offset) {
1045   assert_different_registers(sub_klass, super_klass, temp_reg);
1046   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
1047   if (super_check_offset.is_register()) {
1048     assert_different_registers(sub_klass, super_klass,
1049                                super_check_offset.as_register());
1050   } else if (must_load_sco) {
1051     assert(temp_reg != noreg, "supply either a temp or a register offset");
1052   }
1053 
1054   Label L_fallthrough;
1055   int label_nulls = 0;
1056   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1057   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1058   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
1059   assert(label_nulls <= 1, "at most one NULL in the batch");
1060 
1061   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1062   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1063   Address super_check_offset_addr(super_klass, sco_offset);
1064 
1065   // Hacked jmp, which may only be used just before L_fallthrough.
1066 #define final_jmp(label)                                                \
1067   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
1068   else                            b(label)                /*omit semi*/
1069 
1070   // If the pointers are equal, we are done (e.g., String[] elements).
1071   // This self-check enables sharing of secondary supertype arrays among
1072   // non-primary types such as array-of-interface.  Otherwise, each such
1073   // type would need its own customized SSA.
1074   // We move this check to the front of the fast path because many
1075   // type checks are in fact trivially successful in this manner,
1076   // so we get a nicely predicted branch right at the start of the check.
1077   cmp(sub_klass, super_klass);
1078   br(Assembler::EQ, *L_success);
1079 
1080   // Check the supertype display:
1081   if (must_load_sco) {
1082     // Positive movl does right thing on LP64.
1083     ldrw(temp_reg, super_check_offset_addr);
1084     super_check_offset = RegisterOrConstant(temp_reg);
1085   }
1086   Address super_check_addr(sub_klass, super_check_offset);
1087   ldr(rscratch1, super_check_addr);
1088   cmp(super_klass, rscratch1); // load displayed supertype
1089 
1090   // This check has worked decisively for primary supers.
1091   // Secondary supers are sought in the super_cache ('super_cache_addr').
1092   // (Secondary supers are interfaces and very deeply nested subtypes.)
1093   // This works in the same check above because of a tricky aliasing
1094   // between the super_cache and the primary super display elements.
1095   // (The 'super_check_addr' can address either, as the case requires.)
1096   // Note that the cache is updated below if it does not help us find
1097   // what we need immediately.
1098   // So if it was a primary super, we can just fail immediately.
1099   // Otherwise, it's the slow path for us (no success at this point).
1100 
1101   if (super_check_offset.is_register()) {
1102     br(Assembler::EQ, *L_success);
1103     cmp(super_check_offset.as_register(), sc_offset);
1104     if (L_failure == &L_fallthrough) {
1105       br(Assembler::EQ, *L_slow_path);
1106     } else {
1107       br(Assembler::NE, *L_failure);
1108       final_jmp(*L_slow_path);
1109     }
1110   } else if (super_check_offset.as_constant() == sc_offset) {
1111     // Need a slow path; fast failure is impossible.
1112     if (L_slow_path == &L_fallthrough) {
1113       br(Assembler::EQ, *L_success);
1114     } else {
1115       br(Assembler::NE, *L_slow_path);
1116       final_jmp(*L_success);
1117     }
1118   } else {
1119     // No slow path; it's a fast decision.
1120     if (L_failure == &L_fallthrough) {
1121       br(Assembler::EQ, *L_success);
1122     } else {
1123       br(Assembler::NE, *L_failure);
1124       final_jmp(*L_success);
1125     }
1126   }
1127 
1128   bind(L_fallthrough);
1129 
1130 #undef final_jmp
1131 }
1132 
1133 // These two are taken from x86, but they look generally useful
1134 
1135 // scans count pointer sized words at [addr] for occurence of value,
1136 // generic
repne_scan(Register addr,Register value,Register count,Register scratch)1137 void MacroAssembler::repne_scan(Register addr, Register value, Register count,
1138                                 Register scratch) {
1139   Label Lloop, Lexit;
1140   cbz(count, Lexit);
1141   bind(Lloop);
1142   ldr(scratch, post(addr, wordSize));
1143   cmp(value, scratch);
1144   br(EQ, Lexit);
1145   sub(count, count, 1);
1146   cbnz(count, Lloop);
1147   bind(Lexit);
1148 }
1149 
1150 // scans count 4 byte words at [addr] for occurence of value,
1151 // generic
repne_scanw(Register addr,Register value,Register count,Register scratch)1152 void MacroAssembler::repne_scanw(Register addr, Register value, Register count,
1153                                 Register scratch) {
1154   Label Lloop, Lexit;
1155   cbz(count, Lexit);
1156   bind(Lloop);
1157   ldrw(scratch, post(addr, wordSize));
1158   cmpw(value, scratch);
1159   br(EQ, Lexit);
1160   sub(count, count, 1);
1161   cbnz(count, Lloop);
1162   bind(Lexit);
1163 }
1164 
check_klass_subtype_slow_path(Register sub_klass,Register super_klass,Register temp_reg,Register temp2_reg,Label * L_success,Label * L_failure,bool set_cond_codes)1165 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1166                                                    Register super_klass,
1167                                                    Register temp_reg,
1168                                                    Register temp2_reg,
1169                                                    Label* L_success,
1170                                                    Label* L_failure,
1171                                                    bool set_cond_codes) {
1172   assert_different_registers(sub_klass, super_klass, temp_reg);
1173   if (temp2_reg != noreg)
1174     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1175 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
1176 
1177   Label L_fallthrough;
1178   int label_nulls = 0;
1179   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1180   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1181   assert(label_nulls <= 1, "at most one NULL in the batch");
1182 
1183   // a couple of useful fields in sub_klass:
1184   int ss_offset = in_bytes(Klass::secondary_supers_offset());
1185   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1186   Address secondary_supers_addr(sub_klass, ss_offset);
1187   Address super_cache_addr(     sub_klass, sc_offset);
1188 
1189   BLOCK_COMMENT("check_klass_subtype_slow_path");
1190 
1191   // Do a linear scan of the secondary super-klass chain.
1192   // This code is rarely used, so simplicity is a virtue here.
1193   // The repne_scan instruction uses fixed registers, which we must spill.
1194   // Don't worry too much about pre-existing connections with the input regs.
1195 
1196   assert(sub_klass != r0, "killed reg"); // killed by mov(r0, super)
1197   assert(sub_klass != r2, "killed reg"); // killed by lea(r2, &pst_counter)
1198 
1199   RegSet pushed_registers;
1200   if (!IS_A_TEMP(r2))    pushed_registers += r2;
1201   if (!IS_A_TEMP(r5))    pushed_registers += r5;
1202 
1203   if (super_klass != r0 || UseCompressedOops) {
1204     if (!IS_A_TEMP(r0))   pushed_registers += r0;
1205   }
1206 
1207   push(pushed_registers, sp);
1208 
1209   // Get super_klass value into r0 (even if it was in r5 or r2).
1210   if (super_klass != r0) {
1211     mov(r0, super_klass);
1212   }
1213 
1214 #ifndef PRODUCT
1215   mov(rscratch2, (address)&SharedRuntime::_partial_subtype_ctr);
1216   Address pst_counter_addr(rscratch2);
1217   ldr(rscratch1, pst_counter_addr);
1218   add(rscratch1, rscratch1, 1);
1219   str(rscratch1, pst_counter_addr);
1220 #endif //PRODUCT
1221 
1222   // We will consult the secondary-super array.
1223   ldr(r5, secondary_supers_addr);
1224   // Load the array length.  (Positive movl does right thing on LP64.)
1225   ldrw(r2, Address(r5, Array<Klass*>::length_offset_in_bytes()));
1226   // Skip to start of data.
1227   add(r5, r5, Array<Klass*>::base_offset_in_bytes());
1228 
1229   cmp(sp, zr); // Clear Z flag; SP is never zero
1230   // Scan R2 words at [R5] for an occurrence of R0.
1231   // Set NZ/Z based on last compare.
1232   repne_scan(r5, r0, r2, rscratch1);
1233 
1234   // Unspill the temp. registers:
1235   pop(pushed_registers, sp);
1236 
1237   br(Assembler::NE, *L_failure);
1238 
1239   // Success.  Cache the super we found and proceed in triumph.
1240   str(super_klass, super_cache_addr);
1241 
1242   if (L_success != &L_fallthrough) {
1243     b(*L_success);
1244   }
1245 
1246 #undef IS_A_TEMP
1247 
1248   bind(L_fallthrough);
1249 }
1250 
1251 
verify_oop(Register reg,const char * s)1252 void MacroAssembler::verify_oop(Register reg, const char* s) {
1253   if (!VerifyOops) return;
1254 
1255   // Pass register number to verify_oop_subroutine
1256   const char* b = NULL;
1257   {
1258     ResourceMark rm;
1259     stringStream ss;
1260     ss.print("verify_oop: %s: %s", reg->name(), s);
1261     b = code_string(ss.as_string());
1262   }
1263   BLOCK_COMMENT("verify_oop {");
1264 
1265   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1266   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1267 
1268   mov(r0, reg);
1269   movptr(rscratch1, (uintptr_t)(address)b);
1270 
1271   // call indirectly to solve generation ordering problem
1272   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1273   ldr(rscratch2, Address(rscratch2));
1274   blr(rscratch2);
1275 
1276   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1277   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1278 
1279   BLOCK_COMMENT("} verify_oop");
1280 }
1281 
verify_oop_addr(Address addr,const char * s)1282 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
1283   if (!VerifyOops) return;
1284 
1285   const char* b = NULL;
1286   {
1287     ResourceMark rm;
1288     stringStream ss;
1289     ss.print("verify_oop_addr: %s", s);
1290     b = code_string(ss.as_string());
1291   }
1292   BLOCK_COMMENT("verify_oop_addr {");
1293 
1294   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1295   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1296 
1297   // addr may contain sp so we will have to adjust it based on the
1298   // pushes that we just did.
1299   if (addr.uses(sp)) {
1300     lea(r0, addr);
1301     ldr(r0, Address(r0, 4 * wordSize));
1302   } else {
1303     ldr(r0, addr);
1304   }
1305   movptr(rscratch1, (uintptr_t)(address)b);
1306 
1307   // call indirectly to solve generation ordering problem
1308   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1309   ldr(rscratch2, Address(rscratch2));
1310   blr(rscratch2);
1311 
1312   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1313   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1314 
1315   BLOCK_COMMENT("} verify_oop_addr");
1316 }
1317 
argument_address(RegisterOrConstant arg_slot,int extra_slot_offset)1318 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
1319                                          int extra_slot_offset) {
1320   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
1321   int stackElementSize = Interpreter::stackElementSize;
1322   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
1323 #ifdef ASSERT
1324   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
1325   assert(offset1 - offset == stackElementSize, "correct arithmetic");
1326 #endif
1327   if (arg_slot.is_constant()) {
1328     return Address(esp, arg_slot.as_constant() * stackElementSize
1329                    + offset);
1330   } else {
1331     add(rscratch1, esp, arg_slot.as_register(),
1332         ext::uxtx, exact_log2(stackElementSize));
1333     return Address(rscratch1, offset);
1334   }
1335 }
1336 
call_VM_leaf_base(address entry_point,int number_of_arguments,Label * retaddr)1337 void MacroAssembler::call_VM_leaf_base(address entry_point,
1338                                        int number_of_arguments,
1339                                        Label *retaddr) {
1340   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
1341 
1342   // We add 1 to number_of_arguments because the thread in arg0 is
1343   // not counted
1344   mov(rscratch1, entry_point);
1345   blr(rscratch1);
1346   if (retaddr)
1347     bind(*retaddr);
1348 
1349   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
1350   maybe_isb();
1351 }
1352 
call_VM_leaf(address entry_point,int number_of_arguments)1353 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
1354   call_VM_leaf_base(entry_point, number_of_arguments);
1355 }
1356 
call_VM_leaf(address entry_point,Register arg_0)1357 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
1358   pass_arg0(this, arg_0);
1359   call_VM_leaf_base(entry_point, 1);
1360 }
1361 
call_VM_leaf(address entry_point,Register arg_0,Register arg_1)1362 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1363   pass_arg0(this, arg_0);
1364   pass_arg1(this, arg_1);
1365   call_VM_leaf_base(entry_point, 2);
1366 }
1367 
call_VM_leaf(address entry_point,Register arg_0,Register arg_1,Register arg_2)1368 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
1369                                   Register arg_1, Register arg_2) {
1370   pass_arg0(this, arg_0);
1371   pass_arg1(this, arg_1);
1372   pass_arg2(this, arg_2);
1373   call_VM_leaf_base(entry_point, 3);
1374 }
1375 
super_call_VM_leaf(address entry_point,Register arg_0)1376 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
1377   pass_arg0(this, arg_0);
1378   MacroAssembler::call_VM_leaf_base(entry_point, 1);
1379 }
1380 
super_call_VM_leaf(address entry_point,Register arg_0,Register arg_1)1381 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1382 
1383   assert(arg_0 != c_rarg1, "smashed arg");
1384   pass_arg1(this, arg_1);
1385   pass_arg0(this, arg_0);
1386   MacroAssembler::call_VM_leaf_base(entry_point, 2);
1387 }
1388 
super_call_VM_leaf(address entry_point,Register arg_0,Register arg_1,Register arg_2)1389 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1390   assert(arg_0 != c_rarg2, "smashed arg");
1391   assert(arg_1 != c_rarg2, "smashed arg");
1392   pass_arg2(this, arg_2);
1393   assert(arg_0 != c_rarg1, "smashed arg");
1394   pass_arg1(this, arg_1);
1395   pass_arg0(this, arg_0);
1396   MacroAssembler::call_VM_leaf_base(entry_point, 3);
1397 }
1398 
super_call_VM_leaf(address entry_point,Register arg_0,Register arg_1,Register arg_2,Register arg_3)1399 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1400   assert(arg_0 != c_rarg3, "smashed arg");
1401   assert(arg_1 != c_rarg3, "smashed arg");
1402   assert(arg_2 != c_rarg3, "smashed arg");
1403   pass_arg3(this, arg_3);
1404   assert(arg_0 != c_rarg2, "smashed arg");
1405   assert(arg_1 != c_rarg2, "smashed arg");
1406   pass_arg2(this, arg_2);
1407   assert(arg_0 != c_rarg1, "smashed arg");
1408   pass_arg1(this, arg_1);
1409   pass_arg0(this, arg_0);
1410   MacroAssembler::call_VM_leaf_base(entry_point, 4);
1411 }
1412 
null_check(Register reg,int offset)1413 void MacroAssembler::null_check(Register reg, int offset) {
1414   if (needs_explicit_null_check(offset)) {
1415     // provoke OS NULL exception if reg = NULL by
1416     // accessing M[reg] w/o changing any registers
1417     // NOTE: this is plenty to provoke a segv
1418     ldr(zr, Address(reg));
1419   } else {
1420     // nothing to do, (later) access of M[reg + offset]
1421     // will provoke OS NULL exception if reg = NULL
1422   }
1423 }
1424 
1425 // MacroAssembler protected routines needed to implement
1426 // public methods
1427 
mov(Register r,Address dest)1428 void MacroAssembler::mov(Register r, Address dest) {
1429   code_section()->relocate(pc(), dest.rspec());
1430   u_int64_t imm64 = (u_int64_t)dest.target();
1431   movptr(r, imm64);
1432 }
1433 
1434 // Move a constant pointer into r.  In AArch64 mode the virtual
1435 // address space is 48 bits in size, so we only need three
1436 // instructions to create a patchable instruction sequence that can
1437 // reach anywhere.
movptr(Register r,uintptr_t imm64)1438 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
1439 #ifndef PRODUCT
1440   {
1441     char buffer[64];
1442     snprintf(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
1443     block_comment(buffer);
1444   }
1445 #endif
1446   assert(imm64 < (1ul << 48), "48-bit overflow in address constant");
1447   movz(r, imm64 & 0xffff);
1448   imm64 >>= 16;
1449   movk(r, imm64 & 0xffff, 16);
1450   imm64 >>= 16;
1451   movk(r, imm64 & 0xffff, 32);
1452 }
1453 
1454 // Macro to mov replicated immediate to vector register.
1455 //  Vd will get the following values for different arrangements in T
1456 //   imm32 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
1457 //   imm32 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
1458 //   imm32 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
1459 //   imm32 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
1460 //   imm32 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
1461 //   imm32 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
1462 //   T1D/T2D: invalid
mov(FloatRegister Vd,SIMD_Arrangement T,u_int32_t imm32)1463 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, u_int32_t imm32) {
1464   assert(T != T1D && T != T2D, "invalid arrangement");
1465   if (T == T8B || T == T16B) {
1466     assert((imm32 & ~0xff) == 0, "extraneous bits in unsigned imm32 (T8B/T16B)");
1467     movi(Vd, T, imm32 & 0xff, 0);
1468     return;
1469   }
1470   u_int32_t nimm32 = ~imm32;
1471   if (T == T4H || T == T8H) {
1472     assert((imm32  & ~0xffff) == 0, "extraneous bits in unsigned imm32 (T4H/T8H)");
1473     imm32 &= 0xffff;
1474     nimm32 &= 0xffff;
1475   }
1476   u_int32_t x = imm32;
1477   int movi_cnt = 0;
1478   int movn_cnt = 0;
1479   while (x) { if (x & 0xff) movi_cnt++; x >>= 8; }
1480   x = nimm32;
1481   while (x) { if (x & 0xff) movn_cnt++; x >>= 8; }
1482   if (movn_cnt < movi_cnt) imm32 = nimm32;
1483   unsigned lsl = 0;
1484   while (imm32 && (imm32 & 0xff) == 0) { lsl += 8; imm32 >>= 8; }
1485   if (movn_cnt < movi_cnt)
1486     mvni(Vd, T, imm32 & 0xff, lsl);
1487   else
1488     movi(Vd, T, imm32 & 0xff, lsl);
1489   imm32 >>= 8; lsl += 8;
1490   while (imm32) {
1491     while ((imm32 & 0xff) == 0) { lsl += 8; imm32 >>= 8; }
1492     if (movn_cnt < movi_cnt)
1493       bici(Vd, T, imm32 & 0xff, lsl);
1494     else
1495       orri(Vd, T, imm32 & 0xff, lsl);
1496     lsl += 8; imm32 >>= 8;
1497   }
1498 }
1499 
mov_immediate64(Register dst,u_int64_t imm64)1500 void MacroAssembler::mov_immediate64(Register dst, u_int64_t imm64)
1501 {
1502 #ifndef PRODUCT
1503   {
1504     char buffer[64];
1505     snprintf(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
1506     block_comment(buffer);
1507   }
1508 #endif
1509   if (operand_valid_for_logical_immediate(false, imm64)) {
1510     orr(dst, zr, imm64);
1511   } else {
1512     // we can use a combination of MOVZ or MOVN with
1513     // MOVK to build up the constant
1514     u_int64_t imm_h[4];
1515     int zero_count = 0;
1516     int neg_count = 0;
1517     int i;
1518     for (i = 0; i < 4; i++) {
1519       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
1520       if (imm_h[i] == 0) {
1521         zero_count++;
1522       } else if (imm_h[i] == 0xffffL) {
1523         neg_count++;
1524       }
1525     }
1526     if (zero_count == 4) {
1527       // one MOVZ will do
1528       movz(dst, 0);
1529     } else if (neg_count == 4) {
1530       // one MOVN will do
1531       movn(dst, 0);
1532     } else if (zero_count == 3) {
1533       for (i = 0; i < 4; i++) {
1534         if (imm_h[i] != 0L) {
1535           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1536           break;
1537         }
1538       }
1539     } else if (neg_count == 3) {
1540       // one MOVN will do
1541       for (int i = 0; i < 4; i++) {
1542         if (imm_h[i] != 0xffffL) {
1543           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1544           break;
1545         }
1546       }
1547     } else if (zero_count == 2) {
1548       // one MOVZ and one MOVK will do
1549       for (i = 0; i < 3; i++) {
1550         if (imm_h[i] != 0L) {
1551           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1552           i++;
1553           break;
1554         }
1555       }
1556       for (;i < 4; i++) {
1557         if (imm_h[i] != 0L) {
1558           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1559         }
1560       }
1561     } else if (neg_count == 2) {
1562       // one MOVN and one MOVK will do
1563       for (i = 0; i < 4; i++) {
1564         if (imm_h[i] != 0xffffL) {
1565           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1566           i++;
1567           break;
1568         }
1569       }
1570       for (;i < 4; i++) {
1571         if (imm_h[i] != 0xffffL) {
1572           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1573         }
1574       }
1575     } else if (zero_count == 1) {
1576       // one MOVZ and two MOVKs will do
1577       for (i = 0; i < 4; i++) {
1578         if (imm_h[i] != 0L) {
1579           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1580           i++;
1581           break;
1582         }
1583       }
1584       for (;i < 4; i++) {
1585         if (imm_h[i] != 0x0L) {
1586           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1587         }
1588       }
1589     } else if (neg_count == 1) {
1590       // one MOVN and two MOVKs will do
1591       for (i = 0; i < 4; i++) {
1592         if (imm_h[i] != 0xffffL) {
1593           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1594           i++;
1595           break;
1596         }
1597       }
1598       for (;i < 4; i++) {
1599         if (imm_h[i] != 0xffffL) {
1600           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1601         }
1602       }
1603     } else {
1604       // use a MOVZ and 3 MOVKs (makes it easier to debug)
1605       movz(dst, (u_int32_t)imm_h[0], 0);
1606       for (i = 1; i < 4; i++) {
1607         movk(dst, (u_int32_t)imm_h[i], (i << 4));
1608       }
1609     }
1610   }
1611 }
1612 
mov_immediate32(Register dst,u_int32_t imm32)1613 void MacroAssembler::mov_immediate32(Register dst, u_int32_t imm32)
1614 {
1615 #ifndef PRODUCT
1616     {
1617       char buffer[64];
1618       snprintf(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
1619       block_comment(buffer);
1620     }
1621 #endif
1622   if (operand_valid_for_logical_immediate(true, imm32)) {
1623     orrw(dst, zr, imm32);
1624   } else {
1625     // we can use MOVZ, MOVN or two calls to MOVK to build up the
1626     // constant
1627     u_int32_t imm_h[2];
1628     imm_h[0] = imm32 & 0xffff;
1629     imm_h[1] = ((imm32 >> 16) & 0xffff);
1630     if (imm_h[0] == 0) {
1631       movzw(dst, imm_h[1], 16);
1632     } else if (imm_h[0] == 0xffff) {
1633       movnw(dst, imm_h[1] ^ 0xffff, 16);
1634     } else if (imm_h[1] == 0) {
1635       movzw(dst, imm_h[0], 0);
1636     } else if (imm_h[1] == 0xffff) {
1637       movnw(dst, imm_h[0] ^ 0xffff, 0);
1638     } else {
1639       // use a MOVZ and MOVK (makes it easier to debug)
1640       movzw(dst, imm_h[0], 0);
1641       movkw(dst, imm_h[1], 16);
1642     }
1643   }
1644 }
1645 
1646 // Form an address from base + offset in Rd.  Rd may or may
1647 // not actually be used: you must use the Address that is returned.
1648 // It is up to you to ensure that the shift provided matches the size
1649 // of your data.
form_address(Register Rd,Register base,long byte_offset,int shift)1650 Address MacroAssembler::form_address(Register Rd, Register base, long byte_offset, int shift) {
1651   if (Address::offset_ok_for_immed(byte_offset, shift))
1652     // It fits; no need for any heroics
1653     return Address(base, byte_offset);
1654 
1655   // Don't do anything clever with negative or misaligned offsets
1656   unsigned mask = (1 << shift) - 1;
1657   if (byte_offset < 0 || byte_offset & mask) {
1658     mov(Rd, byte_offset);
1659     add(Rd, base, Rd);
1660     return Address(Rd);
1661   }
1662 
1663   // See if we can do this with two 12-bit offsets
1664   {
1665     unsigned long word_offset = byte_offset >> shift;
1666     unsigned long masked_offset = word_offset & 0xfff000;
1667     if (Address::offset_ok_for_immed(word_offset - masked_offset)
1668         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
1669       add(Rd, base, masked_offset << shift);
1670       word_offset -= masked_offset;
1671       return Address(Rd, word_offset << shift);
1672     }
1673   }
1674 
1675   // Do it the hard way
1676   mov(Rd, byte_offset);
1677   add(Rd, base, Rd);
1678   return Address(Rd);
1679 }
1680 
atomic_incw(Register counter_addr,Register tmp,Register tmp2)1681 void MacroAssembler::atomic_incw(Register counter_addr, Register tmp, Register tmp2) {
1682   if (UseLSE) {
1683     mov(tmp, 1);
1684     ldadd(Assembler::word, tmp, zr, counter_addr);
1685     return;
1686   }
1687   Label retry_load;
1688   if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))
1689     prfm(Address(counter_addr), PSTL1STRM);
1690   bind(retry_load);
1691   // flush and load exclusive from the memory location
1692   ldxrw(tmp, counter_addr);
1693   addw(tmp, tmp, 1);
1694   // if we store+flush with no intervening write tmp wil be zero
1695   stxrw(tmp2, tmp, counter_addr);
1696   cbnzw(tmp2, retry_load);
1697 }
1698 
1699 
corrected_idivl(Register result,Register ra,Register rb,bool want_remainder,Register scratch)1700 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
1701                                     bool want_remainder, Register scratch)
1702 {
1703   // Full implementation of Java idiv and irem.  The function
1704   // returns the (pc) offset of the div instruction - may be needed
1705   // for implicit exceptions.
1706   //
1707   // constraint : ra/rb =/= scratch
1708   //         normal case
1709   //
1710   // input : ra: dividend
1711   //         rb: divisor
1712   //
1713   // result: either
1714   //         quotient  (= ra idiv rb)
1715   //         remainder (= ra irem rb)
1716 
1717   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1718 
1719   int idivl_offset = offset();
1720   if (! want_remainder) {
1721     sdivw(result, ra, rb);
1722   } else {
1723     sdivw(scratch, ra, rb);
1724     Assembler::msubw(result, scratch, rb, ra);
1725   }
1726 
1727   return idivl_offset;
1728 }
1729 
corrected_idivq(Register result,Register ra,Register rb,bool want_remainder,Register scratch)1730 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
1731                                     bool want_remainder, Register scratch)
1732 {
1733   // Full implementation of Java ldiv and lrem.  The function
1734   // returns the (pc) offset of the div instruction - may be needed
1735   // for implicit exceptions.
1736   //
1737   // constraint : ra/rb =/= scratch
1738   //         normal case
1739   //
1740   // input : ra: dividend
1741   //         rb: divisor
1742   //
1743   // result: either
1744   //         quotient  (= ra idiv rb)
1745   //         remainder (= ra irem rb)
1746 
1747   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1748 
1749   int idivq_offset = offset();
1750   if (! want_remainder) {
1751     sdiv(result, ra, rb);
1752   } else {
1753     sdiv(scratch, ra, rb);
1754     Assembler::msub(result, scratch, rb, ra);
1755   }
1756 
1757   return idivq_offset;
1758 }
1759 
1760 // MacroAssembler routines found actually to be needed
1761 
push(Register src)1762 void MacroAssembler::push(Register src)
1763 {
1764   str(src, Address(pre(esp, -1 * wordSize)));
1765 }
1766 
pop(Register dst)1767 void MacroAssembler::pop(Register dst)
1768 {
1769   ldr(dst, Address(post(esp, 1 * wordSize)));
1770 }
1771 
1772 // Note: load_unsigned_short used to be called load_unsigned_word.
load_unsigned_short(Register dst,Address src)1773 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
1774   int off = offset();
1775   ldrh(dst, src);
1776   return off;
1777 }
1778 
load_unsigned_byte(Register dst,Address src)1779 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
1780   int off = offset();
1781   ldrb(dst, src);
1782   return off;
1783 }
1784 
load_signed_short(Register dst,Address src)1785 int MacroAssembler::load_signed_short(Register dst, Address src) {
1786   int off = offset();
1787   ldrsh(dst, src);
1788   return off;
1789 }
1790 
load_signed_byte(Register dst,Address src)1791 int MacroAssembler::load_signed_byte(Register dst, Address src) {
1792   int off = offset();
1793   ldrsb(dst, src);
1794   return off;
1795 }
1796 
load_signed_short32(Register dst,Address src)1797 int MacroAssembler::load_signed_short32(Register dst, Address src) {
1798   int off = offset();
1799   ldrshw(dst, src);
1800   return off;
1801 }
1802 
load_signed_byte32(Register dst,Address src)1803 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
1804   int off = offset();
1805   ldrsbw(dst, src);
1806   return off;
1807 }
1808 
load_sized_value(Register dst,Address src,size_t size_in_bytes,bool is_signed,Register dst2)1809 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
1810   switch (size_in_bytes) {
1811   case  8:  ldr(dst, src); break;
1812   case  4:  ldrw(dst, src); break;
1813   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
1814   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
1815   default:  ShouldNotReachHere();
1816   }
1817 }
1818 
store_sized_value(Address dst,Register src,size_t size_in_bytes,Register src2)1819 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
1820   switch (size_in_bytes) {
1821   case  8:  str(src, dst); break;
1822   case  4:  strw(src, dst); break;
1823   case  2:  strh(src, dst); break;
1824   case  1:  strb(src, dst); break;
1825   default:  ShouldNotReachHere();
1826   }
1827 }
1828 
decrementw(Register reg,int value)1829 void MacroAssembler::decrementw(Register reg, int value)
1830 {
1831   if (value < 0)  { incrementw(reg, -value);      return; }
1832   if (value == 0) {                               return; }
1833   if (value < (1 << 12)) { subw(reg, reg, value); return; }
1834   /* else */ {
1835     guarantee(reg != rscratch2, "invalid dst for register decrement");
1836     movw(rscratch2, (unsigned)value);
1837     subw(reg, reg, rscratch2);
1838   }
1839 }
1840 
decrement(Register reg,int value)1841 void MacroAssembler::decrement(Register reg, int value)
1842 {
1843   if (value < 0)  { increment(reg, -value);      return; }
1844   if (value == 0) {                              return; }
1845   if (value < (1 << 12)) { sub(reg, reg, value); return; }
1846   /* else */ {
1847     assert(reg != rscratch2, "invalid dst for register decrement");
1848     mov(rscratch2, (u_int64_t)value);
1849     sub(reg, reg, rscratch2);
1850   }
1851 }
1852 
decrementw(Address dst,int value)1853 void MacroAssembler::decrementw(Address dst, int value)
1854 {
1855   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
1856   ldrw(rscratch1, dst);
1857   decrementw(rscratch1, value);
1858   strw(rscratch1, dst);
1859 }
1860 
decrement(Address dst,int value)1861 void MacroAssembler::decrement(Address dst, int value)
1862 {
1863   assert(!dst.uses(rscratch1), "invalid address for decrement");
1864   ldr(rscratch1, dst);
1865   decrement(rscratch1, value);
1866   str(rscratch1, dst);
1867 }
1868 
incrementw(Register reg,int value)1869 void MacroAssembler::incrementw(Register reg, int value)
1870 {
1871   if (value < 0)  { decrementw(reg, -value);      return; }
1872   if (value == 0) {                               return; }
1873   if (value < (1 << 12)) { addw(reg, reg, value); return; }
1874   /* else */ {
1875     assert(reg != rscratch2, "invalid dst for register increment");
1876     movw(rscratch2, (unsigned)value);
1877     addw(reg, reg, rscratch2);
1878   }
1879 }
1880 
increment(Register reg,int value)1881 void MacroAssembler::increment(Register reg, int value)
1882 {
1883   if (value < 0)  { decrement(reg, -value);      return; }
1884   if (value == 0) {                              return; }
1885   if (value < (1 << 12)) { add(reg, reg, value); return; }
1886   /* else */ {
1887     assert(reg != rscratch2, "invalid dst for register increment");
1888     movw(rscratch2, (unsigned)value);
1889     add(reg, reg, rscratch2);
1890   }
1891 }
1892 
incrementw(Address dst,int value)1893 void MacroAssembler::incrementw(Address dst, int value)
1894 {
1895   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1896   ldrw(rscratch1, dst);
1897   incrementw(rscratch1, value);
1898   strw(rscratch1, dst);
1899 }
1900 
increment(Address dst,int value)1901 void MacroAssembler::increment(Address dst, int value)
1902 {
1903   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1904   ldr(rscratch1, dst);
1905   increment(rscratch1, value);
1906   str(rscratch1, dst);
1907 }
1908 
1909 
pusha()1910 void MacroAssembler::pusha() {
1911   push(0x7fffffff, sp);
1912 }
1913 
popa()1914 void MacroAssembler::popa() {
1915   pop(0x7fffffff, sp);
1916 }
1917 
1918 // Push lots of registers in the bit set supplied.  Don't push sp.
1919 // Return the number of words pushed
push(unsigned int bitset,Register stack)1920 int MacroAssembler::push(unsigned int bitset, Register stack) {
1921   int words_pushed = 0;
1922 
1923   // Scan bitset to accumulate register pairs
1924   unsigned char regs[32];
1925   int count = 0;
1926   for (int reg = 0; reg <= 30; reg++) {
1927     if (1 & bitset)
1928       regs[count++] = reg;
1929     bitset >>= 1;
1930   }
1931   regs[count++] = zr->encoding_nocheck();
1932   count &= ~1;  // Only push an even nuber of regs
1933 
1934   if (count) {
1935     stp(as_Register(regs[0]), as_Register(regs[1]),
1936        Address(pre(stack, -count * wordSize)));
1937     words_pushed += 2;
1938   }
1939   for (int i = 2; i < count; i += 2) {
1940     stp(as_Register(regs[i]), as_Register(regs[i+1]),
1941        Address(stack, i * wordSize));
1942     words_pushed += 2;
1943   }
1944 
1945   assert(words_pushed == count, "oops, pushed != count");
1946 
1947   return count;
1948 }
1949 
pop(unsigned int bitset,Register stack)1950 int MacroAssembler::pop(unsigned int bitset, Register stack) {
1951   int words_pushed = 0;
1952 
1953   // Scan bitset to accumulate register pairs
1954   unsigned char regs[32];
1955   int count = 0;
1956   for (int reg = 0; reg <= 30; reg++) {
1957     if (1 & bitset)
1958       regs[count++] = reg;
1959     bitset >>= 1;
1960   }
1961   regs[count++] = zr->encoding_nocheck();
1962   count &= ~1;
1963 
1964   for (int i = 2; i < count; i += 2) {
1965     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
1966        Address(stack, i * wordSize));
1967     words_pushed += 2;
1968   }
1969   if (count) {
1970     ldp(as_Register(regs[0]), as_Register(regs[1]),
1971        Address(post(stack, count * wordSize)));
1972     words_pushed += 2;
1973   }
1974 
1975   assert(words_pushed == count, "oops, pushed != count");
1976 
1977   return count;
1978 }
1979 #ifdef ASSERT
verify_heapbase(const char * msg)1980 void MacroAssembler::verify_heapbase(const char* msg) {
1981 #if 0
1982   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
1983   assert (Universe::heap() != NULL, "java heap should be initialized");
1984   if (CheckCompressedOops) {
1985     Label ok;
1986     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
1987     cmpptr(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
1988     br(Assembler::EQ, ok);
1989     stop(msg);
1990     bind(ok);
1991     pop(1 << rscratch1->encoding(), sp);
1992   }
1993 #endif
1994 }
1995 #endif
1996 
stop(const char * msg)1997 void MacroAssembler::stop(const char* msg) {
1998   address ip = pc();
1999   pusha();
2000   movptr(c_rarg0, (uintptr_t)(address)msg);
2001   movptr(c_rarg1, (uintptr_t)(address)ip);
2002   mov(c_rarg2, sp);
2003   mov(c_rarg3, CAST_FROM_FN_PTR(address, MacroAssembler::debug64));
2004   blr(c_rarg3);
2005   hlt(0);
2006 }
2007 
warn(const char * msg)2008 void MacroAssembler::warn(const char* msg) {
2009   pusha();
2010   mov(c_rarg0, (address)msg);
2011   mov(lr, CAST_FROM_FN_PTR(address, warning));
2012   blr(lr);
2013   popa();
2014 }
2015 
2016 // If a constant does not fit in an immediate field, generate some
2017 // number of MOV instructions and then perform the operation.
wrap_add_sub_imm_insn(Register Rd,Register Rn,unsigned imm,add_sub_imm_insn insn1,add_sub_reg_insn insn2)2018 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, unsigned imm,
2019                                            add_sub_imm_insn insn1,
2020                                            add_sub_reg_insn insn2) {
2021   assert(Rd != zr, "Rd = zr and not setting flags?");
2022   if (operand_valid_for_add_sub_immediate((int)imm)) {
2023     (this->*insn1)(Rd, Rn, imm);
2024   } else {
2025     if (uabs(imm) < (1 << 24)) {
2026        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2027        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2028     } else {
2029        assert_different_registers(Rd, Rn);
2030        mov(Rd, (uint64_t)imm);
2031        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2032     }
2033   }
2034 }
2035 
2036 // Seperate vsn which sets the flags. Optimisations are more restricted
2037 // because we must set the flags correctly.
wrap_adds_subs_imm_insn(Register Rd,Register Rn,unsigned imm,add_sub_imm_insn insn1,add_sub_reg_insn insn2)2038 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, unsigned imm,
2039                                            add_sub_imm_insn insn1,
2040                                            add_sub_reg_insn insn2) {
2041   if (operand_valid_for_add_sub_immediate((int)imm)) {
2042     (this->*insn1)(Rd, Rn, imm);
2043   } else {
2044     assert_different_registers(Rd, Rn);
2045     assert(Rd != zr, "overflow in immediate operand");
2046     mov(Rd, (uint64_t)imm);
2047     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2048   }
2049 }
2050 
2051 
add(Register Rd,Register Rn,RegisterOrConstant increment)2052 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2053   if (increment.is_register()) {
2054     add(Rd, Rn, increment.as_register());
2055   } else {
2056     add(Rd, Rn, increment.as_constant());
2057   }
2058 }
2059 
addw(Register Rd,Register Rn,RegisterOrConstant increment)2060 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2061   if (increment.is_register()) {
2062     addw(Rd, Rn, increment.as_register());
2063   } else {
2064     addw(Rd, Rn, increment.as_constant());
2065   }
2066 }
2067 
sub(Register Rd,Register Rn,RegisterOrConstant decrement)2068 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2069   if (decrement.is_register()) {
2070     sub(Rd, Rn, decrement.as_register());
2071   } else {
2072     sub(Rd, Rn, decrement.as_constant());
2073   }
2074 }
2075 
subw(Register Rd,Register Rn,RegisterOrConstant decrement)2076 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2077   if (decrement.is_register()) {
2078     subw(Rd, Rn, decrement.as_register());
2079   } else {
2080     subw(Rd, Rn, decrement.as_constant());
2081   }
2082 }
2083 
reinit_heapbase()2084 void MacroAssembler::reinit_heapbase()
2085 {
2086   if (UseCompressedOops) {
2087     if (Universe::is_fully_initialized()) {
2088       mov(rheapbase, Universe::narrow_ptrs_base());
2089     } else {
2090       lea(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
2091       ldr(rheapbase, Address(rheapbase));
2092     }
2093   }
2094 }
2095 
2096 // this simulates the behaviour of the x86 cmpxchg instruction using a
2097 // load linked/store conditional pair. we use the acquire/release
2098 // versions of these instructions so that we flush pending writes as
2099 // per Java semantics.
2100 
2101 // n.b the x86 version assumes the old value to be compared against is
2102 // in rax and updates rax with the value located in memory if the
2103 // cmpxchg fails. we supply a register for the old value explicitly
2104 
2105 // the aarch64 load linked/store conditional instructions do not
2106 // accept an offset. so, unlike x86, we must provide a plain register
2107 // to identify the memory word to be compared/exchanged rather than a
2108 // register+offset Address.
2109 
cmpxchgptr(Register oldv,Register newv,Register addr,Register tmp,Label & succeed,Label * fail)2110 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2111                                 Label &succeed, Label *fail) {
2112   // oldv holds comparison value
2113   // newv holds value to write in exchange
2114   // addr identifies memory word to compare against/update
2115   if (UseLSE) {
2116     mov(tmp, oldv);
2117     casal(Assembler::xword, oldv, newv, addr);
2118     cmp(tmp, oldv);
2119     br(Assembler::EQ, succeed);
2120     membar(AnyAny);
2121   } else {
2122     Label retry_load, nope;
2123     if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))
2124       prfm(Address(addr), PSTL1STRM);
2125     bind(retry_load);
2126     // flush and load exclusive from the memory location
2127     // and fail if it is not what we expect
2128     ldaxr(tmp, addr);
2129     cmp(tmp, oldv);
2130     br(Assembler::NE, nope);
2131     // if we store+flush with no intervening write tmp wil be zero
2132     stlxr(tmp, newv, addr);
2133     cbzw(tmp, succeed);
2134     // retry so we only ever return after a load fails to compare
2135     // ensures we don't return a stale value after a failed write.
2136     b(retry_load);
2137     // if the memory word differs we return it in oldv and signal a fail
2138     bind(nope);
2139     membar(AnyAny);
2140     mov(oldv, tmp);
2141   }
2142   if (fail)
2143     b(*fail);
2144 }
2145 
cmpxchgw(Register oldv,Register newv,Register addr,Register tmp,Label & succeed,Label * fail)2146 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2147                                 Label &succeed, Label *fail) {
2148   // oldv holds comparison value
2149   // newv holds value to write in exchange
2150   // addr identifies memory word to compare against/update
2151   // tmp returns 0/1 for success/failure
2152   if (UseLSE) {
2153     mov(tmp, oldv);
2154     casal(Assembler::word, oldv, newv, addr);
2155     cmp(tmp, oldv);
2156     br(Assembler::EQ, succeed);
2157     membar(AnyAny);
2158   } else {
2159     Label retry_load, nope;
2160     if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))
2161       prfm(Address(addr), PSTL1STRM);
2162     bind(retry_load);
2163     // flush and load exclusive from the memory location
2164     // and fail if it is not what we expect
2165     ldaxrw(tmp, addr);
2166     cmp(tmp, oldv);
2167     br(Assembler::NE, nope);
2168     // if we store+flush with no intervening write tmp wil be zero
2169     stlxrw(tmp, newv, addr);
2170     cbzw(tmp, succeed);
2171     // retry so we only ever return after a load fails to compare
2172     // ensures we don't return a stale value after a failed write.
2173     b(retry_load);
2174     // if the memory word differs we return it in oldv and signal a fail
2175     bind(nope);
2176     membar(AnyAny);
2177     mov(oldv, tmp);
2178   }
2179   if (fail)
2180     b(*fail);
2181 }
2182 
2183 // A generic CAS; success or failure is in the EQ flag.
cmpxchg(Register addr,Register expected,Register new_val,enum operand_size size,bool acquire,bool release,Register tmp)2184 void MacroAssembler::cmpxchg(Register addr, Register expected,
2185                              Register new_val,
2186                              enum operand_size size,
2187                              bool acquire, bool release,
2188                              Register tmp) {
2189   if (UseLSE) {
2190     mov(tmp, expected);
2191     lse_cas(tmp, new_val, addr, size, acquire, release, /*not_pair*/ true);
2192     cmp(tmp, expected);
2193   } else {
2194     BLOCK_COMMENT("cmpxchg {");
2195     Label retry_load, done;
2196     if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))
2197       prfm(Address(addr), PSTL1STRM);
2198     bind(retry_load);
2199     load_exclusive(tmp, addr, size, acquire);
2200     if (size == xword)
2201       cmp(tmp, expected);
2202     else
2203       cmpw(tmp, expected);
2204     br(Assembler::NE, done);
2205     store_exclusive(tmp, new_val, addr, size, release);
2206     cbnzw(tmp, retry_load);
2207     bind(done);
2208     BLOCK_COMMENT("} cmpxchg");
2209   }
2210 }
2211 
different(Register a,RegisterOrConstant b,Register c)2212 static bool different(Register a, RegisterOrConstant b, Register c) {
2213   if (b.is_constant())
2214     return a != c;
2215   else
2216     return a != b.as_register() && a != c && b.as_register() != c;
2217 }
2218 
2219 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2220 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2221   if (UseLSE) {                                                         \
2222     prev = prev->is_valid() ? prev : zr;                                \
2223     if (incr.is_register()) {                                           \
2224       AOP(sz, incr.as_register(), prev, addr);                          \
2225     } else {                                                            \
2226       mov(rscratch2, incr.as_constant());                               \
2227       AOP(sz, rscratch2, prev, addr);                                   \
2228     }                                                                   \
2229     return;                                                             \
2230   }                                                                     \
2231   Register result = rscratch2;                                          \
2232   if (prev->is_valid())                                                 \
2233     result = different(prev, incr, addr) ? prev : rscratch2;            \
2234                                                                         \
2235   Label retry_load;                                                     \
2236   if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))         \
2237     prfm(Address(addr), PSTL1STRM);                                     \
2238   bind(retry_load);                                                     \
2239   LDXR(result, addr);                                                   \
2240   OP(rscratch1, result, incr);                                          \
2241   STXR(rscratch2, rscratch1, addr);                                     \
2242   cbnzw(rscratch2, retry_load);                                         \
2243   if (prev->is_valid() && prev != result) {                             \
2244     IOP(prev, rscratch1, incr);                                         \
2245   }                                                                     \
2246 }
2247 
ATOMIC_OP(add,ldxr,add,sub,ldadd,stxr,Assembler::xword)2248 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2249 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2250 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2251 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2252 
2253 #undef ATOMIC_OP
2254 
2255 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2256 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2257   if (UseLSE) {                                                         \
2258     prev = prev->is_valid() ? prev : zr;                                \
2259     AOP(sz, newv, prev, addr);                                          \
2260     return;                                                             \
2261   }                                                                     \
2262   Register result = rscratch2;                                          \
2263   if (prev->is_valid())                                                 \
2264     result = different(prev, newv, addr) ? prev : rscratch2;            \
2265                                                                         \
2266   Label retry_load;                                                     \
2267   if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))         \
2268     prfm(Address(addr), PSTL1STRM);                                     \
2269   bind(retry_load);                                                     \
2270   LDXR(result, addr);                                                   \
2271   STXR(rscratch1, newv, addr);                                          \
2272   cbnzw(rscratch1, retry_load);                                         \
2273   if (prev->is_valid() && prev != result)                               \
2274     mov(prev, result);                                                  \
2275 }
2276 
2277 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2278 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2279 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2280 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2281 
2282 #undef ATOMIC_XCHG
2283 
2284 void MacroAssembler::incr_allocated_bytes(Register thread,
2285                                           Register var_size_in_bytes,
2286                                           int con_size_in_bytes,
2287                                           Register t1) {
2288   if (!thread->is_valid()) {
2289     thread = rthread;
2290   }
2291   assert(t1->is_valid(), "need temp reg");
2292 
2293   ldr(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2294   if (var_size_in_bytes->is_valid()) {
2295     add(t1, t1, var_size_in_bytes);
2296   } else {
2297     add(t1, t1, con_size_in_bytes);
2298   }
2299   str(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2300 }
2301 
2302 #ifndef PRODUCT
2303 extern "C" void findpc(intptr_t x);
2304 #endif
2305 
debug64(char * msg,int64_t pc,int64_t regs[])2306 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2307 {
2308   // In order to get locks to work, we need to fake a in_VM state
2309   if (ShowMessageBoxOnError ) {
2310     JavaThread* thread = JavaThread::current();
2311     JavaThreadState saved_state = thread->thread_state();
2312     thread->set_thread_state(_thread_in_vm);
2313 #ifndef PRODUCT
2314     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2315       ttyLocker ttyl;
2316       BytecodeCounter::print();
2317     }
2318 #endif
2319     if (os::message_box(msg, "Execution stopped, print registers?")) {
2320       ttyLocker ttyl;
2321       tty->print_cr(" pc = 0x%016lx", pc);
2322 #ifndef PRODUCT
2323       tty->cr();
2324       findpc(pc);
2325       tty->cr();
2326 #endif
2327       tty->print_cr(" r0 = 0x%016lx", regs[0]);
2328       tty->print_cr(" r1 = 0x%016lx", regs[1]);
2329       tty->print_cr(" r2 = 0x%016lx", regs[2]);
2330       tty->print_cr(" r3 = 0x%016lx", regs[3]);
2331       tty->print_cr(" r4 = 0x%016lx", regs[4]);
2332       tty->print_cr(" r5 = 0x%016lx", regs[5]);
2333       tty->print_cr(" r6 = 0x%016lx", regs[6]);
2334       tty->print_cr(" r7 = 0x%016lx", regs[7]);
2335       tty->print_cr(" r8 = 0x%016lx", regs[8]);
2336       tty->print_cr(" r9 = 0x%016lx", regs[9]);
2337       tty->print_cr("r10 = 0x%016lx", regs[10]);
2338       tty->print_cr("r11 = 0x%016lx", regs[11]);
2339       tty->print_cr("r12 = 0x%016lx", regs[12]);
2340       tty->print_cr("r13 = 0x%016lx", regs[13]);
2341       tty->print_cr("r14 = 0x%016lx", regs[14]);
2342       tty->print_cr("r15 = 0x%016lx", regs[15]);
2343       tty->print_cr("r16 = 0x%016lx", regs[16]);
2344       tty->print_cr("r17 = 0x%016lx", regs[17]);
2345       tty->print_cr("r18 = 0x%016lx", regs[18]);
2346       tty->print_cr("r19 = 0x%016lx", regs[19]);
2347       tty->print_cr("r20 = 0x%016lx", regs[20]);
2348       tty->print_cr("r21 = 0x%016lx", regs[21]);
2349       tty->print_cr("r22 = 0x%016lx", regs[22]);
2350       tty->print_cr("r23 = 0x%016lx", regs[23]);
2351       tty->print_cr("r24 = 0x%016lx", regs[24]);
2352       tty->print_cr("r25 = 0x%016lx", regs[25]);
2353       tty->print_cr("r26 = 0x%016lx", regs[26]);
2354       tty->print_cr("r27 = 0x%016lx", regs[27]);
2355       tty->print_cr("r28 = 0x%016lx", regs[28]);
2356       tty->print_cr("r30 = 0x%016lx", regs[30]);
2357       tty->print_cr("r31 = 0x%016lx", regs[31]);
2358       BREAKPOINT;
2359     }
2360     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
2361   } else {
2362     ttyLocker ttyl;
2363     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
2364                     msg);
2365     assert(false, err_msg("DEBUG MESSAGE: %s", msg));
2366   }
2367 }
2368 
push_call_clobbered_registers()2369 void MacroAssembler::push_call_clobbered_registers() {
2370   push(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2371 
2372   // Push v0-v7, v16-v31.
2373   for (int i = 30; i >= 0; i -= 2) {
2374     if (i <= v7->encoding() || i >= v16->encoding()) {
2375         stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2376              Address(pre(sp, -2 * wordSize)));
2377     }
2378   }
2379 }
2380 
pop_call_clobbered_registers()2381 void MacroAssembler::pop_call_clobbered_registers() {
2382 
2383   for (int i = 0; i < 32; i += 2) {
2384     if (i <= v7->encoding() || i >= v16->encoding()) {
2385       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2386            Address(post(sp, 2 * wordSize)));
2387     }
2388   }
2389 
2390   pop(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2391 }
2392 
push_CPU_state(bool save_vectors)2393 void MacroAssembler::push_CPU_state(bool save_vectors) {
2394   push(0x3fffffff, sp);         // integer registers except lr & sp
2395 
2396   if (!save_vectors) {
2397     for (int i = 30; i >= 0; i -= 2)
2398       stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2399            Address(pre(sp, -2 * wordSize)));
2400   } else {
2401     for (int i = 30; i >= 0; i -= 2)
2402       stpq(as_FloatRegister(i), as_FloatRegister(i+1),
2403            Address(pre(sp, -4 * wordSize)));
2404   }
2405 }
2406 
pop_CPU_state(bool restore_vectors)2407 void MacroAssembler::pop_CPU_state(bool restore_vectors) {
2408   if (!restore_vectors) {
2409     for (int i = 0; i < 32; i += 2)
2410       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2411            Address(post(sp, 2 * wordSize)));
2412   } else {
2413     for (int i = 0; i < 32; i += 2)
2414       ldpq(as_FloatRegister(i), as_FloatRegister(i+1),
2415            Address(post(sp, 4 * wordSize)));
2416   }
2417 
2418   pop(0x3fffffff, sp);         // integer registers except lr & sp
2419 }
2420 
2421 /**
2422  * Helpers for multiply_to_len().
2423  */
add2_with_carry(Register final_dest_hi,Register dest_hi,Register dest_lo,Register src1,Register src2)2424 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2425                                      Register src1, Register src2) {
2426   adds(dest_lo, dest_lo, src1);
2427   adc(dest_hi, dest_hi, zr);
2428   adds(dest_lo, dest_lo, src2);
2429   adc(final_dest_hi, dest_hi, zr);
2430 }
2431 
2432 // Generate an address from (r + r1 extend offset).  "size" is the
2433 // size of the operand.  The result may be in rscratch2.
offsetted_address(Register r,Register r1,Address::extend ext,int offset,int size)2434 Address MacroAssembler::offsetted_address(Register r, Register r1,
2435                                           Address::extend ext, int offset, int size) {
2436   if (offset || (ext.shift() % size != 0)) {
2437     lea(rscratch2, Address(r, r1, ext));
2438     return Address(rscratch2, offset);
2439   } else {
2440     return Address(r, r1, ext);
2441   }
2442 }
2443 
spill_address(int size,int offset,Register tmp)2444 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2445 {
2446   assert(offset >= 0, "spill to negative address?");
2447   // Offset reachable ?
2448   //   Not aligned - 9 bits signed offset
2449   //   Aligned - 12 bits unsigned offset shifted
2450   Register base = sp;
2451   if ((offset & (size-1)) && offset >= (1<<8)) {
2452     add(tmp, base, offset & ((1<<12)-1));
2453     base = tmp;
2454     offset &= -1u<<12;
2455   }
2456 
2457   if (offset >= (1<<12) * size) {
2458     add(tmp, base, offset & (((1<<12)-1)<<12));
2459     base = tmp;
2460     offset &= ~(((1<<12)-1)<<12);
2461   }
2462 
2463   return Address(base, offset);
2464 }
2465 
2466 /**
2467  * Multiply 64 bit by 64 bit first loop.
2468  */
multiply_64_x_64_loop(Register x,Register xstart,Register x_xstart,Register y,Register y_idx,Register z,Register carry,Register product,Register idx,Register kdx)2469 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2470                                            Register y, Register y_idx, Register z,
2471                                            Register carry, Register product,
2472                                            Register idx, Register kdx) {
2473   //
2474   //  jlong carry, x[], y[], z[];
2475   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2476   //    huge_128 product = y[idx] * x[xstart] + carry;
2477   //    z[kdx] = (jlong)product;
2478   //    carry  = (jlong)(product >>> 64);
2479   //  }
2480   //  z[xstart] = carry;
2481   //
2482 
2483   Label L_first_loop, L_first_loop_exit;
2484   Label L_one_x, L_one_y, L_multiply;
2485 
2486   subsw(xstart, xstart, 1);
2487   br(Assembler::MI, L_one_x);
2488 
2489   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2490   ldr(x_xstart, Address(rscratch1));
2491   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2492 
2493   bind(L_first_loop);
2494   subsw(idx, idx, 1);
2495   br(Assembler::MI, L_first_loop_exit);
2496   subsw(idx, idx, 1);
2497   br(Assembler::MI, L_one_y);
2498   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2499   ldr(y_idx, Address(rscratch1));
2500   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2501   bind(L_multiply);
2502 
2503   // AArch64 has a multiply-accumulate instruction that we can't use
2504   // here because it has no way to process carries, so we have to use
2505   // separate add and adc instructions.  Bah.
2506   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2507   mul(product, x_xstart, y_idx);
2508   adds(product, product, carry);
2509   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2510 
2511   subw(kdx, kdx, 2);
2512   ror(product, product, 32); // back to big-endian
2513   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2514 
2515   b(L_first_loop);
2516 
2517   bind(L_one_y);
2518   ldrw(y_idx, Address(y,  0));
2519   b(L_multiply);
2520 
2521   bind(L_one_x);
2522   ldrw(x_xstart, Address(x,  0));
2523   b(L_first_loop);
2524 
2525   bind(L_first_loop_exit);
2526 }
2527 
2528 /**
2529  * Multiply 128 bit by 128. Unrolled inner loop.
2530  *
2531  */
multiply_128_x_128_loop(Register y,Register z,Register carry,Register carry2,Register idx,Register jdx,Register yz_idx1,Register yz_idx2,Register tmp,Register tmp3,Register tmp4,Register tmp6,Register product_hi)2532 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2533                                              Register carry, Register carry2,
2534                                              Register idx, Register jdx,
2535                                              Register yz_idx1, Register yz_idx2,
2536                                              Register tmp, Register tmp3, Register tmp4,
2537                                              Register tmp6, Register product_hi) {
2538 
2539   //   jlong carry, x[], y[], z[];
2540   //   int kdx = ystart+1;
2541   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2542   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2543   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2544   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2545   //     carry  = (jlong)(tmp4 >>> 64);
2546   //     z[kdx+idx+1] = (jlong)tmp3;
2547   //     z[kdx+idx] = (jlong)tmp4;
2548   //   }
2549   //   idx += 2;
2550   //   if (idx > 0) {
2551   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2552   //     z[kdx+idx] = (jlong)yz_idx1;
2553   //     carry  = (jlong)(yz_idx1 >>> 64);
2554   //   }
2555   //
2556 
2557   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2558 
2559   lsrw(jdx, idx, 2);
2560 
2561   bind(L_third_loop);
2562 
2563   subsw(jdx, jdx, 1);
2564   br(Assembler::MI, L_third_loop_exit);
2565   subw(idx, idx, 4);
2566 
2567   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2568 
2569   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2570 
2571   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2572 
2573   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2574   ror(yz_idx2, yz_idx2, 32);
2575 
2576   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2577 
2578   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2579   umulh(tmp4, product_hi, yz_idx1);
2580 
2581   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2582   ror(rscratch2, rscratch2, 32);
2583 
2584   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2585   umulh(carry2, product_hi, yz_idx2);
2586 
2587   // propagate sum of both multiplications into carry:tmp4:tmp3
2588   adds(tmp3, tmp3, carry);
2589   adc(tmp4, tmp4, zr);
2590   adds(tmp3, tmp3, rscratch1);
2591   adcs(tmp4, tmp4, tmp);
2592   adc(carry, carry2, zr);
2593   adds(tmp4, tmp4, rscratch2);
2594   adc(carry, carry, zr);
2595 
2596   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2597   ror(tmp4, tmp4, 32);
2598   stp(tmp4, tmp3, Address(tmp6, 0));
2599 
2600   b(L_third_loop);
2601   bind (L_third_loop_exit);
2602 
2603   andw (idx, idx, 0x3);
2604   cbz(idx, L_post_third_loop_done);
2605 
2606   Label L_check_1;
2607   subsw(idx, idx, 2);
2608   br(Assembler::MI, L_check_1);
2609 
2610   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2611   ldr(yz_idx1, Address(rscratch1, 0));
2612   ror(yz_idx1, yz_idx1, 32);
2613   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2614   umulh(tmp4, product_hi, yz_idx1);
2615   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2616   ldr(yz_idx2, Address(rscratch1, 0));
2617   ror(yz_idx2, yz_idx2, 32);
2618 
2619   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
2620 
2621   ror(tmp3, tmp3, 32);
2622   str(tmp3, Address(rscratch1, 0));
2623 
2624   bind (L_check_1);
2625 
2626   andw (idx, idx, 0x1);
2627   subsw(idx, idx, 1);
2628   br(Assembler::MI, L_post_third_loop_done);
2629   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2630   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
2631   umulh(carry2, tmp4, product_hi);
2632   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2633 
2634   add2_with_carry(carry2, tmp3, tmp4, carry);
2635 
2636   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2637   extr(carry, carry2, tmp3, 32);
2638 
2639   bind(L_post_third_loop_done);
2640 }
2641 
2642 /**
2643  * Code for BigInteger::multiplyToLen() instrinsic.
2644  *
2645  * r0: x
2646  * r1: xlen
2647  * r2: y
2648  * r3: ylen
2649  * r4:  z
2650  * r5: zlen
2651  * r10: tmp1
2652  * r11: tmp2
2653  * r12: tmp3
2654  * r13: tmp4
2655  * r14: tmp5
2656  * r15: tmp6
2657  * r16: tmp7
2658  *
2659  */
multiply_to_len(Register x,Register xlen,Register y,Register ylen,Register z,Register zlen,Register tmp1,Register tmp2,Register tmp3,Register tmp4,Register tmp5,Register tmp6,Register product_hi)2660 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
2661                                      Register z, Register zlen,
2662                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
2663                                      Register tmp5, Register tmp6, Register product_hi) {
2664 
2665   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
2666 
2667   const Register idx = tmp1;
2668   const Register kdx = tmp2;
2669   const Register xstart = tmp3;
2670 
2671   const Register y_idx = tmp4;
2672   const Register carry = tmp5;
2673   const Register product  = xlen;
2674   const Register x_xstart = zlen;  // reuse register
2675 
2676   // First Loop.
2677   //
2678   //  final static long LONG_MASK = 0xffffffffL;
2679   //  int xstart = xlen - 1;
2680   //  int ystart = ylen - 1;
2681   //  long carry = 0;
2682   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2683   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
2684   //    z[kdx] = (int)product;
2685   //    carry = product >>> 32;
2686   //  }
2687   //  z[xstart] = (int)carry;
2688   //
2689 
2690   movw(idx, ylen);      // idx = ylen;
2691   movw(kdx, zlen);      // kdx = xlen+ylen;
2692   mov(carry, zr);       // carry = 0;
2693 
2694   Label L_done;
2695 
2696   movw(xstart, xlen);
2697   subsw(xstart, xstart, 1);
2698   br(Assembler::MI, L_done);
2699 
2700   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
2701 
2702   Label L_second_loop;
2703   cbzw(kdx, L_second_loop);
2704 
2705   Label L_carry;
2706   subw(kdx, kdx, 1);
2707   cbzw(kdx, L_carry);
2708 
2709   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2710   lsr(carry, carry, 32);
2711   subw(kdx, kdx, 1);
2712 
2713   bind(L_carry);
2714   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2715 
2716   // Second and third (nested) loops.
2717   //
2718   // for (int i = xstart-1; i >= 0; i--) { // Second loop
2719   //   carry = 0;
2720   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
2721   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
2722   //                    (z[k] & LONG_MASK) + carry;
2723   //     z[k] = (int)product;
2724   //     carry = product >>> 32;
2725   //   }
2726   //   z[i] = (int)carry;
2727   // }
2728   //
2729   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
2730 
2731   const Register jdx = tmp1;
2732 
2733   bind(L_second_loop);
2734   mov(carry, zr);                // carry = 0;
2735   movw(jdx, ylen);               // j = ystart+1
2736 
2737   subsw(xstart, xstart, 1);      // i = xstart-1;
2738   br(Assembler::MI, L_done);
2739 
2740   str(z, Address(pre(sp, -4 * wordSize)));
2741 
2742   Label L_last_x;
2743   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
2744   subsw(xstart, xstart, 1);       // i = xstart-1;
2745   br(Assembler::MI, L_last_x);
2746 
2747   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
2748   ldr(product_hi, Address(rscratch1));
2749   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
2750 
2751   Label L_third_loop_prologue;
2752   bind(L_third_loop_prologue);
2753 
2754   str(ylen, Address(sp, wordSize));
2755   stp(x, xstart, Address(sp, 2 * wordSize));
2756   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
2757                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
2758   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
2759   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
2760 
2761   addw(tmp3, xlen, 1);
2762   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2763   subsw(tmp3, tmp3, 1);
2764   br(Assembler::MI, L_done);
2765 
2766   lsr(carry, carry, 32);
2767   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2768   b(L_second_loop);
2769 
2770   // Next infrequent code is moved outside loops.
2771   bind(L_last_x);
2772   ldrw(product_hi, Address(x,  0));
2773   b(L_third_loop_prologue);
2774 
2775   bind(L_done);
2776 }
2777 
2778 /**
2779  * Emits code to update CRC-32 with a byte value according to constants in table
2780  *
2781  * @param [in,out]crc   Register containing the crc.
2782  * @param [in]val       Register containing the byte to fold into the CRC.
2783  * @param [in]table     Register containing the table of crc constants.
2784  *
2785  * uint32_t crc;
2786  * val = crc_table[(val ^ crc) & 0xFF];
2787  * crc = val ^ (crc >> 8);
2788  *
2789  */
update_byte_crc32(Register crc,Register val,Register table)2790 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
2791   eor(val, val, crc);
2792   andr(val, val, 0xff);
2793   ldrw(val, Address(table, val, Address::lsl(2)));
2794   eor(crc, val, crc, Assembler::LSR, 8);
2795 }
2796 
2797 /**
2798  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
2799  *
2800  * @param [in,out]crc   Register containing the crc.
2801  * @param [in]v         Register containing the 32-bit to fold into the CRC.
2802  * @param [in]table0    Register containing table 0 of crc constants.
2803  * @param [in]table1    Register containing table 1 of crc constants.
2804  * @param [in]table2    Register containing table 2 of crc constants.
2805  * @param [in]table3    Register containing table 3 of crc constants.
2806  *
2807  * uint32_t crc;
2808  *   v = crc ^ v
2809  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
2810  *
2811  */
update_word_crc32(Register crc,Register v,Register tmp,Register table0,Register table1,Register table2,Register table3,bool upper)2812 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
2813         Register table0, Register table1, Register table2, Register table3,
2814         bool upper) {
2815   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
2816   uxtb(tmp, v);
2817   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
2818   ubfx(tmp, v, 8, 8);
2819   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
2820   eor(crc, crc, tmp);
2821   ubfx(tmp, v, 16, 8);
2822   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
2823   eor(crc, crc, tmp);
2824   ubfx(tmp, v, 24, 8);
2825   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
2826   eor(crc, crc, tmp);
2827 }
2828 
2829 /**
2830  * @param crc   register containing existing CRC (32-bit)
2831  * @param buf   register pointing to input byte buffer (byte*)
2832  * @param len   register containing number of bytes
2833  * @param table register that will contain address of CRC table
2834  * @param tmp   scratch register
2835  */
kernel_crc32(Register crc,Register buf,Register len,Register table0,Register table1,Register table2,Register table3,Register tmp,Register tmp2,Register tmp3)2836 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
2837         Register table0, Register table1, Register table2, Register table3,
2838         Register tmp, Register tmp2, Register tmp3) {
2839   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
2840   unsigned long offset;
2841 
2842     ornw(crc, zr, crc);
2843 
2844   if (UseCRC32) {
2845     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop;
2846 
2847       subs(len, len, 64);
2848       br(Assembler::GE, CRC_by64_loop);
2849       adds(len, len, 64-4);
2850       br(Assembler::GE, CRC_by4_loop);
2851       adds(len, len, 4);
2852       br(Assembler::GT, CRC_by1_loop);
2853       b(L_exit);
2854 
2855     BIND(CRC_by4_loop);
2856       ldrw(tmp, Address(post(buf, 4)));
2857       subs(len, len, 4);
2858       crc32w(crc, crc, tmp);
2859       br(Assembler::GE, CRC_by4_loop);
2860       adds(len, len, 4);
2861       br(Assembler::LE, L_exit);
2862     BIND(CRC_by1_loop);
2863       ldrb(tmp, Address(post(buf, 1)));
2864       subs(len, len, 1);
2865       crc32b(crc, crc, tmp);
2866       br(Assembler::GT, CRC_by1_loop);
2867       b(L_exit);
2868 
2869       align(CodeEntryAlignment);
2870     BIND(CRC_by64_loop);
2871       subs(len, len, 64);
2872       ldp(tmp, tmp3, Address(post(buf, 16)));
2873       crc32x(crc, crc, tmp);
2874       crc32x(crc, crc, tmp3);
2875       ldp(tmp, tmp3, Address(post(buf, 16)));
2876       crc32x(crc, crc, tmp);
2877       crc32x(crc, crc, tmp3);
2878       ldp(tmp, tmp3, Address(post(buf, 16)));
2879       crc32x(crc, crc, tmp);
2880       crc32x(crc, crc, tmp3);
2881       ldp(tmp, tmp3, Address(post(buf, 16)));
2882       crc32x(crc, crc, tmp);
2883       crc32x(crc, crc, tmp3);
2884       br(Assembler::GE, CRC_by64_loop);
2885       adds(len, len, 64-4);
2886       br(Assembler::GE, CRC_by4_loop);
2887       adds(len, len, 4);
2888       br(Assembler::GT, CRC_by1_loop);
2889     BIND(L_exit);
2890       ornw(crc, zr, crc);
2891       return;
2892   }
2893 
2894     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
2895     if (offset) add(table0, table0, offset);
2896     add(table1, table0, 1*256*sizeof(juint));
2897     add(table2, table0, 2*256*sizeof(juint));
2898     add(table3, table0, 3*256*sizeof(juint));
2899 
2900   if (UseNeon) {
2901       cmp(len, 64);
2902       br(Assembler::LT, L_by16);
2903       eor(v16, T16B, v16, v16);
2904 
2905     Label L_fold;
2906 
2907       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
2908 
2909       ld1(v0, v1, T2D, post(buf, 32));
2910       ld1r(v4, T2D, post(tmp, 8));
2911       ld1r(v5, T2D, post(tmp, 8));
2912       ld1r(v6, T2D, post(tmp, 8));
2913       ld1r(v7, T2D, post(tmp, 8));
2914       mov(v16, T4S, 0, crc);
2915 
2916       eor(v0, T16B, v0, v16);
2917       sub(len, len, 64);
2918 
2919     BIND(L_fold);
2920       pmull(v22, T8H, v0, v5, T8B);
2921       pmull(v20, T8H, v0, v7, T8B);
2922       pmull(v23, T8H, v0, v4, T8B);
2923       pmull(v21, T8H, v0, v6, T8B);
2924 
2925       pmull2(v18, T8H, v0, v5, T16B);
2926       pmull2(v16, T8H, v0, v7, T16B);
2927       pmull2(v19, T8H, v0, v4, T16B);
2928       pmull2(v17, T8H, v0, v6, T16B);
2929 
2930       uzp1(v24, v20, v22, T8H);
2931       uzp2(v25, v20, v22, T8H);
2932       eor(v20, T16B, v24, v25);
2933 
2934       uzp1(v26, v16, v18, T8H);
2935       uzp2(v27, v16, v18, T8H);
2936       eor(v16, T16B, v26, v27);
2937 
2938       ushll2(v22, T4S, v20, T8H, 8);
2939       ushll(v20, T4S, v20, T4H, 8);
2940 
2941       ushll2(v18, T4S, v16, T8H, 8);
2942       ushll(v16, T4S, v16, T4H, 8);
2943 
2944       eor(v22, T16B, v23, v22);
2945       eor(v18, T16B, v19, v18);
2946       eor(v20, T16B, v21, v20);
2947       eor(v16, T16B, v17, v16);
2948 
2949       uzp1(v17, v16, v20, T2D);
2950       uzp2(v21, v16, v20, T2D);
2951       eor(v17, T16B, v17, v21);
2952 
2953       ushll2(v20, T2D, v17, T4S, 16);
2954       ushll(v16, T2D, v17, T2S, 16);
2955 
2956       eor(v20, T16B, v20, v22);
2957       eor(v16, T16B, v16, v18);
2958 
2959       uzp1(v17, v20, v16, T2D);
2960       uzp2(v21, v20, v16, T2D);
2961       eor(v28, T16B, v17, v21);
2962 
2963       pmull(v22, T8H, v1, v5, T8B);
2964       pmull(v20, T8H, v1, v7, T8B);
2965       pmull(v23, T8H, v1, v4, T8B);
2966       pmull(v21, T8H, v1, v6, T8B);
2967 
2968       pmull2(v18, T8H, v1, v5, T16B);
2969       pmull2(v16, T8H, v1, v7, T16B);
2970       pmull2(v19, T8H, v1, v4, T16B);
2971       pmull2(v17, T8H, v1, v6, T16B);
2972 
2973       ld1(v0, v1, T2D, post(buf, 32));
2974 
2975       uzp1(v24, v20, v22, T8H);
2976       uzp2(v25, v20, v22, T8H);
2977       eor(v20, T16B, v24, v25);
2978 
2979       uzp1(v26, v16, v18, T8H);
2980       uzp2(v27, v16, v18, T8H);
2981       eor(v16, T16B, v26, v27);
2982 
2983       ushll2(v22, T4S, v20, T8H, 8);
2984       ushll(v20, T4S, v20, T4H, 8);
2985 
2986       ushll2(v18, T4S, v16, T8H, 8);
2987       ushll(v16, T4S, v16, T4H, 8);
2988 
2989       eor(v22, T16B, v23, v22);
2990       eor(v18, T16B, v19, v18);
2991       eor(v20, T16B, v21, v20);
2992       eor(v16, T16B, v17, v16);
2993 
2994       uzp1(v17, v16, v20, T2D);
2995       uzp2(v21, v16, v20, T2D);
2996       eor(v16, T16B, v17, v21);
2997 
2998       ushll2(v20, T2D, v16, T4S, 16);
2999       ushll(v16, T2D, v16, T2S, 16);
3000 
3001       eor(v20, T16B, v22, v20);
3002       eor(v16, T16B, v16, v18);
3003 
3004       uzp1(v17, v20, v16, T2D);
3005       uzp2(v21, v20, v16, T2D);
3006       eor(v20, T16B, v17, v21);
3007 
3008       shl(v16, T2D, v28, 1);
3009       shl(v17, T2D, v20, 1);
3010 
3011       eor(v0, T16B, v0, v16);
3012       eor(v1, T16B, v1, v17);
3013 
3014       subs(len, len, 32);
3015       br(Assembler::GE, L_fold);
3016 
3017       mov(crc, 0);
3018       mov(tmp, v0, T1D, 0);
3019       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3020       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3021       mov(tmp, v0, T1D, 1);
3022       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3023       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3024       mov(tmp, v1, T1D, 0);
3025       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3026       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3027       mov(tmp, v1, T1D, 1);
3028       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3029       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3030 
3031       add(len, len, 32);
3032   }
3033 
3034   BIND(L_by16);
3035     subs(len, len, 16);
3036     br(Assembler::GE, L_by16_loop);
3037     adds(len, len, 16-4);
3038     br(Assembler::GE, L_by4_loop);
3039     adds(len, len, 4);
3040     br(Assembler::GT, L_by1_loop);
3041     b(L_exit);
3042 
3043   BIND(L_by4_loop);
3044     ldrw(tmp, Address(post(buf, 4)));
3045     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3046     subs(len, len, 4);
3047     br(Assembler::GE, L_by4_loop);
3048     adds(len, len, 4);
3049     br(Assembler::LE, L_exit);
3050   BIND(L_by1_loop);
3051     subs(len, len, 1);
3052     ldrb(tmp, Address(post(buf, 1)));
3053     update_byte_crc32(crc, tmp, table0);
3054     br(Assembler::GT, L_by1_loop);
3055     b(L_exit);
3056 
3057     align(CodeEntryAlignment);
3058   BIND(L_by16_loop);
3059     subs(len, len, 16);
3060     ldp(tmp, tmp3, Address(post(buf, 16)));
3061     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3062     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3063     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
3064     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
3065     br(Assembler::GE, L_by16_loop);
3066     adds(len, len, 16-4);
3067     br(Assembler::GE, L_by4_loop);
3068     adds(len, len, 4);
3069     br(Assembler::GT, L_by1_loop);
3070   BIND(L_exit);
3071     ornw(crc, zr, crc);
3072 }
3073 
SkipIfEqual(MacroAssembler * masm,const bool * flag_addr,bool value)3074 SkipIfEqual::SkipIfEqual(
3075     MacroAssembler* masm, const bool* flag_addr, bool value) {
3076   _masm = masm;
3077   unsigned long offset;
3078   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3079   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3080   _masm->cbzw(rscratch1, _label);
3081 }
3082 
~SkipIfEqual()3083 SkipIfEqual::~SkipIfEqual() {
3084   _masm->bind(_label);
3085 }
3086 
addptr(const Address & dst,int32_t src)3087 void MacroAssembler::addptr(const Address &dst, int32_t src) {
3088   Address adr;
3089   switch(dst.getMode()) {
3090   case Address::base_plus_offset:
3091     // This is the expected mode, although we allow all the other
3092     // forms below.
3093     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
3094     break;
3095   default:
3096     lea(rscratch2, dst);
3097     adr = Address(rscratch2);
3098     break;
3099   }
3100   ldr(rscratch1, adr);
3101   add(rscratch1, rscratch1, src);
3102   str(rscratch1, adr);
3103 }
3104 
cmpptr(Register src1,Address src2)3105 void MacroAssembler::cmpptr(Register src1, Address src2) {
3106   unsigned long offset;
3107   adrp(rscratch1, src2, offset);
3108   ldr(rscratch1, Address(rscratch1, offset));
3109   cmp(src1, rscratch1);
3110 }
3111 
store_check(Register obj)3112 void MacroAssembler::store_check(Register obj) {
3113   // Does a store check for the oop in register obj. The content of
3114   // register obj is destroyed afterwards.
3115   store_check_part_1(obj);
3116   store_check_part_2(obj);
3117 }
3118 
store_check(Register obj,Address dst)3119 void MacroAssembler::store_check(Register obj, Address dst) {
3120   store_check(obj);
3121 }
3122 
3123 
3124 // split the store check operation so that other instructions can be scheduled inbetween
store_check_part_1(Register obj)3125 void MacroAssembler::store_check_part_1(Register obj) {
3126   BarrierSet* bs = Universe::heap()->barrier_set();
3127   assert(bs->kind() == BarrierSet::CardTableModRef, "Wrong barrier set kind");
3128   lsr(obj, obj, CardTableModRefBS::card_shift);
3129 }
3130 
store_check_part_2(Register obj)3131 void MacroAssembler::store_check_part_2(Register obj) {
3132   BarrierSet* bs = Universe::heap()->barrier_set();
3133   assert(bs->kind() == BarrierSet::CardTableModRef, "Wrong barrier set kind");
3134   CardTableModRefBS* ct = (CardTableModRefBS*)bs;
3135   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3136 
3137   // The calculation for byte_map_base is as follows:
3138   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
3139   // So this essentially converts an address to a displacement and
3140   // it will never need to be relocated.
3141 
3142   // FIXME: It's not likely that disp will fit into an offset so we
3143   // don't bother to check, but it could save an instruction.
3144   intptr_t disp = (intptr_t) ct->byte_map_base;
3145   load_byte_map_base(rscratch1);
3146 
3147   if (UseConcMarkSweepGC && CMSPrecleaningEnabled) {
3148       membar(StoreStore);
3149   }
3150   strb(zr, Address(obj, rscratch1));
3151 }
3152 
load_klass(Register dst,Register src)3153 void MacroAssembler::load_klass(Register dst, Register src) {
3154   if (UseCompressedClassPointers) {
3155     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3156     decode_klass_not_null(dst);
3157   } else {
3158     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3159   }
3160 }
3161 
cmp_klass(Register oop,Register trial_klass,Register tmp)3162 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3163   if (UseCompressedClassPointers) {
3164     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3165     if (Universe::narrow_klass_base() == NULL) {
3166       cmp(trial_klass, tmp, LSL, Universe::narrow_klass_shift());
3167       return;
3168     } else if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3169                && Universe::narrow_klass_shift() == 0) {
3170       // Only the bottom 32 bits matter
3171       cmpw(trial_klass, tmp);
3172       return;
3173     }
3174     decode_klass_not_null(tmp);
3175   } else {
3176     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3177   }
3178   cmp(trial_klass, tmp);
3179 }
3180 
load_prototype_header(Register dst,Register src)3181 void MacroAssembler::load_prototype_header(Register dst, Register src) {
3182   load_klass(dst, src);
3183   ldr(dst, Address(dst, Klass::prototype_header_offset()));
3184 }
3185 
store_klass(Register dst,Register src)3186 void MacroAssembler::store_klass(Register dst, Register src) {
3187   // FIXME: Should this be a store release?  concurrent gcs assumes
3188   // klass length is valid if klass field is not null.
3189   if (UseCompressedClassPointers) {
3190     encode_klass_not_null(src);
3191     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3192   } else {
3193     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3194   }
3195 }
3196 
store_klass_gap(Register dst,Register src)3197 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3198   if (UseCompressedClassPointers) {
3199     // Store to klass gap in destination
3200     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3201   }
3202 }
3203 
3204 // Algorithm must match oop.inline.hpp encode_heap_oop.
encode_heap_oop(Register d,Register s)3205 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3206 #ifdef ASSERT
3207   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3208 #endif
3209   verify_oop(s, "broken oop in encode_heap_oop");
3210   if (Universe::narrow_oop_base() == NULL) {
3211     if (Universe::narrow_oop_shift() != 0) {
3212       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3213       lsr(d, s, LogMinObjAlignmentInBytes);
3214     } else {
3215       mov(d, s);
3216     }
3217   } else {
3218     subs(d, s, rheapbase);
3219     csel(d, d, zr, Assembler::HS);
3220     lsr(d, d, LogMinObjAlignmentInBytes);
3221 
3222     /*  Old algorithm: is this any worse?
3223     Label nonnull;
3224     cbnz(r, nonnull);
3225     sub(r, r, rheapbase);
3226     bind(nonnull);
3227     lsr(r, r, LogMinObjAlignmentInBytes);
3228     */
3229   }
3230 }
3231 
encode_heap_oop_not_null(Register r)3232 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3233 #ifdef ASSERT
3234   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3235   if (CheckCompressedOops) {
3236     Label ok;
3237     cbnz(r, ok);
3238     stop("null oop passed to encode_heap_oop_not_null");
3239     bind(ok);
3240   }
3241 #endif
3242   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3243   if (Universe::narrow_oop_base() != NULL) {
3244     sub(r, r, rheapbase);
3245   }
3246   if (Universe::narrow_oop_shift() != 0) {
3247     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3248     lsr(r, r, LogMinObjAlignmentInBytes);
3249   }
3250 }
3251 
encode_heap_oop_not_null(Register dst,Register src)3252 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3253 #ifdef ASSERT
3254   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3255   if (CheckCompressedOops) {
3256     Label ok;
3257     cbnz(src, ok);
3258     stop("null oop passed to encode_heap_oop_not_null2");
3259     bind(ok);
3260   }
3261 #endif
3262   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3263 
3264   Register data = src;
3265   if (Universe::narrow_oop_base() != NULL) {
3266     sub(dst, src, rheapbase);
3267     data = dst;
3268   }
3269   if (Universe::narrow_oop_shift() != 0) {
3270     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3271     lsr(dst, data, LogMinObjAlignmentInBytes);
3272     data = dst;
3273   }
3274   if (data == src)
3275     mov(dst, src);
3276 }
3277 
decode_heap_oop(Register d,Register s)3278 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3279 #ifdef ASSERT
3280   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3281 #endif
3282   if (Universe::narrow_oop_base() == NULL) {
3283     if (Universe::narrow_oop_shift() != 0 || d != s) {
3284       lsl(d, s, Universe::narrow_oop_shift());
3285     }
3286   } else {
3287     Label done;
3288     if (d != s)
3289       mov(d, s);
3290     cbz(s, done);
3291     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3292     bind(done);
3293   }
3294   verify_oop(d, "broken oop in decode_heap_oop");
3295 }
3296 
decode_heap_oop_not_null(Register r)3297 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3298   assert (UseCompressedOops, "should only be used for compressed headers");
3299   assert (Universe::heap() != NULL, "java heap should be initialized");
3300   // Cannot assert, unverified entry point counts instructions (see .ad file)
3301   // vtableStubs also counts instructions in pd_code_size_limit.
3302   // Also do not verify_oop as this is called by verify_oop.
3303   if (Universe::narrow_oop_shift() != 0) {
3304     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3305     if (Universe::narrow_oop_base() != NULL) {
3306       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3307     } else {
3308       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3309     }
3310   } else {
3311     assert (Universe::narrow_oop_base() == NULL, "sanity");
3312   }
3313 }
3314 
decode_heap_oop_not_null(Register dst,Register src)3315 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3316   assert (UseCompressedOops, "should only be used for compressed headers");
3317   assert (Universe::heap() != NULL, "java heap should be initialized");
3318   // Cannot assert, unverified entry point counts instructions (see .ad file)
3319   // vtableStubs also counts instructions in pd_code_size_limit.
3320   // Also do not verify_oop as this is called by verify_oop.
3321   if (Universe::narrow_oop_shift() != 0) {
3322     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3323     if (Universe::narrow_oop_base() != NULL) {
3324       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3325     } else {
3326       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3327     }
3328   } else {
3329     assert (Universe::narrow_oop_base() == NULL, "sanity");
3330     if (dst != src) {
3331       mov(dst, src);
3332     }
3333   }
3334 }
3335 
encode_klass_not_null(Register dst,Register src)3336 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3337   if (Universe::narrow_klass_base() == NULL) {
3338     if (Universe::narrow_klass_shift() != 0) {
3339       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3340       lsr(dst, src, LogKlassAlignmentInBytes);
3341     } else {
3342       if (dst != src) mov(dst, src);
3343     }
3344     return;
3345   }
3346 
3347   if (use_XOR_for_compressed_class_base) {
3348     if (Universe::narrow_klass_shift() != 0) {
3349       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3350       lsr(dst, dst, LogKlassAlignmentInBytes);
3351     } else {
3352       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3353     }
3354     return;
3355   }
3356 
3357   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3358       && Universe::narrow_klass_shift() == 0) {
3359     movw(dst, src);
3360     return;
3361   }
3362 
3363 #ifdef ASSERT
3364   verify_heapbase("MacroAssembler::encode_klass_not_null2: heap base corrupted?");
3365 #endif
3366 
3367   Register rbase = dst;
3368   if (dst == src) rbase = rheapbase;
3369   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3370   sub(dst, src, rbase);
3371   if (Universe::narrow_klass_shift() != 0) {
3372     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3373     lsr(dst, dst, LogKlassAlignmentInBytes);
3374   }
3375   if (dst == src) reinit_heapbase();
3376 }
3377 
encode_klass_not_null(Register r)3378 void MacroAssembler::encode_klass_not_null(Register r) {
3379   encode_klass_not_null(r, r);
3380 }
3381 
decode_klass_not_null(Register dst,Register src)3382 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3383   Register rbase = dst;
3384   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3385 
3386   if (Universe::narrow_klass_base() == NULL) {
3387     if (Universe::narrow_klass_shift() != 0) {
3388       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3389       lsl(dst, src, LogKlassAlignmentInBytes);
3390     } else {
3391       if (dst != src) mov(dst, src);
3392     }
3393     return;
3394   }
3395 
3396   if (use_XOR_for_compressed_class_base) {
3397     if (Universe::narrow_klass_shift() != 0) {
3398       lsl(dst, src, LogKlassAlignmentInBytes);
3399       eor(dst, dst, (uint64_t)Universe::narrow_klass_base());
3400     } else {
3401       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3402     }
3403     return;
3404   }
3405 
3406   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3407       && Universe::narrow_klass_shift() == 0) {
3408     if (dst != src)
3409       movw(dst, src);
3410     movk(dst, (uint64_t)Universe::narrow_klass_base() >> 32, 32);
3411     return;
3412   }
3413 
3414   // Cannot assert, unverified entry point counts instructions (see .ad file)
3415   // vtableStubs also counts instructions in pd_code_size_limit.
3416   // Also do not verify_oop as this is called by verify_oop.
3417   if (dst == src) rbase = rheapbase;
3418   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3419   if (Universe::narrow_klass_shift() != 0) {
3420     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3421     add(dst, rbase, src, Assembler::LSL, LogKlassAlignmentInBytes);
3422   } else {
3423     add(dst, rbase, src);
3424   }
3425   if (dst == src) reinit_heapbase();
3426 }
3427 
decode_klass_not_null(Register r)3428 void  MacroAssembler::decode_klass_not_null(Register r) {
3429   decode_klass_not_null(r, r);
3430 }
3431 
set_narrow_oop(Register dst,jobject obj)3432 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
3433   assert (UseCompressedOops, "should only be used for compressed oops");
3434   assert (Universe::heap() != NULL, "java heap should be initialized");
3435   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3436 
3437   int oop_index = oop_recorder()->find_index(obj);
3438   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3439 
3440   InstructionMark im(this);
3441   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3442   code_section()->relocate(inst_mark(), rspec);
3443   movz(dst, 0xDEAD, 16);
3444   movk(dst, 0xBEEF);
3445 }
3446 
set_narrow_klass(Register dst,Klass * k)3447 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
3448   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3449   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3450   int index = oop_recorder()->find_index(k);
3451   assert(! Universe::heap()->is_in_reserved(k), "should not be an oop");
3452 
3453   InstructionMark im(this);
3454   RelocationHolder rspec = metadata_Relocation::spec(index);
3455   code_section()->relocate(inst_mark(), rspec);
3456   narrowKlass nk = Klass::encode_klass(k);
3457   movz(dst, (nk >> 16), 16);
3458   movk(dst, nk & 0xffff);
3459 }
3460 
load_heap_oop(Register dst,Address src)3461 void MacroAssembler::load_heap_oop(Register dst, Address src)
3462 {
3463   if (UseCompressedOops) {
3464     ldrw(dst, src);
3465     decode_heap_oop(dst);
3466   } else {
3467     ldr(dst, src);
3468   }
3469 }
3470 
load_heap_oop_not_null(Register dst,Address src)3471 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src)
3472 {
3473   if (UseCompressedOops) {
3474     ldrw(dst, src);
3475     decode_heap_oop_not_null(dst);
3476   } else {
3477     ldr(dst, src);
3478   }
3479 }
3480 
store_heap_oop(Address dst,Register src)3481 void MacroAssembler::store_heap_oop(Address dst, Register src) {
3482   if (UseCompressedOops) {
3483     assert(!dst.uses(src), "not enough registers");
3484     encode_heap_oop(src);
3485     strw(src, dst);
3486   } else
3487     str(src, dst);
3488 }
3489 
3490 // Used for storing NULLs.
store_heap_oop_null(Address dst)3491 void MacroAssembler::store_heap_oop_null(Address dst) {
3492   if (UseCompressedOops) {
3493     strw(zr, dst);
3494   } else
3495     str(zr, dst);
3496 }
3497 
3498 #if INCLUDE_ALL_GCS
3499 /*
3500  * g1_write_barrier_pre -- G1GC pre-write barrier for store of new_val at
3501  * store_addr.
3502  *
3503  * Allocates rscratch1
3504  */
g1_write_barrier_pre(Register obj,Register pre_val,Register thread,Register tmp,bool tosca_live,bool expand_call)3505 void MacroAssembler::g1_write_barrier_pre(Register obj,
3506                                           Register pre_val,
3507                                           Register thread,
3508                                           Register tmp,
3509                                           bool tosca_live,
3510                                           bool expand_call) {
3511   // If expand_call is true then we expand the call_VM_leaf macro
3512   // directly to skip generating the check by
3513   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
3514 
3515 #ifdef _LP64
3516   assert(thread == rthread, "must be");
3517 #endif // _LP64
3518 
3519   Label done;
3520   Label runtime;
3521 
3522   assert_different_registers(obj, pre_val, tmp, rscratch1);
3523   assert(pre_val != noreg &&  tmp != noreg, "expecting a register");
3524 
3525   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3526                                        PtrQueue::byte_offset_of_active()));
3527   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3528                                        PtrQueue::byte_offset_of_index()));
3529   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3530                                        PtrQueue::byte_offset_of_buf()));
3531 
3532 
3533   // Is marking active?
3534   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
3535     ldrw(tmp, in_progress);
3536   } else {
3537     assert(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
3538     ldrb(tmp, in_progress);
3539   }
3540   cbzw(tmp, done);
3541 
3542   // Do we need to load the previous value?
3543   if (obj != noreg) {
3544     load_heap_oop(pre_val, Address(obj, 0));
3545   }
3546 
3547   // Is the previous value null?
3548   cbz(pre_val, done);
3549 
3550   // Can we store original value in the thread's buffer?
3551   // Is index == 0?
3552   // (The index field is typed as size_t.)
3553 
3554   ldr(tmp, index);                      // tmp := *index_adr
3555   cbz(tmp, runtime);                    // tmp == 0?
3556                                         // If yes, goto runtime
3557 
3558   sub(tmp, tmp, wordSize);              // tmp := tmp - wordSize
3559   str(tmp, index);                      // *index_adr := tmp
3560   ldr(rscratch1, buffer);
3561   add(tmp, tmp, rscratch1);             // tmp := tmp + *buffer_adr
3562 
3563   // Record the previous value
3564   str(pre_val, Address(tmp, 0));
3565   b(done);
3566 
3567   bind(runtime);
3568   // save the live input values
3569   push(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3570 
3571   // Calling the runtime using the regular call_VM_leaf mechanism generates
3572   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
3573   // that checks that the *(rfp+frame::interpreter_frame_last_sp) == NULL.
3574   //
3575   // If we care generating the pre-barrier without a frame (e.g. in the
3576   // intrinsified Reference.get() routine) then ebp might be pointing to
3577   // the caller frame and so this check will most likely fail at runtime.
3578   //
3579   // Expanding the call directly bypasses the generation of the check.
3580   // So when we do not have have a full interpreter frame on the stack
3581   // expand_call should be passed true.
3582 
3583   if (expand_call) {
3584     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
3585     pass_arg1(this, thread);
3586     pass_arg0(this, pre_val);
3587     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
3588   } else {
3589     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
3590   }
3591 
3592   pop(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3593 
3594   bind(done);
3595 }
3596 
3597 /*
3598  * g1_write_barrier_post -- G1GC post-write barrier for store of new_val at
3599  * store_addr
3600  *
3601  * Allocates rscratch1
3602  */
g1_write_barrier_post(Register store_addr,Register new_val,Register thread,Register tmp,Register tmp2)3603 void MacroAssembler::g1_write_barrier_post(Register store_addr,
3604                                            Register new_val,
3605                                            Register thread,
3606                                            Register tmp,
3607                                            Register tmp2) {
3608 #ifdef _LP64
3609   assert(thread == rthread, "must be");
3610 #endif // _LP64
3611   assert_different_registers(store_addr, new_val, thread, tmp, tmp2,
3612                              rscratch1);
3613   assert(store_addr != noreg && new_val != noreg && tmp != noreg
3614          && tmp2 != noreg, "expecting a register");
3615 
3616   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3617                                        PtrQueue::byte_offset_of_index()));
3618   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3619                                        PtrQueue::byte_offset_of_buf()));
3620 
3621   BarrierSet* bs = Universe::heap()->barrier_set();
3622   CardTableModRefBS* ct = (CardTableModRefBS*)bs;
3623   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3624 
3625   Label done;
3626   Label runtime;
3627 
3628   // Does store cross heap regions?
3629 
3630   eor(tmp, store_addr, new_val);
3631   lsr(tmp, tmp, HeapRegion::LogOfHRGrainBytes);
3632   cbz(tmp, done);
3633 
3634   // crosses regions, storing NULL?
3635 
3636   cbz(new_val, done);
3637 
3638   // storing region crossing non-NULL, is card already dirty?
3639 
3640   ExternalAddress cardtable((address) ct->byte_map_base);
3641   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3642   const Register card_addr = tmp;
3643 
3644   lsr(card_addr, store_addr, CardTableModRefBS::card_shift);
3645 
3646   // get the address of the card
3647   load_byte_map_base(tmp2);
3648   add(card_addr, card_addr, tmp2);
3649   ldrb(tmp2, Address(card_addr));
3650   cmpw(tmp2, (int)G1SATBCardTableModRefBS::g1_young_card_val());
3651   br(Assembler::EQ, done);
3652 
3653   assert((int)CardTableModRefBS::dirty_card_val() == 0, "must be 0");
3654 
3655   membar(Assembler::Assembler::StoreLoad);
3656 
3657   ldrb(tmp2, Address(card_addr));
3658   cbzw(tmp2, done);
3659 
3660   // storing a region crossing, non-NULL oop, card is clean.
3661   // dirty card and log.
3662 
3663   strb(zr, Address(card_addr));
3664 
3665   ldr(rscratch1, queue_index);
3666   cbz(rscratch1, runtime);
3667   sub(rscratch1, rscratch1, wordSize);
3668   str(rscratch1, queue_index);
3669 
3670   ldr(tmp2, buffer);
3671   str(card_addr, Address(tmp2, rscratch1));
3672   b(done);
3673 
3674   bind(runtime);
3675   // save the live input values
3676   push(store_addr->bit(true) | new_val->bit(true), sp);
3677   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
3678   pop(store_addr->bit(true) | new_val->bit(true), sp);
3679 
3680   bind(done);
3681 }
3682 
3683 #endif // INCLUDE_ALL_GCS
3684 
allocate_metadata_address(Metadata * obj)3685 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
3686   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
3687   int index = oop_recorder()->allocate_metadata_index(obj);
3688   RelocationHolder rspec = metadata_Relocation::spec(index);
3689   return Address((address)obj, rspec);
3690 }
3691 
3692 // Move an oop into a register.  immediate is true if we want
3693 // immediate instrcutions, i.e. we are not going to patch this
3694 // instruction while the code is being executed by another thread.  In
3695 // that case we can use move immediates rather than the constant pool.
movoop(Register dst,jobject obj,bool immediate)3696 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
3697   int oop_index;
3698   if (obj == NULL) {
3699     oop_index = oop_recorder()->allocate_oop_index(obj);
3700   } else {
3701     oop_index = oop_recorder()->find_index(obj);
3702     assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3703   }
3704   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3705   if (! immediate) {
3706     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
3707     ldr_constant(dst, Address(dummy, rspec));
3708   } else
3709     mov(dst, Address((address)obj, rspec));
3710 }
3711 
3712 // Move a metadata address into a register.
mov_metadata(Register dst,Metadata * obj)3713 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
3714   int oop_index;
3715   if (obj == NULL) {
3716     oop_index = oop_recorder()->allocate_metadata_index(obj);
3717   } else {
3718     oop_index = oop_recorder()->find_index(obj);
3719   }
3720   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
3721   mov(dst, Address((address)obj, rspec));
3722 }
3723 
constant_oop_address(jobject obj)3724 Address MacroAssembler::constant_oop_address(jobject obj) {
3725   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
3726   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
3727   int oop_index = oop_recorder()->find_index(obj);
3728   return Address((address)obj, oop_Relocation::spec(oop_index));
3729 }
3730 
3731 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
tlab_allocate(Register obj,Register var_size_in_bytes,int con_size_in_bytes,Register t1,Register t2,Label & slow_case)3732 void MacroAssembler::tlab_allocate(Register obj,
3733                                    Register var_size_in_bytes,
3734                                    int con_size_in_bytes,
3735                                    Register t1,
3736                                    Register t2,
3737                                    Label& slow_case) {
3738   assert_different_registers(obj, t2);
3739   assert_different_registers(obj, var_size_in_bytes);
3740   Register end = t2;
3741 
3742   // verify_tlab();
3743 
3744   ldr(obj, Address(rthread, JavaThread::tlab_top_offset()));
3745   if (var_size_in_bytes == noreg) {
3746     lea(end, Address(obj, con_size_in_bytes));
3747   } else {
3748     lea(end, Address(obj, var_size_in_bytes));
3749   }
3750   ldr(rscratch1, Address(rthread, JavaThread::tlab_end_offset()));
3751   cmp(end, rscratch1);
3752   br(Assembler::HI, slow_case);
3753 
3754   // update the tlab top pointer
3755   str(end, Address(rthread, JavaThread::tlab_top_offset()));
3756 
3757   // recover var_size_in_bytes if necessary
3758   if (var_size_in_bytes == end) {
3759     sub(var_size_in_bytes, var_size_in_bytes, obj);
3760   }
3761   // verify_tlab();
3762 }
3763 
3764 // Preserves r19, and r3.
tlab_refill(Label & retry,Label & try_eden,Label & slow_case)3765 Register MacroAssembler::tlab_refill(Label& retry,
3766                                      Label& try_eden,
3767                                      Label& slow_case) {
3768   Register top = r0;
3769   Register t1  = r2;
3770   Register t2  = r4;
3771   assert_different_registers(top, rthread, t1, t2, /* preserve: */ r19, r3);
3772   Label do_refill, discard_tlab;
3773 
3774   if (CMSIncrementalMode || !Universe::heap()->supports_inline_contig_alloc()) {
3775     // No allocation in the shared eden.
3776     b(slow_case);
3777   }
3778 
3779   ldr(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3780   ldr(t1,  Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3781 
3782   // calculate amount of free space
3783   sub(t1, t1, top);
3784   lsr(t1, t1, LogHeapWordSize);
3785 
3786   // Retain tlab and allocate object in shared space if
3787   // the amount free in the tlab is too large to discard.
3788 
3789   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3790   cmp(t1, rscratch1);
3791   br(Assembler::LE, discard_tlab);
3792 
3793   // Retain
3794   // ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3795   mov(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
3796   add(rscratch1, rscratch1, t2);
3797   str(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3798 
3799   if (TLABStats) {
3800     // increment number of slow_allocations
3801     addmw(Address(rthread, in_bytes(JavaThread::tlab_slow_allocations_offset())),
3802          1, rscratch1);
3803   }
3804   b(try_eden);
3805 
3806   bind(discard_tlab);
3807   if (TLABStats) {
3808     // increment number of refills
3809     addmw(Address(rthread, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1,
3810          rscratch1);
3811     // accumulate wastage -- t1 is amount free in tlab
3812     addmw(Address(rthread, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1,
3813          rscratch1);
3814   }
3815 
3816   // if tlab is currently allocated (top or end != null) then
3817   // fill [top, end + alignment_reserve) with array object
3818   cbz(top, do_refill);
3819 
3820   // set up the mark word
3821   mov(rscratch1, (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
3822   str(rscratch1, Address(top, oopDesc::mark_offset_in_bytes()));
3823   // set the length to the remaining space
3824   sub(t1, t1, typeArrayOopDesc::header_size(T_INT));
3825   add(t1, t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
3826   lsl(t1, t1, log2_intptr(HeapWordSize/sizeof(jint)));
3827   strw(t1, Address(top, arrayOopDesc::length_offset_in_bytes()));
3828   // set klass to intArrayKlass
3829   {
3830     unsigned long offset;
3831     // dubious reloc why not an oop reloc?
3832     adrp(rscratch1, ExternalAddress((address)Universe::intArrayKlassObj_addr()),
3833          offset);
3834     ldr(t1, Address(rscratch1, offset));
3835   }
3836   // store klass last.  concurrent gcs assumes klass length is valid if
3837   // klass field is not null.
3838   store_klass(top, t1);
3839 
3840   mov(t1, top);
3841   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3842   sub(t1, t1, rscratch1);
3843   incr_allocated_bytes(rthread, t1, 0, rscratch1);
3844 
3845   // refill the tlab with an eden allocation
3846   bind(do_refill);
3847   ldr(t1, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
3848   lsl(t1, t1, LogHeapWordSize);
3849   // allocate new tlab, address returned in top
3850   eden_allocate(top, t1, 0, t2, slow_case);
3851 
3852   // Check that t1 was preserved in eden_allocate.
3853 #ifdef ASSERT
3854   if (UseTLAB) {
3855     Label ok;
3856     Register tsize = r4;
3857     assert_different_registers(tsize, rthread, t1);
3858     str(tsize, Address(pre(sp, -16)));
3859     ldr(tsize, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
3860     lsl(tsize, tsize, LogHeapWordSize);
3861     cmp(t1, tsize);
3862     br(Assembler::EQ, ok);
3863     STOP("assert(t1 != tlab size)");
3864     should_not_reach_here();
3865 
3866     bind(ok);
3867     ldr(tsize, Address(post(sp, 16)));
3868   }
3869 #endif
3870   str(top, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3871   str(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3872   add(top, top, t1);
3873   sub(top, top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
3874   str(top, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3875   verify_tlab();
3876   b(retry);
3877 
3878   return rthread; // for use by caller
3879 }
3880 
3881 // Defines obj, preserves var_size_in_bytes
eden_allocate(Register obj,Register var_size_in_bytes,int con_size_in_bytes,Register t1,Label & slow_case)3882 void MacroAssembler::eden_allocate(Register obj,
3883                                    Register var_size_in_bytes,
3884                                    int con_size_in_bytes,
3885                                    Register t1,
3886                                    Label& slow_case) {
3887   assert_different_registers(obj, var_size_in_bytes, t1);
3888   if (CMSIncrementalMode || !Universe::heap()->supports_inline_contig_alloc()) {
3889     b(slow_case);
3890   } else {
3891     Register end = t1;
3892     Register heap_end = rscratch2;
3893     Label retry;
3894     bind(retry);
3895     {
3896       unsigned long offset;
3897       adrp(rscratch1, ExternalAddress((address) Universe::heap()->end_addr()), offset);
3898       ldr(heap_end, Address(rscratch1, offset));
3899     }
3900 
3901     ExternalAddress heap_top((address) Universe::heap()->top_addr());
3902 
3903     // Get the current top of the heap
3904     {
3905       unsigned long offset;
3906       adrp(rscratch1, heap_top, offset);
3907       // Use add() here after ARDP, rather than lea().
3908       // lea() does not generate anything if its offset is zero.
3909       // However, relocs expect to find either an ADD or a load/store
3910       // insn after an ADRP.  add() always generates an ADD insn, even
3911       // for add(Rn, Rn, 0).
3912       add(rscratch1, rscratch1, offset);
3913       ldaxr(obj, rscratch1);
3914     }
3915 
3916     // Adjust it my the size of our new object
3917     if (var_size_in_bytes == noreg) {
3918       lea(end, Address(obj, con_size_in_bytes));
3919     } else {
3920       lea(end, Address(obj, var_size_in_bytes));
3921     }
3922 
3923     // if end < obj then we wrapped around high memory
3924     cmp(end, obj);
3925     br(Assembler::LO, slow_case);
3926 
3927     cmp(end, heap_end);
3928     br(Assembler::HI, slow_case);
3929 
3930     // If heap_top hasn't been changed by some other thread, update it.
3931     stlxr(rscratch2, end, rscratch1);
3932     cbnzw(rscratch2, retry);
3933   }
3934 }
3935 
verify_tlab()3936 void MacroAssembler::verify_tlab() {
3937 #ifdef ASSERT
3938   if (UseTLAB && VerifyOops) {
3939     Label next, ok;
3940 
3941     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
3942 
3943     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3944     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3945     cmp(rscratch2, rscratch1);
3946     br(Assembler::HS, next);
3947     STOP("assert(top >= start)");
3948     should_not_reach_here();
3949 
3950     bind(next);
3951     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3952     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3953     cmp(rscratch2, rscratch1);
3954     br(Assembler::HS, ok);
3955     STOP("assert(top <= end)");
3956     should_not_reach_here();
3957 
3958     bind(ok);
3959     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
3960   }
3961 #endif
3962 }
3963 
3964 // Writes to stack successive pages until offset reached to check for
3965 // stack overflow + shadow pages.  This clobbers tmp.
bang_stack_size(Register size,Register tmp)3966 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
3967   assert_different_registers(tmp, size, rscratch1);
3968   mov(tmp, sp);
3969   // Bang stack for total size given plus shadow page size.
3970   // Bang one page at a time because large size can bang beyond yellow and
3971   // red zones.
3972   Label loop;
3973   mov(rscratch1, os::vm_page_size());
3974   bind(loop);
3975   lea(tmp, Address(tmp, -os::vm_page_size()));
3976   subsw(size, size, rscratch1);
3977   str(size, Address(tmp));
3978   br(Assembler::GT, loop);
3979 
3980   // Bang down shadow pages too.
3981   // The -1 because we already subtracted 1 page.
3982   for (int i = 0; i< StackShadowPages-1; i++) {
3983     // this could be any sized move but this is can be a debugging crumb
3984     // so the bigger the better.
3985     lea(tmp, Address(tmp, -os::vm_page_size()));
3986     str(size, Address(tmp));
3987   }
3988 }
3989 
3990 
read_polling_page(Register r,address page,relocInfo::relocType rtype)3991 address MacroAssembler::read_polling_page(Register r, address page, relocInfo::relocType rtype) {
3992   unsigned long off;
3993   adrp(r, Address(page, rtype), off);
3994   InstructionMark im(this);
3995   code_section()->relocate(inst_mark(), rtype);
3996   ldrw(zr, Address(r, off));
3997   return inst_mark();
3998 }
3999 
read_polling_page(Register r,relocInfo::relocType rtype)4000 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4001   InstructionMark im(this);
4002   code_section()->relocate(inst_mark(), rtype);
4003   ldrw(zr, Address(r, 0));
4004   return inst_mark();
4005 }
4006 
adrp(Register reg1,const Address & dest,unsigned long & byte_offset)4007 void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byte_offset) {
4008   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4009   unsigned long low_page = (unsigned long)CodeCache::low_bound() >> 12;
4010   unsigned long high_page = (unsigned long)(CodeCache::high_bound()-1) >> 12;
4011   unsigned long dest_page = (unsigned long)dest.target() >> 12;
4012   long offset_low = dest_page - low_page;
4013   long offset_high = dest_page - high_page;
4014 
4015   assert(is_valid_AArch64_address(dest.target()), "bad address");
4016   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4017 
4018   InstructionMark im(this);
4019   code_section()->relocate(inst_mark(), dest.rspec());
4020   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4021   // the code cache so that if it is relocated we know it will still reach
4022   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4023     _adrp(reg1, dest.target());
4024   } else {
4025     unsigned long target = (unsigned long)dest.target();
4026     unsigned long adrp_target
4027       = (target & 0xffffffffUL) | ((unsigned long)pc() & 0xffff00000000UL);
4028 
4029     _adrp(reg1, (address)adrp_target);
4030     movk(reg1, target >> 32, 32);
4031   }
4032   byte_offset = (unsigned long)dest.target() & 0xfff;
4033 }
4034 
load_byte_map_base(Register reg)4035 void MacroAssembler::load_byte_map_base(Register reg) {
4036   jbyte *byte_map_base =
4037     ((CardTableModRefBS*)(Universe::heap()->barrier_set()))->byte_map_base;
4038 
4039   if (is_valid_AArch64_address((address)byte_map_base)) {
4040     // Strictly speaking the byte_map_base isn't an address at all,
4041     // and it might even be negative.
4042     unsigned long offset;
4043     adrp(reg, ExternalAddress((address)byte_map_base), offset);
4044     // We expect offset to be zero with most collectors.
4045     if (offset != 0) {
4046       add(reg, reg, offset);
4047     }
4048   } else {
4049     mov(reg, (uint64_t)byte_map_base);
4050   }
4051 }
4052 
build_frame(int framesize)4053 void MacroAssembler::build_frame(int framesize) {
4054   if (framesize == 0) {
4055     // Is this even possible?
4056     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4057   } else if (framesize < ((1 << 9) + 2 * wordSize)) {
4058     sub(sp, sp, framesize);
4059     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4060   } else {
4061     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4062     if (framesize < ((1 << 12) + 2 * wordSize))
4063       sub(sp, sp, framesize - 2 * wordSize);
4064     else {
4065       mov(rscratch1, framesize - 2 * wordSize);
4066       sub(sp, sp, rscratch1);
4067     }
4068   }
4069 }
4070 
remove_frame(int framesize)4071 void MacroAssembler::remove_frame(int framesize) {
4072   if (framesize == 0) {
4073     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4074   } else if (framesize < ((1 << 9) + 2 * wordSize)) {
4075     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4076     add(sp, sp, framesize);
4077   } else {
4078     if (framesize < ((1 << 12) + 2 * wordSize))
4079       add(sp, sp, framesize - 2 * wordSize);
4080     else {
4081       mov(rscratch1, framesize - 2 * wordSize);
4082       add(sp, sp, rscratch1);
4083     }
4084     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4085   }
4086 }
4087 
4088 // Search for str1 in str2 and return index or -1
string_indexof(Register str2,Register str1,Register cnt2,Register cnt1,Register tmp1,Register tmp2,Register tmp3,Register tmp4,int icnt1,Register result)4089 void MacroAssembler::string_indexof(Register str2, Register str1,
4090                                     Register cnt2, Register cnt1,
4091                                     Register tmp1, Register tmp2,
4092                                     Register tmp3, Register tmp4,
4093                                     int icnt1, Register result) {
4094   Label BM, LINEARSEARCH, DONE, NOMATCH, MATCH;
4095 
4096   Register ch1 = rscratch1;
4097   Register ch2 = rscratch2;
4098   Register cnt1tmp = tmp1;
4099   Register cnt2tmp = tmp2;
4100   Register cnt1_neg = cnt1;
4101   Register cnt2_neg = cnt2;
4102   Register result_tmp = tmp4;
4103 
4104   // Note, inline_string_indexOf() generates checks:
4105   // if (substr.count > string.count) return -1;
4106   // if (substr.count == 0) return 0;
4107 
4108 // We have two strings, a source string in str2, cnt2 and a pattern string
4109 // in str1, cnt1. Find the 1st occurence of pattern in source or return -1.
4110 
4111 // For larger pattern and source we use a simplified Boyer Moore algorithm.
4112 // With a small pattern and source we use linear scan.
4113 
4114   if (icnt1 == -1) {
4115     cmp(cnt1, 256);             // Use Linear Scan if cnt1 < 8 || cnt1 >= 256
4116     ccmp(cnt1, 8, 0b0000, LO);  // Can't handle skip >= 256 because we use
4117     br(LO, LINEARSEARCH);       // a byte array.
4118     cmp(cnt1, cnt2, LSR, 2);    // Source must be 4 * pattern for BM
4119     br(HS, LINEARSEARCH);
4120   }
4121 
4122 // The Boyer Moore alogorithm is based on the description here:-
4123 //
4124 // http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
4125 //
4126 // This describes and algorithm with 2 shift rules. The 'Bad Character' rule
4127 // and the 'Good Suffix' rule.
4128 //
4129 // These rules are essentially heuristics for how far we can shift the
4130 // pattern along the search string.
4131 //
4132 // The implementation here uses the 'Bad Character' rule only because of the
4133 // complexity of initialisation for the 'Good Suffix' rule.
4134 //
4135 // This is also known as the Boyer-Moore-Horspool algorithm:-
4136 //
4137 // http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm
4138 //
4139 // #define ASIZE 128
4140 //
4141 //    int bm(unsigned char *x, int m, unsigned char *y, int n) {
4142 //       int i, j;
4143 //       unsigned c;
4144 //       unsigned char bc[ASIZE];
4145 //
4146 //       /* Preprocessing */
4147 //       for (i = 0; i < ASIZE; ++i)
4148 //          bc[i] = 0;
4149 //       for (i = 0; i < m - 1; ) {
4150 //          c = x[i];
4151 //          ++i;
4152 //          if (c < ASIZE) bc[c] = i;
4153 //       }
4154 //
4155 //       /* Searching */
4156 //       j = 0;
4157 //       while (j <= n - m) {
4158 //          c = y[i+j];
4159 //          if (x[m-1] == c)
4160 //            for (i = m - 2; i >= 0 && x[i] == y[i + j]; --i);
4161 //          if (i < 0) return j;
4162 //          if (c < ASIZE)
4163 //            j = j - bc[y[j+m-1]] + m;
4164 //          else
4165 //            j += 1; // Advance by 1 only if char >= ASIZE
4166 //       }
4167 //    }
4168 
4169   if (icnt1 == -1) {
4170     BIND(BM);
4171 
4172     Label ZLOOP, BCLOOP, BCSKIP, BMLOOPSTR2, BMLOOPSTR1, BMSKIP;
4173     Label BMADV, BMMATCH, BMCHECKEND;
4174 
4175     Register cnt1end = tmp2;
4176     Register str2end = cnt2;
4177     Register skipch = tmp2;
4178 
4179     // Restrict ASIZE to 128 to reduce stack space/initialisation.
4180     // The presence of chars >= ASIZE in the target string does not affect
4181     // performance, but we must be careful not to initialise them in the stack
4182     // array.
4183     // The presence of chars >= ASIZE in the source string may adversely affect
4184     // performance since we can only advance by one when we encounter one.
4185 
4186       stp(zr, zr, pre(sp, -128));
4187       for (int i = 1; i < 8; i++)
4188           stp(zr, zr, Address(sp, i*16));
4189 
4190       mov(cnt1tmp, 0);
4191       sub(cnt1end, cnt1, 1);
4192     BIND(BCLOOP);
4193       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4194       cmp(ch1, 128);
4195       add(cnt1tmp, cnt1tmp, 1);
4196       br(HS, BCSKIP);
4197       strb(cnt1tmp, Address(sp, ch1));
4198     BIND(BCSKIP);
4199       cmp(cnt1tmp, cnt1end);
4200       br(LT, BCLOOP);
4201 
4202       mov(result_tmp, str2);
4203 
4204       sub(cnt2, cnt2, cnt1);
4205       add(str2end, str2, cnt2, LSL, 1);
4206     BIND(BMLOOPSTR2);
4207       sub(cnt1tmp, cnt1, 1);
4208       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4209       ldrh(skipch, Address(str2, cnt1tmp, Address::lsl(1)));
4210       cmp(ch1, skipch);
4211       br(NE, BMSKIP);
4212       subs(cnt1tmp, cnt1tmp, 1);
4213       br(LT, BMMATCH);
4214     BIND(BMLOOPSTR1);
4215       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4216       ldrh(ch2, Address(str2, cnt1tmp, Address::lsl(1)));
4217       cmp(ch1, ch2);
4218       br(NE, BMSKIP);
4219       subs(cnt1tmp, cnt1tmp, 1);
4220       br(GE, BMLOOPSTR1);
4221     BIND(BMMATCH);
4222       sub(result_tmp, str2, result_tmp);
4223       lsr(result, result_tmp, 1);
4224       add(sp, sp, 128);
4225       b(DONE);
4226     BIND(BMADV);
4227       add(str2, str2, 2);
4228       b(BMCHECKEND);
4229     BIND(BMSKIP);
4230       cmp(skipch, 128);
4231       br(HS, BMADV);
4232       ldrb(ch2, Address(sp, skipch));
4233       add(str2, str2, cnt1, LSL, 1);
4234       sub(str2, str2, ch2, LSL, 1);
4235     BIND(BMCHECKEND);
4236       cmp(str2, str2end);
4237       br(LE, BMLOOPSTR2);
4238       add(sp, sp, 128);
4239       b(NOMATCH);
4240   }
4241 
4242   BIND(LINEARSEARCH);
4243   {
4244     Label DO1, DO2, DO3;
4245 
4246     Register str2tmp = tmp2;
4247     Register first = tmp3;
4248 
4249     if (icnt1 == -1)
4250     {
4251         Label DOSHORT, FIRST_LOOP, STR2_NEXT, STR1_LOOP, STR1_NEXT, LAST_WORD;
4252 
4253         cmp(cnt1, 4);
4254         br(LT, DOSHORT);
4255 
4256         sub(cnt2, cnt2, cnt1);
4257         sub(cnt1, cnt1, 4);
4258         mov(result_tmp, cnt2);
4259 
4260         lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4261         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4262         sub(cnt1_neg, zr, cnt1, LSL, 1);
4263         sub(cnt2_neg, zr, cnt2, LSL, 1);
4264         ldr(first, Address(str1, cnt1_neg));
4265 
4266       BIND(FIRST_LOOP);
4267         ldr(ch2, Address(str2, cnt2_neg));
4268         cmp(first, ch2);
4269         br(EQ, STR1_LOOP);
4270       BIND(STR2_NEXT);
4271         adds(cnt2_neg, cnt2_neg, 2);
4272         br(LE, FIRST_LOOP);
4273         b(NOMATCH);
4274 
4275       BIND(STR1_LOOP);
4276         adds(cnt1tmp, cnt1_neg, 8);
4277         add(cnt2tmp, cnt2_neg, 8);
4278         br(GE, LAST_WORD);
4279 
4280       BIND(STR1_NEXT);
4281         ldr(ch1, Address(str1, cnt1tmp));
4282         ldr(ch2, Address(str2, cnt2tmp));
4283         cmp(ch1, ch2);
4284         br(NE, STR2_NEXT);
4285         adds(cnt1tmp, cnt1tmp, 8);
4286         add(cnt2tmp, cnt2tmp, 8);
4287         br(LT, STR1_NEXT);
4288 
4289       BIND(LAST_WORD);
4290         ldr(ch1, Address(str1));
4291         sub(str2tmp, str2, cnt1_neg);         // adjust to corresponding
4292         ldr(ch2, Address(str2tmp, cnt2_neg)); // word in str2
4293         cmp(ch1, ch2);
4294         br(NE, STR2_NEXT);
4295         b(MATCH);
4296 
4297       BIND(DOSHORT);
4298         cmp(cnt1, 2);
4299         br(LT, DO1);
4300         br(GT, DO3);
4301     }
4302 
4303     if (icnt1 == 4) {
4304       Label CH1_LOOP;
4305 
4306         ldr(ch1, str1);
4307         sub(cnt2, cnt2, 4);
4308         mov(result_tmp, cnt2);
4309         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4310         sub(cnt2_neg, zr, cnt2, LSL, 1);
4311 
4312       BIND(CH1_LOOP);
4313         ldr(ch2, Address(str2, cnt2_neg));
4314         cmp(ch1, ch2);
4315         br(EQ, MATCH);
4316         adds(cnt2_neg, cnt2_neg, 2);
4317         br(LE, CH1_LOOP);
4318         b(NOMATCH);
4319     }
4320 
4321     if (icnt1 == -1 || icnt1 == 2) {
4322       Label CH1_LOOP;
4323 
4324       BIND(DO2);
4325         ldrw(ch1, str1);
4326         sub(cnt2, cnt2, 2);
4327         mov(result_tmp, cnt2);
4328         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4329         sub(cnt2_neg, zr, cnt2, LSL, 1);
4330 
4331       BIND(CH1_LOOP);
4332         ldrw(ch2, Address(str2, cnt2_neg));
4333         cmp(ch1, ch2);
4334         br(EQ, MATCH);
4335         adds(cnt2_neg, cnt2_neg, 2);
4336         br(LE, CH1_LOOP);
4337         b(NOMATCH);
4338     }
4339 
4340     if (icnt1 == -1 || icnt1 == 3) {
4341       Label FIRST_LOOP, STR2_NEXT, STR1_LOOP;
4342 
4343       BIND(DO3);
4344         ldrw(first, str1);
4345         ldrh(ch1, Address(str1, 4));
4346 
4347         sub(cnt2, cnt2, 3);
4348         mov(result_tmp, cnt2);
4349         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4350         sub(cnt2_neg, zr, cnt2, LSL, 1);
4351 
4352       BIND(FIRST_LOOP);
4353         ldrw(ch2, Address(str2, cnt2_neg));
4354         cmpw(first, ch2);
4355         br(EQ, STR1_LOOP);
4356       BIND(STR2_NEXT);
4357         adds(cnt2_neg, cnt2_neg, 2);
4358         br(LE, FIRST_LOOP);
4359         b(NOMATCH);
4360 
4361       BIND(STR1_LOOP);
4362         add(cnt2tmp, cnt2_neg, 4);
4363         ldrh(ch2, Address(str2, cnt2tmp));
4364         cmp(ch1, ch2);
4365         br(NE, STR2_NEXT);
4366         b(MATCH);
4367     }
4368 
4369     if (icnt1 == -1 || icnt1 == 1) {
4370       Label CH1_LOOP, HAS_ZERO;
4371       Label DO1_SHORT, DO1_LOOP;
4372 
4373       BIND(DO1);
4374         ldrh(ch1, str1);
4375         cmp(cnt2, 4);
4376         br(LT, DO1_SHORT);
4377 
4378         orr(ch1, ch1, ch1, LSL, 16);
4379         orr(ch1, ch1, ch1, LSL, 32);
4380 
4381         sub(cnt2, cnt2, 4);
4382         mov(result_tmp, cnt2);
4383         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4384         sub(cnt2_neg, zr, cnt2, LSL, 1);
4385 
4386         mov(tmp3, 0x0001000100010001);
4387       BIND(CH1_LOOP);
4388         ldr(ch2, Address(str2, cnt2_neg));
4389         eor(ch2, ch1, ch2);
4390         sub(tmp1, ch2, tmp3);
4391         orr(tmp2, ch2, 0x7fff7fff7fff7fff);
4392         bics(tmp1, tmp1, tmp2);
4393         br(NE, HAS_ZERO);
4394         adds(cnt2_neg, cnt2_neg, 8);
4395         br(LT, CH1_LOOP);
4396 
4397         cmp(cnt2_neg, 8);
4398         mov(cnt2_neg, 0);
4399         br(LT, CH1_LOOP);
4400         b(NOMATCH);
4401 
4402       BIND(HAS_ZERO);
4403         rev(tmp1, tmp1);
4404         clz(tmp1, tmp1);
4405         add(cnt2_neg, cnt2_neg, tmp1, LSR, 3);
4406         b(MATCH);
4407 
4408       BIND(DO1_SHORT);
4409         mov(result_tmp, cnt2);
4410         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4411         sub(cnt2_neg, zr, cnt2, LSL, 1);
4412       BIND(DO1_LOOP);
4413         ldrh(ch2, Address(str2, cnt2_neg));
4414         cmpw(ch1, ch2);
4415         br(EQ, MATCH);
4416         adds(cnt2_neg, cnt2_neg, 2);
4417         br(LT, DO1_LOOP);
4418     }
4419   }
4420   BIND(NOMATCH);
4421     mov(result, -1);
4422     b(DONE);
4423   BIND(MATCH);
4424     add(result, result_tmp, cnt2_neg, ASR, 1);
4425   BIND(DONE);
4426 }
4427 
4428 // Compare strings.
string_compare(Register str1,Register str2,Register cnt1,Register cnt2,Register result,Register tmp1)4429 void MacroAssembler::string_compare(Register str1, Register str2,
4430                                     Register cnt1, Register cnt2, Register result,
4431                                     Register tmp1) {
4432   Label LENGTH_DIFF, DONE, SHORT_LOOP, SHORT_STRING,
4433     NEXT_WORD, DIFFERENCE;
4434 
4435   BLOCK_COMMENT("string_compare {");
4436 
4437   // Compute the minimum of the string lengths and save the difference.
4438   subsw(tmp1, cnt1, cnt2);
4439   cselw(cnt2, cnt1, cnt2, Assembler::LE); // min
4440 
4441   // A very short string
4442   cmpw(cnt2, 4);
4443   br(Assembler::LT, SHORT_STRING);
4444 
4445   // Check if the strings start at the same location.
4446   cmp(str1, str2);
4447   br(Assembler::EQ, LENGTH_DIFF);
4448 
4449   // Compare longwords
4450   {
4451     subw(cnt2, cnt2, 4); // The last longword is a special case
4452 
4453     // Move both string pointers to the last longword of their
4454     // strings, negate the remaining count, and convert it to bytes.
4455     lea(str1, Address(str1, cnt2, Address::uxtw(1)));
4456     lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4457     sub(cnt2, zr, cnt2, LSL, 1);
4458 
4459     // Loop, loading longwords and comparing them into rscratch2.
4460     bind(NEXT_WORD);
4461     ldr(result, Address(str1, cnt2));
4462     ldr(cnt1, Address(str2, cnt2));
4463     adds(cnt2, cnt2, wordSize);
4464     eor(rscratch2, result, cnt1);
4465     cbnz(rscratch2, DIFFERENCE);
4466     br(Assembler::LT, NEXT_WORD);
4467 
4468     // Last longword.  In the case where length == 4 we compare the
4469     // same longword twice, but that's still faster than another
4470     // conditional branch.
4471 
4472     ldr(result, Address(str1));
4473     ldr(cnt1, Address(str2));
4474     eor(rscratch2, result, cnt1);
4475     cbz(rscratch2, LENGTH_DIFF);
4476 
4477     // Find the first different characters in the longwords and
4478     // compute their difference.
4479     bind(DIFFERENCE);
4480     rev(rscratch2, rscratch2);
4481     clz(rscratch2, rscratch2);
4482     andr(rscratch2, rscratch2, -16);
4483     lsrv(result, result, rscratch2);
4484     uxthw(result, result);
4485     lsrv(cnt1, cnt1, rscratch2);
4486     uxthw(cnt1, cnt1);
4487     subw(result, result, cnt1);
4488     b(DONE);
4489   }
4490 
4491   bind(SHORT_STRING);
4492   // Is the minimum length zero?
4493   cbz(cnt2, LENGTH_DIFF);
4494 
4495   bind(SHORT_LOOP);
4496   load_unsigned_short(result, Address(post(str1, 2)));
4497   load_unsigned_short(cnt1, Address(post(str2, 2)));
4498   subw(result, result, cnt1);
4499   cbnz(result, DONE);
4500   sub(cnt2, cnt2, 1);
4501   cbnz(cnt2, SHORT_LOOP);
4502 
4503   // Strings are equal up to min length.  Return the length difference.
4504   bind(LENGTH_DIFF);
4505   mov(result, tmp1);
4506 
4507   // That's it
4508   bind(DONE);
4509 
4510   BLOCK_COMMENT("} string_compare");
4511 }
4512 
4513 
4514 // base:     Address of a buffer to be zeroed, 8 bytes aligned.
4515 // cnt:      Count in HeapWords.
4516 // is_large: True when 'cnt' is known to be >= BlockZeroingLowLimit.
zero_words(Register base,Register cnt)4517 void MacroAssembler::zero_words(Register base, Register cnt)
4518 {
4519   if (UseBlockZeroing) {
4520     block_zero(base, cnt);
4521   } else {
4522     fill_words(base, cnt, zr);
4523   }
4524 }
4525 
4526 // r10 = base:   Address of a buffer to be zeroed, 8 bytes aligned.
4527 // cnt:          Immediate count in HeapWords.
4528 // r11 = tmp:    For use as cnt if we need to call out
4529 #define ShortArraySize (18 * BytesPerLong)
zero_words(Register base,u_int64_t cnt)4530 void MacroAssembler::zero_words(Register base, u_int64_t cnt)
4531 {
4532   Register tmp = r11;
4533   int i = cnt & 1;  // store any odd word to start
4534   if (i) str(zr, Address(base));
4535 
4536   if (cnt <= ShortArraySize / BytesPerLong) {
4537     for (; i < (int)cnt; i += 2)
4538       stp(zr, zr, Address(base, i * wordSize));
4539   } else if (UseBlockZeroing && cnt >= (u_int64_t)(BlockZeroingLowLimit >> LogBytesPerWord)) {
4540     mov(tmp, cnt);
4541     block_zero(base, tmp, true);
4542   } else {
4543     const int unroll = 4; // Number of stp(zr, zr) instructions we'll unroll
4544     int remainder = cnt % (2 * unroll);
4545     for (; i < remainder; i += 2)
4546       stp(zr, zr, Address(base, i * wordSize));
4547 
4548     Label loop;
4549     Register cnt_reg = rscratch1;
4550     Register loop_base = rscratch2;
4551     cnt = cnt - remainder;
4552     mov(cnt_reg, cnt);
4553     // adjust base and prebias by -2 * wordSize so we can pre-increment
4554     add(loop_base, base, (remainder - 2) * wordSize);
4555     bind(loop);
4556     sub(cnt_reg, cnt_reg, 2 * unroll);
4557     for (i = 1; i < unroll; i++)
4558       stp(zr, zr, Address(loop_base, 2 * i * wordSize));
4559     stp(zr, zr, Address(pre(loop_base, 2 * unroll * wordSize)));
4560     cbnz(cnt_reg, loop);
4561   }
4562 }
4563 
4564 // base:   Address of a buffer to be filled, 8 bytes aligned.
4565 // cnt:    Count in 8-byte unit.
4566 // value:  Value to be filled with.
4567 // base will point to the end of the buffer after filling.
fill_words(Register base,Register cnt,Register value)4568 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
4569 {
4570 //  Algorithm:
4571 //
4572 //    scratch1 = cnt & 7;
4573 //    cnt -= scratch1;
4574 //    p += scratch1;
4575 //    switch (scratch1) {
4576 //      do {
4577 //        cnt -= 8;
4578 //          p[-8] = v;
4579 //        case 7:
4580 //          p[-7] = v;
4581 //        case 6:
4582 //          p[-6] = v;
4583 //          // ...
4584 //        case 1:
4585 //          p[-1] = v;
4586 //        case 0:
4587 //          p += 8;
4588 //      } while (cnt);
4589 //    }
4590 
4591   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
4592 
4593   Label fini, skip, entry, loop;
4594   const int unroll = 8; // Number of stp instructions we'll unroll
4595 
4596   cbz(cnt, fini);
4597   tbz(base, 3, skip);
4598   str(value, Address(post(base, 8)));
4599   sub(cnt, cnt, 1);
4600   bind(skip);
4601 
4602   andr(rscratch1, cnt, (unroll-1) * 2);
4603   sub(cnt, cnt, rscratch1);
4604   add(base, base, rscratch1, Assembler::LSL, 3);
4605   adr(rscratch2, entry);
4606   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
4607   br(rscratch2);
4608 
4609   bind(loop);
4610   add(base, base, unroll * 16);
4611   for (int i = -unroll; i < 0; i++)
4612     stp(value, value, Address(base, i * 16));
4613   bind(entry);
4614   subs(cnt, cnt, unroll * 2);
4615   br(Assembler::GE, loop);
4616 
4617   tbz(cnt, 0, fini);
4618   str(value, Address(post(base, 8)));
4619   bind(fini);
4620 }
4621 
4622 // Use DC ZVA to do fast zeroing.
4623 // base:   Address of a buffer to be zeroed, 8 bytes aligned.
4624 // cnt:    Count in HeapWords.
4625 // is_large: True when 'cnt' is known to be >= BlockZeroingLowLimit.
block_zero(Register base,Register cnt,bool is_large)4626 void MacroAssembler::block_zero(Register base, Register cnt, bool is_large)
4627 {
4628   Label small;
4629   Label store_pair, loop_store_pair, done;
4630   Label base_aligned;
4631 
4632   assert_different_registers(base, cnt, rscratch1);
4633   guarantee(base == r10 && cnt == r11, "fix register usage");
4634 
4635   Register tmp = rscratch1;
4636   Register tmp2 = rscratch2;
4637   int zva_length = VM_Version::zva_length();
4638 
4639   // Ensure ZVA length can be divided by 16. This is required by
4640   // the subsequent operations.
4641   assert (zva_length % 16 == 0, "Unexpected ZVA Length");
4642 
4643   if (!is_large) cbz(cnt, done);
4644   tbz(base, 3, base_aligned);
4645   str(zr, Address(post(base, 8)));
4646   sub(cnt, cnt, 1);
4647   bind(base_aligned);
4648 
4649   // Ensure count >= zva_length * 2 so that it still deserves a zva after
4650   // alignment.
4651   if (!is_large || !(BlockZeroingLowLimit >= zva_length * 2)) {
4652     int low_limit = MAX2(zva_length * 2, (int)BlockZeroingLowLimit);
4653     subs(tmp, cnt, low_limit >> 3);
4654     br(Assembler::LT, small);
4655   }
4656 
4657   far_call(StubRoutines::aarch64::get_zero_longs());
4658 
4659   bind(small);
4660 
4661   const int unroll = 8; // Number of stp instructions we'll unroll
4662   Label small_loop, small_table_end;
4663 
4664   andr(tmp, cnt, (unroll-1) * 2);
4665   sub(cnt, cnt, tmp);
4666   add(base, base, tmp, Assembler::LSL, 3);
4667   adr(tmp2, small_table_end);
4668   sub(tmp2, tmp2, tmp, Assembler::LSL, 1);
4669   br(tmp2);
4670 
4671   bind(small_loop);
4672   add(base, base, unroll * 16);
4673   for (int i = -unroll; i < 0; i++)
4674     stp(zr, zr, Address(base, i * 16));
4675   bind(small_table_end);
4676   subs(cnt, cnt, unroll * 2);
4677   br(Assembler::GE, small_loop);
4678 
4679   tbz(cnt, 0, done);
4680   str(zr, Address(post(base, 8)));
4681 
4682   bind(done);
4683 }
4684 
string_equals(Register str1,Register str2,Register cnt,Register result,Register tmp1)4685 void MacroAssembler::string_equals(Register str1, Register str2,
4686                                    Register cnt, Register result,
4687                                    Register tmp1) {
4688   Label SAME_CHARS, DONE, SHORT_LOOP, SHORT_STRING,
4689     NEXT_WORD;
4690 
4691   const Register tmp2 = rscratch1;
4692   assert_different_registers(str1, str2, cnt, result, tmp1, tmp2, rscratch2);
4693 
4694   BLOCK_COMMENT("string_equals {");
4695 
4696   // Start by assuming that the strings are not equal.
4697   mov(result, zr);
4698 
4699   // A very short string
4700   cmpw(cnt, 4);
4701   br(Assembler::LT, SHORT_STRING);
4702 
4703   // Check if the strings start at the same location.
4704   cmp(str1, str2);
4705   br(Assembler::EQ, SAME_CHARS);
4706 
4707   // Compare longwords
4708   {
4709     subw(cnt, cnt, 4); // The last longword is a special case
4710 
4711     // Move both string pointers to the last longword of their
4712     // strings, negate the remaining count, and convert it to bytes.
4713     lea(str1, Address(str1, cnt, Address::uxtw(1)));
4714     lea(str2, Address(str2, cnt, Address::uxtw(1)));
4715     sub(cnt, zr, cnt, LSL, 1);
4716 
4717     // Loop, loading longwords and comparing them into rscratch2.
4718     bind(NEXT_WORD);
4719     ldr(tmp1, Address(str1, cnt));
4720     ldr(tmp2, Address(str2, cnt));
4721     adds(cnt, cnt, wordSize);
4722     eor(rscratch2, tmp1, tmp2);
4723     cbnz(rscratch2, DONE);
4724     br(Assembler::LT, NEXT_WORD);
4725 
4726     // Last longword.  In the case where length == 4 we compare the
4727     // same longword twice, but that's still faster than another
4728     // conditional branch.
4729 
4730     ldr(tmp1, Address(str1));
4731     ldr(tmp2, Address(str2));
4732     eor(rscratch2, tmp1, tmp2);
4733     cbz(rscratch2, SAME_CHARS);
4734     b(DONE);
4735   }
4736 
4737   bind(SHORT_STRING);
4738   // Is the length zero?
4739   cbz(cnt, SAME_CHARS);
4740 
4741   bind(SHORT_LOOP);
4742   load_unsigned_short(tmp1, Address(post(str1, 2)));
4743   load_unsigned_short(tmp2, Address(post(str2, 2)));
4744   subw(tmp1, tmp1, tmp2);
4745   cbnz(tmp1, DONE);
4746   sub(cnt, cnt, 1);
4747   cbnz(cnt, SHORT_LOOP);
4748 
4749   // Strings are equal.
4750   bind(SAME_CHARS);
4751   mov(result, true);
4752 
4753   // That's it
4754   bind(DONE);
4755 
4756   BLOCK_COMMENT("} string_equals");
4757 }
4758 
4759 // Compare char[] arrays aligned to 4 bytes
char_arrays_equals(Register ary1,Register ary2,Register result,Register tmp1)4760 void MacroAssembler::char_arrays_equals(Register ary1, Register ary2,
4761                                         Register result, Register tmp1)
4762 {
4763   Register cnt1 = rscratch1;
4764   Register cnt2 = rscratch2;
4765   Register tmp2 = rscratch2;
4766 
4767   Label SAME, DIFFER, NEXT, TAIL03, TAIL01;
4768 
4769   int length_offset  = arrayOopDesc::length_offset_in_bytes();
4770   int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
4771 
4772   BLOCK_COMMENT("char_arrays_equals  {");
4773 
4774     // different until proven equal
4775     mov(result, false);
4776 
4777     // same array?
4778     cmp(ary1, ary2);
4779     br(Assembler::EQ, SAME);
4780 
4781     // ne if either null
4782     cbz(ary1, DIFFER);
4783     cbz(ary2, DIFFER);
4784 
4785     // lengths ne?
4786     ldrw(cnt1, Address(ary1, length_offset));
4787     ldrw(cnt2, Address(ary2, length_offset));
4788     cmp(cnt1, cnt2);
4789     br(Assembler::NE, DIFFER);
4790 
4791     lea(ary1, Address(ary1, base_offset));
4792     lea(ary2, Address(ary2, base_offset));
4793 
4794     subs(cnt1, cnt1, 4);
4795     br(LT, TAIL03);
4796 
4797   BIND(NEXT);
4798     ldr(tmp1, Address(post(ary1, 8)));
4799     ldr(tmp2, Address(post(ary2, 8)));
4800     subs(cnt1, cnt1, 4);
4801     eor(tmp1, tmp1, tmp2);
4802     cbnz(tmp1, DIFFER);
4803     br(GE, NEXT);
4804 
4805   BIND(TAIL03);  // 0-3 chars left, cnt1 = #chars left - 4
4806     tst(cnt1, 0b10);
4807     br(EQ, TAIL01);
4808     ldrw(tmp1, Address(post(ary1, 4)));
4809     ldrw(tmp2, Address(post(ary2, 4)));
4810     cmp(tmp1, tmp2);
4811     br(NE, DIFFER);
4812   BIND(TAIL01);  // 0-1 chars left
4813     tst(cnt1, 0b01);
4814     br(EQ, SAME);
4815     ldrh(tmp1, ary1);
4816     ldrh(tmp2, ary2);
4817     cmp(tmp1, tmp2);
4818     br(NE, DIFFER);
4819 
4820   BIND(SAME);
4821     mov(result, true);
4822   BIND(DIFFER); // result already set
4823 
4824   BLOCK_COMMENT("} char_arrays_equals");
4825 }
4826 
4827 // encode char[] to byte[] in ISO_8859_1
encode_iso_array(Register src,Register dst,Register len,Register result,FloatRegister Vtmp1,FloatRegister Vtmp2,FloatRegister Vtmp3,FloatRegister Vtmp4)4828 void MacroAssembler::encode_iso_array(Register src, Register dst,
4829                       Register len, Register result,
4830                       FloatRegister Vtmp1, FloatRegister Vtmp2,
4831                       FloatRegister Vtmp3, FloatRegister Vtmp4)
4832 {
4833     Label DONE, NEXT_32, LOOP_8, NEXT_8, LOOP_1, NEXT_1;
4834     Register tmp1 = rscratch1;
4835 
4836       mov(result, len); // Save initial len
4837 
4838       subs(len, len, 32);
4839       br(LT, LOOP_8);
4840 
4841 // The following code uses the SIMD 'uqxtn' and 'uqxtn2' instructions
4842 // to convert chars to bytes. These set the 'QC' bit in the FPSR if
4843 // any char could not fit in a byte, so clear the FPSR so we can test it.
4844       clear_fpsr();
4845 
4846     BIND(NEXT_32);
4847       ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
4848       uqxtn(Vtmp1, T8B, Vtmp1, T8H);  // uqxtn  - write bottom half
4849       uqxtn(Vtmp1, T16B, Vtmp2, T8H); // uqxtn2 - write top half
4850       uqxtn(Vtmp2, T8B, Vtmp3, T8H);
4851       uqxtn(Vtmp2, T16B, Vtmp4, T8H); // uqxtn2
4852       get_fpsr(tmp1);
4853       cbnzw(tmp1, LOOP_8);
4854       st1(Vtmp1, Vtmp2, T16B, post(dst, 32));
4855       subs(len, len, 32);
4856       add(src, src, 64);
4857       br(GE, NEXT_32);
4858 
4859     BIND(LOOP_8);
4860       adds(len, len, 32-8);
4861       br(LT, LOOP_1);
4862       clear_fpsr(); // QC may be set from loop above, clear again
4863     BIND(NEXT_8);
4864       ld1(Vtmp1, T8H, src);
4865       uqxtn(Vtmp1, T8B, Vtmp1, T8H);
4866       get_fpsr(tmp1);
4867       cbnzw(tmp1, LOOP_1);
4868       st1(Vtmp1, T8B, post(dst, 8));
4869       subs(len, len, 8);
4870       add(src, src, 16);
4871       br(GE, NEXT_8);
4872 
4873     BIND(LOOP_1);
4874       adds(len, len, 8);
4875       br(LE, DONE);
4876 
4877     BIND(NEXT_1);
4878       ldrh(tmp1, Address(post(src, 2)));
4879       tst(tmp1, 0xff00);
4880       br(NE, DONE);
4881       strb(tmp1, Address(post(dst, 1)));
4882       subs(len, len, 1);
4883       br(GT, NEXT_1);
4884 
4885     BIND(DONE);
4886       sub(result, result, len); // Return index where we stopped
4887 }
4888