1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2015, Red Hat Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include <sys/types.h>
  27 
  28 #include "precompiled.hpp"
  29 #include "asm/assembler.hpp"
  30 #include "asm/assembler.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 
  33 #include "compiler/disassembler.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "nativeInst_aarch64.hpp"
  36 #include "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/g1/g1CollectedHeap.inline.hpp"
  45 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  46 #include "gc/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 // Macro to mov replicated immediate to vector register.
1412 //  Vd will get the following values for different arrangements in T
1413 //   imm32 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
1414 //   imm32 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
1415 //   imm32 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
1416 //   imm32 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
1417 //   imm32 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
1418 //   imm32 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
1419 //   T1D/T2D: invalid
1420 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, u_int32_t imm32) {
1421   assert(T != T1D && T != T2D, "invalid arrangement");
1422   if (T == T8B || T == T16B) {
1423     assert((imm32 & ~0xff) == 0, "extraneous bits in unsigned imm32 (T8B/T16B)");
1424     movi(Vd, T, imm32 & 0xff, 0);
1425     return;
1426   }
1427   u_int32_t nimm32 = ~imm32;
1428   if (T == T4H || T == T8H) {
1429     assert((imm32  & ~0xffff) == 0, "extraneous bits in unsigned imm32 (T4H/T8H)");
1430     imm32 &= 0xffff;
1431     nimm32 &= 0xffff;
1432   }
1433   u_int32_t x = imm32;
1434   int movi_cnt = 0;
1435   int movn_cnt = 0;
1436   while (x) { if (x & 0xff) movi_cnt++; x >>= 8; }
1437   x = nimm32;
1438   while (x) { if (x & 0xff) movn_cnt++; x >>= 8; }
1439   if (movn_cnt < movi_cnt) imm32 = nimm32;
1440   unsigned lsl = 0;
1441   while (imm32 && (imm32 & 0xff) == 0) { lsl += 8; imm32 >>= 8; }
1442   if (movn_cnt < movi_cnt)
1443     mvni(Vd, T, imm32 & 0xff, lsl);
1444   else
1445     movi(Vd, T, imm32 & 0xff, lsl);
1446   imm32 >>= 8; lsl += 8;
1447   while (imm32) {
1448     while ((imm32 & 0xff) == 0) { lsl += 8; imm32 >>= 8; }
1449     if (movn_cnt < movi_cnt)
1450       bici(Vd, T, imm32 & 0xff, lsl);
1451     else
1452       orri(Vd, T, imm32 & 0xff, lsl);
1453     lsl += 8; imm32 >>= 8;
1454   }
1455 }
1456 
1457 void MacroAssembler::mov_immediate64(Register dst, u_int64_t imm64)
1458 {
1459 #ifndef PRODUCT
1460   {
1461     char buffer[64];
1462     snprintf(buffer, sizeof(buffer), "0x%"PRIX64, imm64);
1463     block_comment(buffer);
1464   }
1465 #endif
1466   if (operand_valid_for_logical_immediate(false, imm64)) {
1467     orr(dst, zr, imm64);
1468   } else {
1469     // we can use a combination of MOVZ or MOVN with
1470     // MOVK to build up the constant
1471     u_int64_t imm_h[4];
1472     int zero_count = 0;
1473     int neg_count = 0;
1474     int i;
1475     for (i = 0; i < 4; i++) {
1476       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
1477       if (imm_h[i] == 0) {
1478         zero_count++;
1479       } else if (imm_h[i] == 0xffffL) {
1480         neg_count++;
1481       }
1482     }
1483     if (zero_count == 4) {
1484       // one MOVZ will do
1485       movz(dst, 0);
1486     } else if (neg_count == 4) {
1487       // one MOVN will do
1488       movn(dst, 0);
1489     } else if (zero_count == 3) {
1490       for (i = 0; i < 4; i++) {
1491         if (imm_h[i] != 0L) {
1492           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1493           break;
1494         }
1495       }
1496     } else if (neg_count == 3) {
1497       // one MOVN will do
1498       for (int i = 0; i < 4; i++) {
1499         if (imm_h[i] != 0xffffL) {
1500           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1501           break;
1502         }
1503       }
1504     } else if (zero_count == 2) {
1505       // one MOVZ and one MOVK will do
1506       for (i = 0; i < 3; i++) {
1507         if (imm_h[i] != 0L) {
1508           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1509           i++;
1510           break;
1511         }
1512       }
1513       for (;i < 4; i++) {
1514         if (imm_h[i] != 0L) {
1515           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1516         }
1517       }
1518     } else if (neg_count == 2) {
1519       // one MOVN and one MOVK will do
1520       for (i = 0; i < 4; i++) {
1521         if (imm_h[i] != 0xffffL) {
1522           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1523           i++;
1524           break;
1525         }
1526       }
1527       for (;i < 4; i++) {
1528         if (imm_h[i] != 0xffffL) {
1529           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1530         }
1531       }
1532     } else if (zero_count == 1) {
1533       // one MOVZ and two MOVKs will do
1534       for (i = 0; i < 4; i++) {
1535         if (imm_h[i] != 0L) {
1536           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1537           i++;
1538           break;
1539         }
1540       }
1541       for (;i < 4; i++) {
1542         if (imm_h[i] != 0x0L) {
1543           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1544         }
1545       }
1546     } else if (neg_count == 1) {
1547       // one MOVN and two MOVKs will do
1548       for (i = 0; i < 4; i++) {
1549         if (imm_h[i] != 0xffffL) {
1550           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1551           i++;
1552           break;
1553         }
1554       }
1555       for (;i < 4; i++) {
1556         if (imm_h[i] != 0xffffL) {
1557           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1558         }
1559       }
1560     } else {
1561       // use a MOVZ and 3 MOVKs (makes it easier to debug)
1562       movz(dst, (u_int32_t)imm_h[0], 0);
1563       for (i = 1; i < 4; i++) {
1564         movk(dst, (u_int32_t)imm_h[i], (i << 4));
1565       }
1566     }
1567   }
1568 }
1569 
1570 void MacroAssembler::mov_immediate32(Register dst, u_int32_t imm32)
1571 {
1572 #ifndef PRODUCT
1573     {
1574       char buffer[64];
1575       snprintf(buffer, sizeof(buffer), "0x%"PRIX32, imm32);
1576       block_comment(buffer);
1577     }
1578 #endif
1579   if (operand_valid_for_logical_immediate(true, imm32)) {
1580     orrw(dst, zr, imm32);
1581   } else {
1582     // we can use MOVZ, MOVN or two calls to MOVK to build up the
1583     // constant
1584     u_int32_t imm_h[2];
1585     imm_h[0] = imm32 & 0xffff;
1586     imm_h[1] = ((imm32 >> 16) & 0xffff);
1587     if (imm_h[0] == 0) {
1588       movzw(dst, imm_h[1], 16);
1589     } else if (imm_h[0] == 0xffff) {
1590       movnw(dst, imm_h[1] ^ 0xffff, 16);
1591     } else if (imm_h[1] == 0) {
1592       movzw(dst, imm_h[0], 0);
1593     } else if (imm_h[1] == 0xffff) {
1594       movnw(dst, imm_h[0] ^ 0xffff, 0);
1595     } else {
1596       // use a MOVZ and MOVK (makes it easier to debug)
1597       movzw(dst, imm_h[0], 0);
1598       movkw(dst, imm_h[1], 16);
1599     }
1600   }
1601 }
1602 
1603 // Form an address from base + offset in Rd.  Rd may or may
1604 // not actually be used: you must use the Address that is returned.
1605 // It is up to you to ensure that the shift provided matches the size
1606 // of your data.
1607 Address MacroAssembler::form_address(Register Rd, Register base, long byte_offset, int shift) {
1608   if (Address::offset_ok_for_immed(byte_offset, shift))
1609     // It fits; no need for any heroics
1610     return Address(base, byte_offset);
1611 
1612   // Don't do anything clever with negative or misaligned offsets
1613   unsigned mask = (1 << shift) - 1;
1614   if (byte_offset < 0 || byte_offset & mask) {
1615     mov(Rd, byte_offset);
1616     add(Rd, base, Rd);
1617     return Address(Rd);
1618   }
1619 
1620   // See if we can do this with two 12-bit offsets
1621   {
1622     unsigned long word_offset = byte_offset >> shift;
1623     unsigned long masked_offset = word_offset & 0xfff000;
1624     if (Address::offset_ok_for_immed(word_offset - masked_offset)
1625         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
1626       add(Rd, base, masked_offset << shift);
1627       word_offset -= masked_offset;
1628       return Address(Rd, word_offset << shift);
1629     }
1630   }
1631 
1632   // Do it the hard way
1633   mov(Rd, byte_offset);
1634   add(Rd, base, Rd);
1635   return Address(Rd);
1636 }
1637 
1638 void MacroAssembler::atomic_incw(Register counter_addr, Register tmp) {
1639   Label retry_load;
1640   bind(retry_load);
1641   // flush and load exclusive from the memory location
1642   ldxrw(tmp, counter_addr);
1643   addw(tmp, tmp, 1);
1644   // if we store+flush with no intervening write tmp wil be zero
1645   stxrw(tmp, tmp, counter_addr);
1646   cbnzw(tmp, retry_load);
1647 }
1648 
1649 
1650 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
1651                                     bool want_remainder, Register scratch)
1652 {
1653   // Full implementation of Java idiv and irem.  The function
1654   // returns the (pc) offset of the div instruction - may be needed
1655   // for implicit exceptions.
1656   //
1657   // constraint : ra/rb =/= scratch
1658   //         normal case
1659   //
1660   // input : ra: dividend
1661   //         rb: divisor
1662   //
1663   // result: either
1664   //         quotient  (= ra idiv rb)
1665   //         remainder (= ra irem rb)
1666 
1667   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1668 
1669   int idivl_offset = offset();
1670   if (! want_remainder) {
1671     sdivw(result, ra, rb);
1672   } else {
1673     sdivw(scratch, ra, rb);
1674     Assembler::msubw(result, scratch, rb, ra);
1675   }
1676 
1677   return idivl_offset;
1678 }
1679 
1680 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
1681                                     bool want_remainder, Register scratch)
1682 {
1683   // Full implementation of Java ldiv and lrem.  The function
1684   // returns the (pc) offset of the div instruction - may be needed
1685   // for implicit exceptions.
1686   //
1687   // constraint : ra/rb =/= scratch
1688   //         normal case
1689   //
1690   // input : ra: dividend
1691   //         rb: divisor
1692   //
1693   // result: either
1694   //         quotient  (= ra idiv rb)
1695   //         remainder (= ra irem rb)
1696 
1697   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1698 
1699   int idivq_offset = offset();
1700   if (! want_remainder) {
1701     sdiv(result, ra, rb);
1702   } else {
1703     sdiv(scratch, ra, rb);
1704     Assembler::msub(result, scratch, rb, ra);
1705   }
1706 
1707   return idivq_offset;
1708 }
1709 
1710 // MacroAssembler routines found actually to be needed
1711 
1712 void MacroAssembler::push(Register src)
1713 {
1714   str(src, Address(pre(esp, -1 * wordSize)));
1715 }
1716 
1717 void MacroAssembler::pop(Register dst)
1718 {
1719   ldr(dst, Address(post(esp, 1 * wordSize)));
1720 }
1721 
1722 // Note: load_unsigned_short used to be called load_unsigned_word.
1723 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
1724   int off = offset();
1725   ldrh(dst, src);
1726   return off;
1727 }
1728 
1729 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
1730   int off = offset();
1731   ldrb(dst, src);
1732   return off;
1733 }
1734 
1735 int MacroAssembler::load_signed_short(Register dst, Address src) {
1736   int off = offset();
1737   ldrsh(dst, src);
1738   return off;
1739 }
1740 
1741 int MacroAssembler::load_signed_byte(Register dst, Address src) {
1742   int off = offset();
1743   ldrsb(dst, src);
1744   return off;
1745 }
1746 
1747 int MacroAssembler::load_signed_short32(Register dst, Address src) {
1748   int off = offset();
1749   ldrshw(dst, src);
1750   return off;
1751 }
1752 
1753 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
1754   int off = offset();
1755   ldrsbw(dst, src);
1756   return off;
1757 }
1758 
1759 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
1760   switch (size_in_bytes) {
1761   case  8:  ldr(dst, src); break;
1762   case  4:  ldrw(dst, src); break;
1763   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
1764   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
1765   default:  ShouldNotReachHere();
1766   }
1767 }
1768 
1769 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
1770   switch (size_in_bytes) {
1771   case  8:  str(src, dst); break;
1772   case  4:  strw(src, dst); break;
1773   case  2:  strh(src, dst); break;
1774   case  1:  strb(src, dst); break;
1775   default:  ShouldNotReachHere();
1776   }
1777 }
1778 
1779 void MacroAssembler::decrementw(Register reg, int value)
1780 {
1781   if (value < 0)  { incrementw(reg, -value);      return; }
1782   if (value == 0) {                               return; }
1783   if (value < (1 << 12)) { subw(reg, reg, value); return; }
1784   /* else */ {
1785     guarantee(reg != rscratch2, "invalid dst for register decrement");
1786     movw(rscratch2, (unsigned)value);
1787     subw(reg, reg, rscratch2);
1788   }
1789 }
1790 
1791 void MacroAssembler::decrement(Register reg, int value)
1792 {
1793   if (value < 0)  { increment(reg, -value);      return; }
1794   if (value == 0) {                              return; }
1795   if (value < (1 << 12)) { sub(reg, reg, value); return; }
1796   /* else */ {
1797     assert(reg != rscratch2, "invalid dst for register decrement");
1798     mov(rscratch2, (unsigned long)value);
1799     sub(reg, reg, rscratch2);
1800   }
1801 }
1802 
1803 void MacroAssembler::decrementw(Address dst, int value)
1804 {
1805   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
1806   ldrw(rscratch1, dst);
1807   decrementw(rscratch1, value);
1808   strw(rscratch1, dst);
1809 }
1810 
1811 void MacroAssembler::decrement(Address dst, int value)
1812 {
1813   assert(!dst.uses(rscratch1), "invalid address for decrement");
1814   ldr(rscratch1, dst);
1815   decrement(rscratch1, value);
1816   str(rscratch1, dst);
1817 }
1818 
1819 void MacroAssembler::incrementw(Register reg, int value)
1820 {
1821   if (value < 0)  { decrementw(reg, -value);      return; }
1822   if (value == 0) {                               return; }
1823   if (value < (1 << 12)) { addw(reg, reg, value); return; }
1824   /* else */ {
1825     assert(reg != rscratch2, "invalid dst for register increment");
1826     movw(rscratch2, (unsigned)value);
1827     addw(reg, reg, rscratch2);
1828   }
1829 }
1830 
1831 void MacroAssembler::increment(Register reg, int value)
1832 {
1833   if (value < 0)  { decrement(reg, -value);      return; }
1834   if (value == 0) {                              return; }
1835   if (value < (1 << 12)) { add(reg, reg, value); return; }
1836   /* else */ {
1837     assert(reg != rscratch2, "invalid dst for register increment");
1838     movw(rscratch2, (unsigned)value);
1839     add(reg, reg, rscratch2);
1840   }
1841 }
1842 
1843 void MacroAssembler::incrementw(Address dst, int value)
1844 {
1845   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1846   ldrw(rscratch1, dst);
1847   incrementw(rscratch1, value);
1848   strw(rscratch1, dst);
1849 }
1850 
1851 void MacroAssembler::increment(Address dst, int value)
1852 {
1853   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1854   ldr(rscratch1, dst);
1855   increment(rscratch1, value);
1856   str(rscratch1, dst);
1857 }
1858 
1859 
1860 void MacroAssembler::pusha() {
1861   push(0x7fffffff, sp);
1862 }
1863 
1864 void MacroAssembler::popa() {
1865   pop(0x7fffffff, sp);
1866 }
1867 
1868 // Push lots of registers in the bit set supplied.  Don't push sp.
1869 // Return the number of words pushed
1870 int MacroAssembler::push(unsigned int bitset, Register stack) {
1871   int words_pushed = 0;
1872 
1873   // Scan bitset to accumulate register pairs
1874   unsigned char regs[32];
1875   int count = 0;
1876   for (int reg = 0; reg <= 30; reg++) {
1877     if (1 & bitset)
1878       regs[count++] = reg;
1879     bitset >>= 1;
1880   }
1881   regs[count++] = zr->encoding_nocheck();
1882   count &= ~1;  // Only push an even nuber of regs
1883 
1884   if (count) {
1885     stp(as_Register(regs[0]), as_Register(regs[1]),
1886        Address(pre(stack, -count * wordSize)));
1887     words_pushed += 2;
1888   }
1889   for (int i = 2; i < count; i += 2) {
1890     stp(as_Register(regs[i]), as_Register(regs[i+1]),
1891        Address(stack, i * wordSize));
1892     words_pushed += 2;
1893   }
1894 
1895   assert(words_pushed == count, "oops, pushed != count");
1896 
1897   return count;
1898 }
1899 
1900 int MacroAssembler::pop(unsigned int bitset, Register stack) {
1901   int words_pushed = 0;
1902 
1903   // Scan bitset to accumulate register pairs
1904   unsigned char regs[32];
1905   int count = 0;
1906   for (int reg = 0; reg <= 30; reg++) {
1907     if (1 & bitset)
1908       regs[count++] = reg;
1909     bitset >>= 1;
1910   }
1911   regs[count++] = zr->encoding_nocheck();
1912   count &= ~1;
1913 
1914   for (int i = 2; i < count; i += 2) {
1915     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
1916        Address(stack, i * wordSize));
1917     words_pushed += 2;
1918   }
1919   if (count) {
1920     ldp(as_Register(regs[0]), as_Register(regs[1]),
1921        Address(post(stack, count * wordSize)));
1922     words_pushed += 2;
1923   }
1924 
1925   assert(words_pushed == count, "oops, pushed != count");
1926 
1927   return count;
1928 }
1929 #ifdef ASSERT
1930 void MacroAssembler::verify_heapbase(const char* msg) {
1931 #if 0
1932   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
1933   assert (Universe::heap() != NULL, "java heap should be initialized");
1934   if (CheckCompressedOops) {
1935     Label ok;
1936     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
1937     cmpptr(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
1938     br(Assembler::EQ, ok);
1939     stop(msg);
1940     bind(ok);
1941     pop(1 << rscratch1->encoding(), sp);
1942   }
1943 #endif
1944 }
1945 #endif
1946 
1947 void MacroAssembler::stop(const char* msg) {
1948   address ip = pc();
1949   pusha();
1950   mov(c_rarg0, (address)msg);
1951   mov(c_rarg1, (address)ip);
1952   mov(c_rarg2, sp);
1953   mov(c_rarg3, CAST_FROM_FN_PTR(address, MacroAssembler::debug64));
1954   // call(c_rarg3);
1955   blrt(c_rarg3, 3, 0, 1);
1956   hlt(0);
1957 }
1958 
1959 // If a constant does not fit in an immediate field, generate some
1960 // number of MOV instructions and then perform the operation.
1961 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, unsigned imm,
1962                                            add_sub_imm_insn insn1,
1963                                            add_sub_reg_insn insn2) {
1964   assert(Rd != zr, "Rd = zr and not setting flags?");
1965   if (operand_valid_for_add_sub_immediate((int)imm)) {
1966     (this->*insn1)(Rd, Rn, imm);
1967   } else {
1968     if (uabs(imm) < (1 << 24)) {
1969        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
1970        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
1971     } else {
1972        assert_different_registers(Rd, Rn);
1973        mov(Rd, (uint64_t)imm);
1974        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
1975     }
1976   }
1977 }
1978 
1979 // Seperate vsn which sets the flags. Optimisations are more restricted
1980 // because we must set the flags correctly.
1981 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, unsigned imm,
1982                                            add_sub_imm_insn insn1,
1983                                            add_sub_reg_insn insn2) {
1984   if (operand_valid_for_add_sub_immediate((int)imm)) {
1985     (this->*insn1)(Rd, Rn, imm);
1986   } else {
1987     assert_different_registers(Rd, Rn);
1988     assert(Rd != zr, "overflow in immediate operand");
1989     mov(Rd, (uint64_t)imm);
1990     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
1991   }
1992 }
1993 
1994 
1995 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
1996   if (increment.is_register()) {
1997     add(Rd, Rn, increment.as_register());
1998   } else {
1999     add(Rd, Rn, increment.as_constant());
2000   }
2001 }
2002 
2003 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2004   if (increment.is_register()) {
2005     addw(Rd, Rn, increment.as_register());
2006   } else {
2007     addw(Rd, Rn, increment.as_constant());
2008   }
2009 }
2010 
2011 void MacroAssembler::reinit_heapbase()
2012 {
2013   if (UseCompressedOops) {
2014     if (Universe::is_fully_initialized()) {
2015       mov(rheapbase, Universe::narrow_ptrs_base());
2016     } else {
2017       lea(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
2018       ldr(rheapbase, Address(rheapbase));
2019     }
2020   }
2021 }
2022 
2023 // this simulates the behaviour of the x86 cmpxchg instruction using a
2024 // load linked/store conditional pair. we use the acquire/release
2025 // versions of these instructions so that we flush pending writes as
2026 // per Java semantics.
2027 
2028 // n.b the x86 version assumes the old value to be compared against is
2029 // in rax and updates rax with the value located in memory if the
2030 // cmpxchg fails. we supply a register for the old value explicitly
2031 
2032 // the aarch64 load linked/store conditional instructions do not
2033 // accept an offset. so, unlike x86, we must provide a plain register
2034 // to identify the memory word to be compared/exchanged rather than a
2035 // register+offset Address.
2036 
2037 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2038                                 Label &succeed, Label *fail) {
2039   // oldv holds comparison value
2040   // newv holds value to write in exchange
2041   // addr identifies memory word to compare against/update
2042   // tmp returns 0/1 for success/failure
2043   Label retry_load, nope;
2044 
2045   bind(retry_load);
2046   // flush and load exclusive from the memory location
2047   // and fail if it is not what we expect
2048   ldaxr(tmp, addr);
2049   cmp(tmp, oldv);
2050   br(Assembler::NE, nope);
2051   // if we store+flush with no intervening write tmp wil be zero
2052   stlxr(tmp, newv, addr);
2053   cbzw(tmp, succeed);
2054   // retry so we only ever return after a load fails to compare
2055   // ensures we don't return a stale value after a failed write.
2056   b(retry_load);
2057   // if the memory word differs we return it in oldv and signal a fail
2058   bind(nope);
2059   membar(AnyAny);
2060   mov(oldv, tmp);
2061   if (fail)
2062     b(*fail);
2063 }
2064 
2065 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2066                                 Label &succeed, Label *fail) {
2067   // oldv holds comparison value
2068   // newv holds value to write in exchange
2069   // addr identifies memory word to compare against/update
2070   // tmp returns 0/1 for success/failure
2071   Label retry_load, nope;
2072 
2073   bind(retry_load);
2074   // flush and load exclusive from the memory location
2075   // and fail if it is not what we expect
2076   ldaxrw(tmp, addr);
2077   cmp(tmp, oldv);
2078   br(Assembler::NE, nope);
2079   // if we store+flush with no intervening write tmp wil be zero
2080   stlxrw(tmp, newv, addr);
2081   cbzw(tmp, succeed);
2082   // retry so we only ever return after a load fails to compare
2083   // ensures we don't return a stale value after a failed write.
2084   b(retry_load);
2085   // if the memory word differs we return it in oldv and signal a fail
2086   bind(nope);
2087   membar(AnyAny);
2088   mov(oldv, tmp);
2089   if (fail)
2090     b(*fail);
2091 }
2092 
2093 static bool different(Register a, RegisterOrConstant b, Register c) {
2094   if (b.is_constant())
2095     return a != c;
2096   else
2097     return a != b.as_register() && a != c && b.as_register() != c;
2098 }
2099 
2100 #define ATOMIC_OP(LDXR, OP, STXR)                                       \
2101 void MacroAssembler::atomic_##OP(Register prev, RegisterOrConstant incr, Register addr) { \
2102   Register result = rscratch2;                                          \
2103   if (prev->is_valid())                                                 \
2104     result = different(prev, incr, addr) ? prev : rscratch2;            \
2105                                                                         \
2106   Label retry_load;                                                     \
2107   bind(retry_load);                                                     \
2108   LDXR(result, addr);                                                   \
2109   OP(rscratch1, result, incr);                                          \
2110   STXR(rscratch1, rscratch1, addr);                                     \
2111   cbnzw(rscratch1, retry_load);                                         \
2112   if (prev->is_valid() && prev != result)                               \
2113     mov(prev, result);                                                  \
2114 }
2115 
2116 ATOMIC_OP(ldxr, add, stxr)
2117 ATOMIC_OP(ldxrw, addw, stxrw)
2118 
2119 #undef ATOMIC_OP
2120 
2121 #define ATOMIC_XCHG(OP, LDXR, STXR)                                     \
2122 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2123   Register result = rscratch2;                                          \
2124   if (prev->is_valid())                                                 \
2125     result = different(prev, newv, addr) ? prev : rscratch2;            \
2126                                                                         \
2127   Label retry_load;                                                     \
2128   bind(retry_load);                                                     \
2129   LDXR(result, addr);                                                   \
2130   STXR(rscratch1, newv, addr);                                          \
2131   cbnzw(rscratch1, retry_load);                                         \
2132   if (prev->is_valid() && prev != result)                               \
2133     mov(prev, result);                                                  \
2134 }
2135 
2136 ATOMIC_XCHG(xchg, ldxr, stxr)
2137 ATOMIC_XCHG(xchgw, ldxrw, stxrw)
2138 
2139 #undef ATOMIC_XCHG
2140 
2141 void MacroAssembler::incr_allocated_bytes(Register thread,
2142                                           Register var_size_in_bytes,
2143                                           int con_size_in_bytes,
2144                                           Register t1) {
2145   if (!thread->is_valid()) {
2146     thread = rthread;
2147   }
2148   assert(t1->is_valid(), "need temp reg");
2149 
2150   ldr(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2151   if (var_size_in_bytes->is_valid()) {
2152     add(t1, t1, var_size_in_bytes);
2153   } else {
2154     add(t1, t1, con_size_in_bytes);
2155   }
2156   str(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2157 }
2158 
2159 #ifndef PRODUCT
2160 extern "C" void findpc(intptr_t x);
2161 #endif
2162 
2163 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2164 {
2165   // In order to get locks to work, we need to fake a in_VM state
2166   if (ShowMessageBoxOnError ) {
2167     JavaThread* thread = JavaThread::current();
2168     JavaThreadState saved_state = thread->thread_state();
2169     thread->set_thread_state(_thread_in_vm);
2170 #ifndef PRODUCT
2171     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2172       ttyLocker ttyl;
2173       BytecodeCounter::print();
2174     }
2175 #endif
2176     if (os::message_box(msg, "Execution stopped, print registers?")) {
2177       ttyLocker ttyl;
2178       tty->print_cr(" pc = 0x%016lx", pc);
2179 #ifndef PRODUCT
2180       tty->cr();
2181       findpc(pc);
2182       tty->cr();
2183 #endif
2184       tty->print_cr(" r0 = 0x%016lx", regs[0]);
2185       tty->print_cr(" r1 = 0x%016lx", regs[1]);
2186       tty->print_cr(" r2 = 0x%016lx", regs[2]);
2187       tty->print_cr(" r3 = 0x%016lx", regs[3]);
2188       tty->print_cr(" r4 = 0x%016lx", regs[4]);
2189       tty->print_cr(" r5 = 0x%016lx", regs[5]);
2190       tty->print_cr(" r6 = 0x%016lx", regs[6]);
2191       tty->print_cr(" r7 = 0x%016lx", regs[7]);
2192       tty->print_cr(" r8 = 0x%016lx", regs[8]);
2193       tty->print_cr(" r9 = 0x%016lx", regs[9]);
2194       tty->print_cr("r10 = 0x%016lx", regs[10]);
2195       tty->print_cr("r11 = 0x%016lx", regs[11]);
2196       tty->print_cr("r12 = 0x%016lx", regs[12]);
2197       tty->print_cr("r13 = 0x%016lx", regs[13]);
2198       tty->print_cr("r14 = 0x%016lx", regs[14]);
2199       tty->print_cr("r15 = 0x%016lx", regs[15]);
2200       tty->print_cr("r16 = 0x%016lx", regs[16]);
2201       tty->print_cr("r17 = 0x%016lx", regs[17]);
2202       tty->print_cr("r18 = 0x%016lx", regs[18]);
2203       tty->print_cr("r19 = 0x%016lx", regs[19]);
2204       tty->print_cr("r20 = 0x%016lx", regs[20]);
2205       tty->print_cr("r21 = 0x%016lx", regs[21]);
2206       tty->print_cr("r22 = 0x%016lx", regs[22]);
2207       tty->print_cr("r23 = 0x%016lx", regs[23]);
2208       tty->print_cr("r24 = 0x%016lx", regs[24]);
2209       tty->print_cr("r25 = 0x%016lx", regs[25]);
2210       tty->print_cr("r26 = 0x%016lx", regs[26]);
2211       tty->print_cr("r27 = 0x%016lx", regs[27]);
2212       tty->print_cr("r28 = 0x%016lx", regs[28]);
2213       tty->print_cr("r30 = 0x%016lx", regs[30]);
2214       tty->print_cr("r31 = 0x%016lx", regs[31]);
2215       BREAKPOINT;
2216     }
2217     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
2218   } else {
2219     ttyLocker ttyl;
2220     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
2221                     msg);
2222     assert(false, err_msg("DEBUG MESSAGE: %s", msg));
2223   }
2224 }
2225 
2226 #ifdef BUILTIN_SIM
2227 // routine to generate an x86 prolog for a stub function which
2228 // bootstraps into the generated ARM code which directly follows the
2229 // stub
2230 //
2231 // the argument encodes the number of general and fp registers
2232 // passed by the caller and the callng convention (currently just
2233 // the number of general registers and assumes C argument passing)
2234 
2235 extern "C" {
2236 int aarch64_stub_prolog_size();
2237 void aarch64_stub_prolog();
2238 void aarch64_prolog();
2239 }
2240 
2241 void MacroAssembler::c_stub_prolog(int gp_arg_count, int fp_arg_count, int ret_type,
2242                                    address *prolog_ptr)
2243 {
2244   int calltype = (((ret_type & 0x3) << 8) |
2245                   ((fp_arg_count & 0xf) << 4) |
2246                   (gp_arg_count & 0xf));
2247 
2248   // the addresses for the x86 to ARM entry code we need to use
2249   address start = pc();
2250   // printf("start = %lx\n", start);
2251   int byteCount =  aarch64_stub_prolog_size();
2252   // printf("byteCount = %x\n", byteCount);
2253   int instructionCount = (byteCount + 3)/ 4;
2254   // printf("instructionCount = %x\n", instructionCount);
2255   for (int i = 0; i < instructionCount; i++) {
2256     nop();
2257   }
2258 
2259   memcpy(start, (void*)aarch64_stub_prolog, byteCount);
2260 
2261   // write the address of the setup routine and the call format at the
2262   // end of into the copied code
2263   u_int64_t *patch_end = (u_int64_t *)(start + byteCount);
2264   if (prolog_ptr)
2265     patch_end[-2] = (u_int64_t)prolog_ptr;
2266   patch_end[-1] = calltype;
2267 }
2268 #endif
2269 
2270 void MacroAssembler::push_CPU_state() {
2271     push(0x3fffffff, sp);         // integer registers except lr & sp
2272 
2273     for (int i = 30; i >= 0; i -= 2)
2274       stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2275            Address(pre(sp, -2 * wordSize)));
2276 }
2277 
2278 void MacroAssembler::pop_CPU_state() {
2279   for (int i = 0; i < 32; i += 2)
2280     ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2281          Address(post(sp, 2 * wordSize)));
2282 
2283   pop(0x3fffffff, sp);         // integer registers except lr & sp
2284 }
2285 
2286 /**
2287  * Helpers for multiply_to_len().
2288  */
2289 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2290                                      Register src1, Register src2) {
2291   adds(dest_lo, dest_lo, src1);
2292   adc(dest_hi, dest_hi, zr);
2293   adds(dest_lo, dest_lo, src2);
2294   adc(final_dest_hi, dest_hi, zr);
2295 }
2296 
2297 // Generate an address from (r + r1 extend offset).  "size" is the
2298 // size of the operand.  The result may be in rscratch2.
2299 Address MacroAssembler::offsetted_address(Register r, Register r1,
2300                                           Address::extend ext, int offset, int size) {
2301   if (offset || (ext.shift() % size != 0)) {
2302     lea(rscratch2, Address(r, r1, ext));
2303     return Address(rscratch2, offset);
2304   } else {
2305     return Address(r, r1, ext);
2306   }
2307 }
2308 
2309 /**
2310  * Multiply 64 bit by 64 bit first loop.
2311  */
2312 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2313                                            Register y, Register y_idx, Register z,
2314                                            Register carry, Register product,
2315                                            Register idx, Register kdx) {
2316   //
2317   //  jlong carry, x[], y[], z[];
2318   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2319   //    huge_128 product = y[idx] * x[xstart] + carry;
2320   //    z[kdx] = (jlong)product;
2321   //    carry  = (jlong)(product >>> 64);
2322   //  }
2323   //  z[xstart] = carry;
2324   //
2325 
2326   Label L_first_loop, L_first_loop_exit;
2327   Label L_one_x, L_one_y, L_multiply;
2328 
2329   subsw(xstart, xstart, 1);
2330   br(Assembler::MI, L_one_x);
2331 
2332   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2333   ldr(x_xstart, Address(rscratch1));
2334   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2335 
2336   bind(L_first_loop);
2337   subsw(idx, idx, 1);
2338   br(Assembler::MI, L_first_loop_exit);
2339   subsw(idx, idx, 1);
2340   br(Assembler::MI, L_one_y);
2341   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2342   ldr(y_idx, Address(rscratch1));
2343   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2344   bind(L_multiply);
2345 
2346   // AArch64 has a multiply-accumulate instruction that we can't use
2347   // here because it has no way to process carries, so we have to use
2348   // separate add and adc instructions.  Bah.
2349   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2350   mul(product, x_xstart, y_idx);
2351   adds(product, product, carry);
2352   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2353 
2354   subw(kdx, kdx, 2);
2355   ror(product, product, 32); // back to big-endian
2356   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2357 
2358   b(L_first_loop);
2359 
2360   bind(L_one_y);
2361   ldrw(y_idx, Address(y,  0));
2362   b(L_multiply);
2363 
2364   bind(L_one_x);
2365   ldrw(x_xstart, Address(x,  0));
2366   b(L_first_loop);
2367 
2368   bind(L_first_loop_exit);
2369 }
2370 
2371 /**
2372  * Multiply 128 bit by 128. Unrolled inner loop.
2373  *
2374  */
2375 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2376                                              Register carry, Register carry2,
2377                                              Register idx, Register jdx,
2378                                              Register yz_idx1, Register yz_idx2,
2379                                              Register tmp, Register tmp3, Register tmp4,
2380                                              Register tmp6, Register product_hi) {
2381 
2382   //   jlong carry, x[], y[], z[];
2383   //   int kdx = ystart+1;
2384   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2385   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2386   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2387   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2388   //     carry  = (jlong)(tmp4 >>> 64);
2389   //     z[kdx+idx+1] = (jlong)tmp3;
2390   //     z[kdx+idx] = (jlong)tmp4;
2391   //   }
2392   //   idx += 2;
2393   //   if (idx > 0) {
2394   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2395   //     z[kdx+idx] = (jlong)yz_idx1;
2396   //     carry  = (jlong)(yz_idx1 >>> 64);
2397   //   }
2398   //
2399 
2400   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2401 
2402   lsrw(jdx, idx, 2);
2403 
2404   bind(L_third_loop);
2405 
2406   subsw(jdx, jdx, 1);
2407   br(Assembler::MI, L_third_loop_exit);
2408   subw(idx, idx, 4);
2409 
2410   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2411 
2412   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2413 
2414   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2415 
2416   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2417   ror(yz_idx2, yz_idx2, 32);
2418 
2419   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2420 
2421   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2422   umulh(tmp4, product_hi, yz_idx1);
2423 
2424   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2425   ror(rscratch2, rscratch2, 32);
2426 
2427   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2428   umulh(carry2, product_hi, yz_idx2);
2429 
2430   // propagate sum of both multiplications into carry:tmp4:tmp3
2431   adds(tmp3, tmp3, carry);
2432   adc(tmp4, tmp4, zr);
2433   adds(tmp3, tmp3, rscratch1);
2434   adcs(tmp4, tmp4, tmp);
2435   adc(carry, carry2, zr);
2436   adds(tmp4, tmp4, rscratch2);
2437   adc(carry, carry, zr);
2438 
2439   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2440   ror(tmp4, tmp4, 32);
2441   stp(tmp4, tmp3, Address(tmp6, 0));
2442 
2443   b(L_third_loop);
2444   bind (L_third_loop_exit);
2445 
2446   andw (idx, idx, 0x3);
2447   cbz(idx, L_post_third_loop_done);
2448 
2449   Label L_check_1;
2450   subsw(idx, idx, 2);
2451   br(Assembler::MI, L_check_1);
2452 
2453   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2454   ldr(yz_idx1, Address(rscratch1, 0));
2455   ror(yz_idx1, yz_idx1, 32);
2456   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2457   umulh(tmp4, product_hi, yz_idx1);
2458   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2459   ldr(yz_idx2, Address(rscratch1, 0));
2460   ror(yz_idx2, yz_idx2, 32);
2461 
2462   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
2463 
2464   ror(tmp3, tmp3, 32);
2465   str(tmp3, Address(rscratch1, 0));
2466 
2467   bind (L_check_1);
2468 
2469   andw (idx, idx, 0x1);
2470   subsw(idx, idx, 1);
2471   br(Assembler::MI, L_post_third_loop_done);
2472   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2473   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
2474   umulh(carry2, tmp4, product_hi);
2475   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2476 
2477   add2_with_carry(carry2, tmp3, tmp4, carry);
2478 
2479   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2480   extr(carry, carry2, tmp3, 32);
2481 
2482   bind(L_post_third_loop_done);
2483 }
2484 
2485 /**
2486  * Code for BigInteger::multiplyToLen() instrinsic.
2487  *
2488  * r0: x
2489  * r1: xlen
2490  * r2: y
2491  * r3: ylen
2492  * r4:  z
2493  * r5: zlen
2494  * r10: tmp1
2495  * r11: tmp2
2496  * r12: tmp3
2497  * r13: tmp4
2498  * r14: tmp5
2499  * r15: tmp6
2500  * r16: tmp7
2501  *
2502  */
2503 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
2504                                      Register z, Register zlen,
2505                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
2506                                      Register tmp5, Register tmp6, Register product_hi) {
2507 
2508   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
2509 
2510   const Register idx = tmp1;
2511   const Register kdx = tmp2;
2512   const Register xstart = tmp3;
2513 
2514   const Register y_idx = tmp4;
2515   const Register carry = tmp5;
2516   const Register product  = xlen;
2517   const Register x_xstart = zlen;  // reuse register
2518 
2519   // First Loop.
2520   //
2521   //  final static long LONG_MASK = 0xffffffffL;
2522   //  int xstart = xlen - 1;
2523   //  int ystart = ylen - 1;
2524   //  long carry = 0;
2525   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2526   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
2527   //    z[kdx] = (int)product;
2528   //    carry = product >>> 32;
2529   //  }
2530   //  z[xstart] = (int)carry;
2531   //
2532 
2533   movw(idx, ylen);      // idx = ylen;
2534   movw(kdx, zlen);      // kdx = xlen+ylen;
2535   mov(carry, zr);       // carry = 0;
2536 
2537   Label L_done;
2538 
2539   movw(xstart, xlen);
2540   subsw(xstart, xstart, 1);
2541   br(Assembler::MI, L_done);
2542 
2543   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
2544 
2545   Label L_second_loop;
2546   cbzw(kdx, L_second_loop);
2547 
2548   Label L_carry;
2549   subw(kdx, kdx, 1);
2550   cbzw(kdx, L_carry);
2551 
2552   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2553   lsr(carry, carry, 32);
2554   subw(kdx, kdx, 1);
2555 
2556   bind(L_carry);
2557   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2558 
2559   // Second and third (nested) loops.
2560   //
2561   // for (int i = xstart-1; i >= 0; i--) { // Second loop
2562   //   carry = 0;
2563   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
2564   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
2565   //                    (z[k] & LONG_MASK) + carry;
2566   //     z[k] = (int)product;
2567   //     carry = product >>> 32;
2568   //   }
2569   //   z[i] = (int)carry;
2570   // }
2571   //
2572   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
2573 
2574   const Register jdx = tmp1;
2575 
2576   bind(L_second_loop);
2577   mov(carry, zr);                // carry = 0;
2578   movw(jdx, ylen);               // j = ystart+1
2579 
2580   subsw(xstart, xstart, 1);      // i = xstart-1;
2581   br(Assembler::MI, L_done);
2582 
2583   str(z, Address(pre(sp, -4 * wordSize)));
2584 
2585   Label L_last_x;
2586   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
2587   subsw(xstart, xstart, 1);       // i = xstart-1;
2588   br(Assembler::MI, L_last_x);
2589 
2590   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
2591   ldr(product_hi, Address(rscratch1));
2592   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
2593 
2594   Label L_third_loop_prologue;
2595   bind(L_third_loop_prologue);
2596 
2597   str(ylen, Address(sp, wordSize));
2598   stp(x, xstart, Address(sp, 2 * wordSize));
2599   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
2600                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
2601   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
2602   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
2603 
2604   addw(tmp3, xlen, 1);
2605   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2606   subsw(tmp3, tmp3, 1);
2607   br(Assembler::MI, L_done);
2608 
2609   lsr(carry, carry, 32);
2610   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2611   b(L_second_loop);
2612 
2613   // Next infrequent code is moved outside loops.
2614   bind(L_last_x);
2615   ldrw(product_hi, Address(x,  0));
2616   b(L_third_loop_prologue);
2617 
2618   bind(L_done);
2619 }
2620 
2621 /**
2622  * Emits code to update CRC-32 with a byte value according to constants in table
2623  *
2624  * @param [in,out]crc   Register containing the crc.
2625  * @param [in]val       Register containing the byte to fold into the CRC.
2626  * @param [in]table     Register containing the table of crc constants.
2627  *
2628  * uint32_t crc;
2629  * val = crc_table[(val ^ crc) & 0xFF];
2630  * crc = val ^ (crc >> 8);
2631  *
2632  */
2633 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
2634   eor(val, val, crc);
2635   andr(val, val, 0xff);
2636   ldrw(val, Address(table, val, Address::lsl(2)));
2637   eor(crc, val, crc, Assembler::LSR, 8);
2638 }
2639 
2640 /**
2641  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
2642  *
2643  * @param [in,out]crc   Register containing the crc.
2644  * @param [in]v         Register containing the 32-bit to fold into the CRC.
2645  * @param [in]table0    Register containing table 0 of crc constants.
2646  * @param [in]table1    Register containing table 1 of crc constants.
2647  * @param [in]table2    Register containing table 2 of crc constants.
2648  * @param [in]table3    Register containing table 3 of crc constants.
2649  *
2650  * uint32_t crc;
2651  *   v = crc ^ v
2652  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
2653  *
2654  */
2655 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
2656         Register table0, Register table1, Register table2, Register table3,
2657         bool upper) {
2658   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
2659   uxtb(tmp, v);
2660   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
2661   ubfx(tmp, v, 8, 8);
2662   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
2663   eor(crc, crc, tmp);
2664   ubfx(tmp, v, 16, 8);
2665   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
2666   eor(crc, crc, tmp);
2667   ubfx(tmp, v, 24, 8);
2668   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
2669   eor(crc, crc, tmp);
2670 }
2671 
2672 /**
2673  * @param crc   register containing existing CRC (32-bit)
2674  * @param buf   register pointing to input byte buffer (byte*)
2675  * @param len   register containing number of bytes
2676  * @param table register that will contain address of CRC table
2677  * @param tmp   scratch register
2678  */
2679 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
2680         Register table0, Register table1, Register table2, Register table3,
2681         Register tmp, Register tmp2, Register tmp3) {
2682   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
2683   unsigned long offset;
2684 
2685     ornw(crc, zr, crc);
2686 
2687   if (UseCRC32) {
2688     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop;
2689 
2690       subs(len, len, 64);
2691       br(Assembler::GE, CRC_by64_loop);
2692       adds(len, len, 64-4);
2693       br(Assembler::GE, CRC_by4_loop);
2694       adds(len, len, 4);
2695       br(Assembler::GT, CRC_by1_loop);
2696       b(L_exit);
2697 
2698     BIND(CRC_by4_loop);
2699       ldrw(tmp, Address(post(buf, 4)));
2700       subs(len, len, 4);
2701       crc32w(crc, crc, tmp);
2702       br(Assembler::GE, CRC_by4_loop);
2703       adds(len, len, 4);
2704       br(Assembler::LE, L_exit);
2705     BIND(CRC_by1_loop);
2706       ldrb(tmp, Address(post(buf, 1)));
2707       subs(len, len, 1);
2708       crc32b(crc, crc, tmp);
2709       br(Assembler::GT, CRC_by1_loop);
2710       b(L_exit);
2711 
2712       align(CodeEntryAlignment);
2713     BIND(CRC_by64_loop);
2714       subs(len, len, 64);
2715       ldp(tmp, tmp3, Address(post(buf, 16)));
2716       crc32x(crc, crc, tmp);
2717       crc32x(crc, crc, tmp3);
2718       ldp(tmp, tmp3, Address(post(buf, 16)));
2719       crc32x(crc, crc, tmp);
2720       crc32x(crc, crc, tmp3);
2721       ldp(tmp, tmp3, Address(post(buf, 16)));
2722       crc32x(crc, crc, tmp);
2723       crc32x(crc, crc, tmp3);
2724       ldp(tmp, tmp3, Address(post(buf, 16)));
2725       crc32x(crc, crc, tmp);
2726       crc32x(crc, crc, tmp3);
2727       br(Assembler::GE, CRC_by64_loop);
2728       adds(len, len, 64-4);
2729       br(Assembler::GE, CRC_by4_loop);
2730       adds(len, len, 4);
2731       br(Assembler::GT, CRC_by1_loop);
2732     BIND(L_exit);
2733       ornw(crc, zr, crc);
2734       return;
2735   }
2736 
2737     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
2738     if (offset) add(table0, table0, offset);
2739     add(table1, table0, 1*256*sizeof(juint));
2740     add(table2, table0, 2*256*sizeof(juint));
2741     add(table3, table0, 3*256*sizeof(juint));
2742 
2743   if (UseNeon) {
2744       cmp(len, 64);
2745       br(Assembler::LT, L_by16);
2746       eor(v16, T16B, v16, v16);
2747 
2748     Label L_fold;
2749 
2750       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
2751 
2752       ld1(v0, v1, T2D, post(buf, 32));
2753       ld1r(v4, T2D, post(tmp, 8));
2754       ld1r(v5, T2D, post(tmp, 8));
2755       ld1r(v6, T2D, post(tmp, 8));
2756       ld1r(v7, T2D, post(tmp, 8));
2757       mov(v16, T4S, 0, crc);
2758 
2759       eor(v0, T16B, v0, v16);
2760       sub(len, len, 64);
2761 
2762     BIND(L_fold);
2763       pmull(v22, T8H, v0, v5, T8B);
2764       pmull(v20, T8H, v0, v7, T8B);
2765       pmull(v23, T8H, v0, v4, T8B);
2766       pmull(v21, T8H, v0, v6, T8B);
2767 
2768       pmull2(v18, T8H, v0, v5, T16B);
2769       pmull2(v16, T8H, v0, v7, T16B);
2770       pmull2(v19, T8H, v0, v4, T16B);
2771       pmull2(v17, T8H, v0, v6, T16B);
2772 
2773       uzp1(v24, v20, v22, T8H);
2774       uzp2(v25, v20, v22, T8H);
2775       eor(v20, T16B, v24, v25);
2776 
2777       uzp1(v26, v16, v18, T8H);
2778       uzp2(v27, v16, v18, T8H);
2779       eor(v16, T16B, v26, v27);
2780 
2781       ushll2(v22, T4S, v20, T8H, 8);
2782       ushll(v20, T4S, v20, T4H, 8);
2783 
2784       ushll2(v18, T4S, v16, T8H, 8);
2785       ushll(v16, T4S, v16, T4H, 8);
2786 
2787       eor(v22, T16B, v23, v22);
2788       eor(v18, T16B, v19, v18);
2789       eor(v20, T16B, v21, v20);
2790       eor(v16, T16B, v17, v16);
2791 
2792       uzp1(v17, v16, v20, T2D);
2793       uzp2(v21, v16, v20, T2D);
2794       eor(v17, T16B, v17, v21);
2795 
2796       ushll2(v20, T2D, v17, T4S, 16);
2797       ushll(v16, T2D, v17, T2S, 16);
2798 
2799       eor(v20, T16B, v20, v22);
2800       eor(v16, T16B, v16, v18);
2801 
2802       uzp1(v17, v20, v16, T2D);
2803       uzp2(v21, v20, v16, T2D);
2804       eor(v28, T16B, v17, v21);
2805 
2806       pmull(v22, T8H, v1, v5, T8B);
2807       pmull(v20, T8H, v1, v7, T8B);
2808       pmull(v23, T8H, v1, v4, T8B);
2809       pmull(v21, T8H, v1, v6, T8B);
2810 
2811       pmull2(v18, T8H, v1, v5, T16B);
2812       pmull2(v16, T8H, v1, v7, T16B);
2813       pmull2(v19, T8H, v1, v4, T16B);
2814       pmull2(v17, T8H, v1, v6, T16B);
2815 
2816       ld1(v0, v1, T2D, post(buf, 32));
2817 
2818       uzp1(v24, v20, v22, T8H);
2819       uzp2(v25, v20, v22, T8H);
2820       eor(v20, T16B, v24, v25);
2821 
2822       uzp1(v26, v16, v18, T8H);
2823       uzp2(v27, v16, v18, T8H);
2824       eor(v16, T16B, v26, v27);
2825 
2826       ushll2(v22, T4S, v20, T8H, 8);
2827       ushll(v20, T4S, v20, T4H, 8);
2828 
2829       ushll2(v18, T4S, v16, T8H, 8);
2830       ushll(v16, T4S, v16, T4H, 8);
2831 
2832       eor(v22, T16B, v23, v22);
2833       eor(v18, T16B, v19, v18);
2834       eor(v20, T16B, v21, v20);
2835       eor(v16, T16B, v17, v16);
2836 
2837       uzp1(v17, v16, v20, T2D);
2838       uzp2(v21, v16, v20, T2D);
2839       eor(v16, T16B, v17, v21);
2840 
2841       ushll2(v20, T2D, v16, T4S, 16);
2842       ushll(v16, T2D, v16, T2S, 16);
2843 
2844       eor(v20, T16B, v22, v20);
2845       eor(v16, T16B, v16, v18);
2846 
2847       uzp1(v17, v20, v16, T2D);
2848       uzp2(v21, v20, v16, T2D);
2849       eor(v20, T16B, v17, v21);
2850 
2851       shl(v16, T2D, v28, 1);
2852       shl(v17, T2D, v20, 1);
2853 
2854       eor(v0, T16B, v0, v16);
2855       eor(v1, T16B, v1, v17);
2856 
2857       subs(len, len, 32);
2858       br(Assembler::GE, L_fold);
2859 
2860       mov(crc, 0);
2861       mov(tmp, v0, T1D, 0);
2862       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2863       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2864       mov(tmp, v0, T1D, 1);
2865       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2866       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2867       mov(tmp, v1, T1D, 0);
2868       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2869       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2870       mov(tmp, v1, T1D, 1);
2871       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2872       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2873 
2874       add(len, len, 32);
2875   }
2876 
2877   BIND(L_by16);
2878     subs(len, len, 16);
2879     br(Assembler::GE, L_by16_loop);
2880     adds(len, len, 16-4);
2881     br(Assembler::GE, L_by4_loop);
2882     adds(len, len, 4);
2883     br(Assembler::GT, L_by1_loop);
2884     b(L_exit);
2885 
2886   BIND(L_by4_loop);
2887     ldrw(tmp, Address(post(buf, 4)));
2888     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
2889     subs(len, len, 4);
2890     br(Assembler::GE, L_by4_loop);
2891     adds(len, len, 4);
2892     br(Assembler::LE, L_exit);
2893   BIND(L_by1_loop);
2894     subs(len, len, 1);
2895     ldrb(tmp, Address(post(buf, 1)));
2896     update_byte_crc32(crc, tmp, table0);
2897     br(Assembler::GT, L_by1_loop);
2898     b(L_exit);
2899 
2900     align(CodeEntryAlignment);
2901   BIND(L_by16_loop);
2902     subs(len, len, 16);
2903     ldp(tmp, tmp3, Address(post(buf, 16)));
2904     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2905     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2906     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
2907     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
2908     br(Assembler::GE, L_by16_loop);
2909     adds(len, len, 16-4);
2910     br(Assembler::GE, L_by4_loop);
2911     adds(len, len, 4);
2912     br(Assembler::GT, L_by1_loop);
2913   BIND(L_exit);
2914     ornw(crc, zr, crc);
2915 }
2916 
2917 /**
2918  * @param crc   register containing existing CRC (32-bit)
2919  * @param buf   register pointing to input byte buffer (byte*)
2920  * @param len   register containing number of bytes
2921  * @param table register that will contain address of CRC table
2922  * @param tmp   scratch register
2923  */
2924 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
2925         Register table0, Register table1, Register table2, Register table3,
2926         Register tmp, Register tmp2, Register tmp3) {
2927   Label L_exit;
2928   Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop;
2929 
2930     subs(len, len, 64);
2931     br(Assembler::GE, CRC_by64_loop);
2932     adds(len, len, 64-4);
2933     br(Assembler::GE, CRC_by4_loop);
2934     adds(len, len, 4);
2935     br(Assembler::GT, CRC_by1_loop);
2936     b(L_exit);
2937 
2938   BIND(CRC_by4_loop);
2939     ldrw(tmp, Address(post(buf, 4)));
2940     subs(len, len, 4);
2941     crc32cw(crc, crc, tmp);
2942     br(Assembler::GE, CRC_by4_loop);
2943     adds(len, len, 4);
2944     br(Assembler::LE, L_exit);
2945   BIND(CRC_by1_loop);
2946     ldrb(tmp, Address(post(buf, 1)));
2947     subs(len, len, 1);
2948     crc32cb(crc, crc, tmp);
2949     br(Assembler::GT, CRC_by1_loop);
2950     b(L_exit);
2951 
2952     align(CodeEntryAlignment);
2953   BIND(CRC_by64_loop);
2954     subs(len, len, 64);
2955     ldp(tmp, tmp3, Address(post(buf, 16)));
2956     crc32cx(crc, crc, tmp);
2957     crc32cx(crc, crc, tmp3);
2958     ldp(tmp, tmp3, Address(post(buf, 16)));
2959     crc32cx(crc, crc, tmp);
2960     crc32cx(crc, crc, tmp3);
2961     ldp(tmp, tmp3, Address(post(buf, 16)));
2962     crc32cx(crc, crc, tmp);
2963     crc32cx(crc, crc, tmp3);
2964     ldp(tmp, tmp3, Address(post(buf, 16)));
2965     crc32cx(crc, crc, tmp);
2966     crc32cx(crc, crc, tmp3);
2967     br(Assembler::GE, CRC_by64_loop);
2968     adds(len, len, 64-4);
2969     br(Assembler::GE, CRC_by4_loop);
2970     adds(len, len, 4);
2971     br(Assembler::GT, CRC_by1_loop);
2972   BIND(L_exit);
2973     return;
2974 }
2975 
2976 SkipIfEqual::SkipIfEqual(
2977     MacroAssembler* masm, const bool* flag_addr, bool value) {
2978   _masm = masm;
2979   unsigned long offset;
2980   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
2981   _masm->ldrb(rscratch1, Address(rscratch1, offset));
2982   _masm->cbzw(rscratch1, _label);
2983 }
2984 
2985 SkipIfEqual::~SkipIfEqual() {
2986   _masm->bind(_label);
2987 }
2988 
2989 void MacroAssembler::cmpptr(Register src1, Address src2) {
2990   unsigned long offset;
2991   adrp(rscratch1, src2, offset);
2992   ldr(rscratch1, Address(rscratch1, offset));
2993   cmp(src1, rscratch1);
2994 }
2995 
2996 void MacroAssembler::store_check(Register obj, Address dst) {
2997   store_check(obj);
2998 }
2999 
3000 void MacroAssembler::store_check(Register obj) {
3001   // Does a store check for the oop in register obj. The content of
3002   // register obj is destroyed afterwards.
3003 
3004   BarrierSet* bs = Universe::heap()->barrier_set();
3005   assert(bs->kind() == BarrierSet::CardTableModRef, "Wrong barrier set kind");
3006 
3007   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
3008   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3009 
3010   lsr(obj, obj, CardTableModRefBS::card_shift);
3011 
3012   assert(CardTableModRefBS::dirty_card_val() == 0, "must be");
3013 
3014   {
3015     ExternalAddress cardtable((address) ct->byte_map_base);
3016     unsigned long offset;
3017     adrp(rscratch1, cardtable, offset);
3018     assert(offset == 0, "byte_map_base is misaligned");
3019   }
3020 
3021   if (UseCondCardMark) {
3022     Label L_already_dirty;
3023     ldrb(rscratch2,  Address(obj, rscratch1));
3024     cbz(rscratch2, L_already_dirty);
3025     strb(zr, Address(obj, rscratch1));
3026     bind(L_already_dirty);
3027   } else {
3028     strb(zr, Address(obj, rscratch1));
3029   }
3030 }
3031 
3032 void MacroAssembler::load_klass(Register dst, Register src) {
3033   if (UseCompressedClassPointers) {
3034     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3035     decode_klass_not_null(dst);
3036   } else {
3037     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3038   }
3039 }
3040 
3041 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3042   if (UseCompressedClassPointers) {
3043     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3044     if (Universe::narrow_klass_base() == NULL) {
3045       cmp(trial_klass, tmp, LSL, Universe::narrow_klass_shift());
3046       return;
3047     } else if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3048                && Universe::narrow_klass_shift() == 0) {
3049       // Only the bottom 32 bits matter
3050       cmpw(trial_klass, tmp);
3051       return;
3052     }
3053     decode_klass_not_null(tmp);
3054   } else {
3055     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3056   }
3057   cmp(trial_klass, tmp);
3058 }
3059 
3060 void MacroAssembler::load_prototype_header(Register dst, Register src) {
3061   load_klass(dst, src);
3062   ldr(dst, Address(dst, Klass::prototype_header_offset()));
3063 }
3064 
3065 void MacroAssembler::store_klass(Register dst, Register src) {
3066   // FIXME: Should this be a store release?  concurrent gcs assumes
3067   // klass length is valid if klass field is not null.
3068   if (UseCompressedClassPointers) {
3069     encode_klass_not_null(src);
3070     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3071   } else {
3072     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3073   }
3074 }
3075 
3076 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3077   if (UseCompressedClassPointers) {
3078     // Store to klass gap in destination
3079     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3080   }
3081 }
3082 
3083 // Algorithm must match oop.inline.hpp encode_heap_oop.
3084 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3085 #ifdef ASSERT
3086   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3087 #endif
3088   verify_oop(s, "broken oop in encode_heap_oop");
3089   if (Universe::narrow_oop_base() == NULL) {
3090     if (Universe::narrow_oop_shift() != 0) {
3091       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3092       lsr(d, s, LogMinObjAlignmentInBytes);
3093     } else {
3094       mov(d, s);
3095     }
3096   } else {
3097     subs(d, s, rheapbase);
3098     csel(d, d, zr, Assembler::HS);
3099     lsr(d, d, LogMinObjAlignmentInBytes);
3100 
3101     /*  Old algorithm: is this any worse?
3102     Label nonnull;
3103     cbnz(r, nonnull);
3104     sub(r, r, rheapbase);
3105     bind(nonnull);
3106     lsr(r, r, LogMinObjAlignmentInBytes);
3107     */
3108   }
3109 }
3110 
3111 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3112 #ifdef ASSERT
3113   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3114   if (CheckCompressedOops) {
3115     Label ok;
3116     cbnz(r, ok);
3117     stop("null oop passed to encode_heap_oop_not_null");
3118     bind(ok);
3119   }
3120 #endif
3121   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3122   if (Universe::narrow_oop_base() != NULL) {
3123     sub(r, r, rheapbase);
3124   }
3125   if (Universe::narrow_oop_shift() != 0) {
3126     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3127     lsr(r, r, LogMinObjAlignmentInBytes);
3128   }
3129 }
3130 
3131 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3132 #ifdef ASSERT
3133   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3134   if (CheckCompressedOops) {
3135     Label ok;
3136     cbnz(src, ok);
3137     stop("null oop passed to encode_heap_oop_not_null2");
3138     bind(ok);
3139   }
3140 #endif
3141   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3142 
3143   Register data = src;
3144   if (Universe::narrow_oop_base() != NULL) {
3145     sub(dst, src, rheapbase);
3146     data = dst;
3147   }
3148   if (Universe::narrow_oop_shift() != 0) {
3149     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3150     lsr(dst, data, LogMinObjAlignmentInBytes);
3151     data = dst;
3152   }
3153   if (data == src)
3154     mov(dst, src);
3155 }
3156 
3157 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3158 #ifdef ASSERT
3159   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3160 #endif
3161   if (Universe::narrow_oop_base() == NULL) {
3162     if (Universe::narrow_oop_shift() != 0 || d != s) {
3163       lsl(d, s, Universe::narrow_oop_shift());
3164     }
3165   } else {
3166     Label done;
3167     if (d != s)
3168       mov(d, s);
3169     cbz(s, done);
3170     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3171     bind(done);
3172   }
3173   verify_oop(d, "broken oop in decode_heap_oop");
3174 }
3175 
3176 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3177   assert (UseCompressedOops, "should only be used for compressed headers");
3178   assert (Universe::heap() != NULL, "java heap should be initialized");
3179   // Cannot assert, unverified entry point counts instructions (see .ad file)
3180   // vtableStubs also counts instructions in pd_code_size_limit.
3181   // Also do not verify_oop as this is called by verify_oop.
3182   if (Universe::narrow_oop_shift() != 0) {
3183     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3184     if (Universe::narrow_oop_base() != NULL) {
3185       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3186     } else {
3187       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3188     }
3189   } else {
3190     assert (Universe::narrow_oop_base() == NULL, "sanity");
3191   }
3192 }
3193 
3194 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3195   assert (UseCompressedOops, "should only be used for compressed headers");
3196   assert (Universe::heap() != NULL, "java heap should be initialized");
3197   // Cannot assert, unverified entry point counts instructions (see .ad file)
3198   // vtableStubs also counts instructions in pd_code_size_limit.
3199   // Also do not verify_oop as this is called by verify_oop.
3200   if (Universe::narrow_oop_shift() != 0) {
3201     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3202     if (Universe::narrow_oop_base() != NULL) {
3203       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3204     } else {
3205       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3206     }
3207   } else {
3208     assert (Universe::narrow_oop_base() == NULL, "sanity");
3209     if (dst != src) {
3210       mov(dst, src);
3211     }
3212   }
3213 }
3214 
3215 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3216   if (Universe::narrow_klass_base() == NULL) {
3217     if (Universe::narrow_klass_shift() != 0) {
3218       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3219       lsr(dst, src, LogKlassAlignmentInBytes);
3220     } else {
3221       if (dst != src) mov(dst, src);
3222     }
3223     return;
3224   }
3225 
3226   if (use_XOR_for_compressed_class_base) {
3227     if (Universe::narrow_klass_shift() != 0) {
3228       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3229       lsr(dst, dst, LogKlassAlignmentInBytes);
3230     } else {
3231       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3232     }
3233     return;
3234   }
3235 
3236   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3237       && Universe::narrow_klass_shift() == 0) {
3238     movw(dst, src);
3239     return;
3240   }
3241 
3242 #ifdef ASSERT
3243   verify_heapbase("MacroAssembler::encode_klass_not_null2: heap base corrupted?");
3244 #endif
3245 
3246   Register rbase = dst;
3247   if (dst == src) rbase = rheapbase;
3248   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3249   sub(dst, src, rbase);
3250   if (Universe::narrow_klass_shift() != 0) {
3251     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3252     lsr(dst, dst, LogKlassAlignmentInBytes);
3253   }
3254   if (dst == src) reinit_heapbase();
3255 }
3256 
3257 void MacroAssembler::encode_klass_not_null(Register r) {
3258   encode_klass_not_null(r, r);
3259 }
3260 
3261 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3262   Register rbase = dst;
3263   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3264 
3265   if (Universe::narrow_klass_base() == NULL) {
3266     if (Universe::narrow_klass_shift() != 0) {
3267       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3268       lsl(dst, src, LogKlassAlignmentInBytes);
3269     } else {
3270       if (dst != src) mov(dst, src);
3271     }
3272     return;
3273   }
3274 
3275   if (use_XOR_for_compressed_class_base) {
3276     if (Universe::narrow_klass_shift() != 0) {
3277       lsl(dst, src, LogKlassAlignmentInBytes);
3278       eor(dst, dst, (uint64_t)Universe::narrow_klass_base());
3279     } else {
3280       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3281     }
3282     return;
3283   }
3284 
3285   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3286       && Universe::narrow_klass_shift() == 0) {
3287     if (dst != src)
3288       movw(dst, src);
3289     movk(dst, (uint64_t)Universe::narrow_klass_base() >> 32, 32);
3290     return;
3291   }
3292 
3293   // Cannot assert, unverified entry point counts instructions (see .ad file)
3294   // vtableStubs also counts instructions in pd_code_size_limit.
3295   // Also do not verify_oop as this is called by verify_oop.
3296   if (dst == src) rbase = rheapbase;
3297   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3298   if (Universe::narrow_klass_shift() != 0) {
3299     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3300     add(dst, rbase, src, Assembler::LSL, LogKlassAlignmentInBytes);
3301   } else {
3302     add(dst, rbase, src);
3303   }
3304   if (dst == src) reinit_heapbase();
3305 }
3306 
3307 void  MacroAssembler::decode_klass_not_null(Register r) {
3308   decode_klass_not_null(r, r);
3309 }
3310 
3311 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
3312   assert (UseCompressedOops, "should only be used for compressed oops");
3313   assert (Universe::heap() != NULL, "java heap should be initialized");
3314   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3315 
3316   int oop_index = oop_recorder()->find_index(obj);
3317   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3318 
3319   InstructionMark im(this);
3320   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3321   code_section()->relocate(inst_mark(), rspec);
3322   movz(dst, 0xDEAD, 16);
3323   movk(dst, 0xBEEF);
3324 }
3325 
3326 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
3327   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3328   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3329   int index = oop_recorder()->find_index(k);
3330   assert(! Universe::heap()->is_in_reserved(k), "should not be an oop");
3331 
3332   InstructionMark im(this);
3333   RelocationHolder rspec = metadata_Relocation::spec(index);
3334   code_section()->relocate(inst_mark(), rspec);
3335   narrowKlass nk = Klass::encode_klass(k);
3336   movz(dst, (nk >> 16), 16);
3337   movk(dst, nk & 0xffff);
3338 }
3339 
3340 void MacroAssembler::load_heap_oop(Register dst, Address src)
3341 {
3342   if (UseCompressedOops) {
3343     ldrw(dst, src);
3344     decode_heap_oop(dst);
3345   } else {
3346     ldr(dst, src);
3347   }
3348 }
3349 
3350 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src)
3351 {
3352   if (UseCompressedOops) {
3353     ldrw(dst, src);
3354     decode_heap_oop_not_null(dst);
3355   } else {
3356     ldr(dst, src);
3357   }
3358 }
3359 
3360 void MacroAssembler::store_heap_oop(Address dst, Register src) {
3361   if (UseCompressedOops) {
3362     assert(!dst.uses(src), "not enough registers");
3363     encode_heap_oop(src);
3364     strw(src, dst);
3365   } else
3366     str(src, dst);
3367 }
3368 
3369 // Used for storing NULLs.
3370 void MacroAssembler::store_heap_oop_null(Address dst) {
3371   if (UseCompressedOops) {
3372     strw(zr, dst);
3373   } else
3374     str(zr, dst);
3375 }
3376 
3377 #if INCLUDE_ALL_GCS
3378 void MacroAssembler::g1_write_barrier_pre(Register obj,
3379                                           Register pre_val,
3380                                           Register thread,
3381                                           Register tmp,
3382                                           bool tosca_live,
3383                                           bool expand_call) {
3384   // If expand_call is true then we expand the call_VM_leaf macro
3385   // directly to skip generating the check by
3386   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
3387 
3388   assert(thread == rthread, "must be");
3389 
3390   Label done;
3391   Label runtime;
3392 
3393   assert(pre_val != noreg, "check this code");
3394 
3395   if (obj != noreg)
3396     assert_different_registers(obj, pre_val, tmp);
3397 
3398   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3399                                        PtrQueue::byte_offset_of_active()));
3400   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3401                                        PtrQueue::byte_offset_of_index()));
3402   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3403                                        PtrQueue::byte_offset_of_buf()));
3404 
3405 
3406   // Is marking active?
3407   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
3408     ldrw(tmp, in_progress);
3409   } else {
3410     assert(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
3411     ldrb(tmp, in_progress);
3412   }
3413   cbzw(tmp, done);
3414 
3415   // Do we need to load the previous value?
3416   if (obj != noreg) {
3417     load_heap_oop(pre_val, Address(obj, 0));
3418   }
3419 
3420   // Is the previous value null?
3421   cbz(pre_val, done);
3422 
3423   // Can we store original value in the thread's buffer?
3424   // Is index == 0?
3425   // (The index field is typed as size_t.)
3426 
3427   ldr(tmp, index);                      // tmp := *index_adr
3428   cbz(tmp, runtime);                    // tmp == 0?
3429                                         // If yes, goto runtime
3430 
3431   sub(tmp, tmp, wordSize);              // tmp := tmp - wordSize
3432   str(tmp, index);                      // *index_adr := tmp
3433   ldr(rscratch1, buffer);
3434   add(tmp, tmp, rscratch1);             // tmp := tmp + *buffer_adr
3435 
3436   // Record the previous value
3437   str(pre_val, Address(tmp, 0));
3438   b(done);
3439 
3440   bind(runtime);
3441   // save the live input values
3442   push(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3443 
3444   // Calling the runtime using the regular call_VM_leaf mechanism generates
3445   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
3446   // that checks that the *(rfp+frame::interpreter_frame_last_sp) == NULL.
3447   //
3448   // If we care generating the pre-barrier without a frame (e.g. in the
3449   // intrinsified Reference.get() routine) then ebp might be pointing to
3450   // the caller frame and so this check will most likely fail at runtime.
3451   //
3452   // Expanding the call directly bypasses the generation of the check.
3453   // So when we do not have have a full interpreter frame on the stack
3454   // expand_call should be passed true.
3455 
3456   if (expand_call) {
3457     assert(pre_val != c_rarg1, "smashed arg");
3458     pass_arg1(this, thread);
3459     pass_arg0(this, pre_val);
3460     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
3461   } else {
3462     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
3463   }
3464 
3465   pop(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3466 
3467   bind(done);
3468 }
3469 
3470 void MacroAssembler::g1_write_barrier_post(Register store_addr,
3471                                            Register new_val,
3472                                            Register thread,
3473                                            Register tmp,
3474                                            Register tmp2) {
3475   assert(thread == rthread, "must be");
3476 
3477   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3478                                        PtrQueue::byte_offset_of_index()));
3479   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3480                                        PtrQueue::byte_offset_of_buf()));
3481 
3482   BarrierSet* bs = Universe::heap()->barrier_set();
3483   CardTableModRefBS* ct = (CardTableModRefBS*)bs;
3484   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3485 
3486   Label done;
3487   Label runtime;
3488 
3489   // Does store cross heap regions?
3490 
3491   eor(tmp, store_addr, new_val);
3492   lsr(tmp, tmp, HeapRegion::LogOfHRGrainBytes);
3493   cbz(tmp, done);
3494 
3495   // crosses regions, storing NULL?
3496 
3497   cbz(new_val, done);
3498 
3499   // storing region crossing non-NULL, is card already dirty?
3500 
3501   ExternalAddress cardtable((address) ct->byte_map_base);
3502   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3503   const Register card_addr = tmp;
3504 
3505   lsr(card_addr, store_addr, CardTableModRefBS::card_shift);
3506 
3507   unsigned long offset;
3508   adrp(tmp2, cardtable, offset);
3509 
3510   // get the address of the card
3511   add(card_addr, card_addr, tmp2);
3512   ldrb(tmp2, Address(card_addr, offset));
3513   cmpw(tmp2, (int)G1SATBCardTableModRefBS::g1_young_card_val());
3514   br(Assembler::EQ, done);
3515 
3516   assert((int)CardTableModRefBS::dirty_card_val() == 0, "must be 0");
3517 
3518   membar(Assembler::StoreLoad);
3519 
3520   ldrb(tmp2, Address(card_addr, offset));
3521   cbzw(tmp2, done);
3522 
3523   // storing a region crossing, non-NULL oop, card is clean.
3524   // dirty card and log.
3525 
3526   strb(zr, Address(card_addr, offset));
3527 
3528   ldr(rscratch1, queue_index);
3529   cbz(rscratch1, runtime);
3530   sub(rscratch1, rscratch1, wordSize);
3531   str(rscratch1, queue_index);
3532 
3533   ldr(tmp2, buffer);
3534   str(card_addr, Address(tmp2, rscratch1));
3535   b(done);
3536 
3537   bind(runtime);
3538   // save the live input values
3539   push(store_addr->bit(true) | new_val->bit(true), sp);
3540   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
3541   pop(store_addr->bit(true) | new_val->bit(true), sp);
3542 
3543   bind(done);
3544 }
3545 
3546 #endif // INCLUDE_ALL_GCS
3547 
3548 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
3549   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
3550   int index = oop_recorder()->allocate_metadata_index(obj);
3551   RelocationHolder rspec = metadata_Relocation::spec(index);
3552   return Address((address)obj, rspec);
3553 }
3554 
3555 // Move an oop into a register.  immediate is true if we want
3556 // immediate instrcutions, i.e. we are not going to patch this
3557 // instruction while the code is being executed by another thread.  In
3558 // that case we can use move immediates rather than the constant pool.
3559 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
3560   int oop_index;
3561   if (obj == NULL) {
3562     oop_index = oop_recorder()->allocate_oop_index(obj);
3563   } else {
3564     oop_index = oop_recorder()->find_index(obj);
3565     assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3566   }
3567   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3568   if (! immediate) {
3569     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
3570     ldr_constant(dst, Address(dummy, rspec));
3571   } else
3572     mov(dst, Address((address)obj, rspec));
3573 }
3574 
3575 // Move a metadata address into a register.
3576 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
3577   int oop_index;
3578   if (obj == NULL) {
3579     oop_index = oop_recorder()->allocate_metadata_index(obj);
3580   } else {
3581     oop_index = oop_recorder()->find_index(obj);
3582   }
3583   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
3584   mov(dst, Address((address)obj, rspec));
3585 }
3586 
3587 Address MacroAssembler::constant_oop_address(jobject obj) {
3588   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
3589   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
3590   int oop_index = oop_recorder()->find_index(obj);
3591   return Address((address)obj, oop_Relocation::spec(oop_index));
3592 }
3593 
3594 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
3595 void MacroAssembler::tlab_allocate(Register obj,
3596                                    Register var_size_in_bytes,
3597                                    int con_size_in_bytes,
3598                                    Register t1,
3599                                    Register t2,
3600                                    Label& slow_case) {
3601   assert_different_registers(obj, t2);
3602   assert_different_registers(obj, var_size_in_bytes);
3603   Register end = t2;
3604 
3605   // verify_tlab();
3606 
3607   ldr(obj, Address(rthread, JavaThread::tlab_top_offset()));
3608   if (var_size_in_bytes == noreg) {
3609     lea(end, Address(obj, con_size_in_bytes));
3610   } else {
3611     lea(end, Address(obj, var_size_in_bytes));
3612   }
3613   ldr(rscratch1, Address(rthread, JavaThread::tlab_end_offset()));
3614   cmp(end, rscratch1);
3615   br(Assembler::HI, slow_case);
3616 
3617   // update the tlab top pointer
3618   str(end, Address(rthread, JavaThread::tlab_top_offset()));
3619 
3620   // recover var_size_in_bytes if necessary
3621   if (var_size_in_bytes == end) {
3622     sub(var_size_in_bytes, var_size_in_bytes, obj);
3623   }
3624   // verify_tlab();
3625 }
3626 
3627 // Preserves r19, and r3.
3628 Register MacroAssembler::tlab_refill(Label& retry,
3629                                      Label& try_eden,
3630                                      Label& slow_case) {
3631   Register top = r0;
3632   Register t1  = r2;
3633   Register t2  = r4;
3634   assert_different_registers(top, rthread, t1, t2, /* preserve: */ r19, r3);
3635   Label do_refill, discard_tlab;
3636 
3637   if (!Universe::heap()->supports_inline_contig_alloc()) {
3638     // No allocation in the shared eden.
3639     b(slow_case);
3640   }
3641 
3642   ldr(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3643   ldr(t1,  Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3644 
3645   // calculate amount of free space
3646   sub(t1, t1, top);
3647   lsr(t1, t1, LogHeapWordSize);
3648 
3649   // Retain tlab and allocate object in shared space if
3650   // the amount free in the tlab is too large to discard.
3651 
3652   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3653   cmp(t1, rscratch1);
3654   br(Assembler::LE, discard_tlab);
3655 
3656   // Retain
3657   // ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3658   mov(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
3659   add(rscratch1, rscratch1, t2);
3660   str(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3661 
3662   if (TLABStats) {
3663     // increment number of slow_allocations
3664     addmw(Address(rthread, in_bytes(JavaThread::tlab_slow_allocations_offset())),
3665          1, rscratch1);
3666   }
3667   b(try_eden);
3668 
3669   bind(discard_tlab);
3670   if (TLABStats) {
3671     // increment number of refills
3672     addmw(Address(rthread, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1,
3673          rscratch1);
3674     // accumulate wastage -- t1 is amount free in tlab
3675     addmw(Address(rthread, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1,
3676          rscratch1);
3677   }
3678 
3679   // if tlab is currently allocated (top or end != null) then
3680   // fill [top, end + alignment_reserve) with array object
3681   cbz(top, do_refill);
3682 
3683   // set up the mark word
3684   mov(rscratch1, (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
3685   str(rscratch1, Address(top, oopDesc::mark_offset_in_bytes()));
3686   // set the length to the remaining space
3687   sub(t1, t1, typeArrayOopDesc::header_size(T_INT));
3688   add(t1, t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
3689   lsl(t1, t1, log2_intptr(HeapWordSize/sizeof(jint)));
3690   strw(t1, Address(top, arrayOopDesc::length_offset_in_bytes()));
3691   // set klass to intArrayKlass
3692   {
3693     unsigned long offset;
3694     // dubious reloc why not an oop reloc?
3695     adrp(rscratch1, ExternalAddress((address)Universe::intArrayKlassObj_addr()),
3696          offset);
3697     ldr(t1, Address(rscratch1, offset));
3698   }
3699   // store klass last.  concurrent gcs assumes klass length is valid if
3700   // klass field is not null.
3701   store_klass(top, t1);
3702 
3703   mov(t1, top);
3704   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3705   sub(t1, t1, rscratch1);
3706   incr_allocated_bytes(rthread, t1, 0, rscratch1);
3707 
3708   // refill the tlab with an eden allocation
3709   bind(do_refill);
3710   ldr(t1, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
3711   lsl(t1, t1, LogHeapWordSize);
3712   // allocate new tlab, address returned in top
3713   eden_allocate(top, t1, 0, t2, slow_case);
3714 
3715   // Check that t1 was preserved in eden_allocate.
3716 #ifdef ASSERT
3717   if (UseTLAB) {
3718     Label ok;
3719     Register tsize = r4;
3720     assert_different_registers(tsize, rthread, t1);
3721     str(tsize, Address(pre(sp, -16)));
3722     ldr(tsize, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
3723     lsl(tsize, tsize, LogHeapWordSize);
3724     cmp(t1, tsize);
3725     br(Assembler::EQ, ok);
3726     STOP("assert(t1 != tlab size)");
3727     should_not_reach_here();
3728 
3729     bind(ok);
3730     ldr(tsize, Address(post(sp, 16)));
3731   }
3732 #endif
3733   str(top, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3734   str(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3735   add(top, top, t1);
3736   sub(top, top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
3737   str(top, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3738   verify_tlab();
3739   b(retry);
3740 
3741   return rthread; // for use by caller
3742 }
3743 
3744 // Defines obj, preserves var_size_in_bytes
3745 void MacroAssembler::eden_allocate(Register obj,
3746                                    Register var_size_in_bytes,
3747                                    int con_size_in_bytes,
3748                                    Register t1,
3749                                    Label& slow_case) {
3750   assert_different_registers(obj, var_size_in_bytes, t1);
3751   if (!Universe::heap()->supports_inline_contig_alloc()) {
3752     b(slow_case);
3753   } else {
3754     Register end = t1;
3755     Register heap_end = rscratch2;
3756     Label retry;
3757     bind(retry);
3758     {
3759       unsigned long offset;
3760       adrp(rscratch1, ExternalAddress((address) Universe::heap()->end_addr()), offset);
3761       ldr(heap_end, Address(rscratch1, offset));
3762     }
3763 
3764     ExternalAddress heap_top((address) Universe::heap()->top_addr());
3765 
3766     // Get the current top of the heap
3767     {
3768       unsigned long offset;
3769       adrp(rscratch1, heap_top, offset);
3770       // Use add() here after ARDP, rather than lea().
3771       // lea() does not generate anything if its offset is zero.
3772       // However, relocs expect to find either an ADD or a load/store
3773       // insn after an ADRP.  add() always generates an ADD insn, even
3774       // for add(Rn, Rn, 0).
3775       add(rscratch1, rscratch1, offset);
3776       ldaxr(obj, rscratch1);
3777     }
3778 
3779     // Adjust it my the size of our new object
3780     if (var_size_in_bytes == noreg) {
3781       lea(end, Address(obj, con_size_in_bytes));
3782     } else {
3783       lea(end, Address(obj, var_size_in_bytes));
3784     }
3785 
3786     // if end < obj then we wrapped around high memory
3787     cmp(end, obj);
3788     br(Assembler::LO, slow_case);
3789 
3790     cmp(end, heap_end);
3791     br(Assembler::HI, slow_case);
3792 
3793     // If heap_top hasn't been changed by some other thread, update it.
3794     stlxr(rscratch1, end, rscratch1);
3795     cbnzw(rscratch1, retry);
3796   }
3797 }
3798 
3799 void MacroAssembler::verify_tlab() {
3800 #ifdef ASSERT
3801   if (UseTLAB && VerifyOops) {
3802     Label next, ok;
3803 
3804     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
3805 
3806     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3807     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3808     cmp(rscratch2, rscratch1);
3809     br(Assembler::HS, next);
3810     STOP("assert(top >= start)");
3811     should_not_reach_here();
3812 
3813     bind(next);
3814     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3815     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3816     cmp(rscratch2, rscratch1);
3817     br(Assembler::HS, ok);
3818     STOP("assert(top <= end)");
3819     should_not_reach_here();
3820 
3821     bind(ok);
3822     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
3823   }
3824 #endif
3825 }
3826 
3827 // Writes to stack successive pages until offset reached to check for
3828 // stack overflow + shadow pages.  This clobbers tmp.
3829 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
3830   assert_different_registers(tmp, size, rscratch1);
3831   mov(tmp, sp);
3832   // Bang stack for total size given plus shadow page size.
3833   // Bang one page at a time because large size can bang beyond yellow and
3834   // red zones.
3835   Label loop;
3836   mov(rscratch1, os::vm_page_size());
3837   bind(loop);
3838   lea(tmp, Address(tmp, -os::vm_page_size()));
3839   subsw(size, size, rscratch1);
3840   str(size, Address(tmp));
3841   br(Assembler::GT, loop);
3842 
3843   // Bang down shadow pages too.
3844   // At this point, (tmp-0) is the last address touched, so don't
3845   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
3846   // was post-decremented.)  Skip this address by starting at i=1, and
3847   // touch a few more pages below.  N.B.  It is important to touch all
3848   // the way down to and including i=StackShadowPages.
3849   for (int i = 0; i< StackShadowPages-1; i++) {
3850     // this could be any sized move but this is can be a debugging crumb
3851     // so the bigger the better.
3852     lea(tmp, Address(tmp, -os::vm_page_size()));
3853     str(size, Address(tmp));
3854   }
3855 }
3856 
3857 
3858 address MacroAssembler::read_polling_page(Register r, address page, relocInfo::relocType rtype) {
3859   unsigned long off;
3860   adrp(r, Address(page, rtype), off);
3861   InstructionMark im(this);
3862   code_section()->relocate(inst_mark(), rtype);
3863   ldrw(zr, Address(r, off));
3864   return inst_mark();
3865 }
3866 
3867 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
3868   InstructionMark im(this);
3869   code_section()->relocate(inst_mark(), rtype);
3870   ldrw(zr, Address(r, 0));
3871   return inst_mark();
3872 }
3873 
3874 void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byte_offset) {
3875   relocInfo::relocType rtype = dest.rspec().reloc()->type();
3876   if (uabs(pc() - dest.target()) >= (1LL << 32)) {
3877     guarantee(rtype == relocInfo::none
3878               || rtype == relocInfo::external_word_type
3879               || rtype == relocInfo::poll_type
3880               || rtype == relocInfo::poll_return_type,
3881               "can only use a fixed address with an ADRP");
3882     // Out of range.  This doesn't happen very often, but we have to
3883     // handle it
3884     mov(reg1, dest);
3885     byte_offset = 0;
3886   } else {
3887     InstructionMark im(this);
3888     code_section()->relocate(inst_mark(), dest.rspec());
3889     byte_offset = (uint64_t)dest.target() & 0xfff;
3890     _adrp(reg1, dest.target());
3891   }
3892 }
3893 
3894 void MacroAssembler::build_frame(int framesize) {
3895   assert(framesize > 0, "framesize must be > 0");
3896   if (framesize < ((1 << 9) + 2 * wordSize)) {
3897     sub(sp, sp, framesize);
3898     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
3899     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
3900   } else {
3901     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
3902     if (PreserveFramePointer) mov(rfp, sp);
3903     if (framesize < ((1 << 12) + 2 * wordSize))
3904       sub(sp, sp, framesize - 2 * wordSize);
3905     else {
3906       mov(rscratch1, framesize - 2 * wordSize);
3907       sub(sp, sp, rscratch1);
3908     }
3909   }
3910 }
3911 
3912 void MacroAssembler::remove_frame(int framesize) {
3913   assert(framesize > 0, "framesize must be > 0");
3914   if (framesize < ((1 << 9) + 2 * wordSize)) {
3915     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
3916     add(sp, sp, framesize);
3917   } else {
3918     if (framesize < ((1 << 12) + 2 * wordSize))
3919       add(sp, sp, framesize - 2 * wordSize);
3920     else {
3921       mov(rscratch1, framesize - 2 * wordSize);
3922       add(sp, sp, rscratch1);
3923     }
3924     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
3925   }
3926 }
3927 
3928 
3929 // Search for str1 in str2 and return index or -1
3930 void MacroAssembler::string_indexof(Register str2, Register str1,
3931                                     Register cnt2, Register cnt1,
3932                                     Register tmp1, Register tmp2,
3933                                     Register tmp3, Register tmp4,
3934                                     int icnt1, Register result) {
3935   Label BM, LINEARSEARCH, DONE, NOMATCH, MATCH;
3936 
3937   Register ch1 = rscratch1;
3938   Register ch2 = rscratch2;
3939   Register cnt1tmp = tmp1;
3940   Register cnt2tmp = tmp2;
3941   Register cnt1_neg = cnt1;
3942   Register cnt2_neg = cnt2;
3943   Register result_tmp = tmp4;
3944 
3945   // Note, inline_string_indexOf() generates checks:
3946   // if (substr.count > string.count) return -1;
3947   // if (substr.count == 0) return 0;
3948 
3949 // We have two strings, a source string in str2, cnt2 and a pattern string
3950 // in str1, cnt1. Find the 1st occurence of pattern in source or return -1.
3951 
3952 // For larger pattern and source we use a simplified Boyer Moore algorithm.
3953 // With a small pattern and source we use linear scan.
3954 
3955   if (icnt1 == -1) {
3956     cmp(cnt1, 256);             // Use Linear Scan if cnt1 < 8 || cnt1 >= 256
3957     ccmp(cnt1, 8, 0b0000, LO);  // Can't handle skip >= 256 because we use
3958     br(LO, LINEARSEARCH);       // a byte array.
3959     cmp(cnt1, cnt2, LSR, 2);    // Source must be 4 * pattern for BM
3960     br(HS, LINEARSEARCH);
3961   }
3962 
3963 // The Boyer Moore alogorithm is based on the description here:-
3964 //
3965 // http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
3966 //
3967 // This describes and algorithm with 2 shift rules. The 'Bad Character' rule
3968 // and the 'Good Suffix' rule.
3969 //
3970 // These rules are essentially heuristics for how far we can shift the
3971 // pattern along the search string.
3972 //
3973 // The implementation here uses the 'Bad Character' rule only because of the
3974 // complexity of initialisation for the 'Good Suffix' rule.
3975 //
3976 // This is also known as the Boyer-Moore-Horspool algorithm:-
3977 //
3978 // http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm
3979 //
3980 // #define ASIZE 128
3981 //
3982 //    int bm(unsigned char *x, int m, unsigned char *y, int n) {
3983 //       int i, j;
3984 //       unsigned c;
3985 //       unsigned char bc[ASIZE];
3986 //
3987 //       /* Preprocessing */
3988 //       for (i = 0; i < ASIZE; ++i)
3989 //          bc[i] = 0;
3990 //       for (i = 0; i < m - 1; ) {
3991 //          c = x[i];
3992 //          ++i;
3993 //          if (c < ASIZE) bc[c] = i;
3994 //       }
3995 //
3996 //       /* Searching */
3997 //       j = 0;
3998 //       while (j <= n - m) {
3999 //          c = y[i+j];
4000 //          if (x[m-1] == c)
4001 //            for (i = m - 2; i >= 0 && x[i] == y[i + j]; --i);
4002 //          if (i < 0) return j;
4003 //          if (c < ASIZE)
4004 //            j = j - bc[y[j+m-1]] + m;
4005 //          else
4006 //            j += 1; // Advance by 1 only if char >= ASIZE
4007 //       }
4008 //    }
4009 
4010   if (icnt1 == -1) {
4011     BIND(BM);
4012 
4013     Label ZLOOP, BCLOOP, BCSKIP, BMLOOPSTR2, BMLOOPSTR1, BMSKIP;
4014     Label BMADV, BMMATCH, BMCHECKEND;
4015 
4016     Register cnt1end = tmp2;
4017     Register str2end = cnt2;
4018     Register skipch = tmp2;
4019 
4020     // Restrict ASIZE to 128 to reduce stack space/initialisation.
4021     // The presence of chars >= ASIZE in the target string does not affect
4022     // performance, but we must be careful not to initialise them in the stack
4023     // array.
4024     // The presence of chars >= ASIZE in the source string may adversely affect
4025     // performance since we can only advance by one when we encounter one.
4026 
4027       stp(zr, zr, pre(sp, -128));
4028       for (int i = 1; i < 8; i++)
4029           stp(zr, zr, Address(sp, i*16));
4030 
4031       mov(cnt1tmp, 0);
4032       sub(cnt1end, cnt1, 1);
4033     BIND(BCLOOP);
4034       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4035       cmp(ch1, 128);
4036       add(cnt1tmp, cnt1tmp, 1);
4037       br(HS, BCSKIP);
4038       strb(cnt1tmp, Address(sp, ch1));
4039     BIND(BCSKIP);
4040       cmp(cnt1tmp, cnt1end);
4041       br(LT, BCLOOP);
4042 
4043       mov(result_tmp, str2);
4044 
4045       sub(cnt2, cnt2, cnt1);
4046       add(str2end, str2, cnt2, LSL, 1);
4047     BIND(BMLOOPSTR2);
4048       sub(cnt1tmp, cnt1, 1);
4049       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4050       ldrh(skipch, Address(str2, cnt1tmp, Address::lsl(1)));
4051       cmp(ch1, skipch);
4052       br(NE, BMSKIP);
4053       subs(cnt1tmp, cnt1tmp, 1);
4054       br(LT, BMMATCH);
4055     BIND(BMLOOPSTR1);
4056       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4057       ldrh(ch2, Address(str2, cnt1tmp, Address::lsl(1)));
4058       cmp(ch1, ch2);
4059       br(NE, BMSKIP);
4060       subs(cnt1tmp, cnt1tmp, 1);
4061       br(GE, BMLOOPSTR1);
4062     BIND(BMMATCH);
4063       sub(result_tmp, str2, result_tmp);
4064       lsr(result, result_tmp, 1);
4065       add(sp, sp, 128);
4066       b(DONE);
4067     BIND(BMADV);
4068       add(str2, str2, 2);
4069       b(BMCHECKEND);
4070     BIND(BMSKIP);
4071       cmp(skipch, 128);
4072       br(HS, BMADV);
4073       ldrb(ch2, Address(sp, skipch));
4074       add(str2, str2, cnt1, LSL, 1);
4075       sub(str2, str2, ch2, LSL, 1);
4076     BIND(BMCHECKEND);
4077       cmp(str2, str2end);
4078       br(LE, BMLOOPSTR2);
4079       add(sp, sp, 128);
4080       b(NOMATCH);
4081   }
4082 
4083   BIND(LINEARSEARCH);
4084   {
4085     Label DO1, DO2, DO3;
4086 
4087     Register str2tmp = tmp2;
4088     Register first = tmp3;
4089 
4090     if (icnt1 == -1)
4091     {
4092         Label DOSHORT, FIRST_LOOP, STR2_NEXT, STR1_LOOP, STR1_NEXT, LAST_WORD;
4093 
4094         cmp(cnt1, 4);
4095         br(LT, DOSHORT);
4096 
4097         sub(cnt2, cnt2, cnt1);
4098         sub(cnt1, cnt1, 4);
4099         mov(result_tmp, cnt2);
4100 
4101         lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4102         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4103         sub(cnt1_neg, zr, cnt1, LSL, 1);
4104         sub(cnt2_neg, zr, cnt2, LSL, 1);
4105         ldr(first, Address(str1, cnt1_neg));
4106 
4107       BIND(FIRST_LOOP);
4108         ldr(ch2, Address(str2, cnt2_neg));
4109         cmp(first, ch2);
4110         br(EQ, STR1_LOOP);
4111       BIND(STR2_NEXT);
4112         adds(cnt2_neg, cnt2_neg, 2);
4113         br(LE, FIRST_LOOP);
4114         b(NOMATCH);
4115 
4116       BIND(STR1_LOOP);
4117         adds(cnt1tmp, cnt1_neg, 8);
4118         add(cnt2tmp, cnt2_neg, 8);
4119         br(GE, LAST_WORD);
4120 
4121       BIND(STR1_NEXT);
4122         ldr(ch1, Address(str1, cnt1tmp));
4123         ldr(ch2, Address(str2, cnt2tmp));
4124         cmp(ch1, ch2);
4125         br(NE, STR2_NEXT);
4126         adds(cnt1tmp, cnt1tmp, 8);
4127         add(cnt2tmp, cnt2tmp, 8);
4128         br(LT, STR1_NEXT);
4129 
4130       BIND(LAST_WORD);
4131         ldr(ch1, Address(str1));
4132         sub(str2tmp, str2, cnt1_neg);         // adjust to corresponding
4133         ldr(ch2, Address(str2tmp, cnt2_neg)); // word in str2
4134         cmp(ch1, ch2);
4135         br(NE, STR2_NEXT);
4136         b(MATCH);
4137 
4138       BIND(DOSHORT);
4139         cmp(cnt1, 2);
4140         br(LT, DO1);
4141         br(GT, DO3);
4142     }
4143 
4144     if (icnt1 == 4) {
4145       Label CH1_LOOP;
4146 
4147         ldr(ch1, str1);
4148         sub(cnt2, cnt2, 4);
4149         mov(result_tmp, cnt2);
4150         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4151         sub(cnt2_neg, zr, cnt2, LSL, 1);
4152 
4153       BIND(CH1_LOOP);
4154         ldr(ch2, Address(str2, cnt2_neg));
4155         cmp(ch1, ch2);
4156         br(EQ, MATCH);
4157         adds(cnt2_neg, cnt2_neg, 2);
4158         br(LE, CH1_LOOP);
4159         b(NOMATCH);
4160     }
4161 
4162     if (icnt1 == -1 || icnt1 == 2) {
4163       Label CH1_LOOP;
4164 
4165       BIND(DO2);
4166         ldrw(ch1, str1);
4167         sub(cnt2, cnt2, 2);
4168         mov(result_tmp, cnt2);
4169         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4170         sub(cnt2_neg, zr, cnt2, LSL, 1);
4171 
4172       BIND(CH1_LOOP);
4173         ldrw(ch2, Address(str2, cnt2_neg));
4174         cmp(ch1, ch2);
4175         br(EQ, MATCH);
4176         adds(cnt2_neg, cnt2_neg, 2);
4177         br(LE, CH1_LOOP);
4178         b(NOMATCH);
4179     }
4180 
4181     if (icnt1 == -1 || icnt1 == 3) {
4182       Label FIRST_LOOP, STR2_NEXT, STR1_LOOP;
4183 
4184       BIND(DO3);
4185         ldrw(first, str1);
4186         ldrh(ch1, Address(str1, 4));
4187 
4188         sub(cnt2, cnt2, 3);
4189         mov(result_tmp, cnt2);
4190         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4191         sub(cnt2_neg, zr, cnt2, LSL, 1);
4192 
4193       BIND(FIRST_LOOP);
4194         ldrw(ch2, Address(str2, cnt2_neg));
4195         cmpw(first, ch2);
4196         br(EQ, STR1_LOOP);
4197       BIND(STR2_NEXT);
4198         adds(cnt2_neg, cnt2_neg, 2);
4199         br(LE, FIRST_LOOP);
4200         b(NOMATCH);
4201 
4202       BIND(STR1_LOOP);
4203         add(cnt2tmp, cnt2_neg, 4);
4204         ldrh(ch2, Address(str2, cnt2tmp));
4205         cmp(ch1, ch2);
4206         br(NE, STR2_NEXT);
4207         b(MATCH);
4208     }
4209 
4210     if (icnt1 == -1 || icnt1 == 1) {
4211       Label CH1_LOOP, HAS_ZERO;
4212       Label DO1_SHORT, DO1_LOOP;
4213 
4214       BIND(DO1);
4215         ldrh(ch1, str1);
4216         cmp(cnt2, 4);
4217         br(LT, DO1_SHORT);
4218 
4219         orr(ch1, ch1, ch1, LSL, 16);
4220         orr(ch1, ch1, ch1, LSL, 32);
4221 
4222         sub(cnt2, cnt2, 4);
4223         mov(result_tmp, cnt2);
4224         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4225         sub(cnt2_neg, zr, cnt2, LSL, 1);
4226 
4227         mov(tmp3, 0x0001000100010001);
4228       BIND(CH1_LOOP);
4229         ldr(ch2, Address(str2, cnt2_neg));
4230         eor(ch2, ch1, ch2);
4231         sub(tmp1, ch2, tmp3);
4232         orr(tmp2, ch2, 0x7fff7fff7fff7fff);
4233         bics(tmp1, tmp1, tmp2);
4234         br(NE, HAS_ZERO);
4235         adds(cnt2_neg, cnt2_neg, 8);
4236         br(LT, CH1_LOOP);
4237 
4238         cmp(cnt2_neg, 8);
4239         mov(cnt2_neg, 0);
4240         br(LT, CH1_LOOP);
4241         b(NOMATCH);
4242 
4243       BIND(HAS_ZERO);
4244         rev(tmp1, tmp1);
4245         clz(tmp1, tmp1);
4246         add(cnt2_neg, cnt2_neg, tmp1, LSR, 3);
4247         b(MATCH);
4248 
4249       BIND(DO1_SHORT);
4250         mov(result_tmp, cnt2);
4251         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4252         sub(cnt2_neg, zr, cnt2, LSL, 1);
4253       BIND(DO1_LOOP);
4254         ldrh(ch2, Address(str2, cnt2_neg));
4255         cmpw(ch1, ch2);
4256         br(EQ, MATCH);
4257         adds(cnt2_neg, cnt2_neg, 2);
4258         br(LT, DO1_LOOP);
4259     }
4260   }
4261   BIND(NOMATCH);
4262     mov(result, -1);
4263     b(DONE);
4264   BIND(MATCH);
4265     add(result, result_tmp, cnt2_neg, ASR, 1);
4266   BIND(DONE);
4267 }
4268 
4269 // Compare strings.
4270 void MacroAssembler::string_compare(Register str1, Register str2,
4271                                     Register cnt1, Register cnt2, Register result,
4272                                     Register tmp1) {
4273   Label LENGTH_DIFF, DONE, SHORT_LOOP, SHORT_STRING,
4274     NEXT_WORD, DIFFERENCE;
4275 
4276   BLOCK_COMMENT("string_compare {");
4277 
4278   // Compute the minimum of the string lengths and save the difference.
4279   subsw(tmp1, cnt1, cnt2);
4280   cselw(cnt2, cnt1, cnt2, Assembler::LE); // min
4281 
4282   // A very short string
4283   cmpw(cnt2, 4);
4284   br(Assembler::LT, SHORT_STRING);
4285 
4286   // Check if the strings start at the same location.
4287   cmp(str1, str2);
4288   br(Assembler::EQ, LENGTH_DIFF);
4289 
4290   // Compare longwords
4291   {
4292     subw(cnt2, cnt2, 4); // The last longword is a special case
4293 
4294     // Move both string pointers to the last longword of their
4295     // strings, negate the remaining count, and convert it to bytes.
4296     lea(str1, Address(str1, cnt2, Address::uxtw(1)));
4297     lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4298     sub(cnt2, zr, cnt2, LSL, 1);
4299 
4300     // Loop, loading longwords and comparing them into rscratch2.
4301     bind(NEXT_WORD);
4302     ldr(result, Address(str1, cnt2));
4303     ldr(cnt1, Address(str2, cnt2));
4304     adds(cnt2, cnt2, wordSize);
4305     eor(rscratch2, result, cnt1);
4306     cbnz(rscratch2, DIFFERENCE);
4307     br(Assembler::LT, NEXT_WORD);
4308 
4309     // Last longword.  In the case where length == 4 we compare the
4310     // same longword twice, but that's still faster than another
4311     // conditional branch.
4312 
4313     ldr(result, Address(str1));
4314     ldr(cnt1, Address(str2));
4315     eor(rscratch2, result, cnt1);
4316     cbz(rscratch2, LENGTH_DIFF);
4317 
4318     // Find the first different characters in the longwords and
4319     // compute their difference.
4320     bind(DIFFERENCE);
4321     rev(rscratch2, rscratch2);
4322     clz(rscratch2, rscratch2);
4323     andr(rscratch2, rscratch2, -16);
4324     lsrv(result, result, rscratch2);
4325     uxthw(result, result);
4326     lsrv(cnt1, cnt1, rscratch2);
4327     uxthw(cnt1, cnt1);
4328     subw(result, result, cnt1);
4329     b(DONE);
4330   }
4331 
4332   bind(SHORT_STRING);
4333   // Is the minimum length zero?
4334   cbz(cnt2, LENGTH_DIFF);
4335 
4336   bind(SHORT_LOOP);
4337   load_unsigned_short(result, Address(post(str1, 2)));
4338   load_unsigned_short(cnt1, Address(post(str2, 2)));
4339   subw(result, result, cnt1);
4340   cbnz(result, DONE);
4341   sub(cnt2, cnt2, 1);
4342   cbnz(cnt2, SHORT_LOOP);
4343 
4344   // Strings are equal up to min length.  Return the length difference.
4345   bind(LENGTH_DIFF);
4346   mov(result, tmp1);
4347 
4348   // That's it
4349   bind(DONE);
4350 
4351   BLOCK_COMMENT("} string_compare");
4352 }
4353 
4354 
4355 void MacroAssembler::string_equals(Register str1, Register str2,
4356                                    Register cnt, Register result,
4357                                    Register tmp1) {
4358   Label SAME_CHARS, DONE, SHORT_LOOP, SHORT_STRING,
4359     NEXT_WORD;
4360 
4361   const Register tmp2 = rscratch1;
4362   assert_different_registers(str1, str2, cnt, result, tmp1, tmp2, rscratch2);
4363 
4364   BLOCK_COMMENT("string_equals {");
4365 
4366   // Start by assuming that the strings are not equal.
4367   mov(result, zr);
4368 
4369   // A very short string
4370   cmpw(cnt, 4);
4371   br(Assembler::LT, SHORT_STRING);
4372 
4373   // Check if the strings start at the same location.
4374   cmp(str1, str2);
4375   br(Assembler::EQ, SAME_CHARS);
4376 
4377   // Compare longwords
4378   {
4379     subw(cnt, cnt, 4); // The last longword is a special case
4380 
4381     // Move both string pointers to the last longword of their
4382     // strings, negate the remaining count, and convert it to bytes.
4383     lea(str1, Address(str1, cnt, Address::uxtw(1)));
4384     lea(str2, Address(str2, cnt, Address::uxtw(1)));
4385     sub(cnt, zr, cnt, LSL, 1);
4386 
4387     // Loop, loading longwords and comparing them into rscratch2.
4388     bind(NEXT_WORD);
4389     ldr(tmp1, Address(str1, cnt));
4390     ldr(tmp2, Address(str2, cnt));
4391     adds(cnt, cnt, wordSize);
4392     eor(rscratch2, tmp1, tmp2);
4393     cbnz(rscratch2, DONE);
4394     br(Assembler::LT, NEXT_WORD);
4395 
4396     // Last longword.  In the case where length == 4 we compare the
4397     // same longword twice, but that's still faster than another
4398     // conditional branch.
4399 
4400     ldr(tmp1, Address(str1));
4401     ldr(tmp2, Address(str2));
4402     eor(rscratch2, tmp1, tmp2);
4403     cbz(rscratch2, SAME_CHARS);
4404     b(DONE);
4405   }
4406 
4407   bind(SHORT_STRING);
4408   // Is the length zero?
4409   cbz(cnt, SAME_CHARS);
4410 
4411   bind(SHORT_LOOP);
4412   load_unsigned_short(tmp1, Address(post(str1, 2)));
4413   load_unsigned_short(tmp2, Address(post(str2, 2)));
4414   subw(tmp1, tmp1, tmp2);
4415   cbnz(tmp1, DONE);
4416   sub(cnt, cnt, 1);
4417   cbnz(cnt, SHORT_LOOP);
4418 
4419   // Strings are equal.
4420   bind(SAME_CHARS);
4421   mov(result, true);
4422 
4423   // That's it
4424   bind(DONE);
4425 
4426   BLOCK_COMMENT("} string_equals");
4427 }
4428 
4429 // Compare char[] arrays aligned to 4 bytes
4430 void MacroAssembler::char_arrays_equals(Register ary1, Register ary2,
4431                                         Register result, Register tmp1)
4432 {
4433   Register cnt1 = rscratch1;
4434   Register cnt2 = rscratch2;
4435   Register tmp2 = rscratch2;
4436 
4437   Label SAME, DIFFER, NEXT, TAIL03, TAIL01;
4438 
4439   int length_offset  = arrayOopDesc::length_offset_in_bytes();
4440   int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
4441 
4442   BLOCK_COMMENT("char_arrays_equals  {");
4443 
4444     // different until proven equal
4445     mov(result, false);
4446 
4447     // same array?
4448     cmp(ary1, ary2);
4449     br(Assembler::EQ, SAME);
4450 
4451     // ne if either null
4452     cbz(ary1, DIFFER);
4453     cbz(ary2, DIFFER);
4454 
4455     // lengths ne?
4456     ldrw(cnt1, Address(ary1, length_offset));
4457     ldrw(cnt2, Address(ary2, length_offset));
4458     cmp(cnt1, cnt2);
4459     br(Assembler::NE, DIFFER);
4460 
4461     lea(ary1, Address(ary1, base_offset));
4462     lea(ary2, Address(ary2, base_offset));
4463 
4464     subs(cnt1, cnt1, 4);
4465     br(LT, TAIL03);
4466 
4467   BIND(NEXT);
4468     ldr(tmp1, Address(post(ary1, 8)));
4469     ldr(tmp2, Address(post(ary2, 8)));
4470     subs(cnt1, cnt1, 4);
4471     eor(tmp1, tmp1, tmp2);
4472     cbnz(tmp1, DIFFER);
4473     br(GE, NEXT);
4474 
4475   BIND(TAIL03);  // 0-3 chars left, cnt1 = #chars left - 4
4476     tst(cnt1, 0b10);
4477     br(EQ, TAIL01);
4478     ldrw(tmp1, Address(post(ary1, 4)));
4479     ldrw(tmp2, Address(post(ary2, 4)));
4480     cmp(tmp1, tmp2);
4481     br(NE, DIFFER);
4482   BIND(TAIL01);  // 0-1 chars left
4483     tst(cnt1, 0b01);
4484     br(EQ, SAME);
4485     ldrh(tmp1, ary1);
4486     ldrh(tmp2, ary2);
4487     cmp(tmp1, tmp2);
4488     br(NE, DIFFER);
4489 
4490   BIND(SAME);
4491     mov(result, true);
4492   BIND(DIFFER); // result already set
4493 
4494   BLOCK_COMMENT("} char_arrays_equals");
4495 }
4496 
4497 // encode char[] to byte[] in ISO_8859_1
4498 void MacroAssembler::encode_iso_array(Register src, Register dst,
4499                       Register len, Register result,
4500                       FloatRegister Vtmp1, FloatRegister Vtmp2,
4501                       FloatRegister Vtmp3, FloatRegister Vtmp4)
4502 {
4503     Label DONE, NEXT_32, LOOP_8, NEXT_8, LOOP_1, NEXT_1;
4504     Register tmp1 = rscratch1;
4505 
4506       mov(result, len); // Save initial len
4507 
4508 #ifndef BUILTIN_SIM
4509       subs(len, len, 32);
4510       br(LT, LOOP_8);
4511 
4512 // The following code uses the SIMD 'uqxtn' and 'uqxtn2' instructions
4513 // to convert chars to bytes. These set the 'QC' bit in the FPSR if
4514 // any char could not fit in a byte, so clear the FPSR so we can test it.
4515       clear_fpsr();
4516 
4517     BIND(NEXT_32);
4518       ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
4519       uqxtn(Vtmp1, T8B, Vtmp1, T8H);  // uqxtn  - write bottom half
4520       uqxtn(Vtmp1, T16B, Vtmp2, T8H); // uqxtn2 - write top half
4521       uqxtn(Vtmp2, T8B, Vtmp3, T8H);
4522       uqxtn(Vtmp2, T16B, Vtmp4, T8H); // uqxtn2
4523       get_fpsr(tmp1);
4524       cbnzw(tmp1, LOOP_8);
4525       st1(Vtmp1, Vtmp2, T16B, post(dst, 32));
4526       subs(len, len, 32);
4527       add(src, src, 64);
4528       br(GE, NEXT_32);
4529 
4530     BIND(LOOP_8);
4531       adds(len, len, 32-8);
4532       br(LT, LOOP_1);
4533       clear_fpsr(); // QC may be set from loop above, clear again
4534     BIND(NEXT_8);
4535       ld1(Vtmp1, T8H, src);
4536       uqxtn(Vtmp1, T8B, Vtmp1, T8H);
4537       get_fpsr(tmp1);
4538       cbnzw(tmp1, LOOP_1);
4539       st1(Vtmp1, T8B, post(dst, 8));
4540       subs(len, len, 8);
4541       add(src, src, 16);
4542       br(GE, NEXT_8);
4543 
4544     BIND(LOOP_1);
4545       adds(len, len, 8);
4546       br(LE, DONE);
4547 #else
4548       cbz(len, DONE);
4549 #endif
4550     BIND(NEXT_1);
4551       ldrh(tmp1, Address(post(src, 2)));
4552       tst(tmp1, 0xff00);
4553       br(NE, DONE);
4554       strb(tmp1, Address(post(dst, 1)));
4555       subs(len, len, 1);
4556       br(GT, NEXT_1);
4557 
4558     BIND(DONE);
4559       sub(result, result, len); // Return index where we stopped
4560 }