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