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