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