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