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