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