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