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