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