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