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