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