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/barrierSetAssembler.hpp"
  34 #include "gc/shared/cardTableBarrierSet.hpp"
  35 #include "interpreter/interpreter.hpp"
  36 #include "compiler/disassembler.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "nativeInst_aarch64.hpp"
  39 #include "oops/compressedOops.inline.hpp"
  40 #include "oops/klass.inline.hpp"
  41 #include "oops/oop.hpp"
  42 #include "opto/compile.hpp"
  43 #include "opto/intrinsicnode.hpp"
  44 #include "opto/node.hpp"
  45 #include "runtime/biasedLocking.hpp"
  46 #include "runtime/icache.hpp"
  47 #include "runtime/interfaceSupport.inline.hpp"
  48 #include "runtime/jniHandles.inline.hpp"
  49 #include "runtime/sharedRuntime.hpp"
  50 #include "runtime/thread.hpp"
  51 #if INCLUDE_ALL_GCS
  52 #include "gc/g1/g1BarrierSet.hpp"
  53 #include "gc/g1/g1CardTable.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 = CompressedOops::encode((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::resolve_jobject(Register value, Register thread, Register tmp) {
2095   BarrierSetAssembler *bs = Universe::heap()->barrier_set()->barrier_set_assembler();
2096   Label done, not_weak;
2097   cbz(value, done);           // Use NULL as-is.
2098 
2099   STATIC_ASSERT(JNIHandles::weak_tag_mask == 1u);
2100   tbz(r0, 0, not_weak);    // Test for jweak tag.
2101 
2102   // Resolve jweak.
2103   bs->load_at(this, IN_ROOT | ON_PHANTOM_OOP_REF, T_OBJECT,
2104                     value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
2105   verify_oop(value);
2106   b(done);
2107 
2108   bind(not_weak);
2109   // Resolve (untagged) jobject.
2110   bs->load_at(this, IN_ROOT | ON_STRONG_OOP_REF, T_OBJECT,
2111                     value, Address(value, 0), tmp, thread);
2112   verify_oop(value);
2113   bind(done);
2114 }
2115 
2116 void MacroAssembler::stop(const char* msg) {
2117   address ip = pc();
2118   pusha();
2119   mov(c_rarg0, (address)msg);
2120   mov(c_rarg1, (address)ip);
2121   mov(c_rarg2, sp);
2122   mov(c_rarg3, CAST_FROM_FN_PTR(address, MacroAssembler::debug64));
2123   // call(c_rarg3);
2124   blrt(c_rarg3, 3, 0, 1);
2125   hlt(0);
2126 }
2127 
2128 void MacroAssembler::unimplemented(const char* what) {
2129   const char* buf = NULL;
2130   {
2131     ResourceMark rm;
2132     stringStream ss;
2133     ss.print("unimplemented: %s", what);
2134     buf = code_string(ss.as_string());
2135   }
2136   stop(buf);
2137 }
2138 
2139 // If a constant does not fit in an immediate field, generate some
2140 // number of MOV instructions and then perform the operation.
2141 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, unsigned imm,
2142                                            add_sub_imm_insn insn1,
2143                                            add_sub_reg_insn insn2) {
2144   assert(Rd != zr, "Rd = zr and not setting flags?");
2145   if (operand_valid_for_add_sub_immediate((int)imm)) {
2146     (this->*insn1)(Rd, Rn, imm);
2147   } else {
2148     if (uabs(imm) < (1 << 24)) {
2149        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2150        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2151     } else {
2152        assert_different_registers(Rd, Rn);
2153        mov(Rd, (uint64_t)imm);
2154        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2155     }
2156   }
2157 }
2158 
2159 // Seperate vsn which sets the flags. Optimisations are more restricted
2160 // because we must set the flags correctly.
2161 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, unsigned imm,
2162                                            add_sub_imm_insn insn1,
2163                                            add_sub_reg_insn insn2) {
2164   if (operand_valid_for_add_sub_immediate((int)imm)) {
2165     (this->*insn1)(Rd, Rn, imm);
2166   } else {
2167     assert_different_registers(Rd, Rn);
2168     assert(Rd != zr, "overflow in immediate operand");
2169     mov(Rd, (uint64_t)imm);
2170     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2171   }
2172 }
2173 
2174 
2175 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2176   if (increment.is_register()) {
2177     add(Rd, Rn, increment.as_register());
2178   } else {
2179     add(Rd, Rn, increment.as_constant());
2180   }
2181 }
2182 
2183 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2184   if (increment.is_register()) {
2185     addw(Rd, Rn, increment.as_register());
2186   } else {
2187     addw(Rd, Rn, increment.as_constant());
2188   }
2189 }
2190 
2191 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2192   if (decrement.is_register()) {
2193     sub(Rd, Rn, decrement.as_register());
2194   } else {
2195     sub(Rd, Rn, decrement.as_constant());
2196   }
2197 }
2198 
2199 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2200   if (decrement.is_register()) {
2201     subw(Rd, Rn, decrement.as_register());
2202   } else {
2203     subw(Rd, Rn, decrement.as_constant());
2204   }
2205 }
2206 
2207 void MacroAssembler::reinit_heapbase()
2208 {
2209   if (UseCompressedOops) {
2210     if (Universe::is_fully_initialized()) {
2211       mov(rheapbase, Universe::narrow_ptrs_base());
2212     } else {
2213       lea(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
2214       ldr(rheapbase, Address(rheapbase));
2215     }
2216   }
2217 }
2218 
2219 // this simulates the behaviour of the x86 cmpxchg instruction using a
2220 // load linked/store conditional pair. we use the acquire/release
2221 // versions of these instructions so that we flush pending writes as
2222 // per Java semantics.
2223 
2224 // n.b the x86 version assumes the old value to be compared against is
2225 // in rax and updates rax with the value located in memory if the
2226 // cmpxchg fails. we supply a register for the old value explicitly
2227 
2228 // the aarch64 load linked/store conditional instructions do not
2229 // accept an offset. so, unlike x86, we must provide a plain register
2230 // to identify the memory word to be compared/exchanged rather than a
2231 // register+offset Address.
2232 
2233 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2234                                 Label &succeed, Label *fail) {
2235   // oldv holds comparison value
2236   // newv holds value to write in exchange
2237   // addr identifies memory word to compare against/update
2238   if (UseLSE) {
2239     mov(tmp, oldv);
2240     casal(Assembler::xword, oldv, newv, addr);
2241     cmp(tmp, oldv);
2242     br(Assembler::EQ, succeed);
2243     membar(AnyAny);
2244   } else {
2245     Label retry_load, nope;
2246     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2247       prfm(Address(addr), PSTL1STRM);
2248     bind(retry_load);
2249     // flush and load exclusive from the memory location
2250     // and fail if it is not what we expect
2251     ldaxr(tmp, addr);
2252     cmp(tmp, oldv);
2253     br(Assembler::NE, nope);
2254     // if we store+flush with no intervening write tmp wil be zero
2255     stlxr(tmp, newv, addr);
2256     cbzw(tmp, succeed);
2257     // retry so we only ever return after a load fails to compare
2258     // ensures we don't return a stale value after a failed write.
2259     b(retry_load);
2260     // if the memory word differs we return it in oldv and signal a fail
2261     bind(nope);
2262     membar(AnyAny);
2263     mov(oldv, tmp);
2264   }
2265   if (fail)
2266     b(*fail);
2267 }
2268 
2269 void MacroAssembler::cmpxchg_obj_header(Register oldv, Register newv, Register obj, Register tmp,
2270                                         Label &succeed, Label *fail) {
2271   assert(oopDesc::mark_offset_in_bytes() == 0, "assumption");
2272   cmpxchgptr(oldv, newv, obj, tmp, succeed, fail);
2273 }
2274 
2275 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2276                                 Label &succeed, Label *fail) {
2277   // oldv holds comparison value
2278   // newv holds value to write in exchange
2279   // addr identifies memory word to compare against/update
2280   // tmp returns 0/1 for success/failure
2281   if (UseLSE) {
2282     mov(tmp, oldv);
2283     casal(Assembler::word, oldv, newv, addr);
2284     cmp(tmp, oldv);
2285     br(Assembler::EQ, succeed);
2286     membar(AnyAny);
2287   } else {
2288     Label retry_load, nope;
2289     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2290       prfm(Address(addr), PSTL1STRM);
2291     bind(retry_load);
2292     // flush and load exclusive from the memory location
2293     // and fail if it is not what we expect
2294     ldaxrw(tmp, addr);
2295     cmp(tmp, oldv);
2296     br(Assembler::NE, nope);
2297     // if we store+flush with no intervening write tmp wil be zero
2298     stlxrw(tmp, newv, addr);
2299     cbzw(tmp, succeed);
2300     // retry so we only ever return after a load fails to compare
2301     // ensures we don't return a stale value after a failed write.
2302     b(retry_load);
2303     // if the memory word differs we return it in oldv and signal a fail
2304     bind(nope);
2305     membar(AnyAny);
2306     mov(oldv, tmp);
2307   }
2308   if (fail)
2309     b(*fail);
2310 }
2311 
2312 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
2313 // doesn't retry and may fail spuriously.  If the oldval is wanted,
2314 // Pass a register for the result, otherwise pass noreg.
2315 
2316 // Clobbers rscratch1
2317 void MacroAssembler::cmpxchg(Register addr, Register expected,
2318                              Register new_val,
2319                              enum operand_size size,
2320                              bool acquire, bool release,
2321                              bool weak,
2322                              Register result) {
2323   if (result == noreg)  result = rscratch1;
2324   if (UseLSE) {
2325     mov(result, expected);
2326     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
2327     cmp(result, expected);
2328   } else {
2329     BLOCK_COMMENT("cmpxchg {");
2330     Label retry_load, done;
2331     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2332       prfm(Address(addr), PSTL1STRM);
2333     bind(retry_load);
2334     load_exclusive(result, addr, size, acquire);
2335     if (size == xword)
2336       cmp(result, expected);
2337     else
2338       cmpw(result, expected);
2339     br(Assembler::NE, done);
2340     store_exclusive(rscratch1, new_val, addr, size, release);
2341     if (weak) {
2342       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
2343     } else {
2344       cbnzw(rscratch1, retry_load);
2345     }
2346     bind(done);
2347     BLOCK_COMMENT("} cmpxchg");
2348   }
2349 }
2350 
2351 static bool different(Register a, RegisterOrConstant b, Register c) {
2352   if (b.is_constant())
2353     return a != c;
2354   else
2355     return a != b.as_register() && a != c && b.as_register() != c;
2356 }
2357 
2358 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2359 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2360   if (UseLSE) {                                                         \
2361     prev = prev->is_valid() ? prev : zr;                                \
2362     if (incr.is_register()) {                                           \
2363       AOP(sz, incr.as_register(), prev, addr);                          \
2364     } else {                                                            \
2365       mov(rscratch2, incr.as_constant());                               \
2366       AOP(sz, rscratch2, prev, addr);                                   \
2367     }                                                                   \
2368     return;                                                             \
2369   }                                                                     \
2370   Register result = rscratch2;                                          \
2371   if (prev->is_valid())                                                 \
2372     result = different(prev, incr, addr) ? prev : rscratch2;            \
2373                                                                         \
2374   Label retry_load;                                                     \
2375   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2376     prfm(Address(addr), PSTL1STRM);                                     \
2377   bind(retry_load);                                                     \
2378   LDXR(result, addr);                                                   \
2379   OP(rscratch1, result, incr);                                          \
2380   STXR(rscratch2, rscratch1, addr);                                     \
2381   cbnzw(rscratch2, retry_load);                                         \
2382   if (prev->is_valid() && prev != result) {                             \
2383     IOP(prev, rscratch1, incr);                                         \
2384   }                                                                     \
2385 }
2386 
2387 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2388 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2389 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2390 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2391 
2392 #undef ATOMIC_OP
2393 
2394 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2395 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2396   if (UseLSE) {                                                         \
2397     prev = prev->is_valid() ? prev : zr;                                \
2398     AOP(sz, newv, prev, addr);                                          \
2399     return;                                                             \
2400   }                                                                     \
2401   Register result = rscratch2;                                          \
2402   if (prev->is_valid())                                                 \
2403     result = different(prev, newv, addr) ? prev : rscratch2;            \
2404                                                                         \
2405   Label retry_load;                                                     \
2406   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2407     prfm(Address(addr), PSTL1STRM);                                     \
2408   bind(retry_load);                                                     \
2409   LDXR(result, addr);                                                   \
2410   STXR(rscratch1, newv, addr);                                          \
2411   cbnzw(rscratch1, retry_load);                                         \
2412   if (prev->is_valid() && prev != result)                               \
2413     mov(prev, result);                                                  \
2414 }
2415 
2416 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2417 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2418 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2419 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2420 
2421 #undef ATOMIC_XCHG
2422 
2423 void MacroAssembler::incr_allocated_bytes(Register thread,
2424                                           Register var_size_in_bytes,
2425                                           int con_size_in_bytes,
2426                                           Register t1) {
2427   if (!thread->is_valid()) {
2428     thread = rthread;
2429   }
2430   assert(t1->is_valid(), "need temp reg");
2431 
2432   ldr(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2433   if (var_size_in_bytes->is_valid()) {
2434     add(t1, t1, var_size_in_bytes);
2435   } else {
2436     add(t1, t1, con_size_in_bytes);
2437   }
2438   str(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2439 }
2440 
2441 #ifndef PRODUCT
2442 extern "C" void findpc(intptr_t x);
2443 #endif
2444 
2445 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2446 {
2447   // In order to get locks to work, we need to fake a in_VM state
2448   if (ShowMessageBoxOnError ) {
2449     JavaThread* thread = JavaThread::current();
2450     JavaThreadState saved_state = thread->thread_state();
2451     thread->set_thread_state(_thread_in_vm);
2452 #ifndef PRODUCT
2453     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2454       ttyLocker ttyl;
2455       BytecodeCounter::print();
2456     }
2457 #endif
2458     if (os::message_box(msg, "Execution stopped, print registers?")) {
2459       ttyLocker ttyl;
2460       tty->print_cr(" pc = 0x%016lx", pc);
2461 #ifndef PRODUCT
2462       tty->cr();
2463       findpc(pc);
2464       tty->cr();
2465 #endif
2466       tty->print_cr(" r0 = 0x%016lx", regs[0]);
2467       tty->print_cr(" r1 = 0x%016lx", regs[1]);
2468       tty->print_cr(" r2 = 0x%016lx", regs[2]);
2469       tty->print_cr(" r3 = 0x%016lx", regs[3]);
2470       tty->print_cr(" r4 = 0x%016lx", regs[4]);
2471       tty->print_cr(" r5 = 0x%016lx", regs[5]);
2472       tty->print_cr(" r6 = 0x%016lx", regs[6]);
2473       tty->print_cr(" r7 = 0x%016lx", regs[7]);
2474       tty->print_cr(" r8 = 0x%016lx", regs[8]);
2475       tty->print_cr(" r9 = 0x%016lx", regs[9]);
2476       tty->print_cr("r10 = 0x%016lx", regs[10]);
2477       tty->print_cr("r11 = 0x%016lx", regs[11]);
2478       tty->print_cr("r12 = 0x%016lx", regs[12]);
2479       tty->print_cr("r13 = 0x%016lx", regs[13]);
2480       tty->print_cr("r14 = 0x%016lx", regs[14]);
2481       tty->print_cr("r15 = 0x%016lx", regs[15]);
2482       tty->print_cr("r16 = 0x%016lx", regs[16]);
2483       tty->print_cr("r17 = 0x%016lx", regs[17]);
2484       tty->print_cr("r18 = 0x%016lx", regs[18]);
2485       tty->print_cr("r19 = 0x%016lx", regs[19]);
2486       tty->print_cr("r20 = 0x%016lx", regs[20]);
2487       tty->print_cr("r21 = 0x%016lx", regs[21]);
2488       tty->print_cr("r22 = 0x%016lx", regs[22]);
2489       tty->print_cr("r23 = 0x%016lx", regs[23]);
2490       tty->print_cr("r24 = 0x%016lx", regs[24]);
2491       tty->print_cr("r25 = 0x%016lx", regs[25]);
2492       tty->print_cr("r26 = 0x%016lx", regs[26]);
2493       tty->print_cr("r27 = 0x%016lx", regs[27]);
2494       tty->print_cr("r28 = 0x%016lx", regs[28]);
2495       tty->print_cr("r30 = 0x%016lx", regs[30]);
2496       tty->print_cr("r31 = 0x%016lx", regs[31]);
2497       BREAKPOINT;
2498     }
2499     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
2500   } else {
2501     ttyLocker ttyl;
2502     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
2503                     msg);
2504     assert(false, "DEBUG MESSAGE: %s", msg);
2505   }
2506 }
2507 
2508 #ifdef BUILTIN_SIM
2509 // routine to generate an x86 prolog for a stub function which
2510 // bootstraps into the generated ARM code which directly follows the
2511 // stub
2512 //
2513 // the argument encodes the number of general and fp registers
2514 // passed by the caller and the callng convention (currently just
2515 // the number of general registers and assumes C argument passing)
2516 
2517 extern "C" {
2518 int aarch64_stub_prolog_size();
2519 void aarch64_stub_prolog();
2520 void aarch64_prolog();
2521 }
2522 
2523 void MacroAssembler::c_stub_prolog(int gp_arg_count, int fp_arg_count, int ret_type,
2524                                    address *prolog_ptr)
2525 {
2526   int calltype = (((ret_type & 0x3) << 8) |
2527                   ((fp_arg_count & 0xf) << 4) |
2528                   (gp_arg_count & 0xf));
2529 
2530   // the addresses for the x86 to ARM entry code we need to use
2531   address start = pc();
2532   // printf("start = %lx\n", start);
2533   int byteCount =  aarch64_stub_prolog_size();
2534   // printf("byteCount = %x\n", byteCount);
2535   int instructionCount = (byteCount + 3)/ 4;
2536   // printf("instructionCount = %x\n", instructionCount);
2537   for (int i = 0; i < instructionCount; i++) {
2538     nop();
2539   }
2540 
2541   memcpy(start, (void*)aarch64_stub_prolog, byteCount);
2542 
2543   // write the address of the setup routine and the call format at the
2544   // end of into the copied code
2545   u_int64_t *patch_end = (u_int64_t *)(start + byteCount);
2546   if (prolog_ptr)
2547     patch_end[-2] = (u_int64_t)prolog_ptr;
2548   patch_end[-1] = calltype;
2549 }
2550 #endif
2551 
2552 void MacroAssembler::push_call_clobbered_registers() {
2553   push(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2554 
2555   // Push v0-v7, v16-v31.
2556   for (int i = 30; i >= 0; i -= 2) {
2557     if (i <= v7->encoding() || i >= v16->encoding()) {
2558         stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2559              Address(pre(sp, -2 * wordSize)));
2560     }
2561   }
2562 }
2563 
2564 void MacroAssembler::pop_call_clobbered_registers() {
2565 
2566   for (int i = 0; i < 32; i += 2) {
2567     if (i <= v7->encoding() || i >= v16->encoding()) {
2568       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2569            Address(post(sp, 2 * wordSize)));
2570     }
2571   }
2572 
2573   pop(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2574 }
2575 
2576 void MacroAssembler::push_CPU_state(bool save_vectors) {
2577   push(0x3fffffff, sp);         // integer registers except lr & sp
2578 
2579   if (!save_vectors) {
2580     for (int i = 30; i >= 0; i -= 2)
2581       stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2582            Address(pre(sp, -2 * wordSize)));
2583   } else {
2584     for (int i = 30; i >= 0; i -= 2)
2585       stpq(as_FloatRegister(i), as_FloatRegister(i+1),
2586            Address(pre(sp, -4 * wordSize)));
2587   }
2588 }
2589 
2590 void MacroAssembler::pop_CPU_state(bool restore_vectors) {
2591   if (!restore_vectors) {
2592     for (int i = 0; i < 32; i += 2)
2593       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2594            Address(post(sp, 2 * wordSize)));
2595   } else {
2596     for (int i = 0; i < 32; i += 2)
2597       ldpq(as_FloatRegister(i), as_FloatRegister(i+1),
2598            Address(post(sp, 4 * wordSize)));
2599   }
2600 
2601   pop(0x3fffffff, sp);         // integer registers except lr & sp
2602 }
2603 
2604 /**
2605  * Helpers for multiply_to_len().
2606  */
2607 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2608                                      Register src1, Register src2) {
2609   adds(dest_lo, dest_lo, src1);
2610   adc(dest_hi, dest_hi, zr);
2611   adds(dest_lo, dest_lo, src2);
2612   adc(final_dest_hi, dest_hi, zr);
2613 }
2614 
2615 // Generate an address from (r + r1 extend offset).  "size" is the
2616 // size of the operand.  The result may be in rscratch2.
2617 Address MacroAssembler::offsetted_address(Register r, Register r1,
2618                                           Address::extend ext, int offset, int size) {
2619   if (offset || (ext.shift() % size != 0)) {
2620     lea(rscratch2, Address(r, r1, ext));
2621     return Address(rscratch2, offset);
2622   } else {
2623     return Address(r, r1, ext);
2624   }
2625 }
2626 
2627 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2628 {
2629   assert(offset >= 0, "spill to negative address?");
2630   // Offset reachable ?
2631   //   Not aligned - 9 bits signed offset
2632   //   Aligned - 12 bits unsigned offset shifted
2633   Register base = sp;
2634   if ((offset & (size-1)) && offset >= (1<<8)) {
2635     add(tmp, base, offset & ((1<<12)-1));
2636     base = tmp;
2637     offset &= -1<<12;
2638   }
2639 
2640   if (offset >= (1<<12) * size) {
2641     add(tmp, base, offset & (((1<<12)-1)<<12));
2642     base = tmp;
2643     offset &= ~(((1<<12)-1)<<12);
2644   }
2645 
2646   return Address(base, offset);
2647 }
2648 
2649 // Checks whether offset is aligned.
2650 // Returns true if it is, else false.
2651 bool MacroAssembler::merge_alignment_check(Register base,
2652                                            size_t size,
2653                                            long cur_offset,
2654                                            long prev_offset) const {
2655   if (AvoidUnalignedAccesses) {
2656     if (base == sp) {
2657       // Checks whether low offset if aligned to pair of registers.
2658       long pair_mask = size * 2 - 1;
2659       long offset = prev_offset > cur_offset ? cur_offset : prev_offset;
2660       return (offset & pair_mask) == 0;
2661     } else { // If base is not sp, we can't guarantee the access is aligned.
2662       return false;
2663     }
2664   } else {
2665     long mask = size - 1;
2666     // Load/store pair instruction only supports element size aligned offset.
2667     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
2668   }
2669 }
2670 
2671 // Checks whether current and previous loads/stores can be merged.
2672 // Returns true if it can be merged, else false.
2673 bool MacroAssembler::ldst_can_merge(Register rt,
2674                                     const Address &adr,
2675                                     size_t cur_size_in_bytes,
2676                                     bool is_store) const {
2677   address prev = pc() - NativeInstruction::instruction_size;
2678   address last = code()->last_insn();
2679 
2680   if (last == NULL || !nativeInstruction_at(last)->is_Imm_LdSt()) {
2681     return false;
2682   }
2683 
2684   if (adr.getMode() != Address::base_plus_offset || prev != last) {
2685     return false;
2686   }
2687 
2688   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
2689   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
2690 
2691   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
2692   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
2693 
2694   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
2695     return false;
2696   }
2697 
2698   long max_offset = 63 * prev_size_in_bytes;
2699   long min_offset = -64 * prev_size_in_bytes;
2700 
2701   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
2702 
2703   // Only same base can be merged.
2704   if (adr.base() != prev_ldst->base()) {
2705     return false;
2706   }
2707 
2708   long cur_offset = adr.offset();
2709   long prev_offset = prev_ldst->offset();
2710   size_t diff = abs(cur_offset - prev_offset);
2711   if (diff != prev_size_in_bytes) {
2712     return false;
2713   }
2714 
2715   // Following cases can not be merged:
2716   // ldr x2, [x2, #8]
2717   // ldr x3, [x2, #16]
2718   // or:
2719   // ldr x2, [x3, #8]
2720   // ldr x2, [x3, #16]
2721   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
2722   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
2723     return false;
2724   }
2725 
2726   long low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
2727   // Offset range must be in ldp/stp instruction's range.
2728   if (low_offset > max_offset || low_offset < min_offset) {
2729     return false;
2730   }
2731 
2732   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
2733     return true;
2734   }
2735 
2736   return false;
2737 }
2738 
2739 // Merge current load/store with previous load/store into ldp/stp.
2740 void MacroAssembler::merge_ldst(Register rt,
2741                                 const Address &adr,
2742                                 size_t cur_size_in_bytes,
2743                                 bool is_store) {
2744 
2745   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
2746 
2747   Register rt_low, rt_high;
2748   address prev = pc() - NativeInstruction::instruction_size;
2749   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
2750 
2751   long offset;
2752 
2753   if (adr.offset() < prev_ldst->offset()) {
2754     offset = adr.offset();
2755     rt_low = rt;
2756     rt_high = prev_ldst->target();
2757   } else {
2758     offset = prev_ldst->offset();
2759     rt_low = prev_ldst->target();
2760     rt_high = rt;
2761   }
2762 
2763   Address adr_p = Address(prev_ldst->base(), offset);
2764   // Overwrite previous generated binary.
2765   code_section()->set_end(prev);
2766 
2767   const int sz = prev_ldst->size_in_bytes();
2768   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
2769   if (!is_store) {
2770     BLOCK_COMMENT("merged ldr pair");
2771     if (sz == 8) {
2772       ldp(rt_low, rt_high, adr_p);
2773     } else {
2774       ldpw(rt_low, rt_high, adr_p);
2775     }
2776   } else {
2777     BLOCK_COMMENT("merged str pair");
2778     if (sz == 8) {
2779       stp(rt_low, rt_high, adr_p);
2780     } else {
2781       stpw(rt_low, rt_high, adr_p);
2782     }
2783   }
2784 }
2785 
2786 /**
2787  * Multiply 64 bit by 64 bit first loop.
2788  */
2789 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2790                                            Register y, Register y_idx, Register z,
2791                                            Register carry, Register product,
2792                                            Register idx, Register kdx) {
2793   //
2794   //  jlong carry, x[], y[], z[];
2795   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2796   //    huge_128 product = y[idx] * x[xstart] + carry;
2797   //    z[kdx] = (jlong)product;
2798   //    carry  = (jlong)(product >>> 64);
2799   //  }
2800   //  z[xstart] = carry;
2801   //
2802 
2803   Label L_first_loop, L_first_loop_exit;
2804   Label L_one_x, L_one_y, L_multiply;
2805 
2806   subsw(xstart, xstart, 1);
2807   br(Assembler::MI, L_one_x);
2808 
2809   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2810   ldr(x_xstart, Address(rscratch1));
2811   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2812 
2813   bind(L_first_loop);
2814   subsw(idx, idx, 1);
2815   br(Assembler::MI, L_first_loop_exit);
2816   subsw(idx, idx, 1);
2817   br(Assembler::MI, L_one_y);
2818   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2819   ldr(y_idx, Address(rscratch1));
2820   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2821   bind(L_multiply);
2822 
2823   // AArch64 has a multiply-accumulate instruction that we can't use
2824   // here because it has no way to process carries, so we have to use
2825   // separate add and adc instructions.  Bah.
2826   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2827   mul(product, x_xstart, y_idx);
2828   adds(product, product, carry);
2829   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2830 
2831   subw(kdx, kdx, 2);
2832   ror(product, product, 32); // back to big-endian
2833   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2834 
2835   b(L_first_loop);
2836 
2837   bind(L_one_y);
2838   ldrw(y_idx, Address(y,  0));
2839   b(L_multiply);
2840 
2841   bind(L_one_x);
2842   ldrw(x_xstart, Address(x,  0));
2843   b(L_first_loop);
2844 
2845   bind(L_first_loop_exit);
2846 }
2847 
2848 /**
2849  * Multiply 128 bit by 128. Unrolled inner loop.
2850  *
2851  */
2852 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2853                                              Register carry, Register carry2,
2854                                              Register idx, Register jdx,
2855                                              Register yz_idx1, Register yz_idx2,
2856                                              Register tmp, Register tmp3, Register tmp4,
2857                                              Register tmp6, Register product_hi) {
2858 
2859   //   jlong carry, x[], y[], z[];
2860   //   int kdx = ystart+1;
2861   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2862   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2863   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2864   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2865   //     carry  = (jlong)(tmp4 >>> 64);
2866   //     z[kdx+idx+1] = (jlong)tmp3;
2867   //     z[kdx+idx] = (jlong)tmp4;
2868   //   }
2869   //   idx += 2;
2870   //   if (idx > 0) {
2871   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2872   //     z[kdx+idx] = (jlong)yz_idx1;
2873   //     carry  = (jlong)(yz_idx1 >>> 64);
2874   //   }
2875   //
2876 
2877   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2878 
2879   lsrw(jdx, idx, 2);
2880 
2881   bind(L_third_loop);
2882 
2883   subsw(jdx, jdx, 1);
2884   br(Assembler::MI, L_third_loop_exit);
2885   subw(idx, idx, 4);
2886 
2887   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2888 
2889   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2890 
2891   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2892 
2893   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2894   ror(yz_idx2, yz_idx2, 32);
2895 
2896   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2897 
2898   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2899   umulh(tmp4, product_hi, yz_idx1);
2900 
2901   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2902   ror(rscratch2, rscratch2, 32);
2903 
2904   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2905   umulh(carry2, product_hi, yz_idx2);
2906 
2907   // propagate sum of both multiplications into carry:tmp4:tmp3
2908   adds(tmp3, tmp3, carry);
2909   adc(tmp4, tmp4, zr);
2910   adds(tmp3, tmp3, rscratch1);
2911   adcs(tmp4, tmp4, tmp);
2912   adc(carry, carry2, zr);
2913   adds(tmp4, tmp4, rscratch2);
2914   adc(carry, carry, zr);
2915 
2916   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2917   ror(tmp4, tmp4, 32);
2918   stp(tmp4, tmp3, Address(tmp6, 0));
2919 
2920   b(L_third_loop);
2921   bind (L_third_loop_exit);
2922 
2923   andw (idx, idx, 0x3);
2924   cbz(idx, L_post_third_loop_done);
2925 
2926   Label L_check_1;
2927   subsw(idx, idx, 2);
2928   br(Assembler::MI, L_check_1);
2929 
2930   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2931   ldr(yz_idx1, Address(rscratch1, 0));
2932   ror(yz_idx1, yz_idx1, 32);
2933   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2934   umulh(tmp4, product_hi, yz_idx1);
2935   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2936   ldr(yz_idx2, Address(rscratch1, 0));
2937   ror(yz_idx2, yz_idx2, 32);
2938 
2939   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
2940 
2941   ror(tmp3, tmp3, 32);
2942   str(tmp3, Address(rscratch1, 0));
2943 
2944   bind (L_check_1);
2945 
2946   andw (idx, idx, 0x1);
2947   subsw(idx, idx, 1);
2948   br(Assembler::MI, L_post_third_loop_done);
2949   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2950   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
2951   umulh(carry2, tmp4, product_hi);
2952   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2953 
2954   add2_with_carry(carry2, tmp3, tmp4, carry);
2955 
2956   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2957   extr(carry, carry2, tmp3, 32);
2958 
2959   bind(L_post_third_loop_done);
2960 }
2961 
2962 /**
2963  * Code for BigInteger::multiplyToLen() instrinsic.
2964  *
2965  * r0: x
2966  * r1: xlen
2967  * r2: y
2968  * r3: ylen
2969  * r4:  z
2970  * r5: zlen
2971  * r10: tmp1
2972  * r11: tmp2
2973  * r12: tmp3
2974  * r13: tmp4
2975  * r14: tmp5
2976  * r15: tmp6
2977  * r16: tmp7
2978  *
2979  */
2980 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
2981                                      Register z, Register zlen,
2982                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
2983                                      Register tmp5, Register tmp6, Register product_hi) {
2984 
2985   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
2986 
2987   const Register idx = tmp1;
2988   const Register kdx = tmp2;
2989   const Register xstart = tmp3;
2990 
2991   const Register y_idx = tmp4;
2992   const Register carry = tmp5;
2993   const Register product  = xlen;
2994   const Register x_xstart = zlen;  // reuse register
2995 
2996   // First Loop.
2997   //
2998   //  final static long LONG_MASK = 0xffffffffL;
2999   //  int xstart = xlen - 1;
3000   //  int ystart = ylen - 1;
3001   //  long carry = 0;
3002   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3003   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
3004   //    z[kdx] = (int)product;
3005   //    carry = product >>> 32;
3006   //  }
3007   //  z[xstart] = (int)carry;
3008   //
3009 
3010   movw(idx, ylen);      // idx = ylen;
3011   movw(kdx, zlen);      // kdx = xlen+ylen;
3012   mov(carry, zr);       // carry = 0;
3013 
3014   Label L_done;
3015 
3016   movw(xstart, xlen);
3017   subsw(xstart, xstart, 1);
3018   br(Assembler::MI, L_done);
3019 
3020   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
3021 
3022   Label L_second_loop;
3023   cbzw(kdx, L_second_loop);
3024 
3025   Label L_carry;
3026   subw(kdx, kdx, 1);
3027   cbzw(kdx, L_carry);
3028 
3029   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3030   lsr(carry, carry, 32);
3031   subw(kdx, kdx, 1);
3032 
3033   bind(L_carry);
3034   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3035 
3036   // Second and third (nested) loops.
3037   //
3038   // for (int i = xstart-1; i >= 0; i--) { // Second loop
3039   //   carry = 0;
3040   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
3041   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
3042   //                    (z[k] & LONG_MASK) + carry;
3043   //     z[k] = (int)product;
3044   //     carry = product >>> 32;
3045   //   }
3046   //   z[i] = (int)carry;
3047   // }
3048   //
3049   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
3050 
3051   const Register jdx = tmp1;
3052 
3053   bind(L_second_loop);
3054   mov(carry, zr);                // carry = 0;
3055   movw(jdx, ylen);               // j = ystart+1
3056 
3057   subsw(xstart, xstart, 1);      // i = xstart-1;
3058   br(Assembler::MI, L_done);
3059 
3060   str(z, Address(pre(sp, -4 * wordSize)));
3061 
3062   Label L_last_x;
3063   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
3064   subsw(xstart, xstart, 1);       // i = xstart-1;
3065   br(Assembler::MI, L_last_x);
3066 
3067   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
3068   ldr(product_hi, Address(rscratch1));
3069   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
3070 
3071   Label L_third_loop_prologue;
3072   bind(L_third_loop_prologue);
3073 
3074   str(ylen, Address(sp, wordSize));
3075   stp(x, xstart, Address(sp, 2 * wordSize));
3076   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
3077                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
3078   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
3079   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
3080 
3081   addw(tmp3, xlen, 1);
3082   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3083   subsw(tmp3, tmp3, 1);
3084   br(Assembler::MI, L_done);
3085 
3086   lsr(carry, carry, 32);
3087   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3088   b(L_second_loop);
3089 
3090   // Next infrequent code is moved outside loops.
3091   bind(L_last_x);
3092   ldrw(product_hi, Address(x,  0));
3093   b(L_third_loop_prologue);
3094 
3095   bind(L_done);
3096 }
3097 
3098 // Code for BigInteger::mulAdd instrinsic
3099 // out     = r0
3100 // in      = r1
3101 // offset  = r2  (already out.length-offset)
3102 // len     = r3
3103 // k       = r4
3104 //
3105 // pseudo code from java implementation:
3106 // carry = 0;
3107 // offset = out.length-offset - 1;
3108 // for (int j=len-1; j >= 0; j--) {
3109 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
3110 //     out[offset--] = (int)product;
3111 //     carry = product >>> 32;
3112 // }
3113 // return (int)carry;
3114 void MacroAssembler::mul_add(Register out, Register in, Register offset,
3115       Register len, Register k) {
3116     Label LOOP, END;
3117     // pre-loop
3118     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
3119     csel(out, zr, out, Assembler::EQ);
3120     br(Assembler::EQ, END);
3121     add(in, in, len, LSL, 2); // in[j+1] address
3122     add(offset, out, offset, LSL, 2); // out[offset + 1] address
3123     mov(out, zr); // used to keep carry now
3124     BIND(LOOP);
3125     ldrw(rscratch1, Address(pre(in, -4)));
3126     madd(rscratch1, rscratch1, k, out);
3127     ldrw(rscratch2, Address(pre(offset, -4)));
3128     add(rscratch1, rscratch1, rscratch2);
3129     strw(rscratch1, Address(offset));
3130     lsr(out, rscratch1, 32);
3131     subs(len, len, 1);
3132     br(Assembler::NE, LOOP);
3133     BIND(END);
3134 }
3135 
3136 /**
3137  * Emits code to update CRC-32 with a byte value according to constants in table
3138  *
3139  * @param [in,out]crc   Register containing the crc.
3140  * @param [in]val       Register containing the byte to fold into the CRC.
3141  * @param [in]table     Register containing the table of crc constants.
3142  *
3143  * uint32_t crc;
3144  * val = crc_table[(val ^ crc) & 0xFF];
3145  * crc = val ^ (crc >> 8);
3146  *
3147  */
3148 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
3149   eor(val, val, crc);
3150   andr(val, val, 0xff);
3151   ldrw(val, Address(table, val, Address::lsl(2)));
3152   eor(crc, val, crc, Assembler::LSR, 8);
3153 }
3154 
3155 /**
3156  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
3157  *
3158  * @param [in,out]crc   Register containing the crc.
3159  * @param [in]v         Register containing the 32-bit to fold into the CRC.
3160  * @param [in]table0    Register containing table 0 of crc constants.
3161  * @param [in]table1    Register containing table 1 of crc constants.
3162  * @param [in]table2    Register containing table 2 of crc constants.
3163  * @param [in]table3    Register containing table 3 of crc constants.
3164  *
3165  * uint32_t crc;
3166  *   v = crc ^ v
3167  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
3168  *
3169  */
3170 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
3171         Register table0, Register table1, Register table2, Register table3,
3172         bool upper) {
3173   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
3174   uxtb(tmp, v);
3175   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
3176   ubfx(tmp, v, 8, 8);
3177   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
3178   eor(crc, crc, tmp);
3179   ubfx(tmp, v, 16, 8);
3180   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
3181   eor(crc, crc, tmp);
3182   ubfx(tmp, v, 24, 8);
3183   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
3184   eor(crc, crc, tmp);
3185 }
3186 
3187 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
3188         Register len, Register tmp0, Register tmp1, Register tmp2,
3189         Register tmp3) {
3190     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3191     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3192 
3193     mvnw(crc, crc);
3194 
3195     subs(len, len, 128);
3196     br(Assembler::GE, CRC_by64_pre);
3197   BIND(CRC_less64);
3198     adds(len, len, 128-32);
3199     br(Assembler::GE, CRC_by32_loop);
3200   BIND(CRC_less32);
3201     adds(len, len, 32-4);
3202     br(Assembler::GE, CRC_by4_loop);
3203     adds(len, len, 4);
3204     br(Assembler::GT, CRC_by1_loop);
3205     b(L_exit);
3206 
3207   BIND(CRC_by32_loop);
3208     ldp(tmp0, tmp1, Address(post(buf, 16)));
3209     subs(len, len, 32);
3210     crc32x(crc, crc, tmp0);
3211     ldr(tmp2, Address(post(buf, 8)));
3212     crc32x(crc, crc, tmp1);
3213     ldr(tmp3, Address(post(buf, 8)));
3214     crc32x(crc, crc, tmp2);
3215     crc32x(crc, crc, tmp3);
3216     br(Assembler::GE, CRC_by32_loop);
3217     cmn(len, 32);
3218     br(Assembler::NE, CRC_less32);
3219     b(L_exit);
3220 
3221   BIND(CRC_by4_loop);
3222     ldrw(tmp0, Address(post(buf, 4)));
3223     subs(len, len, 4);
3224     crc32w(crc, crc, tmp0);
3225     br(Assembler::GE, CRC_by4_loop);
3226     adds(len, len, 4);
3227     br(Assembler::LE, L_exit);
3228   BIND(CRC_by1_loop);
3229     ldrb(tmp0, Address(post(buf, 1)));
3230     subs(len, len, 1);
3231     crc32b(crc, crc, tmp0);
3232     br(Assembler::GT, CRC_by1_loop);
3233     b(L_exit);
3234 
3235   BIND(CRC_by64_pre);
3236     sub(buf, buf, 8);
3237     ldp(tmp0, tmp1, Address(buf, 8));
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 
3251     b(CRC_by64_loop);
3252 
3253     align(CodeEntryAlignment);
3254   BIND(CRC_by64_loop);
3255     subs(len, len, 64);
3256     crc32x(crc, crc, tmp2);
3257     ldr(tmp0, Address(buf, 8));
3258     crc32x(crc, crc, tmp3);
3259     ldr(tmp1, Address(buf, 16));
3260     crc32x(crc, crc, tmp0);
3261     ldr(tmp2, Address(buf, 24));
3262     crc32x(crc, crc, tmp1);
3263     ldr(tmp3, Address(buf, 32));
3264     crc32x(crc, crc, tmp2);
3265     ldr(tmp0, Address(buf, 40));
3266     crc32x(crc, crc, tmp3);
3267     ldr(tmp1, Address(buf, 48));
3268     crc32x(crc, crc, tmp0);
3269     ldr(tmp2, Address(buf, 56));
3270     crc32x(crc, crc, tmp1);
3271     ldr(tmp3, Address(pre(buf, 64)));
3272     br(Assembler::GE, CRC_by64_loop);
3273 
3274     // post-loop
3275     crc32x(crc, crc, tmp2);
3276     crc32x(crc, crc, tmp3);
3277 
3278     sub(len, len, 64);
3279     add(buf, buf, 8);
3280     cmn(len, 128);
3281     br(Assembler::NE, CRC_less64);
3282   BIND(L_exit);
3283     mvnw(crc, crc);
3284 }
3285 
3286 /**
3287  * @param crc   register containing existing CRC (32-bit)
3288  * @param buf   register pointing to input byte buffer (byte*)
3289  * @param len   register containing number of bytes
3290  * @param table register that will contain address of CRC table
3291  * @param tmp   scratch register
3292  */
3293 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
3294         Register table0, Register table1, Register table2, Register table3,
3295         Register tmp, Register tmp2, Register tmp3) {
3296   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
3297   unsigned long offset;
3298 
3299   if (UseCRC32) {
3300       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
3301       return;
3302   }
3303 
3304     mvnw(crc, crc);
3305 
3306     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
3307     if (offset) add(table0, table0, offset);
3308     add(table1, table0, 1*256*sizeof(juint));
3309     add(table2, table0, 2*256*sizeof(juint));
3310     add(table3, table0, 3*256*sizeof(juint));
3311 
3312   if (UseNeon) {
3313       cmp(len, 64);
3314       br(Assembler::LT, L_by16);
3315       eor(v16, T16B, v16, v16);
3316 
3317     Label L_fold;
3318 
3319       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
3320 
3321       ld1(v0, v1, T2D, post(buf, 32));
3322       ld1r(v4, T2D, post(tmp, 8));
3323       ld1r(v5, T2D, post(tmp, 8));
3324       ld1r(v6, T2D, post(tmp, 8));
3325       ld1r(v7, T2D, post(tmp, 8));
3326       mov(v16, T4S, 0, crc);
3327 
3328       eor(v0, T16B, v0, v16);
3329       sub(len, len, 64);
3330 
3331     BIND(L_fold);
3332       pmull(v22, T8H, v0, v5, T8B);
3333       pmull(v20, T8H, v0, v7, T8B);
3334       pmull(v23, T8H, v0, v4, T8B);
3335       pmull(v21, T8H, v0, v6, T8B);
3336 
3337       pmull2(v18, T8H, v0, v5, T16B);
3338       pmull2(v16, T8H, v0, v7, T16B);
3339       pmull2(v19, T8H, v0, v4, T16B);
3340       pmull2(v17, T8H, v0, v6, T16B);
3341 
3342       uzp1(v24, v20, v22, T8H);
3343       uzp2(v25, v20, v22, T8H);
3344       eor(v20, T16B, v24, v25);
3345 
3346       uzp1(v26, v16, v18, T8H);
3347       uzp2(v27, v16, v18, T8H);
3348       eor(v16, T16B, v26, v27);
3349 
3350       ushll2(v22, T4S, v20, T8H, 8);
3351       ushll(v20, T4S, v20, T4H, 8);
3352 
3353       ushll2(v18, T4S, v16, T8H, 8);
3354       ushll(v16, T4S, v16, T4H, 8);
3355 
3356       eor(v22, T16B, v23, v22);
3357       eor(v18, T16B, v19, v18);
3358       eor(v20, T16B, v21, v20);
3359       eor(v16, T16B, v17, v16);
3360 
3361       uzp1(v17, v16, v20, T2D);
3362       uzp2(v21, v16, v20, T2D);
3363       eor(v17, T16B, v17, v21);
3364 
3365       ushll2(v20, T2D, v17, T4S, 16);
3366       ushll(v16, T2D, v17, T2S, 16);
3367 
3368       eor(v20, T16B, v20, v22);
3369       eor(v16, T16B, v16, v18);
3370 
3371       uzp1(v17, v20, v16, T2D);
3372       uzp2(v21, v20, v16, T2D);
3373       eor(v28, T16B, v17, v21);
3374 
3375       pmull(v22, T8H, v1, v5, T8B);
3376       pmull(v20, T8H, v1, v7, T8B);
3377       pmull(v23, T8H, v1, v4, T8B);
3378       pmull(v21, T8H, v1, v6, T8B);
3379 
3380       pmull2(v18, T8H, v1, v5, T16B);
3381       pmull2(v16, T8H, v1, v7, T16B);
3382       pmull2(v19, T8H, v1, v4, T16B);
3383       pmull2(v17, T8H, v1, v6, T16B);
3384 
3385       ld1(v0, v1, T2D, post(buf, 32));
3386 
3387       uzp1(v24, v20, v22, T8H);
3388       uzp2(v25, v20, v22, T8H);
3389       eor(v20, T16B, v24, v25);
3390 
3391       uzp1(v26, v16, v18, T8H);
3392       uzp2(v27, v16, v18, T8H);
3393       eor(v16, T16B, v26, v27);
3394 
3395       ushll2(v22, T4S, v20, T8H, 8);
3396       ushll(v20, T4S, v20, T4H, 8);
3397 
3398       ushll2(v18, T4S, v16, T8H, 8);
3399       ushll(v16, T4S, v16, T4H, 8);
3400 
3401       eor(v22, T16B, v23, v22);
3402       eor(v18, T16B, v19, v18);
3403       eor(v20, T16B, v21, v20);
3404       eor(v16, T16B, v17, v16);
3405 
3406       uzp1(v17, v16, v20, T2D);
3407       uzp2(v21, v16, v20, T2D);
3408       eor(v16, T16B, v17, v21);
3409 
3410       ushll2(v20, T2D, v16, T4S, 16);
3411       ushll(v16, T2D, v16, T2S, 16);
3412 
3413       eor(v20, T16B, v22, v20);
3414       eor(v16, T16B, v16, v18);
3415 
3416       uzp1(v17, v20, v16, T2D);
3417       uzp2(v21, v20, v16, T2D);
3418       eor(v20, T16B, v17, v21);
3419 
3420       shl(v16, T2D, v28, 1);
3421       shl(v17, T2D, v20, 1);
3422 
3423       eor(v0, T16B, v0, v16);
3424       eor(v1, T16B, v1, v17);
3425 
3426       subs(len, len, 32);
3427       br(Assembler::GE, L_fold);
3428 
3429       mov(crc, 0);
3430       mov(tmp, v0, T1D, 0);
3431       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3432       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3433       mov(tmp, v0, T1D, 1);
3434       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3435       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3436       mov(tmp, v1, T1D, 0);
3437       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3438       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3439       mov(tmp, v1, T1D, 1);
3440       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3441       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3442 
3443       add(len, len, 32);
3444   }
3445 
3446   BIND(L_by16);
3447     subs(len, len, 16);
3448     br(Assembler::GE, L_by16_loop);
3449     adds(len, len, 16-4);
3450     br(Assembler::GE, L_by4_loop);
3451     adds(len, len, 4);
3452     br(Assembler::GT, L_by1_loop);
3453     b(L_exit);
3454 
3455   BIND(L_by4_loop);
3456     ldrw(tmp, Address(post(buf, 4)));
3457     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3458     subs(len, len, 4);
3459     br(Assembler::GE, L_by4_loop);
3460     adds(len, len, 4);
3461     br(Assembler::LE, L_exit);
3462   BIND(L_by1_loop);
3463     subs(len, len, 1);
3464     ldrb(tmp, Address(post(buf, 1)));
3465     update_byte_crc32(crc, tmp, table0);
3466     br(Assembler::GT, L_by1_loop);
3467     b(L_exit);
3468 
3469     align(CodeEntryAlignment);
3470   BIND(L_by16_loop);
3471     subs(len, len, 16);
3472     ldp(tmp, tmp3, Address(post(buf, 16)));
3473     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3474     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3475     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
3476     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
3477     br(Assembler::GE, L_by16_loop);
3478     adds(len, len, 16-4);
3479     br(Assembler::GE, L_by4_loop);
3480     adds(len, len, 4);
3481     br(Assembler::GT, L_by1_loop);
3482   BIND(L_exit);
3483     mvnw(crc, crc);
3484 }
3485 
3486 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
3487         Register len, Register tmp0, Register tmp1, Register tmp2,
3488         Register tmp3) {
3489     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3490     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3491 
3492     subs(len, len, 128);
3493     br(Assembler::GE, CRC_by64_pre);
3494   BIND(CRC_less64);
3495     adds(len, len, 128-32);
3496     br(Assembler::GE, CRC_by32_loop);
3497   BIND(CRC_less32);
3498     adds(len, len, 32-4);
3499     br(Assembler::GE, CRC_by4_loop);
3500     adds(len, len, 4);
3501     br(Assembler::GT, CRC_by1_loop);
3502     b(L_exit);
3503 
3504   BIND(CRC_by32_loop);
3505     ldp(tmp0, tmp1, Address(post(buf, 16)));
3506     subs(len, len, 32);
3507     crc32cx(crc, crc, tmp0);
3508     ldr(tmp2, Address(post(buf, 8)));
3509     crc32cx(crc, crc, tmp1);
3510     ldr(tmp3, Address(post(buf, 8)));
3511     crc32cx(crc, crc, tmp2);
3512     crc32cx(crc, crc, tmp3);
3513     br(Assembler::GE, CRC_by32_loop);
3514     cmn(len, 32);
3515     br(Assembler::NE, CRC_less32);
3516     b(L_exit);
3517 
3518   BIND(CRC_by4_loop);
3519     ldrw(tmp0, Address(post(buf, 4)));
3520     subs(len, len, 4);
3521     crc32cw(crc, crc, tmp0);
3522     br(Assembler::GE, CRC_by4_loop);
3523     adds(len, len, 4);
3524     br(Assembler::LE, L_exit);
3525   BIND(CRC_by1_loop);
3526     ldrb(tmp0, Address(post(buf, 1)));
3527     subs(len, len, 1);
3528     crc32cb(crc, crc, tmp0);
3529     br(Assembler::GT, CRC_by1_loop);
3530     b(L_exit);
3531 
3532   BIND(CRC_by64_pre);
3533     sub(buf, buf, 8);
3534     ldp(tmp0, tmp1, Address(buf, 8));
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 
3548     b(CRC_by64_loop);
3549 
3550     align(CodeEntryAlignment);
3551   BIND(CRC_by64_loop);
3552     subs(len, len, 64);
3553     crc32cx(crc, crc, tmp2);
3554     ldr(tmp0, Address(buf, 8));
3555     crc32cx(crc, crc, tmp3);
3556     ldr(tmp1, Address(buf, 16));
3557     crc32cx(crc, crc, tmp0);
3558     ldr(tmp2, Address(buf, 24));
3559     crc32cx(crc, crc, tmp1);
3560     ldr(tmp3, Address(buf, 32));
3561     crc32cx(crc, crc, tmp2);
3562     ldr(tmp0, Address(buf, 40));
3563     crc32cx(crc, crc, tmp3);
3564     ldr(tmp1, Address(buf, 48));
3565     crc32cx(crc, crc, tmp0);
3566     ldr(tmp2, Address(buf, 56));
3567     crc32cx(crc, crc, tmp1);
3568     ldr(tmp3, Address(pre(buf, 64)));
3569     br(Assembler::GE, CRC_by64_loop);
3570 
3571     // post-loop
3572     crc32cx(crc, crc, tmp2);
3573     crc32cx(crc, crc, tmp3);
3574 
3575     sub(len, len, 64);
3576     add(buf, buf, 8);
3577     cmn(len, 128);
3578     br(Assembler::NE, CRC_less64);
3579   BIND(L_exit);
3580 }
3581 
3582 /**
3583  * @param crc   register containing existing CRC (32-bit)
3584  * @param buf   register pointing to input byte buffer (byte*)
3585  * @param len   register containing number of bytes
3586  * @param table register that will contain address of CRC table
3587  * @param tmp   scratch register
3588  */
3589 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
3590         Register table0, Register table1, Register table2, Register table3,
3591         Register tmp, Register tmp2, Register tmp3) {
3592   kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
3593 }
3594 
3595 
3596 SkipIfEqual::SkipIfEqual(
3597     MacroAssembler* masm, const bool* flag_addr, bool value) {
3598   _masm = masm;
3599   unsigned long offset;
3600   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3601   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3602   _masm->cbzw(rscratch1, _label);
3603 }
3604 
3605 SkipIfEqual::~SkipIfEqual() {
3606   _masm->bind(_label);
3607 }
3608 
3609 void MacroAssembler::addptr(const Address &dst, int32_t src) {
3610   Address adr;
3611   switch(dst.getMode()) {
3612   case Address::base_plus_offset:
3613     // This is the expected mode, although we allow all the other
3614     // forms below.
3615     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
3616     break;
3617   default:
3618     lea(rscratch2, dst);
3619     adr = Address(rscratch2);
3620     break;
3621   }
3622   ldr(rscratch1, adr);
3623   add(rscratch1, rscratch1, src);
3624   str(rscratch1, adr);
3625 }
3626 
3627 void MacroAssembler::cmpptr(Register src1, Address src2) {
3628   unsigned long offset;
3629   adrp(rscratch1, src2, offset);
3630   ldr(rscratch1, Address(rscratch1, offset));
3631   cmp(src1, rscratch1);
3632 }
3633 
3634 void MacroAssembler::load_klass(Register dst, Register src) {
3635   if (UseCompressedClassPointers) {
3636     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3637     decode_klass_not_null(dst);
3638   } else {
3639     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3640   }
3641 }
3642 
3643 // ((OopHandle)result).resolve();
3644 void MacroAssembler::resolve_oop_handle(Register result) {
3645   // OopHandle::resolve is an indirection.
3646   ldr(result, Address(result, 0));
3647 }
3648 
3649 void MacroAssembler::load_mirror(Register dst, Register method) {
3650   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
3651   ldr(dst, Address(rmethod, Method::const_offset()));
3652   ldr(dst, Address(dst, ConstMethod::constants_offset()));
3653   ldr(dst, Address(dst, ConstantPool::pool_holder_offset_in_bytes()));
3654   ldr(dst, Address(dst, mirror_offset));
3655   resolve_oop_handle(dst);
3656 }
3657 
3658 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3659   if (UseCompressedClassPointers) {
3660     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3661     if (Universe::narrow_klass_base() == NULL) {
3662       cmp(trial_klass, tmp, LSL, Universe::narrow_klass_shift());
3663       return;
3664     } else if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3665                && Universe::narrow_klass_shift() == 0) {
3666       // Only the bottom 32 bits matter
3667       cmpw(trial_klass, tmp);
3668       return;
3669     }
3670     decode_klass_not_null(tmp);
3671   } else {
3672     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3673   }
3674   cmp(trial_klass, tmp);
3675 }
3676 
3677 void MacroAssembler::load_prototype_header(Register dst, Register src) {
3678   load_klass(dst, src);
3679   ldr(dst, Address(dst, Klass::prototype_header_offset()));
3680 }
3681 
3682 void MacroAssembler::store_klass(Register dst, Register src) {
3683   // FIXME: Should this be a store release?  concurrent gcs assumes
3684   // klass length is valid if klass field is not null.
3685   if (UseCompressedClassPointers) {
3686     encode_klass_not_null(src);
3687     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3688   } else {
3689     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3690   }
3691 }
3692 
3693 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3694   if (UseCompressedClassPointers) {
3695     // Store to klass gap in destination
3696     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3697   }
3698 }
3699 
3700 // Algorithm must match CompressedOops::encode.
3701 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3702 #ifdef ASSERT
3703   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3704 #endif
3705   verify_oop(s, "broken oop in encode_heap_oop");
3706   if (Universe::narrow_oop_base() == NULL) {
3707     if (Universe::narrow_oop_shift() != 0) {
3708       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3709       lsr(d, s, LogMinObjAlignmentInBytes);
3710     } else {
3711       mov(d, s);
3712     }
3713   } else {
3714     subs(d, s, rheapbase);
3715     csel(d, d, zr, Assembler::HS);
3716     lsr(d, d, LogMinObjAlignmentInBytes);
3717 
3718     /*  Old algorithm: is this any worse?
3719     Label nonnull;
3720     cbnz(r, nonnull);
3721     sub(r, r, rheapbase);
3722     bind(nonnull);
3723     lsr(r, r, LogMinObjAlignmentInBytes);
3724     */
3725   }
3726 }
3727 
3728 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3729 #ifdef ASSERT
3730   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3731   if (CheckCompressedOops) {
3732     Label ok;
3733     cbnz(r, ok);
3734     stop("null oop passed to encode_heap_oop_not_null");
3735     bind(ok);
3736   }
3737 #endif
3738   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3739   if (Universe::narrow_oop_base() != NULL) {
3740     sub(r, r, rheapbase);
3741   }
3742   if (Universe::narrow_oop_shift() != 0) {
3743     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3744     lsr(r, r, LogMinObjAlignmentInBytes);
3745   }
3746 }
3747 
3748 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3749 #ifdef ASSERT
3750   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3751   if (CheckCompressedOops) {
3752     Label ok;
3753     cbnz(src, ok);
3754     stop("null oop passed to encode_heap_oop_not_null2");
3755     bind(ok);
3756   }
3757 #endif
3758   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3759 
3760   Register data = src;
3761   if (Universe::narrow_oop_base() != NULL) {
3762     sub(dst, src, rheapbase);
3763     data = dst;
3764   }
3765   if (Universe::narrow_oop_shift() != 0) {
3766     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3767     lsr(dst, data, LogMinObjAlignmentInBytes);
3768     data = dst;
3769   }
3770   if (data == src)
3771     mov(dst, src);
3772 }
3773 
3774 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3775 #ifdef ASSERT
3776   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3777 #endif
3778   if (Universe::narrow_oop_base() == NULL) {
3779     if (Universe::narrow_oop_shift() != 0 || d != s) {
3780       lsl(d, s, Universe::narrow_oop_shift());
3781     }
3782   } else {
3783     Label done;
3784     if (d != s)
3785       mov(d, s);
3786     cbz(s, done);
3787     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3788     bind(done);
3789   }
3790   verify_oop(d, "broken oop in decode_heap_oop");
3791 }
3792 
3793 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3794   assert (UseCompressedOops, "should only be used for compressed headers");
3795   assert (Universe::heap() != NULL, "java heap should be initialized");
3796   // Cannot assert, unverified entry point counts instructions (see .ad file)
3797   // vtableStubs also counts instructions in pd_code_size_limit.
3798   // Also do not verify_oop as this is called by verify_oop.
3799   if (Universe::narrow_oop_shift() != 0) {
3800     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3801     if (Universe::narrow_oop_base() != NULL) {
3802       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3803     } else {
3804       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3805     }
3806   } else {
3807     assert (Universe::narrow_oop_base() == NULL, "sanity");
3808   }
3809 }
3810 
3811 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3812   assert (UseCompressedOops, "should only be used for compressed headers");
3813   assert (Universe::heap() != NULL, "java heap should be initialized");
3814   // Cannot assert, unverified entry point counts instructions (see .ad file)
3815   // vtableStubs also counts instructions in pd_code_size_limit.
3816   // Also do not verify_oop as this is called by verify_oop.
3817   if (Universe::narrow_oop_shift() != 0) {
3818     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3819     if (Universe::narrow_oop_base() != NULL) {
3820       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3821     } else {
3822       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3823     }
3824   } else {
3825     assert (Universe::narrow_oop_base() == NULL, "sanity");
3826     if (dst != src) {
3827       mov(dst, src);
3828     }
3829   }
3830 }
3831 
3832 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3833   if (Universe::narrow_klass_base() == NULL) {
3834     if (Universe::narrow_klass_shift() != 0) {
3835       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3836       lsr(dst, src, LogKlassAlignmentInBytes);
3837     } else {
3838       if (dst != src) mov(dst, src);
3839     }
3840     return;
3841   }
3842 
3843   if (use_XOR_for_compressed_class_base) {
3844     if (Universe::narrow_klass_shift() != 0) {
3845       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3846       lsr(dst, dst, LogKlassAlignmentInBytes);
3847     } else {
3848       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3849     }
3850     return;
3851   }
3852 
3853   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3854       && Universe::narrow_klass_shift() == 0) {
3855     movw(dst, src);
3856     return;
3857   }
3858 
3859 #ifdef ASSERT
3860   verify_heapbase("MacroAssembler::encode_klass_not_null2: heap base corrupted?");
3861 #endif
3862 
3863   Register rbase = dst;
3864   if (dst == src) rbase = rheapbase;
3865   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3866   sub(dst, src, rbase);
3867   if (Universe::narrow_klass_shift() != 0) {
3868     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3869     lsr(dst, dst, LogKlassAlignmentInBytes);
3870   }
3871   if (dst == src) reinit_heapbase();
3872 }
3873 
3874 void MacroAssembler::encode_klass_not_null(Register r) {
3875   encode_klass_not_null(r, r);
3876 }
3877 
3878 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3879   Register rbase = dst;
3880   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3881 
3882   if (Universe::narrow_klass_base() == NULL) {
3883     if (Universe::narrow_klass_shift() != 0) {
3884       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3885       lsl(dst, src, LogKlassAlignmentInBytes);
3886     } else {
3887       if (dst != src) mov(dst, src);
3888     }
3889     return;
3890   }
3891 
3892   if (use_XOR_for_compressed_class_base) {
3893     if (Universe::narrow_klass_shift() != 0) {
3894       lsl(dst, src, LogKlassAlignmentInBytes);
3895       eor(dst, dst, (uint64_t)Universe::narrow_klass_base());
3896     } else {
3897       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3898     }
3899     return;
3900   }
3901 
3902   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3903       && Universe::narrow_klass_shift() == 0) {
3904     if (dst != src)
3905       movw(dst, src);
3906     movk(dst, (uint64_t)Universe::narrow_klass_base() >> 32, 32);
3907     return;
3908   }
3909 
3910   // Cannot assert, unverified entry point counts instructions (see .ad file)
3911   // vtableStubs also counts instructions in pd_code_size_limit.
3912   // Also do not verify_oop as this is called by verify_oop.
3913   if (dst == src) rbase = rheapbase;
3914   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3915   if (Universe::narrow_klass_shift() != 0) {
3916     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3917     add(dst, rbase, src, Assembler::LSL, LogKlassAlignmentInBytes);
3918   } else {
3919     add(dst, rbase, src);
3920   }
3921   if (dst == src) reinit_heapbase();
3922 }
3923 
3924 void  MacroAssembler::decode_klass_not_null(Register r) {
3925   decode_klass_not_null(r, r);
3926 }
3927 
3928 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
3929 #ifdef ASSERT
3930   {
3931     ThreadInVMfromUnknown tiv;
3932     assert (UseCompressedOops, "should only be used for compressed oops");
3933     assert (Universe::heap() != NULL, "java heap should be initialized");
3934     assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3935     assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3936   }
3937 #endif
3938   int oop_index = oop_recorder()->find_index(obj);
3939   InstructionMark im(this);
3940   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3941   code_section()->relocate(inst_mark(), rspec);
3942   movz(dst, 0xDEAD, 16);
3943   movk(dst, 0xBEEF);
3944 }
3945 
3946 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
3947   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3948   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3949   int index = oop_recorder()->find_index(k);
3950   assert(! Universe::heap()->is_in_reserved(k), "should not be an oop");
3951 
3952   InstructionMark im(this);
3953   RelocationHolder rspec = metadata_Relocation::spec(index);
3954   code_section()->relocate(inst_mark(), rspec);
3955   narrowKlass nk = Klass::encode_klass(k);
3956   movz(dst, (nk >> 16), 16);
3957   movk(dst, nk & 0xffff);
3958 }
3959 
3960 void MacroAssembler::load_heap_oop(Register dst, Address src)
3961 {
3962   if (UseCompressedOops) {
3963     ldrw(dst, src);
3964     decode_heap_oop(dst);
3965   } else {
3966     ldr(dst, src);
3967   }
3968 }
3969 
3970 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src)
3971 {
3972   if (UseCompressedOops) {
3973     ldrw(dst, src);
3974     decode_heap_oop_not_null(dst);
3975   } else {
3976     ldr(dst, src);
3977   }
3978 }
3979 
3980 void MacroAssembler::store_heap_oop(Address dst, Register src) {
3981   if (UseCompressedOops) {
3982     assert(!dst.uses(src), "not enough registers");
3983     encode_heap_oop(src);
3984     strw(src, dst);
3985   } else
3986     str(src, dst);
3987 }
3988 
3989 // Used for storing NULLs.
3990 void MacroAssembler::store_heap_oop_null(Address dst) {
3991   if (UseCompressedOops) {
3992     strw(zr, dst);
3993   } else
3994     str(zr, dst);
3995 }
3996 
3997 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
3998   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
3999   int index = oop_recorder()->allocate_metadata_index(obj);
4000   RelocationHolder rspec = metadata_Relocation::spec(index);
4001   return Address((address)obj, rspec);
4002 }
4003 
4004 // Move an oop into a register.  immediate is true if we want
4005 // immediate instrcutions, i.e. we are not going to patch this
4006 // instruction while the code is being executed by another thread.  In
4007 // that case we can use move immediates rather than the constant pool.
4008 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
4009   int oop_index;
4010   if (obj == NULL) {
4011     oop_index = oop_recorder()->allocate_oop_index(obj);
4012   } else {
4013 #ifdef ASSERT
4014     {
4015       ThreadInVMfromUnknown tiv;
4016       assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
4017     }
4018 #endif
4019     oop_index = oop_recorder()->find_index(obj);
4020   }
4021   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4022   if (! immediate) {
4023     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
4024     ldr_constant(dst, Address(dummy, rspec));
4025   } else
4026     mov(dst, Address((address)obj, rspec));
4027 }
4028 
4029 // Move a metadata address into a register.
4030 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
4031   int oop_index;
4032   if (obj == NULL) {
4033     oop_index = oop_recorder()->allocate_metadata_index(obj);
4034   } else {
4035     oop_index = oop_recorder()->find_index(obj);
4036   }
4037   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
4038   mov(dst, Address((address)obj, rspec));
4039 }
4040 
4041 Address MacroAssembler::constant_oop_address(jobject obj) {
4042 #ifdef ASSERT
4043   {
4044     ThreadInVMfromUnknown tiv;
4045     assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
4046     assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
4047   }
4048 #endif
4049   int oop_index = oop_recorder()->find_index(obj);
4050   return Address((address)obj, oop_Relocation::spec(oop_index));
4051 }
4052 
4053 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4054 void MacroAssembler::tlab_allocate(Register obj,
4055                                    Register var_size_in_bytes,
4056                                    int con_size_in_bytes,
4057                                    Register t1,
4058                                    Register t2,
4059                                    Label& slow_case) {
4060   assert_different_registers(obj, t2);
4061   assert_different_registers(obj, var_size_in_bytes);
4062   Register end = t2;
4063 
4064   // verify_tlab();
4065 
4066   ldr(obj, Address(rthread, JavaThread::tlab_top_offset()));
4067   if (var_size_in_bytes == noreg) {
4068     lea(end, Address(obj, con_size_in_bytes));
4069   } else {
4070     lea(end, Address(obj, var_size_in_bytes));
4071   }
4072   ldr(rscratch1, Address(rthread, JavaThread::tlab_end_offset()));
4073   cmp(end, rscratch1);
4074   br(Assembler::HI, slow_case);
4075 
4076   // update the tlab top pointer
4077   str(end, Address(rthread, JavaThread::tlab_top_offset()));
4078 
4079   // recover var_size_in_bytes if necessary
4080   if (var_size_in_bytes == end) {
4081     sub(var_size_in_bytes, var_size_in_bytes, obj);
4082   }
4083   // verify_tlab();
4084 }
4085 
4086 // Zero words; len is in bytes
4087 // Destroys all registers except addr
4088 // len must be a nonzero multiple of wordSize
4089 void MacroAssembler::zero_memory(Register addr, Register len, Register t1) {
4090   assert_different_registers(addr, len, t1, rscratch1, rscratch2);
4091 
4092 #ifdef ASSERT
4093   { Label L;
4094     tst(len, BytesPerWord - 1);
4095     br(Assembler::EQ, L);
4096     stop("len is not a multiple of BytesPerWord");
4097     bind(L);
4098   }
4099 #endif
4100 
4101 #ifndef PRODUCT
4102   block_comment("zero memory");
4103 #endif
4104 
4105   Label loop;
4106   Label entry;
4107 
4108 //  Algorithm:
4109 //
4110 //    scratch1 = cnt & 7;
4111 //    cnt -= scratch1;
4112 //    p += scratch1;
4113 //    switch (scratch1) {
4114 //      do {
4115 //        cnt -= 8;
4116 //          p[-8] = 0;
4117 //        case 7:
4118 //          p[-7] = 0;
4119 //        case 6:
4120 //          p[-6] = 0;
4121 //          // ...
4122 //        case 1:
4123 //          p[-1] = 0;
4124 //        case 0:
4125 //          p += 8;
4126 //      } while (cnt);
4127 //    }
4128 
4129   const int unroll = 8; // Number of str(zr) instructions we'll unroll
4130 
4131   lsr(len, len, LogBytesPerWord);
4132   andr(rscratch1, len, unroll - 1);  // tmp1 = cnt % unroll
4133   sub(len, len, rscratch1);      // cnt -= unroll
4134   // t1 always points to the end of the region we're about to zero
4135   add(t1, addr, rscratch1, Assembler::LSL, LogBytesPerWord);
4136   adr(rscratch2, entry);
4137   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 2);
4138   br(rscratch2);
4139   bind(loop);
4140   sub(len, len, unroll);
4141   for (int i = -unroll; i < 0; i++)
4142     Assembler::str(zr, Address(t1, i * wordSize));
4143   bind(entry);
4144   add(t1, t1, unroll * wordSize);
4145   cbnz(len, loop);
4146 }
4147 
4148 // Defines obj, preserves var_size_in_bytes
4149 void MacroAssembler::eden_allocate(Register obj,
4150                                    Register var_size_in_bytes,
4151                                    int con_size_in_bytes,
4152                                    Register t1,
4153                                    Label& slow_case) {
4154   assert_different_registers(obj, var_size_in_bytes, t1);
4155   if (!Universe::heap()->supports_inline_contig_alloc()) {
4156     b(slow_case);
4157   } else {
4158     Register end = t1;
4159     Register heap_end = rscratch2;
4160     Label retry;
4161     bind(retry);
4162     {
4163       unsigned long offset;
4164       adrp(rscratch1, ExternalAddress((address) Universe::heap()->end_addr()), offset);
4165       ldr(heap_end, Address(rscratch1, offset));
4166     }
4167 
4168     ExternalAddress heap_top((address) Universe::heap()->top_addr());
4169 
4170     // Get the current top of the heap
4171     {
4172       unsigned long offset;
4173       adrp(rscratch1, heap_top, offset);
4174       // Use add() here after ARDP, rather than lea().
4175       // lea() does not generate anything if its offset is zero.
4176       // However, relocs expect to find either an ADD or a load/store
4177       // insn after an ADRP.  add() always generates an ADD insn, even
4178       // for add(Rn, Rn, 0).
4179       add(rscratch1, rscratch1, offset);
4180       ldaxr(obj, rscratch1);
4181     }
4182 
4183     // Adjust it my the size of our new object
4184     if (var_size_in_bytes == noreg) {
4185       lea(end, Address(obj, con_size_in_bytes));
4186     } else {
4187       lea(end, Address(obj, var_size_in_bytes));
4188     }
4189 
4190     // if end < obj then we wrapped around high memory
4191     cmp(end, obj);
4192     br(Assembler::LO, slow_case);
4193 
4194     cmp(end, heap_end);
4195     br(Assembler::HI, slow_case);
4196 
4197     // If heap_top hasn't been changed by some other thread, update it.
4198     stlxr(rscratch2, end, rscratch1);
4199     cbnzw(rscratch2, retry);
4200   }
4201 }
4202 
4203 void MacroAssembler::verify_tlab() {
4204 #ifdef ASSERT
4205   if (UseTLAB && VerifyOops) {
4206     Label next, ok;
4207 
4208     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4209 
4210     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4211     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4212     cmp(rscratch2, rscratch1);
4213     br(Assembler::HS, next);
4214     STOP("assert(top >= start)");
4215     should_not_reach_here();
4216 
4217     bind(next);
4218     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4219     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4220     cmp(rscratch2, rscratch1);
4221     br(Assembler::HS, ok);
4222     STOP("assert(top <= end)");
4223     should_not_reach_here();
4224 
4225     bind(ok);
4226     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4227   }
4228 #endif
4229 }
4230 
4231 // Writes to stack successive pages until offset reached to check for
4232 // stack overflow + shadow pages.  This clobbers tmp.
4233 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4234   assert_different_registers(tmp, size, rscratch1);
4235   mov(tmp, sp);
4236   // Bang stack for total size given plus shadow page size.
4237   // Bang one page at a time because large size can bang beyond yellow and
4238   // red zones.
4239   Label loop;
4240   mov(rscratch1, os::vm_page_size());
4241   bind(loop);
4242   lea(tmp, Address(tmp, -os::vm_page_size()));
4243   subsw(size, size, rscratch1);
4244   str(size, Address(tmp));
4245   br(Assembler::GT, loop);
4246 
4247   // Bang down shadow pages too.
4248   // At this point, (tmp-0) is the last address touched, so don't
4249   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4250   // was post-decremented.)  Skip this address by starting at i=1, and
4251   // touch a few more pages below.  N.B.  It is important to touch all
4252   // the way down to and including i=StackShadowPages.
4253   for (int i = 0; i < (int)(JavaThread::stack_shadow_zone_size() / os::vm_page_size()) - 1; i++) {
4254     // this could be any sized move but this is can be a debugging crumb
4255     // so the bigger the better.
4256     lea(tmp, Address(tmp, -os::vm_page_size()));
4257     str(size, Address(tmp));
4258   }
4259 }
4260 
4261 
4262 // Move the address of the polling page into dest.
4263 void MacroAssembler::get_polling_page(Register dest, address page, relocInfo::relocType rtype) {
4264   if (SafepointMechanism::uses_thread_local_poll()) {
4265     ldr(dest, Address(rthread, Thread::polling_page_offset()));
4266   } else {
4267     unsigned long off;
4268     adrp(dest, Address(page, rtype), off);
4269     assert(off == 0, "polling page must be page aligned");
4270   }
4271 }
4272 
4273 // Move the address of the polling page into r, then read the polling
4274 // page.
4275 address MacroAssembler::read_polling_page(Register r, address page, relocInfo::relocType rtype) {
4276   get_polling_page(r, page, rtype);
4277   return read_polling_page(r, rtype);
4278 }
4279 
4280 // Read the polling page.  The address of the polling page must
4281 // already be in r.
4282 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4283   InstructionMark im(this);
4284   code_section()->relocate(inst_mark(), rtype);
4285   ldrw(zr, Address(r, 0));
4286   return inst_mark();
4287 }
4288 
4289 void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byte_offset) {
4290   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4291   unsigned long low_page = (unsigned long)CodeCache::low_bound() >> 12;
4292   unsigned long high_page = (unsigned long)(CodeCache::high_bound()-1) >> 12;
4293   unsigned long dest_page = (unsigned long)dest.target() >> 12;
4294   long offset_low = dest_page - low_page;
4295   long offset_high = dest_page - high_page;
4296 
4297   assert(is_valid_AArch64_address(dest.target()), "bad address");
4298   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4299 
4300   InstructionMark im(this);
4301   code_section()->relocate(inst_mark(), dest.rspec());
4302   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4303   // the code cache so that if it is relocated we know it will still reach
4304   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4305     _adrp(reg1, dest.target());
4306   } else {
4307     unsigned long target = (unsigned long)dest.target();
4308     unsigned long adrp_target
4309       = (target & 0xffffffffUL) | ((unsigned long)pc() & 0xffff00000000UL);
4310 
4311     _adrp(reg1, (address)adrp_target);
4312     movk(reg1, target >> 32, 32);
4313   }
4314   byte_offset = (unsigned long)dest.target() & 0xfff;
4315 }
4316 
4317 void MacroAssembler::load_byte_map_base(Register reg) {
4318   jbyte *byte_map_base =
4319     ((CardTableBarrierSet*)(Universe::heap()->barrier_set()))->card_table()->byte_map_base();
4320 
4321   if (is_valid_AArch64_address((address)byte_map_base)) {
4322     // Strictly speaking the byte_map_base isn't an address at all,
4323     // and it might even be negative.
4324     unsigned long offset;
4325     adrp(reg, ExternalAddress((address)byte_map_base), offset);
4326     // We expect offset to be zero with most collectors.
4327     if (offset != 0) {
4328       add(reg, reg, offset);
4329     }
4330   } else {
4331     mov(reg, (uint64_t)byte_map_base);
4332   }
4333 }
4334 
4335 void MacroAssembler::build_frame(int framesize) {
4336   assert(framesize > 0, "framesize must be > 0");
4337   if (framesize < ((1 << 9) + 2 * wordSize)) {
4338     sub(sp, sp, framesize);
4339     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4340     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
4341   } else {
4342     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4343     if (PreserveFramePointer) mov(rfp, sp);
4344     if (framesize < ((1 << 12) + 2 * wordSize))
4345       sub(sp, sp, framesize - 2 * wordSize);
4346     else {
4347       mov(rscratch1, framesize - 2 * wordSize);
4348       sub(sp, sp, rscratch1);
4349     }
4350   }
4351 }
4352 
4353 void MacroAssembler::remove_frame(int framesize) {
4354   assert(framesize > 0, "framesize must be > 0");
4355   if (framesize < ((1 << 9) + 2 * wordSize)) {
4356     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4357     add(sp, sp, framesize);
4358   } else {
4359     if (framesize < ((1 << 12) + 2 * wordSize))
4360       add(sp, sp, framesize - 2 * wordSize);
4361     else {
4362       mov(rscratch1, framesize - 2 * wordSize);
4363       add(sp, sp, rscratch1);
4364     }
4365     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4366   }
4367 }
4368 
4369 typedef void (MacroAssembler::* chr_insn)(Register Rt, const Address &adr);
4370 
4371 // Search for str1 in str2 and return index or -1
4372 void MacroAssembler::string_indexof(Register str2, Register str1,
4373                                     Register cnt2, Register cnt1,
4374                                     Register tmp1, Register tmp2,
4375                                     Register tmp3, Register tmp4,
4376                                     int icnt1, Register result, int ae) {
4377   Label BM, LINEARSEARCH, DONE, NOMATCH, MATCH;
4378 
4379   Register ch1 = rscratch1;
4380   Register ch2 = rscratch2;
4381   Register cnt1tmp = tmp1;
4382   Register cnt2tmp = tmp2;
4383   Register cnt1_neg = cnt1;
4384   Register cnt2_neg = cnt2;
4385   Register result_tmp = tmp4;
4386 
4387   bool isL = ae == StrIntrinsicNode::LL;
4388 
4389   bool str1_isL = ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL;
4390   bool str2_isL = ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::LU;
4391   int str1_chr_shift = str1_isL ? 0:1;
4392   int str2_chr_shift = str2_isL ? 0:1;
4393   int str1_chr_size = str1_isL ? 1:2;
4394   int str2_chr_size = str2_isL ? 1:2;
4395   chr_insn str1_load_1chr = str1_isL ? (chr_insn)&MacroAssembler::ldrb :
4396                                       (chr_insn)&MacroAssembler::ldrh;
4397   chr_insn str2_load_1chr = str2_isL ? (chr_insn)&MacroAssembler::ldrb :
4398                                       (chr_insn)&MacroAssembler::ldrh;
4399   chr_insn load_2chr = isL ? (chr_insn)&MacroAssembler::ldrh : (chr_insn)&MacroAssembler::ldrw;
4400   chr_insn load_4chr = isL ? (chr_insn)&MacroAssembler::ldrw : (chr_insn)&MacroAssembler::ldr;
4401 
4402   // Note, inline_string_indexOf() generates checks:
4403   // if (substr.count > string.count) return -1;
4404   // if (substr.count == 0) return 0;
4405 
4406 // We have two strings, a source string in str2, cnt2 and a pattern string
4407 // in str1, cnt1. Find the 1st occurence of pattern in source or return -1.
4408 
4409 // For larger pattern and source we use a simplified Boyer Moore algorithm.
4410 // With a small pattern and source we use linear scan.
4411 
4412   if (icnt1 == -1) {
4413     cmp(cnt1, 256);             // Use Linear Scan if cnt1 < 8 || cnt1 >= 256
4414     ccmp(cnt1, 8, 0b0000, LO);  // Can't handle skip >= 256 because we use
4415     br(LO, LINEARSEARCH);       // a byte array.
4416     cmp(cnt1, cnt2, LSR, 2);    // Source must be 4 * pattern for BM
4417     br(HS, LINEARSEARCH);
4418   }
4419 
4420 // The Boyer Moore alogorithm is based on the description here:-
4421 //
4422 // http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
4423 //
4424 // This describes and algorithm with 2 shift rules. The 'Bad Character' rule
4425 // and the 'Good Suffix' rule.
4426 //
4427 // These rules are essentially heuristics for how far we can shift the
4428 // pattern along the search string.
4429 //
4430 // The implementation here uses the 'Bad Character' rule only because of the
4431 // complexity of initialisation for the 'Good Suffix' rule.
4432 //
4433 // This is also known as the Boyer-Moore-Horspool algorithm:-
4434 //
4435 // http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm
4436 //
4437 // #define ASIZE 128
4438 //
4439 //    int bm(unsigned char *x, int m, unsigned char *y, int n) {
4440 //       int i, j;
4441 //       unsigned c;
4442 //       unsigned char bc[ASIZE];
4443 //
4444 //       /* Preprocessing */
4445 //       for (i = 0; i < ASIZE; ++i)
4446 //          bc[i] = 0;
4447 //       for (i = 0; i < m - 1; ) {
4448 //          c = x[i];
4449 //          ++i;
4450 //          if (c < ASIZE) bc[c] = i;
4451 //       }
4452 //
4453 //       /* Searching */
4454 //       j = 0;
4455 //       while (j <= n - m) {
4456 //          c = y[i+j];
4457 //          if (x[m-1] == c)
4458 //            for (i = m - 2; i >= 0 && x[i] == y[i + j]; --i);
4459 //          if (i < 0) return j;
4460 //          if (c < ASIZE)
4461 //            j = j - bc[y[j+m-1]] + m;
4462 //          else
4463 //            j += 1; // Advance by 1 only if char >= ASIZE
4464 //       }
4465 //    }
4466 
4467   if (icnt1 == -1) {
4468     BIND(BM);
4469 
4470     Label ZLOOP, BCLOOP, BCSKIP, BMLOOPSTR2, BMLOOPSTR1, BMSKIP;
4471     Label BMADV, BMMATCH, BMCHECKEND;
4472 
4473     Register cnt1end = tmp2;
4474     Register str2end = cnt2;
4475     Register skipch = tmp2;
4476 
4477     // Restrict ASIZE to 128 to reduce stack space/initialisation.
4478     // The presence of chars >= ASIZE in the target string does not affect
4479     // performance, but we must be careful not to initialise them in the stack
4480     // array.
4481     // The presence of chars >= ASIZE in the source string may adversely affect
4482     // performance since we can only advance by one when we encounter one.
4483 
4484       stp(zr, zr, pre(sp, -128));
4485       for (int i = 1; i < 8; i++)
4486           stp(zr, zr, Address(sp, i*16));
4487 
4488       mov(cnt1tmp, 0);
4489       sub(cnt1end, cnt1, 1);
4490     BIND(BCLOOP);
4491       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4492       cmp(ch1, 128);
4493       add(cnt1tmp, cnt1tmp, 1);
4494       br(HS, BCSKIP);
4495       strb(cnt1tmp, Address(sp, ch1));
4496     BIND(BCSKIP);
4497       cmp(cnt1tmp, cnt1end);
4498       br(LT, BCLOOP);
4499 
4500       mov(result_tmp, str2);
4501 
4502       sub(cnt2, cnt2, cnt1);
4503       add(str2end, str2, cnt2, LSL, str2_chr_shift);
4504     BIND(BMLOOPSTR2);
4505       sub(cnt1tmp, cnt1, 1);
4506       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4507       (this->*str2_load_1chr)(skipch, Address(str2, cnt1tmp, Address::lsl(str2_chr_shift)));
4508       cmp(ch1, skipch);
4509       br(NE, BMSKIP);
4510       subs(cnt1tmp, cnt1tmp, 1);
4511       br(LT, BMMATCH);
4512     BIND(BMLOOPSTR1);
4513       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4514       (this->*str2_load_1chr)(ch2, Address(str2, cnt1tmp, Address::lsl(str2_chr_shift)));
4515       cmp(ch1, ch2);
4516       br(NE, BMSKIP);
4517       subs(cnt1tmp, cnt1tmp, 1);
4518       br(GE, BMLOOPSTR1);
4519     BIND(BMMATCH);
4520       sub(result, str2, result_tmp);
4521       if (!str2_isL) lsr(result, result, 1);
4522       add(sp, sp, 128);
4523       b(DONE);
4524     BIND(BMADV);
4525       add(str2, str2, str2_chr_size);
4526       b(BMCHECKEND);
4527     BIND(BMSKIP);
4528       cmp(skipch, 128);
4529       br(HS, BMADV);
4530       ldrb(ch2, Address(sp, skipch));
4531       add(str2, str2, cnt1, LSL, str2_chr_shift);
4532       sub(str2, str2, ch2, LSL, str2_chr_shift);
4533     BIND(BMCHECKEND);
4534       cmp(str2, str2end);
4535       br(LE, BMLOOPSTR2);
4536       add(sp, sp, 128);
4537       b(NOMATCH);
4538   }
4539 
4540   BIND(LINEARSEARCH);
4541   {
4542     Label DO1, DO2, DO3;
4543 
4544     Register str2tmp = tmp2;
4545     Register first = tmp3;
4546 
4547     if (icnt1 == -1)
4548     {
4549         Label DOSHORT, FIRST_LOOP, STR2_NEXT, STR1_LOOP, STR1_NEXT;
4550 
4551         cmp(cnt1, str1_isL == str2_isL ? 4 : 2);
4552         br(LT, DOSHORT);
4553 
4554         sub(cnt2, cnt2, cnt1);
4555         mov(result_tmp, cnt2);
4556 
4557         lea(str1, Address(str1, cnt1, Address::lsl(str1_chr_shift)));
4558         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4559         sub(cnt1_neg, zr, cnt1, LSL, str1_chr_shift);
4560         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4561         (this->*str1_load_1chr)(first, Address(str1, cnt1_neg));
4562 
4563       BIND(FIRST_LOOP);
4564         (this->*str2_load_1chr)(ch2, Address(str2, cnt2_neg));
4565         cmp(first, ch2);
4566         br(EQ, STR1_LOOP);
4567       BIND(STR2_NEXT);
4568         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4569         br(LE, FIRST_LOOP);
4570         b(NOMATCH);
4571 
4572       BIND(STR1_LOOP);
4573         adds(cnt1tmp, cnt1_neg, str1_chr_size);
4574         add(cnt2tmp, cnt2_neg, str2_chr_size);
4575         br(GE, MATCH);
4576 
4577       BIND(STR1_NEXT);
4578         (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp));
4579         (this->*str2_load_1chr)(ch2, Address(str2, cnt2tmp));
4580         cmp(ch1, ch2);
4581         br(NE, STR2_NEXT);
4582         adds(cnt1tmp, cnt1tmp, str1_chr_size);
4583         add(cnt2tmp, cnt2tmp, str2_chr_size);
4584         br(LT, STR1_NEXT);
4585         b(MATCH);
4586 
4587       BIND(DOSHORT);
4588       if (str1_isL == str2_isL) {
4589         cmp(cnt1, 2);
4590         br(LT, DO1);
4591         br(GT, DO3);
4592       }
4593     }
4594 
4595     if (icnt1 == 4) {
4596       Label CH1_LOOP;
4597 
4598         (this->*load_4chr)(ch1, str1);
4599         sub(cnt2, cnt2, 4);
4600         mov(result_tmp, cnt2);
4601         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4602         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4603 
4604       BIND(CH1_LOOP);
4605         (this->*load_4chr)(ch2, Address(str2, cnt2_neg));
4606         cmp(ch1, ch2);
4607         br(EQ, MATCH);
4608         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4609         br(LE, CH1_LOOP);
4610         b(NOMATCH);
4611     }
4612 
4613     if ((icnt1 == -1 && str1_isL == str2_isL) || icnt1 == 2) {
4614       Label CH1_LOOP;
4615 
4616       BIND(DO2);
4617         (this->*load_2chr)(ch1, str1);
4618         sub(cnt2, cnt2, 2);
4619         mov(result_tmp, cnt2);
4620         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4621         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4622 
4623       BIND(CH1_LOOP);
4624         (this->*load_2chr)(ch2, Address(str2, cnt2_neg));
4625         cmp(ch1, ch2);
4626         br(EQ, MATCH);
4627         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4628         br(LE, CH1_LOOP);
4629         b(NOMATCH);
4630     }
4631 
4632     if ((icnt1 == -1 && str1_isL == str2_isL) || icnt1 == 3) {
4633       Label FIRST_LOOP, STR2_NEXT, STR1_LOOP;
4634 
4635       BIND(DO3);
4636         (this->*load_2chr)(first, str1);
4637         (this->*str1_load_1chr)(ch1, Address(str1, 2*str1_chr_size));
4638 
4639         sub(cnt2, cnt2, 3);
4640         mov(result_tmp, cnt2);
4641         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4642         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4643 
4644       BIND(FIRST_LOOP);
4645         (this->*load_2chr)(ch2, Address(str2, cnt2_neg));
4646         cmpw(first, ch2);
4647         br(EQ, STR1_LOOP);
4648       BIND(STR2_NEXT);
4649         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4650         br(LE, FIRST_LOOP);
4651         b(NOMATCH);
4652 
4653       BIND(STR1_LOOP);
4654         add(cnt2tmp, cnt2_neg, 2*str2_chr_size);
4655         (this->*str2_load_1chr)(ch2, Address(str2, cnt2tmp));
4656         cmp(ch1, ch2);
4657         br(NE, STR2_NEXT);
4658         b(MATCH);
4659     }
4660 
4661     if (icnt1 == -1 || icnt1 == 1) {
4662       Label CH1_LOOP, HAS_ZERO;
4663       Label DO1_SHORT, DO1_LOOP;
4664 
4665       BIND(DO1);
4666         (this->*str1_load_1chr)(ch1, str1);
4667         cmp(cnt2, 8);
4668         br(LT, DO1_SHORT);
4669 
4670         if (str2_isL) {
4671           if (!str1_isL) {
4672             tst(ch1, 0xff00);
4673             br(NE, NOMATCH);
4674           }
4675           orr(ch1, ch1, ch1, LSL, 8);
4676         }
4677         orr(ch1, ch1, ch1, LSL, 16);
4678         orr(ch1, ch1, ch1, LSL, 32);
4679 
4680         sub(cnt2, cnt2, 8/str2_chr_size);
4681         mov(result_tmp, cnt2);
4682         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4683         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4684 
4685         mov(tmp3, str2_isL ? 0x0101010101010101 : 0x0001000100010001);
4686       BIND(CH1_LOOP);
4687         ldr(ch2, Address(str2, cnt2_neg));
4688         eor(ch2, ch1, ch2);
4689         sub(tmp1, ch2, tmp3);
4690         orr(tmp2, ch2, str2_isL ? 0x7f7f7f7f7f7f7f7f : 0x7fff7fff7fff7fff);
4691         bics(tmp1, tmp1, tmp2);
4692         br(NE, HAS_ZERO);
4693         adds(cnt2_neg, cnt2_neg, 8);
4694         br(LT, CH1_LOOP);
4695 
4696         cmp(cnt2_neg, 8);
4697         mov(cnt2_neg, 0);
4698         br(LT, CH1_LOOP);
4699         b(NOMATCH);
4700 
4701       BIND(HAS_ZERO);
4702         rev(tmp1, tmp1);
4703         clz(tmp1, tmp1);
4704         add(cnt2_neg, cnt2_neg, tmp1, LSR, 3);
4705         b(MATCH);
4706 
4707       BIND(DO1_SHORT);
4708         mov(result_tmp, cnt2);
4709         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4710         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4711       BIND(DO1_LOOP);
4712         (this->*str2_load_1chr)(ch2, Address(str2, cnt2_neg));
4713         cmpw(ch1, ch2);
4714         br(EQ, MATCH);
4715         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4716         br(LT, DO1_LOOP);
4717     }
4718   }
4719   BIND(NOMATCH);
4720     mov(result, -1);
4721     b(DONE);
4722   BIND(MATCH);
4723     add(result, result_tmp, cnt2_neg, ASR, str2_chr_shift);
4724   BIND(DONE);
4725 }
4726 
4727 typedef void (MacroAssembler::* chr_insn)(Register Rt, const Address &adr);
4728 typedef void (MacroAssembler::* uxt_insn)(Register Rd, Register Rn);
4729 
4730 void MacroAssembler::string_indexof_char(Register str1, Register cnt1,
4731                                          Register ch, Register result,
4732                                          Register tmp1, Register tmp2, Register tmp3)
4733 {
4734   Label CH1_LOOP, HAS_ZERO, DO1_SHORT, DO1_LOOP, MATCH, NOMATCH, DONE;
4735   Register cnt1_neg = cnt1;
4736   Register ch1 = rscratch1;
4737   Register result_tmp = rscratch2;
4738 
4739   cmp(cnt1, 4);
4740   br(LT, DO1_SHORT);
4741 
4742   orr(ch, ch, ch, LSL, 16);
4743   orr(ch, ch, ch, LSL, 32);
4744 
4745   sub(cnt1, cnt1, 4);
4746   mov(result_tmp, cnt1);
4747   lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4748   sub(cnt1_neg, zr, cnt1, LSL, 1);
4749 
4750   mov(tmp3, 0x0001000100010001);
4751 
4752   BIND(CH1_LOOP);
4753     ldr(ch1, Address(str1, cnt1_neg));
4754     eor(ch1, ch, ch1);
4755     sub(tmp1, ch1, tmp3);
4756     orr(tmp2, ch1, 0x7fff7fff7fff7fff);
4757     bics(tmp1, tmp1, tmp2);
4758     br(NE, HAS_ZERO);
4759     adds(cnt1_neg, cnt1_neg, 8);
4760     br(LT, CH1_LOOP);
4761 
4762     cmp(cnt1_neg, 8);
4763     mov(cnt1_neg, 0);
4764     br(LT, CH1_LOOP);
4765     b(NOMATCH);
4766 
4767   BIND(HAS_ZERO);
4768     rev(tmp1, tmp1);
4769     clz(tmp1, tmp1);
4770     add(cnt1_neg, cnt1_neg, tmp1, LSR, 3);
4771     b(MATCH);
4772 
4773   BIND(DO1_SHORT);
4774     mov(result_tmp, cnt1);
4775     lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4776     sub(cnt1_neg, zr, cnt1, LSL, 1);
4777   BIND(DO1_LOOP);
4778     ldrh(ch1, Address(str1, cnt1_neg));
4779     cmpw(ch, ch1);
4780     br(EQ, MATCH);
4781     adds(cnt1_neg, cnt1_neg, 2);
4782     br(LT, DO1_LOOP);
4783   BIND(NOMATCH);
4784     mov(result, -1);
4785     b(DONE);
4786   BIND(MATCH);
4787     add(result, result_tmp, cnt1_neg, ASR, 1);
4788   BIND(DONE);
4789 }
4790 
4791 // Compare strings.
4792 void MacroAssembler::string_compare(Register str1, Register str2,
4793                                     Register cnt1, Register cnt2, Register result,
4794                                     Register tmp1,
4795                                     FloatRegister vtmp, FloatRegister vtmpZ, int ae) {
4796   Label LENGTH_DIFF, DONE, SHORT_LOOP, SHORT_STRING,
4797     NEXT_WORD, DIFFERENCE;
4798 
4799   bool isLL = ae == StrIntrinsicNode::LL;
4800   bool isLU = ae == StrIntrinsicNode::LU;
4801   bool isUL = ae == StrIntrinsicNode::UL;
4802 
4803   bool str1_isL = isLL || isLU;
4804   bool str2_isL = isLL || isUL;
4805 
4806   int str1_chr_shift = str1_isL ? 0 : 1;
4807   int str2_chr_shift = str2_isL ? 0 : 1;
4808   int str1_chr_size = str1_isL ? 1 : 2;
4809   int str2_chr_size = str2_isL ? 1 : 2;
4810 
4811   chr_insn str1_load_chr = str1_isL ? (chr_insn)&MacroAssembler::ldrb :
4812                                       (chr_insn)&MacroAssembler::ldrh;
4813   chr_insn str2_load_chr = str2_isL ? (chr_insn)&MacroAssembler::ldrb :
4814                                       (chr_insn)&MacroAssembler::ldrh;
4815   uxt_insn ext_chr = isLL ? (uxt_insn)&MacroAssembler::uxtbw :
4816                             (uxt_insn)&MacroAssembler::uxthw;
4817 
4818   BLOCK_COMMENT("string_compare {");
4819 
4820   // Bizzarely, the counts are passed in bytes, regardless of whether they
4821   // are L or U strings, however the result is always in characters.
4822   if (!str1_isL) asrw(cnt1, cnt1, 1);
4823   if (!str2_isL) asrw(cnt2, cnt2, 1);
4824 
4825   // Compute the minimum of the string lengths and save the difference.
4826   subsw(tmp1, cnt1, cnt2);
4827   cselw(cnt2, cnt1, cnt2, Assembler::LE); // min
4828 
4829   // A very short string
4830   cmpw(cnt2, isLL ? 8:4);
4831   br(Assembler::LT, SHORT_STRING);
4832 
4833   // Check if the strings start at the same location.
4834   cmp(str1, str2);
4835   br(Assembler::EQ, LENGTH_DIFF);
4836 
4837   // Compare longwords
4838   {
4839     subw(cnt2, cnt2, isLL ? 8:4); // The last longword is a special case
4840 
4841     // Move both string pointers to the last longword of their
4842     // strings, negate the remaining count, and convert it to bytes.
4843     lea(str1, Address(str1, cnt2, Address::uxtw(str1_chr_shift)));
4844     lea(str2, Address(str2, cnt2, Address::uxtw(str2_chr_shift)));
4845     if (isLU || isUL) {
4846       sub(cnt1, zr, cnt2, LSL, str1_chr_shift);
4847       eor(vtmpZ, T16B, vtmpZ, vtmpZ);
4848     }
4849     sub(cnt2, zr, cnt2, LSL, str2_chr_shift);
4850 
4851     // Loop, loading longwords and comparing them into rscratch2.
4852     bind(NEXT_WORD);
4853     if (isLU) {
4854       ldrs(vtmp, Address(str1, cnt1));
4855       zip1(vtmp, T8B, vtmp, vtmpZ);
4856       umov(result, vtmp, D, 0);
4857     } else {
4858       ldr(result, Address(str1, isUL ? cnt1:cnt2));
4859     }
4860     if (isUL) {
4861       ldrs(vtmp, Address(str2, cnt2));
4862       zip1(vtmp, T8B, vtmp, vtmpZ);
4863       umov(rscratch1, vtmp, D, 0);
4864     } else {
4865       ldr(rscratch1, Address(str2, cnt2));
4866     }
4867     adds(cnt2, cnt2, isUL ? 4:8);
4868     if (isLU || isUL) add(cnt1, cnt1, isLU ? 4:8);
4869     eor(rscratch2, result, rscratch1);
4870     cbnz(rscratch2, DIFFERENCE);
4871     br(Assembler::LT, NEXT_WORD);
4872 
4873     // Last longword.  In the case where length == 4 we compare the
4874     // same longword twice, but that's still faster than another
4875     // conditional branch.
4876 
4877     if (isLU) {
4878       ldrs(vtmp, Address(str1));
4879       zip1(vtmp, T8B, vtmp, vtmpZ);
4880       umov(result, vtmp, D, 0);
4881     } else {
4882       ldr(result, Address(str1));
4883     }
4884     if (isUL) {
4885       ldrs(vtmp, Address(str2));
4886       zip1(vtmp, T8B, vtmp, vtmpZ);
4887       umov(rscratch1, vtmp, D, 0);
4888     } else {
4889       ldr(rscratch1, Address(str2));
4890     }
4891     eor(rscratch2, result, rscratch1);
4892     cbz(rscratch2, LENGTH_DIFF);
4893 
4894     // Find the first different characters in the longwords and
4895     // compute their difference.
4896     bind(DIFFERENCE);
4897     rev(rscratch2, rscratch2);
4898     clz(rscratch2, rscratch2);
4899     andr(rscratch2, rscratch2, isLL ? -8 : -16);
4900     lsrv(result, result, rscratch2);
4901     (this->*ext_chr)(result, result);
4902     lsrv(rscratch1, rscratch1, rscratch2);
4903     (this->*ext_chr)(rscratch1, rscratch1);
4904     subw(result, result, rscratch1);
4905     b(DONE);
4906   }
4907 
4908   bind(SHORT_STRING);
4909   // Is the minimum length zero?
4910   cbz(cnt2, LENGTH_DIFF);
4911 
4912   bind(SHORT_LOOP);
4913   (this->*str1_load_chr)(result, Address(post(str1, str1_chr_size)));
4914   (this->*str2_load_chr)(cnt1, Address(post(str2, str2_chr_size)));
4915   subw(result, result, cnt1);
4916   cbnz(result, DONE);
4917   sub(cnt2, cnt2, 1);
4918   cbnz(cnt2, SHORT_LOOP);
4919 
4920   // Strings are equal up to min length.  Return the length difference.
4921   bind(LENGTH_DIFF);
4922   mov(result, tmp1);
4923 
4924   // That's it
4925   bind(DONE);
4926 
4927   BLOCK_COMMENT("} string_compare");
4928 }
4929 
4930 // This method checks if provided byte array contains byte with highest bit set.
4931 void MacroAssembler::has_negatives(Register ary1, Register len, Register result) {
4932     // Simple and most common case of aligned small array which is not at the
4933     // end of memory page is placed here. All other cases are in stub.
4934     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
4935     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
4936     assert_different_registers(ary1, len, result);
4937 
4938     cmpw(len, 0);
4939     br(LE, SET_RESULT);
4940     cmpw(len, 4 * wordSize);
4941     br(GE, STUB_LONG); // size > 32 then go to stub
4942 
4943     int shift = 64 - exact_log2(os::vm_page_size());
4944     lsl(rscratch1, ary1, shift);
4945     mov(rscratch2, (size_t)(4 * wordSize) << shift);
4946     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
4947     br(CS, STUB); // at the end of page then go to stub
4948     subs(len, len, wordSize);
4949     br(LT, END);
4950 
4951   BIND(LOOP);
4952     ldr(rscratch1, Address(post(ary1, wordSize)));
4953     tst(rscratch1, UPPER_BIT_MASK);
4954     br(NE, SET_RESULT);
4955     subs(len, len, wordSize);
4956     br(GE, LOOP);
4957     cmpw(len, -wordSize);
4958     br(EQ, SET_RESULT);
4959 
4960   BIND(END);
4961     ldr(result, Address(ary1));
4962     sub(len, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
4963     lslv(result, result, len);
4964     tst(result, UPPER_BIT_MASK);
4965     b(SET_RESULT);
4966 
4967   BIND(STUB);
4968     RuntimeAddress has_neg =  RuntimeAddress(StubRoutines::aarch64::has_negatives());
4969     assert(has_neg.target() != NULL, "has_negatives stub has not been generated");
4970     trampoline_call(has_neg);
4971     b(DONE);
4972 
4973   BIND(STUB_LONG);
4974     RuntimeAddress has_neg_long =  RuntimeAddress(
4975             StubRoutines::aarch64::has_negatives_long());
4976     assert(has_neg_long.target() != NULL, "has_negatives stub has not been generated");
4977     trampoline_call(has_neg_long);
4978     b(DONE);
4979 
4980   BIND(SET_RESULT);
4981     cset(result, NE); // set true or false
4982 
4983   BIND(DONE);
4984 }
4985 
4986 void MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
4987                                    Register tmp4, Register tmp5, Register result,
4988                                    Register cnt1, int elem_size)
4989 {
4990   Label DONE;
4991   Register tmp1 = rscratch1;
4992   Register tmp2 = rscratch2;
4993   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4994   int elem_per_word = wordSize/elem_size;
4995   int log_elem_size = exact_log2(elem_size);
4996   int length_offset = arrayOopDesc::length_offset_in_bytes();
4997   int base_offset
4998     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
4999   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
5000 
5001   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
5002   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5003 
5004 #ifndef PRODUCT
5005   {
5006     const char kind = (elem_size == 2) ? 'U' : 'L';
5007     char comment[64];
5008     snprintf(comment, sizeof comment, "array_equals%c{", kind);
5009     BLOCK_COMMENT(comment);
5010   }
5011 #endif
5012   if (UseSimpleArrayEquals) {
5013     Label NEXT_WORD, SHORT, SAME, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
5014     // if (a1==a2)
5015     //     return true;
5016     // if (a==null || a2==null)
5017     //     return false;
5018     // a1 & a2 == 0 means (some-pointer is null) or
5019     // (very-rare-or-even-probably-impossible-pointer-values)
5020     // so, we can save one branch in most cases
5021     eor(rscratch1, a1, a2);
5022     tst(a1, a2);
5023     mov(result, false);
5024     cbz(rscratch1, SAME);
5025     br(EQ, A_MIGHT_BE_NULL);
5026     // if (a1.length != a2.length)
5027     //      return false;
5028     bind(A_IS_NOT_NULL);
5029     ldrw(cnt1, Address(a1, length_offset));
5030     ldrw(cnt2, Address(a2, length_offset));
5031     eorw(tmp5, cnt1, cnt2);
5032     cbnzw(tmp5, DONE);
5033     lea(a1, Address(a1, base_offset));
5034     lea(a2, Address(a2, base_offset));
5035     // Check for short strings, i.e. smaller than wordSize.
5036     subs(cnt1, cnt1, elem_per_word);
5037     br(Assembler::LT, SHORT);
5038     // Main 8 byte comparison loop.
5039     bind(NEXT_WORD); {
5040       ldr(tmp1, Address(post(a1, wordSize)));
5041       ldr(tmp2, Address(post(a2, wordSize)));
5042       subs(cnt1, cnt1, elem_per_word);
5043       eor(tmp5, tmp1, tmp2);
5044       cbnz(tmp5, DONE);
5045     } br(GT, NEXT_WORD);
5046     // Last longword.  In the case where length == 4 we compare the
5047     // same longword twice, but that's still faster than another
5048     // conditional branch.
5049     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5050     // length == 4.
5051     if (log_elem_size > 0)
5052       lsl(cnt1, cnt1, log_elem_size);
5053     ldr(tmp3, Address(a1, cnt1));
5054     ldr(tmp4, Address(a2, cnt1));
5055     eor(tmp5, tmp3, tmp4);
5056     cbnz(tmp5, DONE);
5057     b(SAME);
5058     bind(A_MIGHT_BE_NULL);
5059     // in case both a1 and a2 are not-null, proceed with loads
5060     cbz(a1, DONE);
5061     cbz(a2, DONE);
5062     b(A_IS_NOT_NULL);
5063     bind(SHORT);
5064 
5065     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
5066     {
5067       ldrw(tmp1, Address(post(a1, 4)));
5068       ldrw(tmp2, Address(post(a2, 4)));
5069       eorw(tmp5, tmp1, tmp2);
5070       cbnzw(tmp5, DONE);
5071     }
5072     bind(TAIL03);
5073     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
5074     {
5075       ldrh(tmp3, Address(post(a1, 2)));
5076       ldrh(tmp4, Address(post(a2, 2)));
5077       eorw(tmp5, tmp3, tmp4);
5078       cbnzw(tmp5, DONE);
5079     }
5080     bind(TAIL01);
5081     if (elem_size == 1) { // Only needed when comparing byte arrays.
5082       tbz(cnt1, 0, SAME); // 0-1 bytes left.
5083       {
5084         ldrb(tmp1, a1);
5085         ldrb(tmp2, a2);
5086         eorw(tmp5, tmp1, tmp2);
5087         cbnzw(tmp5, DONE);
5088       }
5089     }
5090     bind(SAME);
5091     mov(result, true);
5092   } else {
5093     Label NEXT_DWORD, A_IS_NULL, SHORT, TAIL, TAIL2, STUB, EARLY_OUT,
5094         CSET_EQ, LAST_CHECK, LEN_IS_ZERO, SAME;
5095     cbz(a1, A_IS_NULL);
5096     ldrw(cnt1, Address(a1, length_offset));
5097     cbz(a2, A_IS_NULL);
5098     ldrw(cnt2, Address(a2, length_offset));
5099     mov(result, false);
5100     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
5101     // faster to perform another branch before comparing a1 and a2
5102     cmp(cnt1, elem_per_word);
5103     br(LE, SHORT); // short or same
5104     cmp(a1, a2);
5105     br(EQ, SAME);
5106     ldr(tmp3, Address(pre(a1, base_offset)));
5107     cmp(cnt1, stubBytesThreshold);
5108     br(GE, STUB);
5109     ldr(tmp4, Address(pre(a2, base_offset)));
5110     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
5111     cmp(cnt2, cnt1);
5112     br(NE, DONE);
5113 
5114     // Main 16 byte comparison loop with 2 exits
5115     bind(NEXT_DWORD); {
5116       ldr(tmp1, Address(pre(a1, wordSize)));
5117       ldr(tmp2, Address(pre(a2, wordSize)));
5118       subs(cnt1, cnt1, 2 * elem_per_word);
5119       br(LE, TAIL);
5120       eor(tmp4, tmp3, tmp4);
5121       cbnz(tmp4, DONE);
5122       ldr(tmp3, Address(pre(a1, wordSize)));
5123       ldr(tmp4, Address(pre(a2, wordSize)));
5124       cmp(cnt1, elem_per_word);
5125       br(LE, TAIL2);
5126       cmp(tmp1, tmp2);
5127     } br(EQ, NEXT_DWORD);
5128     b(DONE);
5129 
5130     bind(TAIL);
5131     eor(tmp4, tmp3, tmp4);
5132     eor(tmp2, tmp1, tmp2);
5133     lslv(tmp2, tmp2, tmp5);
5134     orr(tmp5, tmp4, tmp2);
5135     cmp(tmp5, zr);
5136     b(CSET_EQ);
5137 
5138     bind(TAIL2);
5139     eor(tmp2, tmp1, tmp2);
5140     cbnz(tmp2, DONE);
5141     b(LAST_CHECK);
5142 
5143     bind(STUB);
5144     ldr(tmp4, Address(pre(a2, base_offset)));
5145     cmp(cnt2, cnt1);
5146     br(NE, DONE);
5147     if (elem_size == 2) { // convert to byte counter
5148       lsl(cnt1, cnt1, 1);
5149     }
5150     eor(tmp5, tmp3, tmp4);
5151     cbnz(tmp5, DONE);
5152     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
5153     assert(stub.target() != NULL, "array_equals_long stub has not been generated");
5154     trampoline_call(stub);
5155     b(DONE);
5156 
5157     bind(SAME);
5158     mov(result, true);
5159     b(DONE);
5160     bind(A_IS_NULL);
5161     // a1 or a2 is null. if a2 == a2 then return true. else return false
5162     cmp(a1, a2);
5163     b(CSET_EQ);
5164     bind(EARLY_OUT);
5165     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
5166     // so, if a2 == null => return false(0), else return true, so we can return a2
5167     mov(result, a2);
5168     b(DONE);
5169     bind(LEN_IS_ZERO);
5170     cmp(cnt2, zr);
5171     b(CSET_EQ);
5172     bind(SHORT);
5173     cbz(cnt1, LEN_IS_ZERO);
5174     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
5175     ldr(tmp3, Address(a1, base_offset));
5176     ldr(tmp4, Address(a2, base_offset));
5177     bind(LAST_CHECK);
5178     eor(tmp4, tmp3, tmp4);
5179     lslv(tmp5, tmp4, tmp5);
5180     cmp(tmp5, zr);
5181     bind(CSET_EQ);
5182     cset(result, EQ);
5183   }
5184 
5185   // That's it.
5186   bind(DONE);
5187 
5188   BLOCK_COMMENT("} array_equals");
5189 }
5190 
5191 // Compare Strings
5192 
5193 // For Strings we're passed the address of the first characters in a1
5194 // and a2 and the length in cnt1.
5195 // elem_size is the element size in bytes: either 1 or 2.
5196 // There are two implementations.  For arrays >= 8 bytes, all
5197 // comparisons (including the final one, which may overlap) are
5198 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
5199 // halfword, then a short, and then a byte.
5200 
5201 void MacroAssembler::string_equals(Register a1, Register a2,
5202                                    Register result, Register cnt1, int elem_size)
5203 {
5204   Label SAME, DONE, SHORT, NEXT_WORD;
5205   Register tmp1 = rscratch1;
5206   Register tmp2 = rscratch2;
5207   Register cnt2 = tmp2;  // cnt2 only used in array length compare
5208 
5209   assert(elem_size == 1 || elem_size == 2, "must be 2 or 1 byte");
5210   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5211 
5212 #ifndef PRODUCT
5213   {
5214     const char kind = (elem_size == 2) ? 'U' : 'L';
5215     char comment[64];
5216     snprintf(comment, sizeof comment, "{string_equals%c", kind);
5217     BLOCK_COMMENT(comment);
5218   }
5219 #endif
5220 
5221   mov(result, false);
5222 
5223   // Check for short strings, i.e. smaller than wordSize.
5224   subs(cnt1, cnt1, wordSize);
5225   br(Assembler::LT, SHORT);
5226   // Main 8 byte comparison loop.
5227   bind(NEXT_WORD); {
5228     ldr(tmp1, Address(post(a1, wordSize)));
5229     ldr(tmp2, Address(post(a2, wordSize)));
5230     subs(cnt1, cnt1, wordSize);
5231     eor(tmp1, tmp1, tmp2);
5232     cbnz(tmp1, DONE);
5233   } br(GT, NEXT_WORD);
5234   // Last longword.  In the case where length == 4 we compare the
5235   // same longword twice, but that's still faster than another
5236   // conditional branch.
5237   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5238   // length == 4.
5239   ldr(tmp1, Address(a1, cnt1));
5240   ldr(tmp2, Address(a2, cnt1));
5241   eor(tmp2, tmp1, tmp2);
5242   cbnz(tmp2, DONE);
5243   b(SAME);
5244 
5245   bind(SHORT);
5246   Label TAIL03, TAIL01;
5247 
5248   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
5249   {
5250     ldrw(tmp1, Address(post(a1, 4)));
5251     ldrw(tmp2, Address(post(a2, 4)));
5252     eorw(tmp1, tmp1, tmp2);
5253     cbnzw(tmp1, DONE);
5254   }
5255   bind(TAIL03);
5256   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
5257   {
5258     ldrh(tmp1, Address(post(a1, 2)));
5259     ldrh(tmp2, Address(post(a2, 2)));
5260     eorw(tmp1, tmp1, tmp2);
5261     cbnzw(tmp1, DONE);
5262   }
5263   bind(TAIL01);
5264   if (elem_size == 1) { // Only needed when comparing 1-byte elements
5265     tbz(cnt1, 0, SAME); // 0-1 bytes left.
5266     {
5267       ldrb(tmp1, a1);
5268       ldrb(tmp2, a2);
5269       eorw(tmp1, tmp1, tmp2);
5270       cbnzw(tmp1, DONE);
5271     }
5272   }
5273   // Arrays are equal.
5274   bind(SAME);
5275   mov(result, true);
5276 
5277   // That's it.
5278   bind(DONE);
5279   BLOCK_COMMENT("} string_equals");
5280 }
5281 
5282 
5283 // The size of the blocks erased by the zero_blocks stub.  We must
5284 // handle anything smaller than this ourselves in zero_words().
5285 const int MacroAssembler::zero_words_block_size = 8;
5286 
5287 // zero_words() is used by C2 ClearArray patterns.  It is as small as
5288 // possible, handling small word counts locally and delegating
5289 // anything larger to the zero_blocks stub.  It is expanded many times
5290 // in compiled code, so it is important to keep it short.
5291 
5292 // ptr:   Address of a buffer to be zeroed.
5293 // cnt:   Count in HeapWords.
5294 //
5295 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
5296 void MacroAssembler::zero_words(Register ptr, Register cnt)
5297 {
5298   assert(is_power_of_2(zero_words_block_size), "adjust this");
5299   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
5300 
5301   BLOCK_COMMENT("zero_words {");
5302   cmp(cnt, zero_words_block_size);
5303   Label around, done, done16;
5304   br(LO, around);
5305   {
5306     RuntimeAddress zero_blocks =  RuntimeAddress(StubRoutines::aarch64::zero_blocks());
5307     assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
5308     if (StubRoutines::aarch64::complete()) {
5309       trampoline_call(zero_blocks);
5310     } else {
5311       bl(zero_blocks);
5312     }
5313   }
5314   bind(around);
5315   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
5316     Label l;
5317     tbz(cnt, exact_log2(i), l);
5318     for (int j = 0; j < i; j += 2) {
5319       stp(zr, zr, post(ptr, 16));
5320     }
5321     bind(l);
5322   }
5323   {
5324     Label l;
5325     tbz(cnt, 0, l);
5326     str(zr, Address(ptr));
5327     bind(l);
5328   }
5329   BLOCK_COMMENT("} zero_words");
5330 }
5331 
5332 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
5333 // cnt:          Immediate count in HeapWords.
5334 #define SmallArraySize (18 * BytesPerLong)
5335 void MacroAssembler::zero_words(Register base, u_int64_t cnt)
5336 {
5337   BLOCK_COMMENT("zero_words {");
5338   int i = cnt & 1;  // store any odd word to start
5339   if (i) str(zr, Address(base));
5340 
5341   if (cnt <= SmallArraySize / BytesPerLong) {
5342     for (; i < (int)cnt; i += 2)
5343       stp(zr, zr, Address(base, i * wordSize));
5344   } else {
5345     const int unroll = 4; // Number of stp(zr, zr) instructions we'll unroll
5346     int remainder = cnt % (2 * unroll);
5347     for (; i < remainder; i += 2)
5348       stp(zr, zr, Address(base, i * wordSize));
5349 
5350     Label loop;
5351     Register cnt_reg = rscratch1;
5352     Register loop_base = rscratch2;
5353     cnt = cnt - remainder;
5354     mov(cnt_reg, cnt);
5355     // adjust base and prebias by -2 * wordSize so we can pre-increment
5356     add(loop_base, base, (remainder - 2) * wordSize);
5357     bind(loop);
5358     sub(cnt_reg, cnt_reg, 2 * unroll);
5359     for (i = 1; i < unroll; i++)
5360       stp(zr, zr, Address(loop_base, 2 * i * wordSize));
5361     stp(zr, zr, Address(pre(loop_base, 2 * unroll * wordSize)));
5362     cbnz(cnt_reg, loop);
5363   }
5364   BLOCK_COMMENT("} zero_words");
5365 }
5366 
5367 // Zero blocks of memory by using DC ZVA.
5368 //
5369 // Aligns the base address first sufficently for DC ZVA, then uses
5370 // DC ZVA repeatedly for every full block.  cnt is the size to be
5371 // zeroed in HeapWords.  Returns the count of words left to be zeroed
5372 // in cnt.
5373 //
5374 // NOTE: This is intended to be used in the zero_blocks() stub.  If
5375 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
5376 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
5377   Register tmp = rscratch1;
5378   Register tmp2 = rscratch2;
5379   int zva_length = VM_Version::zva_length();
5380   Label initial_table_end, loop_zva;
5381   Label fini;
5382 
5383   // Base must be 16 byte aligned. If not just return and let caller handle it
5384   tst(base, 0x0f);
5385   br(Assembler::NE, fini);
5386   // Align base with ZVA length.
5387   neg(tmp, base);
5388   andr(tmp, tmp, zva_length - 1);
5389 
5390   // tmp: the number of bytes to be filled to align the base with ZVA length.
5391   add(base, base, tmp);
5392   sub(cnt, cnt, tmp, Assembler::ASR, 3);
5393   adr(tmp2, initial_table_end);
5394   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
5395   br(tmp2);
5396 
5397   for (int i = -zva_length + 16; i < 0; i += 16)
5398     stp(zr, zr, Address(base, i));
5399   bind(initial_table_end);
5400 
5401   sub(cnt, cnt, zva_length >> 3);
5402   bind(loop_zva);
5403   dc(Assembler::ZVA, base);
5404   subs(cnt, cnt, zva_length >> 3);
5405   add(base, base, zva_length);
5406   br(Assembler::GE, loop_zva);
5407   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
5408   bind(fini);
5409 }
5410 
5411 // base:   Address of a buffer to be filled, 8 bytes aligned.
5412 // cnt:    Count in 8-byte unit.
5413 // value:  Value to be filled with.
5414 // base will point to the end of the buffer after filling.
5415 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
5416 {
5417 //  Algorithm:
5418 //
5419 //    scratch1 = cnt & 7;
5420 //    cnt -= scratch1;
5421 //    p += scratch1;
5422 //    switch (scratch1) {
5423 //      do {
5424 //        cnt -= 8;
5425 //          p[-8] = v;
5426 //        case 7:
5427 //          p[-7] = v;
5428 //        case 6:
5429 //          p[-6] = v;
5430 //          // ...
5431 //        case 1:
5432 //          p[-1] = v;
5433 //        case 0:
5434 //          p += 8;
5435 //      } while (cnt);
5436 //    }
5437 
5438   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
5439 
5440   Label fini, skip, entry, loop;
5441   const int unroll = 8; // Number of stp instructions we'll unroll
5442 
5443   cbz(cnt, fini);
5444   tbz(base, 3, skip);
5445   str(value, Address(post(base, 8)));
5446   sub(cnt, cnt, 1);
5447   bind(skip);
5448 
5449   andr(rscratch1, cnt, (unroll-1) * 2);
5450   sub(cnt, cnt, rscratch1);
5451   add(base, base, rscratch1, Assembler::LSL, 3);
5452   adr(rscratch2, entry);
5453   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
5454   br(rscratch2);
5455 
5456   bind(loop);
5457   add(base, base, unroll * 16);
5458   for (int i = -unroll; i < 0; i++)
5459     stp(value, value, Address(base, i * 16));
5460   bind(entry);
5461   subs(cnt, cnt, unroll * 2);
5462   br(Assembler::GE, loop);
5463 
5464   tbz(cnt, 0, fini);
5465   str(value, Address(post(base, 8)));
5466   bind(fini);
5467 }
5468 
5469 // Intrinsic for sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray and
5470 // java/lang/StringUTF16.compress.
5471 void MacroAssembler::encode_iso_array(Register src, Register dst,
5472                       Register len, Register result,
5473                       FloatRegister Vtmp1, FloatRegister Vtmp2,
5474                       FloatRegister Vtmp3, FloatRegister Vtmp4)
5475 {
5476     Label DONE, NEXT_32, LOOP_8, NEXT_8, LOOP_1, NEXT_1;
5477     Register tmp1 = rscratch1;
5478 
5479       mov(result, len); // Save initial len
5480 
5481 #ifndef BUILTIN_SIM
5482       subs(len, len, 32);
5483       br(LT, LOOP_8);
5484 
5485 // The following code uses the SIMD 'uqxtn' and 'uqxtn2' instructions
5486 // to convert chars to bytes. These set the 'QC' bit in the FPSR if
5487 // any char could not fit in a byte, so clear the FPSR so we can test it.
5488       clear_fpsr();
5489 
5490     BIND(NEXT_32);
5491       ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
5492       uqxtn(Vtmp1, T8B, Vtmp1, T8H);  // uqxtn  - write bottom half
5493       uqxtn(Vtmp1, T16B, Vtmp2, T8H); // uqxtn2 - write top half
5494       uqxtn(Vtmp2, T8B, Vtmp3, T8H);
5495       uqxtn(Vtmp2, T16B, Vtmp4, T8H); // uqxtn2
5496       get_fpsr(tmp1);
5497       cbnzw(tmp1, LOOP_8);
5498       st1(Vtmp1, Vtmp2, T16B, post(dst, 32));
5499       subs(len, len, 32);
5500       add(src, src, 64);
5501       br(GE, NEXT_32);
5502 
5503     BIND(LOOP_8);
5504       adds(len, len, 32-8);
5505       br(LT, LOOP_1);
5506       clear_fpsr(); // QC may be set from loop above, clear again
5507     BIND(NEXT_8);
5508       ld1(Vtmp1, T8H, src);
5509       uqxtn(Vtmp1, T8B, Vtmp1, T8H);
5510       get_fpsr(tmp1);
5511       cbnzw(tmp1, LOOP_1);
5512       st1(Vtmp1, T8B, post(dst, 8));
5513       subs(len, len, 8);
5514       add(src, src, 16);
5515       br(GE, NEXT_8);
5516 
5517     BIND(LOOP_1);
5518       adds(len, len, 8);
5519       br(LE, DONE);
5520 #else
5521       cbz(len, DONE);
5522 #endif
5523     BIND(NEXT_1);
5524       ldrh(tmp1, Address(post(src, 2)));
5525       tst(tmp1, 0xff00);
5526       br(NE, DONE);
5527       strb(tmp1, Address(post(dst, 1)));
5528       subs(len, len, 1);
5529       br(GT, NEXT_1);
5530 
5531     BIND(DONE);
5532       sub(result, result, len); // Return index where we stopped
5533                                 // Return len == 0 if we processed all
5534                                 // characters
5535 }
5536 
5537 
5538 // Inflate byte[] array to char[].
5539 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5540                                         FloatRegister vtmp1, FloatRegister vtmp2, FloatRegister vtmp3,
5541                                         Register tmp4) {
5542   Label big, done;
5543 
5544   assert_different_registers(src, dst, len, tmp4, rscratch1);
5545 
5546   fmovd(vtmp1 , zr);
5547   lsrw(rscratch1, len, 3);
5548 
5549   cbnzw(rscratch1, big);
5550 
5551   // Short string: less than 8 bytes.
5552   {
5553     Label loop, around, tiny;
5554 
5555     subsw(len, len, 4);
5556     andw(len, len, 3);
5557     br(LO, tiny);
5558 
5559     // Use SIMD to do 4 bytes.
5560     ldrs(vtmp2, post(src, 4));
5561     zip1(vtmp3, T8B, vtmp2, vtmp1);
5562     strd(vtmp3, post(dst, 8));
5563 
5564     cbzw(len, done);
5565 
5566     // Do the remaining bytes by steam.
5567     bind(loop);
5568     ldrb(tmp4, post(src, 1));
5569     strh(tmp4, post(dst, 2));
5570     subw(len, len, 1);
5571 
5572     bind(tiny);
5573     cbnz(len, loop);
5574 
5575     bind(around);
5576     b(done);
5577   }
5578 
5579   // Unpack the bytes 8 at a time.
5580   bind(big);
5581   andw(len, len, 7);
5582 
5583   {
5584     Label loop, around;
5585 
5586     bind(loop);
5587     ldrd(vtmp2, post(src, 8));
5588     sub(rscratch1, rscratch1, 1);
5589     zip1(vtmp3, T16B, vtmp2, vtmp1);
5590     st1(vtmp3, T8H, post(dst, 16));
5591     cbnz(rscratch1, loop);
5592 
5593     bind(around);
5594   }
5595 
5596   // Do the tail of up to 8 bytes.
5597   sub(src, src, 8);
5598   add(src, src, len, ext::uxtw, 0);
5599   ldrd(vtmp2, Address(src));
5600   sub(dst, dst, 16);
5601   add(dst, dst, len, ext::uxtw, 1);
5602   zip1(vtmp3, T16B, vtmp2, vtmp1);
5603   st1(vtmp3, T8H, Address(dst));
5604 
5605   bind(done);
5606 }
5607 
5608 // Compress char[] array to byte[].
5609 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5610                                          FloatRegister tmp1Reg, FloatRegister tmp2Reg,
5611                                          FloatRegister tmp3Reg, FloatRegister tmp4Reg,
5612                                          Register result) {
5613   encode_iso_array(src, dst, len, result,
5614                    tmp1Reg, tmp2Reg, tmp3Reg, tmp4Reg);
5615   cmp(len, zr);
5616   csel(result, result, zr, EQ);
5617 }
5618 
5619 // get_thread() can be called anywhere inside generated code so we
5620 // need to save whatever non-callee save context might get clobbered
5621 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5622 // the call setup code.
5623 //
5624 // aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5625 //
5626 void MacroAssembler::get_thread(Register dst) {
5627   RegSet saved_regs = RegSet::range(r0, r1) + lr - dst;
5628   push(saved_regs, sp);
5629 
5630   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5631   blrt(lr, 1, 0, 1);
5632   if (dst != c_rarg0) {
5633     mov(dst, c_rarg0);
5634   }
5635 
5636   pop(saved_regs, sp);
5637 }