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