1 /*
   2  * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2016, 2019, SAP SE. 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 "precompiled.hpp"
  27 #include "asm/codeBuffer.hpp"
  28 #include "asm/macroAssembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/barrierSet.hpp"
  31 #include "gc/shared/barrierSetAssembler.hpp"
  32 #include "gc/shared/collectedHeap.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "gc/shared/cardTableBarrierSet.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "memory/universe.hpp"
  37 #include "oops/accessDecorators.hpp"
  38 #include "oops/compressedOops.inline.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "opto/compile.hpp"
  41 #include "opto/intrinsicnode.hpp"
  42 #include "opto/matcher.hpp"
  43 #include "prims/methodHandles.hpp"
  44 #include "registerSaver_s390.hpp"
  45 #include "runtime/biasedLocking.hpp"
  46 #include "runtime/icache.hpp"
  47 #include "runtime/interfaceSupport.inline.hpp"
  48 #include "runtime/objectMonitor.hpp"
  49 #include "runtime/os.hpp"
  50 #include "runtime/safepoint.hpp"
  51 #include "runtime/safepointMechanism.hpp"
  52 #include "runtime/sharedRuntime.hpp"
  53 #include "runtime/stubRoutines.hpp"
  54 #include "utilities/events.hpp"
  55 #include "utilities/macros.hpp"
  56 
  57 #include <ucontext.h>
  58 
  59 #define BLOCK_COMMENT(str) block_comment(str)
  60 #define BIND(label)        bind(label); BLOCK_COMMENT(#label ":")
  61 
  62 // Move 32-bit register if destination and source are different.
  63 void MacroAssembler::lr_if_needed(Register rd, Register rs) {
  64   if (rs != rd) { z_lr(rd, rs); }
  65 }
  66 
  67 // Move register if destination and source are different.
  68 void MacroAssembler::lgr_if_needed(Register rd, Register rs) {
  69   if (rs != rd) { z_lgr(rd, rs); }
  70 }
  71 
  72 // Zero-extend 32-bit register into 64-bit register if destination and source are different.
  73 void MacroAssembler::llgfr_if_needed(Register rd, Register rs) {
  74   if (rs != rd) { z_llgfr(rd, rs); }
  75 }
  76 
  77 // Move float register if destination and source are different.
  78 void MacroAssembler::ldr_if_needed(FloatRegister rd, FloatRegister rs) {
  79   if (rs != rd) { z_ldr(rd, rs); }
  80 }
  81 
  82 // Move integer register if destination and source are different.
  83 // It is assumed that shorter-than-int types are already
  84 // appropriately sign-extended.
  85 void MacroAssembler::move_reg_if_needed(Register dst, BasicType dst_type, Register src,
  86                                         BasicType src_type) {
  87   assert((dst_type != T_FLOAT) && (dst_type != T_DOUBLE), "use move_freg for float types");
  88   assert((src_type != T_FLOAT) && (src_type != T_DOUBLE), "use move_freg for float types");
  89 
  90   if (dst_type == src_type) {
  91     lgr_if_needed(dst, src); // Just move all 64 bits.
  92     return;
  93   }
  94 
  95   switch (dst_type) {
  96     // Do not support these types for now.
  97     //  case T_BOOLEAN:
  98     case T_BYTE:  // signed byte
  99       switch (src_type) {
 100         case T_INT:
 101           z_lgbr(dst, src);
 102           break;
 103         default:
 104           ShouldNotReachHere();
 105       }
 106       return;
 107 
 108     case T_CHAR:
 109     case T_SHORT:
 110       switch (src_type) {
 111         case T_INT:
 112           if (dst_type == T_CHAR) {
 113             z_llghr(dst, src);
 114           } else {
 115             z_lghr(dst, src);
 116           }
 117           break;
 118         default:
 119           ShouldNotReachHere();
 120       }
 121       return;
 122 
 123     case T_INT:
 124       switch (src_type) {
 125         case T_BOOLEAN:
 126         case T_BYTE:
 127         case T_CHAR:
 128         case T_SHORT:
 129         case T_INT:
 130         case T_LONG:
 131         case T_OBJECT:
 132         case T_ARRAY:
 133         case T_VOID:
 134         case T_ADDRESS:
 135           lr_if_needed(dst, src);
 136           // llgfr_if_needed(dst, src);  // zero-extend (in case we need to find a bug).
 137           return;
 138 
 139         default:
 140           assert(false, "non-integer src type");
 141           return;
 142       }
 143     case T_LONG:
 144       switch (src_type) {
 145         case T_BOOLEAN:
 146         case T_BYTE:
 147         case T_CHAR:
 148         case T_SHORT:
 149         case T_INT:
 150           z_lgfr(dst, src); // sign extension
 151           return;
 152 
 153         case T_LONG:
 154         case T_OBJECT:
 155         case T_ARRAY:
 156         case T_VOID:
 157         case T_ADDRESS:
 158           lgr_if_needed(dst, src);
 159           return;
 160 
 161         default:
 162           assert(false, "non-integer src type");
 163           return;
 164       }
 165       return;
 166     case T_OBJECT:
 167     case T_ARRAY:
 168     case T_VOID:
 169     case T_ADDRESS:
 170       switch (src_type) {
 171         // These types don't make sense to be converted to pointers:
 172         //      case T_BOOLEAN:
 173         //      case T_BYTE:
 174         //      case T_CHAR:
 175         //      case T_SHORT:
 176 
 177         case T_INT:
 178           z_llgfr(dst, src); // zero extension
 179           return;
 180 
 181         case T_LONG:
 182         case T_OBJECT:
 183         case T_ARRAY:
 184         case T_VOID:
 185         case T_ADDRESS:
 186           lgr_if_needed(dst, src);
 187           return;
 188 
 189         default:
 190           assert(false, "non-integer src type");
 191           return;
 192       }
 193       return;
 194     default:
 195       assert(false, "non-integer dst type");
 196       return;
 197   }
 198 }
 199 
 200 // Move float register if destination and source are different.
 201 void MacroAssembler::move_freg_if_needed(FloatRegister dst, BasicType dst_type,
 202                                          FloatRegister src, BasicType src_type) {
 203   assert((dst_type == T_FLOAT) || (dst_type == T_DOUBLE), "use move_reg for int types");
 204   assert((src_type == T_FLOAT) || (src_type == T_DOUBLE), "use move_reg for int types");
 205   if (dst_type == src_type) {
 206     ldr_if_needed(dst, src); // Just move all 64 bits.
 207   } else {
 208     switch (dst_type) {
 209       case T_FLOAT:
 210         assert(src_type == T_DOUBLE, "invalid float type combination");
 211         z_ledbr(dst, src);
 212         return;
 213       case T_DOUBLE:
 214         assert(src_type == T_FLOAT, "invalid float type combination");
 215         z_ldebr(dst, src);
 216         return;
 217       default:
 218         assert(false, "non-float dst type");
 219         return;
 220     }
 221   }
 222 }
 223 
 224 // Optimized emitter for reg to mem operations.
 225 // Uses modern instructions if running on modern hardware, classic instructions
 226 // otherwise. Prefers (usually shorter) classic instructions if applicable.
 227 // Data register (reg) cannot be used as work register.
 228 //
 229 // Don't rely on register locking, instead pass a scratch register (Z_R0 by default).
 230 // CAUTION! Passing registers >= Z_R2 may produce bad results on old CPUs!
 231 void MacroAssembler::freg2mem_opt(FloatRegister reg,
 232                                   int64_t       disp,
 233                                   Register      index,
 234                                   Register      base,
 235                                   void (MacroAssembler::*modern) (FloatRegister, int64_t, Register, Register),
 236                                   void (MacroAssembler::*classic)(FloatRegister, int64_t, Register, Register),
 237                                   Register      scratch) {
 238   index = (index == noreg) ? Z_R0 : index;
 239   if (Displacement::is_shortDisp(disp)) {
 240     (this->*classic)(reg, disp, index, base);
 241   } else {
 242     if (Displacement::is_validDisp(disp)) {
 243       (this->*modern)(reg, disp, index, base);
 244     } else {
 245       if (scratch != Z_R0 && scratch != Z_R1) {
 246         (this->*modern)(reg, disp, index, base);      // Will fail with disp out of range.
 247       } else {
 248         if (scratch != Z_R0) {   // scratch == Z_R1
 249           if ((scratch == index) || (index == base)) {
 250             (this->*modern)(reg, disp, index, base);  // Will fail with disp out of range.
 251           } else {
 252             add2reg(scratch, disp, base);
 253             (this->*classic)(reg, 0, index, scratch);
 254             if (base == scratch) {
 255               add2reg(base, -disp);  // Restore base.
 256             }
 257           }
 258         } else {   // scratch == Z_R0
 259           z_lgr(scratch, base);
 260           add2reg(base, disp);
 261           (this->*classic)(reg, 0, index, base);
 262           z_lgr(base, scratch);      // Restore base.
 263         }
 264       }
 265     }
 266   }
 267 }
 268 
 269 void MacroAssembler::freg2mem_opt(FloatRegister reg, const Address &a, bool is_double) {
 270   if (is_double) {
 271     freg2mem_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_FFUN(z_stdy), CLASSIC_FFUN(z_std));
 272   } else {
 273     freg2mem_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_FFUN(z_stey), CLASSIC_FFUN(z_ste));
 274   }
 275 }
 276 
 277 // Optimized emitter for mem to reg operations.
 278 // Uses modern instructions if running on modern hardware, classic instructions
 279 // otherwise. Prefers (usually shorter) classic instructions if applicable.
 280 // data register (reg) cannot be used as work register.
 281 //
 282 // Don't rely on register locking, instead pass a scratch register (Z_R0 by default).
 283 // CAUTION! Passing registers >= Z_R2 may produce bad results on old CPUs!
 284 void MacroAssembler::mem2freg_opt(FloatRegister reg,
 285                                   int64_t       disp,
 286                                   Register      index,
 287                                   Register      base,
 288                                   void (MacroAssembler::*modern) (FloatRegister, int64_t, Register, Register),
 289                                   void (MacroAssembler::*classic)(FloatRegister, int64_t, Register, Register),
 290                                   Register      scratch) {
 291   index = (index == noreg) ? Z_R0 : index;
 292   if (Displacement::is_shortDisp(disp)) {
 293     (this->*classic)(reg, disp, index, base);
 294   } else {
 295     if (Displacement::is_validDisp(disp)) {
 296       (this->*modern)(reg, disp, index, base);
 297     } else {
 298       if (scratch != Z_R0 && scratch != Z_R1) {
 299         (this->*modern)(reg, disp, index, base);      // Will fail with disp out of range.
 300       } else {
 301         if (scratch != Z_R0) {   // scratch == Z_R1
 302           if ((scratch == index) || (index == base)) {
 303             (this->*modern)(reg, disp, index, base);  // Will fail with disp out of range.
 304           } else {
 305             add2reg(scratch, disp, base);
 306             (this->*classic)(reg, 0, index, scratch);
 307             if (base == scratch) {
 308               add2reg(base, -disp);  // Restore base.
 309             }
 310           }
 311         } else {   // scratch == Z_R0
 312           z_lgr(scratch, base);
 313           add2reg(base, disp);
 314           (this->*classic)(reg, 0, index, base);
 315           z_lgr(base, scratch);      // Restore base.
 316         }
 317       }
 318     }
 319   }
 320 }
 321 
 322 void MacroAssembler::mem2freg_opt(FloatRegister reg, const Address &a, bool is_double) {
 323   if (is_double) {
 324     mem2freg_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_FFUN(z_ldy), CLASSIC_FFUN(z_ld));
 325   } else {
 326     mem2freg_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_FFUN(z_ley), CLASSIC_FFUN(z_le));
 327   }
 328 }
 329 
 330 // Optimized emitter for reg to mem operations.
 331 // Uses modern instructions if running on modern hardware, classic instructions
 332 // otherwise. Prefers (usually shorter) classic instructions if applicable.
 333 // Data register (reg) cannot be used as work register.
 334 //
 335 // Don't rely on register locking, instead pass a scratch register
 336 // (Z_R0 by default)
 337 // CAUTION! passing registers >= Z_R2 may produce bad results on old CPUs!
 338 void MacroAssembler::reg2mem_opt(Register reg,
 339                                  int64_t  disp,
 340                                  Register index,
 341                                  Register base,
 342                                  void (MacroAssembler::*modern) (Register, int64_t, Register, Register),
 343                                  void (MacroAssembler::*classic)(Register, int64_t, Register, Register),
 344                                  Register scratch) {
 345   index = (index == noreg) ? Z_R0 : index;
 346   if (Displacement::is_shortDisp(disp)) {
 347     (this->*classic)(reg, disp, index, base);
 348   } else {
 349     if (Displacement::is_validDisp(disp)) {
 350       (this->*modern)(reg, disp, index, base);
 351     } else {
 352       if (scratch != Z_R0 && scratch != Z_R1) {
 353         (this->*modern)(reg, disp, index, base);      // Will fail with disp out of range.
 354       } else {
 355         if (scratch != Z_R0) {   // scratch == Z_R1
 356           if ((scratch == index) || (index == base)) {
 357             (this->*modern)(reg, disp, index, base);  // Will fail with disp out of range.
 358           } else {
 359             add2reg(scratch, disp, base);
 360             (this->*classic)(reg, 0, index, scratch);
 361             if (base == scratch) {
 362               add2reg(base, -disp);  // Restore base.
 363             }
 364           }
 365         } else {   // scratch == Z_R0
 366           if ((scratch == reg) || (scratch == base) || (reg == base)) {
 367             (this->*modern)(reg, disp, index, base);  // Will fail with disp out of range.
 368           } else {
 369             z_lgr(scratch, base);
 370             add2reg(base, disp);
 371             (this->*classic)(reg, 0, index, base);
 372             z_lgr(base, scratch);    // Restore base.
 373           }
 374         }
 375       }
 376     }
 377   }
 378 }
 379 
 380 int MacroAssembler::reg2mem_opt(Register reg, const Address &a, bool is_double) {
 381   int store_offset = offset();
 382   if (is_double) {
 383     reg2mem_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_IFUN(z_stg), CLASSIC_IFUN(z_stg));
 384   } else {
 385     reg2mem_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_IFUN(z_sty), CLASSIC_IFUN(z_st));
 386   }
 387   return store_offset;
 388 }
 389 
 390 // Optimized emitter for mem to reg operations.
 391 // Uses modern instructions if running on modern hardware, classic instructions
 392 // otherwise. Prefers (usually shorter) classic instructions if applicable.
 393 // Data register (reg) will be used as work register where possible.
 394 void MacroAssembler::mem2reg_opt(Register reg,
 395                                  int64_t  disp,
 396                                  Register index,
 397                                  Register base,
 398                                  void (MacroAssembler::*modern) (Register, int64_t, Register, Register),
 399                                  void (MacroAssembler::*classic)(Register, int64_t, Register, Register)) {
 400   index = (index == noreg) ? Z_R0 : index;
 401   if (Displacement::is_shortDisp(disp)) {
 402     (this->*classic)(reg, disp, index, base);
 403   } else {
 404     if (Displacement::is_validDisp(disp)) {
 405       (this->*modern)(reg, disp, index, base);
 406     } else {
 407       if ((reg == index) && (reg == base)) {
 408         z_sllg(reg, reg, 1);
 409         add2reg(reg, disp);
 410         (this->*classic)(reg, 0, noreg, reg);
 411       } else if ((reg == index) && (reg != Z_R0)) {
 412         add2reg(reg, disp);
 413         (this->*classic)(reg, 0, reg, base);
 414       } else if (reg == base) {
 415         add2reg(reg, disp);
 416         (this->*classic)(reg, 0, index, reg);
 417       } else if (reg != Z_R0) {
 418         add2reg(reg, disp, base);
 419         (this->*classic)(reg, 0, index, reg);
 420       } else { // reg == Z_R0 && reg != base here
 421         add2reg(base, disp);
 422         (this->*classic)(reg, 0, index, base);
 423         add2reg(base, -disp);
 424       }
 425     }
 426   }
 427 }
 428 
 429 void MacroAssembler::mem2reg_opt(Register reg, const Address &a, bool is_double) {
 430   if (is_double) {
 431     z_lg(reg, a);
 432   } else {
 433     mem2reg_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_IFUN(z_ly), CLASSIC_IFUN(z_l));
 434   }
 435 }
 436 
 437 void MacroAssembler::mem2reg_signed_opt(Register reg, const Address &a) {
 438   mem2reg_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_IFUN(z_lgf), CLASSIC_IFUN(z_lgf));
 439 }
 440 
 441 void MacroAssembler::and_imm(Register r, long mask,
 442                              Register tmp /* = Z_R0 */,
 443                              bool wide    /* = false */) {
 444   assert(wide || Immediate::is_simm32(mask), "mask value too large");
 445 
 446   if (!wide) {
 447     z_nilf(r, mask);
 448     return;
 449   }
 450 
 451   assert(r != tmp, " need a different temporary register !");
 452   load_const_optimized(tmp, mask);
 453   z_ngr(r, tmp);
 454 }
 455 
 456 // Calculate the 1's complement.
 457 // Note: The condition code is neither preserved nor correctly set by this code!!!
 458 // Note: (wide == false) does not protect the high order half of the target register
 459 //       from alteration. It only serves as optimization hint for 32-bit results.
 460 void MacroAssembler::not_(Register r1, Register r2, bool wide) {
 461 
 462   if ((r2 == noreg) || (r2 == r1)) { // Calc 1's complement in place.
 463     z_xilf(r1, -1);
 464     if (wide) {
 465       z_xihf(r1, -1);
 466     }
 467   } else { // Distinct src and dst registers.
 468     load_const_optimized(r1, -1);
 469     z_xgr(r1, r2);
 470   }
 471 }
 472 
 473 unsigned long MacroAssembler::create_mask(int lBitPos, int rBitPos) {
 474   assert(lBitPos >=  0,      "zero is  leftmost bit position");
 475   assert(rBitPos <= 63,      "63   is rightmost bit position");
 476   assert(lBitPos <= rBitPos, "inverted selection interval");
 477   return (lBitPos == 0 ? (unsigned long)(-1L) : ((1UL<<(63-lBitPos+1))-1)) & (~((1UL<<(63-rBitPos))-1));
 478 }
 479 
 480 // Helper function for the "Rotate_then_<logicalOP>" emitters.
 481 // Rotate src, then mask register contents such that only bits in range survive.
 482 // For oneBits == false, all bits not in range are set to 0. Useful for deleting all bits outside range.
 483 // For oneBits == true,  all bits not in range are set to 1. Useful for preserving all bits outside range.
 484 // The caller must ensure that the selected range only contains bits with defined value.
 485 void MacroAssembler::rotate_then_mask(Register dst, Register src, int lBitPos, int rBitPos,
 486                                       int nRotate, bool src32bit, bool dst32bit, bool oneBits) {
 487   assert(!(dst32bit && lBitPos < 32), "selection interval out of range for int destination");
 488   bool sll4rll = (nRotate >= 0) && (nRotate <= (63-rBitPos)); // Substitute SLL(G) for RLL(G).
 489   bool srl4rll = (nRotate <  0) && (-nRotate <= lBitPos);     // Substitute SRL(G) for RLL(G).
 490   //  Pre-determine which parts of dst will be zero after shift/rotate.
 491   bool llZero  =  sll4rll && (nRotate >= 16);
 492   bool lhZero  = (sll4rll && (nRotate >= 32)) || (srl4rll && (nRotate <= -48));
 493   bool lfZero  = llZero && lhZero;
 494   bool hlZero  = (sll4rll && (nRotate >= 48)) || (srl4rll && (nRotate <= -32));
 495   bool hhZero  =                                 (srl4rll && (nRotate <= -16));
 496   bool hfZero  = hlZero && hhZero;
 497 
 498   // rotate then mask src operand.
 499   // if oneBits == true,  all bits outside selected range are 1s.
 500   // if oneBits == false, all bits outside selected range are 0s.
 501   if (src32bit) {   // There might be garbage in the upper 32 bits which will get masked away.
 502     if (dst32bit) {
 503       z_rll(dst, src, nRotate);   // Copy and rotate, upper half of reg remains undisturbed.
 504     } else {
 505       if      (sll4rll) { z_sllg(dst, src,  nRotate); }
 506       else if (srl4rll) { z_srlg(dst, src, -nRotate); }
 507       else              { z_rllg(dst, src,  nRotate); }
 508     }
 509   } else {
 510     if      (sll4rll) { z_sllg(dst, src,  nRotate); }
 511     else if (srl4rll) { z_srlg(dst, src, -nRotate); }
 512     else              { z_rllg(dst, src,  nRotate); }
 513   }
 514 
 515   unsigned long  range_mask    = create_mask(lBitPos, rBitPos);
 516   unsigned int   range_mask_h  = (unsigned int)(range_mask >> 32);
 517   unsigned int   range_mask_l  = (unsigned int)range_mask;
 518   unsigned short range_mask_hh = (unsigned short)(range_mask >> 48);
 519   unsigned short range_mask_hl = (unsigned short)(range_mask >> 32);
 520   unsigned short range_mask_lh = (unsigned short)(range_mask >> 16);
 521   unsigned short range_mask_ll = (unsigned short)range_mask;
 522   // Works for z9 and newer H/W.
 523   if (oneBits) {
 524     if ((~range_mask_l) != 0)                { z_oilf(dst, ~range_mask_l); } // All bits outside range become 1s.
 525     if (((~range_mask_h) != 0) && !dst32bit) { z_oihf(dst, ~range_mask_h); }
 526   } else {
 527     // All bits outside range become 0s
 528     if (((~range_mask_l) != 0) &&              !lfZero) {
 529       z_nilf(dst, range_mask_l);
 530     }
 531     if (((~range_mask_h) != 0) && !dst32bit && !hfZero) {
 532       z_nihf(dst, range_mask_h);
 533     }
 534   }
 535 }
 536 
 537 // Rotate src, then insert selected range from rotated src into dst.
 538 // Clear dst before, if requested.
 539 void MacroAssembler::rotate_then_insert(Register dst, Register src, int lBitPos, int rBitPos,
 540                                         int nRotate, bool clear_dst) {
 541   // This version does not depend on src being zero-extended int2long.
 542   nRotate &= 0x003f;                                       // For risbg, pretend it's an unsigned value.
 543   z_risbg(dst, src, lBitPos, rBitPos, nRotate, clear_dst); // Rotate, then insert selected, clear the rest.
 544 }
 545 
 546 // Rotate src, then and selected range from rotated src into dst.
 547 // Set condition code only if so requested. Otherwise it is unpredictable.
 548 // See performance note in macroAssembler_s390.hpp for important information.
 549 void MacroAssembler::rotate_then_and(Register dst, Register src, int lBitPos, int rBitPos,
 550                                      int nRotate, bool test_only) {
 551   guarantee(!test_only, "Emitter not fit for test_only instruction variant.");
 552   // This version does not depend on src being zero-extended int2long.
 553   nRotate &= 0x003f;                                       // For risbg, pretend it's an unsigned value.
 554   z_rxsbg(dst, src, lBitPos, rBitPos, nRotate, test_only); // Rotate, then xor selected.
 555 }
 556 
 557 // Rotate src, then or selected range from rotated src into dst.
 558 // Set condition code only if so requested. Otherwise it is unpredictable.
 559 // See performance note in macroAssembler_s390.hpp for important information.
 560 void MacroAssembler::rotate_then_or(Register dst, Register src,  int  lBitPos,  int  rBitPos,
 561                                     int nRotate, bool test_only) {
 562   guarantee(!test_only, "Emitter not fit for test_only instruction variant.");
 563   // This version does not depend on src being zero-extended int2long.
 564   nRotate &= 0x003f;                                       // For risbg, pretend it's an unsigned value.
 565   z_rosbg(dst, src, lBitPos, rBitPos, nRotate, test_only); // Rotate, then xor selected.
 566 }
 567 
 568 // Rotate src, then xor selected range from rotated src into dst.
 569 // Set condition code only if so requested. Otherwise it is unpredictable.
 570 // See performance note in macroAssembler_s390.hpp for important information.
 571 void MacroAssembler::rotate_then_xor(Register dst, Register src,  int  lBitPos,  int  rBitPos,
 572                                      int nRotate, bool test_only) {
 573   guarantee(!test_only, "Emitter not fit for test_only instruction variant.");
 574     // This version does not depend on src being zero-extended int2long.
 575   nRotate &= 0x003f;                                       // For risbg, pretend it's an unsigned value.
 576   z_rxsbg(dst, src, lBitPos, rBitPos, nRotate, test_only); // Rotate, then xor selected.
 577 }
 578 
 579 void MacroAssembler::add64(Register r1, RegisterOrConstant inc) {
 580   if (inc.is_register()) {
 581     z_agr(r1, inc.as_register());
 582   } else { // constant
 583     intptr_t imm = inc.as_constant();
 584     add2reg(r1, imm);
 585   }
 586 }
 587 // Helper function to multiply the 64bit contents of a register by a 16bit constant.
 588 // The optimization tries to avoid the mghi instruction, since it uses the FPU for
 589 // calculation and is thus rather slow.
 590 //
 591 // There is no handling for special cases, e.g. cval==0 or cval==1.
 592 //
 593 // Returns len of generated code block.
 594 unsigned int MacroAssembler::mul_reg64_const16(Register rval, Register work, int cval) {
 595   int block_start = offset();
 596 
 597   bool sign_flip = cval < 0;
 598   cval = sign_flip ? -cval : cval;
 599 
 600   BLOCK_COMMENT("Reg64*Con16 {");
 601 
 602   int bit1 = cval & -cval;
 603   if (bit1 == cval) {
 604     z_sllg(rval, rval, exact_log2(bit1));
 605     if (sign_flip) { z_lcgr(rval, rval); }
 606   } else {
 607     int bit2 = (cval-bit1) & -(cval-bit1);
 608     if ((bit1+bit2) == cval) {
 609       z_sllg(work, rval, exact_log2(bit1));
 610       z_sllg(rval, rval, exact_log2(bit2));
 611       z_agr(rval, work);
 612       if (sign_flip) { z_lcgr(rval, rval); }
 613     } else {
 614       if (sign_flip) { z_mghi(rval, -cval); }
 615       else           { z_mghi(rval,  cval); }
 616     }
 617   }
 618   BLOCK_COMMENT("} Reg64*Con16");
 619 
 620   int block_end = offset();
 621   return block_end - block_start;
 622 }
 623 
 624 // Generic operation r1 := r2 + imm.
 625 //
 626 // Should produce the best code for each supported CPU version.
 627 // r2 == noreg yields r1 := r1 + imm
 628 // imm == 0 emits either no instruction or r1 := r2 !
 629 // NOTES: 1) Don't use this function where fixed sized
 630 //           instruction sequences are required!!!
 631 //        2) Don't use this function if condition code
 632 //           setting is required!
 633 //        3) Despite being declared as int64_t, the parameter imm
 634 //           must be a simm_32 value (= signed 32-bit integer).
 635 void MacroAssembler::add2reg(Register r1, int64_t imm, Register r2) {
 636   assert(Immediate::is_simm32(imm), "probably an implicit conversion went wrong");
 637 
 638   if (r2 == noreg) { r2 = r1; }
 639 
 640   // Handle special case imm == 0.
 641   if (imm == 0) {
 642     lgr_if_needed(r1, r2);
 643     // Nothing else to do.
 644     return;
 645   }
 646 
 647   if (!PreferLAoverADD || (r2 == Z_R0)) {
 648     bool distinctOpnds = VM_Version::has_DistinctOpnds();
 649 
 650     // Can we encode imm in 16 bits signed?
 651     if (Immediate::is_simm16(imm)) {
 652       if (r1 == r2) {
 653         z_aghi(r1, imm);
 654         return;
 655       }
 656       if (distinctOpnds) {
 657         z_aghik(r1, r2, imm);
 658         return;
 659       }
 660       z_lgr(r1, r2);
 661       z_aghi(r1, imm);
 662       return;
 663     }
 664   } else {
 665     // Can we encode imm in 12 bits unsigned?
 666     if (Displacement::is_shortDisp(imm)) {
 667       z_la(r1, imm, r2);
 668       return;
 669     }
 670     // Can we encode imm in 20 bits signed?
 671     if (Displacement::is_validDisp(imm)) {
 672       // Always use LAY instruction, so we don't need the tmp register.
 673       z_lay(r1, imm, r2);
 674       return;
 675     }
 676 
 677   }
 678 
 679   // Can handle it (all possible values) with long immediates.
 680   lgr_if_needed(r1, r2);
 681   z_agfi(r1, imm);
 682 }
 683 
 684 // Generic operation r := b + x + d
 685 //
 686 // Addition of several operands with address generation semantics - sort of:
 687 //  - no restriction on the registers. Any register will do for any operand.
 688 //  - x == noreg: operand will be disregarded.
 689 //  - b == noreg: will use (contents of) result reg as operand (r := r + d).
 690 //  - x == Z_R0:  just disregard
 691 //  - b == Z_R0:  use as operand. This is not address generation semantics!!!
 692 //
 693 // The same restrictions as on add2reg() are valid!!!
 694 void MacroAssembler::add2reg_with_index(Register r, int64_t d, Register x, Register b) {
 695   assert(Immediate::is_simm32(d), "probably an implicit conversion went wrong");
 696 
 697   if (x == noreg) { x = Z_R0; }
 698   if (b == noreg) { b = r; }
 699 
 700   // Handle special case x == R0.
 701   if (x == Z_R0) {
 702     // Can simply add the immediate value to the base register.
 703     add2reg(r, d, b);
 704     return;
 705   }
 706 
 707   if (!PreferLAoverADD || (b == Z_R0)) {
 708     bool distinctOpnds = VM_Version::has_DistinctOpnds();
 709     // Handle special case d == 0.
 710     if (d == 0) {
 711       if (b == x)        { z_sllg(r, b, 1); return; }
 712       if (r == x)        { z_agr(r, b);     return; }
 713       if (r == b)        { z_agr(r, x);     return; }
 714       if (distinctOpnds) { z_agrk(r, x, b); return; }
 715       z_lgr(r, b);
 716       z_agr(r, x);
 717     } else {
 718       if (x == b)             { z_sllg(r, x, 1); }
 719       else if (r == x)        { z_agr(r, b); }
 720       else if (r == b)        { z_agr(r, x); }
 721       else if (distinctOpnds) { z_agrk(r, x, b); }
 722       else {
 723         z_lgr(r, b);
 724         z_agr(r, x);
 725       }
 726       add2reg(r, d);
 727     }
 728   } else {
 729     // Can we encode imm in 12 bits unsigned?
 730     if (Displacement::is_shortDisp(d)) {
 731       z_la(r, d, x, b);
 732       return;
 733     }
 734     // Can we encode imm in 20 bits signed?
 735     if (Displacement::is_validDisp(d)) {
 736       z_lay(r, d, x, b);
 737       return;
 738     }
 739     z_la(r, 0, x, b);
 740     add2reg(r, d);
 741   }
 742 }
 743 
 744 // Generic emitter (32bit) for direct memory increment.
 745 // For optimal code, do not specify Z_R0 as temp register.
 746 void MacroAssembler::add2mem_32(const Address &a, int64_t imm, Register tmp) {
 747   if (VM_Version::has_MemWithImmALUOps() && Immediate::is_simm8(imm)) {
 748     z_asi(a, imm);
 749   } else {
 750     z_lgf(tmp, a);
 751     add2reg(tmp, imm);
 752     z_st(tmp, a);
 753   }
 754 }
 755 
 756 void MacroAssembler::add2mem_64(const Address &a, int64_t imm, Register tmp) {
 757   if (VM_Version::has_MemWithImmALUOps() && Immediate::is_simm8(imm)) {
 758     z_agsi(a, imm);
 759   } else {
 760     z_lg(tmp, a);
 761     add2reg(tmp, imm);
 762     z_stg(tmp, a);
 763   }
 764 }
 765 
 766 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
 767   switch (size_in_bytes) {
 768     case  8: z_lg(dst, src); break;
 769     case  4: is_signed ? z_lgf(dst, src) : z_llgf(dst, src); break;
 770     case  2: is_signed ? z_lgh(dst, src) : z_llgh(dst, src); break;
 771     case  1: is_signed ? z_lgb(dst, src) : z_llgc(dst, src); break;
 772     default: ShouldNotReachHere();
 773   }
 774 }
 775 
 776 void MacroAssembler::store_sized_value(Register src, Address dst, size_t size_in_bytes) {
 777   switch (size_in_bytes) {
 778     case  8: z_stg(src, dst); break;
 779     case  4: z_st(src, dst); break;
 780     case  2: z_sth(src, dst); break;
 781     case  1: z_stc(src, dst); break;
 782     default: ShouldNotReachHere();
 783   }
 784 }
 785 
 786 // Split a si20 offset (20bit, signed) into an ui12 offset (12bit, unsigned) and
 787 // a high-order summand in register tmp.
 788 //
 789 // return value: <  0: No split required, si20 actually has property uimm12.
 790 //               >= 0: Split performed. Use return value as uimm12 displacement and
 791 //                     tmp as index register.
 792 int MacroAssembler::split_largeoffset(int64_t si20_offset, Register tmp, bool fixed_codelen, bool accumulate) {
 793   assert(Immediate::is_simm20(si20_offset), "sanity");
 794   int lg_off = (int)si20_offset &  0x0fff; // Punch out low-order 12 bits, always positive.
 795   int ll_off = (int)si20_offset & ~0x0fff; // Force low-order 12 bits to zero.
 796   assert((Displacement::is_shortDisp(si20_offset) && (ll_off == 0)) ||
 797          !Displacement::is_shortDisp(si20_offset), "unexpected offset values");
 798   assert((lg_off+ll_off) == si20_offset, "offset splitup error");
 799 
 800   Register work = accumulate? Z_R0 : tmp;
 801 
 802   if (fixed_codelen) {          // Len of code = 10 = 4 + 6.
 803     z_lghi(work, ll_off>>12);   // Implicit sign extension.
 804     z_slag(work, work, 12);
 805   } else {                      // Len of code = 0..10.
 806     if (ll_off == 0) { return -1; }
 807     // ll_off has 8 significant bits (at most) plus sign.
 808     if ((ll_off & 0x0000f000) == 0) {    // Non-zero bits only in upper halfbyte.
 809       z_llilh(work, ll_off >> 16);
 810       if (ll_off < 0) {                  // Sign-extension required.
 811         z_lgfr(work, work);
 812       }
 813     } else {
 814       if ((ll_off & 0x000f0000) == 0) {  // Non-zero bits only in lower halfbyte.
 815         z_llill(work, ll_off);
 816       } else {                           // Non-zero bits in both halfbytes.
 817         z_lghi(work, ll_off>>12);        // Implicit sign extension.
 818         z_slag(work, work, 12);
 819       }
 820     }
 821   }
 822   if (accumulate) { z_algr(tmp, work); } // len of code += 4
 823   return lg_off;
 824 }
 825 
 826 void MacroAssembler::load_float_largeoffset(FloatRegister t, int64_t si20, Register a, Register tmp) {
 827   if (Displacement::is_validDisp(si20)) {
 828     z_ley(t, si20, a);
 829   } else {
 830     // Fixed_codelen = true is a simple way to ensure that the size of load_float_largeoffset
 831     // does not depend on si20 (scratch buffer emit size == code buffer emit size for constant
 832     // pool loads).
 833     bool accumulate    = true;
 834     bool fixed_codelen = true;
 835     Register work;
 836 
 837     if (fixed_codelen) {
 838       z_lgr(tmp, a);  // Lgr_if_needed not applicable due to fixed_codelen.
 839     } else {
 840       accumulate = (a == tmp);
 841     }
 842     work = tmp;
 843 
 844     int disp12 = split_largeoffset(si20, work, fixed_codelen, accumulate);
 845     if (disp12 < 0) {
 846       z_le(t, si20, work);
 847     } else {
 848       if (accumulate) {
 849         z_le(t, disp12, work);
 850       } else {
 851         z_le(t, disp12, work, a);
 852       }
 853     }
 854   }
 855 }
 856 
 857 void MacroAssembler::load_double_largeoffset(FloatRegister t, int64_t si20, Register a, Register tmp) {
 858   if (Displacement::is_validDisp(si20)) {
 859     z_ldy(t, si20, a);
 860   } else {
 861     // Fixed_codelen = true is a simple way to ensure that the size of load_double_largeoffset
 862     // does not depend on si20 (scratch buffer emit size == code buffer emit size for constant
 863     // pool loads).
 864     bool accumulate    = true;
 865     bool fixed_codelen = true;
 866     Register work;
 867 
 868     if (fixed_codelen) {
 869       z_lgr(tmp, a);  // Lgr_if_needed not applicable due to fixed_codelen.
 870     } else {
 871       accumulate = (a == tmp);
 872     }
 873     work = tmp;
 874 
 875     int disp12 = split_largeoffset(si20, work, fixed_codelen, accumulate);
 876     if (disp12 < 0) {
 877       z_ld(t, si20, work);
 878     } else {
 879       if (accumulate) {
 880         z_ld(t, disp12, work);
 881       } else {
 882         z_ld(t, disp12, work, a);
 883       }
 884     }
 885   }
 886 }
 887 
 888 // PCrelative TOC access.
 889 // Returns distance (in bytes) from current position to start of consts section.
 890 // Returns 0 (zero) if no consts section exists or if it has size zero.
 891 long MacroAssembler::toc_distance() {
 892   CodeSection* cs = code()->consts();
 893   return (long)((cs != NULL) ? cs->start()-pc() : 0);
 894 }
 895 
 896 // Implementation on x86/sparc assumes that constant and instruction section are
 897 // adjacent, but this doesn't hold. Two special situations may occur, that we must
 898 // be able to handle:
 899 //   1. const section may be located apart from the inst section.
 900 //   2. const section may be empty
 901 // In both cases, we use the const section's start address to compute the "TOC",
 902 // this seems to occur only temporarily; in the final step we always seem to end up
 903 // with the pc-relatice variant.
 904 //
 905 // PC-relative offset could be +/-2**32 -> use long for disp
 906 // Furthermore: makes no sense to have special code for
 907 // adjacent const and inst sections.
 908 void MacroAssembler::load_toc(Register Rtoc) {
 909   // Simply use distance from start of const section (should be patched in the end).
 910   long disp = toc_distance();
 911 
 912   RelocationHolder rspec = internal_word_Relocation::spec(pc() + disp);
 913   relocate(rspec);
 914   z_larl(Rtoc, RelAddr::pcrel_off32(disp));  // Offset is in halfwords.
 915 }
 916 
 917 // PCrelative TOC access.
 918 // Load from anywhere pcrelative (with relocation of load instr)
 919 void MacroAssembler::load_long_pcrelative(Register Rdst, address dataLocation) {
 920   address          pc             = this->pc();
 921   ptrdiff_t        total_distance = dataLocation - pc;
 922   RelocationHolder rspec          = internal_word_Relocation::spec(dataLocation);
 923 
 924   assert((total_distance & 0x01L) == 0, "halfword alignment is mandatory");
 925   assert(total_distance != 0, "sanity");
 926 
 927   // Some extra safety net.
 928   if (!RelAddr::is_in_range_of_RelAddr32(total_distance)) {
 929     guarantee(RelAddr::is_in_range_of_RelAddr32(total_distance), "load_long_pcrelative can't handle distance " INTPTR_FORMAT, total_distance);
 930   }
 931 
 932   (this)->relocate(rspec, relocInfo::pcrel_addr_format);
 933   z_lgrl(Rdst, RelAddr::pcrel_off32(total_distance));
 934 }
 935 
 936 
 937 // PCrelative TOC access.
 938 // Load from anywhere pcrelative (with relocation of load instr)
 939 // loaded addr has to be relocated when added to constant pool.
 940 void MacroAssembler::load_addr_pcrelative(Register Rdst, address addrLocation) {
 941   address          pc             = this->pc();
 942   ptrdiff_t        total_distance = addrLocation - pc;
 943   RelocationHolder rspec          = internal_word_Relocation::spec(addrLocation);
 944 
 945   assert((total_distance & 0x01L) == 0, "halfword alignment is mandatory");
 946 
 947   // Some extra safety net.
 948   if (!RelAddr::is_in_range_of_RelAddr32(total_distance)) {
 949     guarantee(RelAddr::is_in_range_of_RelAddr32(total_distance), "load_long_pcrelative can't handle distance " INTPTR_FORMAT, total_distance);
 950   }
 951 
 952   (this)->relocate(rspec, relocInfo::pcrel_addr_format);
 953   z_lgrl(Rdst, RelAddr::pcrel_off32(total_distance));
 954 }
 955 
 956 // Generic operation: load a value from memory and test.
 957 // CondCode indicates the sign (<0, ==0, >0) of the loaded value.
 958 void MacroAssembler::load_and_test_byte(Register dst, const Address &a) {
 959   z_lb(dst, a);
 960   z_ltr(dst, dst);
 961 }
 962 
 963 void MacroAssembler::load_and_test_short(Register dst, const Address &a) {
 964   int64_t disp = a.disp20();
 965   if (Displacement::is_shortDisp(disp)) {
 966     z_lh(dst, a);
 967   } else if (Displacement::is_longDisp(disp)) {
 968     z_lhy(dst, a);
 969   } else {
 970     guarantee(false, "displacement out of range");
 971   }
 972   z_ltr(dst, dst);
 973 }
 974 
 975 void MacroAssembler::load_and_test_int(Register dst, const Address &a) {
 976   z_lt(dst, a);
 977 }
 978 
 979 void MacroAssembler::load_and_test_int2long(Register dst, const Address &a) {
 980   z_ltgf(dst, a);
 981 }
 982 
 983 void MacroAssembler::load_and_test_long(Register dst, const Address &a) {
 984   z_ltg(dst, a);
 985 }
 986 
 987 // Test a bit in memory.
 988 void MacroAssembler::testbit(const Address &a, unsigned int bit) {
 989   assert(a.index() == noreg, "no index reg allowed in testbit");
 990   if (bit <= 7) {
 991     z_tm(a.disp() + 3, a.base(), 1 << bit);
 992   } else if (bit <= 15) {
 993     z_tm(a.disp() + 2, a.base(), 1 << (bit - 8));
 994   } else if (bit <= 23) {
 995     z_tm(a.disp() + 1, a.base(), 1 << (bit - 16));
 996   } else if (bit <= 31) {
 997     z_tm(a.disp() + 0, a.base(), 1 << (bit - 24));
 998   } else {
 999     ShouldNotReachHere();
1000   }
1001 }
1002 
1003 // Test a bit in a register. Result is reflected in CC.
1004 void MacroAssembler::testbit(Register r, unsigned int bitPos) {
1005   if (bitPos < 16) {
1006     z_tmll(r, 1U<<bitPos);
1007   } else if (bitPos < 32) {
1008     z_tmlh(r, 1U<<(bitPos-16));
1009   } else if (bitPos < 48) {
1010     z_tmhl(r, 1U<<(bitPos-32));
1011   } else if (bitPos < 64) {
1012     z_tmhh(r, 1U<<(bitPos-48));
1013   } else {
1014     ShouldNotReachHere();
1015   }
1016 }
1017 
1018 void MacroAssembler::prefetch_read(Address a) {
1019   z_pfd(1, a.disp20(), a.indexOrR0(), a.base());
1020 }
1021 void MacroAssembler::prefetch_update(Address a) {
1022   z_pfd(2, a.disp20(), a.indexOrR0(), a.base());
1023 }
1024 
1025 // Clear a register, i.e. load const zero into reg.
1026 // Return len (in bytes) of generated instruction(s).
1027 // whole_reg: Clear 64 bits if true, 32 bits otherwise.
1028 // set_cc:    Use instruction that sets the condition code, if true.
1029 int MacroAssembler::clear_reg(Register r, bool whole_reg, bool set_cc) {
1030   unsigned int start_off = offset();
1031   if (whole_reg) {
1032     set_cc ? z_xgr(r, r) : z_laz(r, 0, Z_R0);
1033   } else {  // Only 32bit register.
1034     set_cc ? z_xr(r, r) : z_lhi(r, 0);
1035   }
1036   return offset() - start_off;
1037 }
1038 
1039 #ifdef ASSERT
1040 int MacroAssembler::preset_reg(Register r, unsigned long pattern, int pattern_len) {
1041   switch (pattern_len) {
1042     case 1:
1043       pattern = (pattern & 0x000000ff)  | ((pattern & 0x000000ff)<<8);
1044     case 2:
1045       pattern = (pattern & 0x0000ffff)  | ((pattern & 0x0000ffff)<<16);
1046     case 4:
1047       pattern = (pattern & 0xffffffffL) | ((pattern & 0xffffffffL)<<32);
1048     case 8:
1049       return load_const_optimized_rtn_len(r, pattern, true);
1050       break;
1051     default:
1052       guarantee(false, "preset_reg: bad len");
1053   }
1054   return 0;
1055 }
1056 #endif
1057 
1058 // addr: Address descriptor of memory to clear index register will not be used !
1059 // size: Number of bytes to clear.
1060 //    !!! DO NOT USE THEM FOR ATOMIC MEMORY CLEARING !!!
1061 //    !!! Use store_const() instead                  !!!
1062 void MacroAssembler::clear_mem(const Address& addr, unsigned size) {
1063   guarantee(size <= 256, "MacroAssembler::clear_mem: size too large");
1064 
1065   if (size == 1) {
1066     z_mvi(addr, 0);
1067     return;
1068   }
1069 
1070   switch (size) {
1071     case 2: z_mvhhi(addr, 0);
1072       return;
1073     case 4: z_mvhi(addr, 0);
1074       return;
1075     case 8: z_mvghi(addr, 0);
1076       return;
1077     default: ; // Fallthru to xc.
1078   }
1079 
1080   z_xc(addr, size, addr);
1081 }
1082 
1083 void MacroAssembler::align(int modulus) {
1084   while (offset() % modulus != 0) z_nop();
1085 }
1086 
1087 // Special version for non-relocateable code if required alignment
1088 // is larger than CodeEntryAlignment.
1089 void MacroAssembler::align_address(int modulus) {
1090   while ((uintptr_t)pc() % modulus != 0) z_nop();
1091 }
1092 
1093 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
1094                                          Register temp_reg,
1095                                          int64_t extra_slot_offset) {
1096   // On Z, we can have index and disp in an Address. So don't call argument_offset,
1097   // which issues an unnecessary add instruction.
1098   int stackElementSize = Interpreter::stackElementSize;
1099   int64_t offset = extra_slot_offset * stackElementSize;
1100   const Register argbase = Z_esp;
1101   if (arg_slot.is_constant()) {
1102     offset += arg_slot.as_constant() * stackElementSize;
1103     return Address(argbase, offset);
1104   }
1105   // else
1106   assert(temp_reg != noreg, "must specify");
1107   assert(temp_reg != Z_ARG1, "base and index are conflicting");
1108   z_sllg(temp_reg, arg_slot.as_register(), exact_log2(stackElementSize)); // tempreg = arg_slot << 3
1109   return Address(argbase, temp_reg, offset);
1110 }
1111 
1112 
1113 //===================================================================
1114 //===   START   C O N S T A N T S   I N   C O D E   S T R E A M   ===
1115 //===================================================================
1116 //===            P A T CH A B L E   C O N S T A N T S             ===
1117 //===================================================================
1118 
1119 
1120 //---------------------------------------------------
1121 //  Load (patchable) constant into register
1122 //---------------------------------------------------
1123 
1124 
1125 // Load absolute address (and try to optimize).
1126 //   Note: This method is usable only for position-fixed code,
1127 //         referring to a position-fixed target location.
1128 //         If not so, relocations and patching must be used.
1129 void MacroAssembler::load_absolute_address(Register d, address addr) {
1130   assert(addr != NULL, "should not happen");
1131   BLOCK_COMMENT("load_absolute_address:");
1132   if (addr == NULL) {
1133     z_larl(d, pc()); // Dummy emit for size calc.
1134     return;
1135   }
1136 
1137   if (RelAddr::is_in_range_of_RelAddr32(addr, pc())) {
1138     z_larl(d, addr);
1139     return;
1140   }
1141 
1142   load_const_optimized(d, (long)addr);
1143 }
1144 
1145 // Load a 64bit constant.
1146 // Patchable code sequence, but not atomically patchable.
1147 // Make sure to keep code size constant -> no value-dependent optimizations.
1148 // Do not kill condition code.
1149 void MacroAssembler::load_const(Register t, long x) {
1150   // Note: Right shift is only cleanly defined for unsigned types
1151   //       or for signed types with nonnegative values.
1152   Assembler::z_iihf(t, (long)((unsigned long)x >> 32));
1153   Assembler::z_iilf(t, (long)((unsigned long)x & 0xffffffffUL));
1154 }
1155 
1156 // Load a 32bit constant into a 64bit register, sign-extend or zero-extend.
1157 // Patchable code sequence, but not atomically patchable.
1158 // Make sure to keep code size constant -> no value-dependent optimizations.
1159 // Do not kill condition code.
1160 void MacroAssembler::load_const_32to64(Register t, int64_t x, bool sign_extend) {
1161   if (sign_extend) { Assembler::z_lgfi(t, x); }
1162   else             { Assembler::z_llilf(t, x); }
1163 }
1164 
1165 // Load narrow oop constant, no decompression.
1166 void MacroAssembler::load_narrow_oop(Register t, narrowOop a) {
1167   assert(UseCompressedOops, "must be on to call this method");
1168   load_const_32to64(t, a, false /*sign_extend*/);
1169 }
1170 
1171 // Load narrow klass constant, compression required.
1172 void MacroAssembler::load_narrow_klass(Register t, Klass* k) {
1173   assert(UseCompressedClassPointers, "must be on to call this method");
1174   narrowKlass encoded_k = CompressedKlassPointers::encode(k);
1175   load_const_32to64(t, encoded_k, false /*sign_extend*/);
1176 }
1177 
1178 //------------------------------------------------------
1179 //  Compare (patchable) constant with register.
1180 //------------------------------------------------------
1181 
1182 // Compare narrow oop in reg with narrow oop constant, no decompression.
1183 void MacroAssembler::compare_immediate_narrow_oop(Register oop1, narrowOop oop2) {
1184   assert(UseCompressedOops, "must be on to call this method");
1185 
1186   Assembler::z_clfi(oop1, oop2);
1187 }
1188 
1189 // Compare narrow oop in reg with narrow oop constant, no decompression.
1190 void MacroAssembler::compare_immediate_narrow_klass(Register klass1, Klass* klass2) {
1191   assert(UseCompressedClassPointers, "must be on to call this method");
1192   narrowKlass encoded_k = CompressedKlassPointers::encode(klass2);
1193 
1194   Assembler::z_clfi(klass1, encoded_k);
1195 }
1196 
1197 //----------------------------------------------------------
1198 //  Check which kind of load_constant we have here.
1199 //----------------------------------------------------------
1200 
1201 // Detection of CPU version dependent load_const sequence.
1202 // The detection is valid only for code sequences generated by load_const,
1203 // not load_const_optimized.
1204 bool MacroAssembler::is_load_const(address a) {
1205   unsigned long inst1, inst2;
1206   unsigned int  len1,  len2;
1207 
1208   len1 = get_instruction(a, &inst1);
1209   len2 = get_instruction(a + len1, &inst2);
1210 
1211   return is_z_iihf(inst1) && is_z_iilf(inst2);
1212 }
1213 
1214 // Detection of CPU version dependent load_const_32to64 sequence.
1215 // Mostly used for narrow oops and narrow Klass pointers.
1216 // The detection is valid only for code sequences generated by load_const_32to64.
1217 bool MacroAssembler::is_load_const_32to64(address pos) {
1218   unsigned long inst1, inst2;
1219   unsigned int len1;
1220 
1221   len1 = get_instruction(pos, &inst1);
1222   return is_z_llilf(inst1);
1223 }
1224 
1225 // Detection of compare_immediate_narrow sequence.
1226 // The detection is valid only for code sequences generated by compare_immediate_narrow_oop.
1227 bool MacroAssembler::is_compare_immediate32(address pos) {
1228   return is_equal(pos, CLFI_ZOPC, RIL_MASK);
1229 }
1230 
1231 // Detection of compare_immediate_narrow sequence.
1232 // The detection is valid only for code sequences generated by compare_immediate_narrow_oop.
1233 bool MacroAssembler::is_compare_immediate_narrow_oop(address pos) {
1234   return is_compare_immediate32(pos);
1235   }
1236 
1237 // Detection of compare_immediate_narrow sequence.
1238 // The detection is valid only for code sequences generated by compare_immediate_narrow_klass.
1239 bool MacroAssembler::is_compare_immediate_narrow_klass(address pos) {
1240   return is_compare_immediate32(pos);
1241 }
1242 
1243 //-----------------------------------
1244 //  patch the load_constant
1245 //-----------------------------------
1246 
1247 // CPU-version dependend patching of load_const.
1248 void MacroAssembler::patch_const(address a, long x) {
1249   assert(is_load_const(a), "not a load of a constant");
1250   // Note: Right shift is only cleanly defined for unsigned types
1251   //       or for signed types with nonnegative values.
1252   set_imm32((address)a, (long)((unsigned long)x >> 32));
1253   set_imm32((address)(a + 6), (long)((unsigned long)x & 0xffffffffUL));
1254 }
1255 
1256 // Patching the value of CPU version dependent load_const_32to64 sequence.
1257 // The passed ptr MUST be in compressed format!
1258 int MacroAssembler::patch_load_const_32to64(address pos, int64_t np) {
1259   assert(is_load_const_32to64(pos), "not a load of a narrow ptr (oop or klass)");
1260 
1261   set_imm32(pos, np);
1262   return 6;
1263 }
1264 
1265 // Patching the value of CPU version dependent compare_immediate_narrow sequence.
1266 // The passed ptr MUST be in compressed format!
1267 int MacroAssembler::patch_compare_immediate_32(address pos, int64_t np) {
1268   assert(is_compare_immediate32(pos), "not a compressed ptr compare");
1269 
1270   set_imm32(pos, np);
1271   return 6;
1272 }
1273 
1274 // Patching the immediate value of CPU version dependent load_narrow_oop sequence.
1275 // The passed ptr must NOT be in compressed format!
1276 int MacroAssembler::patch_load_narrow_oop(address pos, oop o) {
1277   assert(UseCompressedOops, "Can only patch compressed oops");
1278 
1279   narrowOop no = CompressedOops::encode(o);
1280   return patch_load_const_32to64(pos, no);
1281 }
1282 
1283 // Patching the immediate value of CPU version dependent load_narrow_klass sequence.
1284 // The passed ptr must NOT be in compressed format!
1285 int MacroAssembler::patch_load_narrow_klass(address pos, Klass* k) {
1286   assert(UseCompressedClassPointers, "Can only patch compressed klass pointers");
1287 
1288   narrowKlass nk = CompressedKlassPointers::encode(k);
1289   return patch_load_const_32to64(pos, nk);
1290 }
1291 
1292 // Patching the immediate value of CPU version dependent compare_immediate_narrow_oop sequence.
1293 // The passed ptr must NOT be in compressed format!
1294 int MacroAssembler::patch_compare_immediate_narrow_oop(address pos, oop o) {
1295   assert(UseCompressedOops, "Can only patch compressed oops");
1296 
1297   narrowOop no = CompressedOops::encode(o);
1298   return patch_compare_immediate_32(pos, no);
1299 }
1300 
1301 // Patching the immediate value of CPU version dependent compare_immediate_narrow_klass sequence.
1302 // The passed ptr must NOT be in compressed format!
1303 int MacroAssembler::patch_compare_immediate_narrow_klass(address pos, Klass* k) {
1304   assert(UseCompressedClassPointers, "Can only patch compressed klass pointers");
1305 
1306   narrowKlass nk = CompressedKlassPointers::encode(k);
1307   return patch_compare_immediate_32(pos, nk);
1308 }
1309 
1310 //------------------------------------------------------------------------
1311 //  Extract the constant from a load_constant instruction stream.
1312 //------------------------------------------------------------------------
1313 
1314 // Get constant from a load_const sequence.
1315 long MacroAssembler::get_const(address a) {
1316   assert(is_load_const(a), "not a load of a constant");
1317   unsigned long x;
1318   x =  (((unsigned long) (get_imm32(a,0) & 0xffffffff)) << 32);
1319   x |= (((unsigned long) (get_imm32(a,1) & 0xffffffff)));
1320   return (long) x;
1321 }
1322 
1323 //--------------------------------------
1324 //  Store a constant in memory.
1325 //--------------------------------------
1326 
1327 // General emitter to move a constant to memory.
1328 // The store is atomic.
1329 //  o Address must be given in RS format (no index register)
1330 //  o Displacement should be 12bit unsigned for efficiency. 20bit signed also supported.
1331 //  o Constant can be 1, 2, 4, or 8 bytes, signed or unsigned.
1332 //  o Memory slot can be 1, 2, 4, or 8 bytes, signed or unsigned.
1333 //  o Memory slot must be at least as wide as constant, will assert otherwise.
1334 //  o Signed constants will sign-extend, unsigned constants will zero-extend to slot width.
1335 int MacroAssembler::store_const(const Address &dest, long imm,
1336                                 unsigned int lm, unsigned int lc,
1337                                 Register scratch) {
1338   int64_t  disp = dest.disp();
1339   Register base = dest.base();
1340   assert(!dest.has_index(), "not supported");
1341   assert((lm==1)||(lm==2)||(lm==4)||(lm==8), "memory   length not supported");
1342   assert((lc==1)||(lc==2)||(lc==4)||(lc==8), "constant length not supported");
1343   assert(lm>=lc, "memory slot too small");
1344   assert(lc==8 || Immediate::is_simm(imm, lc*8), "const out of range");
1345   assert(Displacement::is_validDisp(disp), "displacement out of range");
1346 
1347   bool is_shortDisp = Displacement::is_shortDisp(disp);
1348   int store_offset = -1;
1349 
1350   // For target len == 1 it's easy.
1351   if (lm == 1) {
1352     store_offset = offset();
1353     if (is_shortDisp) {
1354       z_mvi(disp, base, imm);
1355       return store_offset;
1356     } else {
1357       z_mviy(disp, base, imm);
1358       return store_offset;
1359     }
1360   }
1361 
1362   // All the "good stuff" takes an unsigned displacement.
1363   if (is_shortDisp) {
1364     // NOTE: Cannot use clear_mem for imm==0, because it is not atomic.
1365 
1366     store_offset = offset();
1367     switch (lm) {
1368       case 2:  // Lc == 1 handled correctly here, even for unsigned. Instruction does no widening.
1369         z_mvhhi(disp, base, imm);
1370         return store_offset;
1371       case 4:
1372         if (Immediate::is_simm16(imm)) {
1373           z_mvhi(disp, base, imm);
1374           return store_offset;
1375         }
1376         break;
1377       case 8:
1378         if (Immediate::is_simm16(imm)) {
1379           z_mvghi(disp, base, imm);
1380           return store_offset;
1381         }
1382         break;
1383       default:
1384         ShouldNotReachHere();
1385         break;
1386     }
1387   }
1388 
1389   //  Can't optimize, so load value and store it.
1390   guarantee(scratch != noreg, " need a scratch register here !");
1391   if (imm != 0) {
1392     load_const_optimized(scratch, imm);  // Preserves CC anyway.
1393   } else {
1394     // Leave CC alone!!
1395     (void) clear_reg(scratch, true, false); // Indicate unused result.
1396   }
1397 
1398   store_offset = offset();
1399   if (is_shortDisp) {
1400     switch (lm) {
1401       case 2:
1402         z_sth(scratch, disp, Z_R0, base);
1403         return store_offset;
1404       case 4:
1405         z_st(scratch, disp, Z_R0, base);
1406         return store_offset;
1407       case 8:
1408         z_stg(scratch, disp, Z_R0, base);
1409         return store_offset;
1410       default:
1411         ShouldNotReachHere();
1412         break;
1413     }
1414   } else {
1415     switch (lm) {
1416       case 2:
1417         z_sthy(scratch, disp, Z_R0, base);
1418         return store_offset;
1419       case 4:
1420         z_sty(scratch, disp, Z_R0, base);
1421         return store_offset;
1422       case 8:
1423         z_stg(scratch, disp, Z_R0, base);
1424         return store_offset;
1425       default:
1426         ShouldNotReachHere();
1427         break;
1428     }
1429   }
1430   return -1; // should not reach here
1431 }
1432 
1433 //===================================================================
1434 //===       N O T   P A T CH A B L E   C O N S T A N T S          ===
1435 //===================================================================
1436 
1437 // Load constant x into register t with a fast instrcution sequence
1438 // depending on the bits in x. Preserves CC under all circumstances.
1439 int MacroAssembler::load_const_optimized_rtn_len(Register t, long x, bool emit) {
1440   if (x == 0) {
1441     int len;
1442     if (emit) {
1443       len = clear_reg(t, true, false);
1444     } else {
1445       len = 4;
1446     }
1447     return len;
1448   }
1449 
1450   if (Immediate::is_simm16(x)) {
1451     if (emit) { z_lghi(t, x); }
1452     return 4;
1453   }
1454 
1455   // 64 bit value: | part1 | part2 | part3 | part4 |
1456   // At least one part is not zero!
1457   // Note: Right shift is only cleanly defined for unsigned types
1458   //       or for signed types with nonnegative values.
1459   int part1 = (int)((unsigned long)x >> 48) & 0x0000ffff;
1460   int part2 = (int)((unsigned long)x >> 32) & 0x0000ffff;
1461   int part3 = (int)((unsigned long)x >> 16) & 0x0000ffff;
1462   int part4 = (int)x & 0x0000ffff;
1463   int part12 = (int)((unsigned long)x >> 32);
1464   int part34 = (int)x;
1465 
1466   // Lower word only (unsigned).
1467   if (part12 == 0) {
1468     if (part3 == 0) {
1469       if (emit) z_llill(t, part4);
1470       return 4;
1471     }
1472     if (part4 == 0) {
1473       if (emit) z_llilh(t, part3);
1474       return 4;
1475     }
1476     if (emit) z_llilf(t, part34);
1477     return 6;
1478   }
1479 
1480   // Upper word only.
1481   if (part34 == 0) {
1482     if (part1 == 0) {
1483       if (emit) z_llihl(t, part2);
1484       return 4;
1485     }
1486     if (part2 == 0) {
1487       if (emit) z_llihh(t, part1);
1488       return 4;
1489     }
1490     if (emit) z_llihf(t, part12);
1491     return 6;
1492   }
1493 
1494   // Lower word only (signed).
1495   if ((part1 == 0x0000ffff) && (part2 == 0x0000ffff) && ((part3 & 0x00008000) != 0)) {
1496     if (emit) z_lgfi(t, part34);
1497     return 6;
1498   }
1499 
1500   int len = 0;
1501 
1502   if ((part1 == 0) || (part2 == 0)) {
1503     if (part1 == 0) {
1504       if (emit) z_llihl(t, part2);
1505       len += 4;
1506     } else {
1507       if (emit) z_llihh(t, part1);
1508       len += 4;
1509     }
1510   } else {
1511     if (emit) z_llihf(t, part12);
1512     len += 6;
1513   }
1514 
1515   if ((part3 == 0) || (part4 == 0)) {
1516     if (part3 == 0) {
1517       if (emit) z_iill(t, part4);
1518       len += 4;
1519     } else {
1520       if (emit) z_iilh(t, part3);
1521       len += 4;
1522     }
1523   } else {
1524     if (emit) z_iilf(t, part34);
1525     len += 6;
1526   }
1527   return len;
1528 }
1529 
1530 //=====================================================================
1531 //===     H I G H E R   L E V E L   B R A N C H   E M I T T E R S   ===
1532 //=====================================================================
1533 
1534 // Note: In the worst case, one of the scratch registers is destroyed!!!
1535 void MacroAssembler::compare32_and_branch(Register r1, RegisterOrConstant x2, branch_condition cond, Label& lbl) {
1536   // Right operand is constant.
1537   if (x2.is_constant()) {
1538     jlong value = x2.as_constant();
1539     compare_and_branch_optimized(r1, value, cond, lbl, /*len64=*/false, /*has_sign=*/true);
1540     return;
1541   }
1542 
1543   // Right operand is in register.
1544   compare_and_branch_optimized(r1, x2.as_register(), cond, lbl, /*len64=*/false, /*has_sign=*/true);
1545 }
1546 
1547 // Note: In the worst case, one of the scratch registers is destroyed!!!
1548 void MacroAssembler::compareU32_and_branch(Register r1, RegisterOrConstant x2, branch_condition cond, Label& lbl) {
1549   // Right operand is constant.
1550   if (x2.is_constant()) {
1551     jlong value = x2.as_constant();
1552     compare_and_branch_optimized(r1, value, cond, lbl, /*len64=*/false, /*has_sign=*/false);
1553     return;
1554   }
1555 
1556   // Right operand is in register.
1557   compare_and_branch_optimized(r1, x2.as_register(), cond, lbl, /*len64=*/false, /*has_sign=*/false);
1558 }
1559 
1560 // Note: In the worst case, one of the scratch registers is destroyed!!!
1561 void MacroAssembler::compare64_and_branch(Register r1, RegisterOrConstant x2, branch_condition cond, Label& lbl) {
1562   // Right operand is constant.
1563   if (x2.is_constant()) {
1564     jlong value = x2.as_constant();
1565     compare_and_branch_optimized(r1, value, cond, lbl, /*len64=*/true, /*has_sign=*/true);
1566     return;
1567   }
1568 
1569   // Right operand is in register.
1570   compare_and_branch_optimized(r1, x2.as_register(), cond, lbl, /*len64=*/true, /*has_sign=*/true);
1571 }
1572 
1573 void MacroAssembler::compareU64_and_branch(Register r1, RegisterOrConstant x2, branch_condition cond, Label& lbl) {
1574   // Right operand is constant.
1575   if (x2.is_constant()) {
1576     jlong value = x2.as_constant();
1577     compare_and_branch_optimized(r1, value, cond, lbl, /*len64=*/true, /*has_sign=*/false);
1578     return;
1579   }
1580 
1581   // Right operand is in register.
1582   compare_and_branch_optimized(r1, x2.as_register(), cond, lbl, /*len64=*/true, /*has_sign=*/false);
1583 }
1584 
1585 // Generate an optimal branch to the branch target.
1586 // Optimal means that a relative branch (brc or brcl) is used if the
1587 // branch distance is short enough. Loading the target address into a
1588 // register and branching via reg is used as fallback only.
1589 //
1590 // Used registers:
1591 //   Z_R1 - work reg. Holds branch target address.
1592 //          Used in fallback case only.
1593 //
1594 // This version of branch_optimized is good for cases where the target address is known
1595 // and constant, i.e. is never changed (no relocation, no patching).
1596 void MacroAssembler::branch_optimized(Assembler::branch_condition cond, address branch_addr) {
1597   address branch_origin = pc();
1598 
1599   if (RelAddr::is_in_range_of_RelAddr16(branch_addr, branch_origin)) {
1600     z_brc(cond, branch_addr);
1601   } else if (RelAddr::is_in_range_of_RelAddr32(branch_addr, branch_origin)) {
1602     z_brcl(cond, branch_addr);
1603   } else {
1604     load_const_optimized(Z_R1, branch_addr);  // CC must not get killed by load_const_optimized.
1605     z_bcr(cond, Z_R1);
1606   }
1607 }
1608 
1609 // This version of branch_optimized is good for cases where the target address
1610 // is potentially not yet known at the time the code is emitted.
1611 //
1612 // One very common case is a branch to an unbound label which is handled here.
1613 // The caller might know (or hope) that the branch distance is short enough
1614 // to be encoded in a 16bit relative address. In this case he will pass a
1615 // NearLabel branch_target.
1616 // Care must be taken with unbound labels. Each call to target(label) creates
1617 // an entry in the patch queue for that label to patch all references of the label
1618 // once it gets bound. Those recorded patch locations must be patchable. Otherwise,
1619 // an assertion fires at patch time.
1620 void MacroAssembler::branch_optimized(Assembler::branch_condition cond, Label& branch_target) {
1621   if (branch_target.is_bound()) {
1622     address branch_addr = target(branch_target);
1623     branch_optimized(cond, branch_addr);
1624   } else if (branch_target.is_near()) {
1625     z_brc(cond, branch_target);  // Caller assures that the target will be in range for z_brc.
1626   } else {
1627     z_brcl(cond, branch_target); // Let's hope target is in range. Otherwise, we will abort at patch time.
1628   }
1629 }
1630 
1631 // Generate an optimal compare and branch to the branch target.
1632 // Optimal means that a relative branch (clgrj, brc or brcl) is used if the
1633 // branch distance is short enough. Loading the target address into a
1634 // register and branching via reg is used as fallback only.
1635 //
1636 // Input:
1637 //   r1 - left compare operand
1638 //   r2 - right compare operand
1639 void MacroAssembler::compare_and_branch_optimized(Register r1,
1640                                                   Register r2,
1641                                                   Assembler::branch_condition cond,
1642                                                   address  branch_addr,
1643                                                   bool     len64,
1644                                                   bool     has_sign) {
1645   unsigned int casenum = (len64?2:0)+(has_sign?0:1);
1646 
1647   address branch_origin = pc();
1648   if (VM_Version::has_CompareBranch() && RelAddr::is_in_range_of_RelAddr16(branch_addr, branch_origin)) {
1649     switch (casenum) {
1650       case 0: z_crj( r1, r2, cond, branch_addr); break;
1651       case 1: z_clrj (r1, r2, cond, branch_addr); break;
1652       case 2: z_cgrj(r1, r2, cond, branch_addr); break;
1653       case 3: z_clgrj(r1, r2, cond, branch_addr); break;
1654       default: ShouldNotReachHere(); break;
1655     }
1656   } else {
1657     switch (casenum) {
1658       case 0: z_cr( r1, r2); break;
1659       case 1: z_clr(r1, r2); break;
1660       case 2: z_cgr(r1, r2); break;
1661       case 3: z_clgr(r1, r2); break;
1662       default: ShouldNotReachHere(); break;
1663     }
1664     branch_optimized(cond, branch_addr);
1665   }
1666 }
1667 
1668 // Generate an optimal compare and branch to the branch target.
1669 // Optimal means that a relative branch (clgij, brc or brcl) is used if the
1670 // branch distance is short enough. Loading the target address into a
1671 // register and branching via reg is used as fallback only.
1672 //
1673 // Input:
1674 //   r1 - left compare operand (in register)
1675 //   x2 - right compare operand (immediate)
1676 void MacroAssembler::compare_and_branch_optimized(Register r1,
1677                                                   jlong    x2,
1678                                                   Assembler::branch_condition cond,
1679                                                   Label&   branch_target,
1680                                                   bool     len64,
1681                                                   bool     has_sign) {
1682   address      branch_origin = pc();
1683   bool         x2_imm8       = (has_sign && Immediate::is_simm8(x2)) || (!has_sign && Immediate::is_uimm8(x2));
1684   bool         is_RelAddr16  = branch_target.is_near() ||
1685                                (branch_target.is_bound() &&
1686                                 RelAddr::is_in_range_of_RelAddr16(target(branch_target), branch_origin));
1687   unsigned int casenum       = (len64?2:0)+(has_sign?0:1);
1688 
1689   if (VM_Version::has_CompareBranch() && is_RelAddr16 && x2_imm8) {
1690     switch (casenum) {
1691       case 0: z_cij( r1, x2, cond, branch_target); break;
1692       case 1: z_clij(r1, x2, cond, branch_target); break;
1693       case 2: z_cgij(r1, x2, cond, branch_target); break;
1694       case 3: z_clgij(r1, x2, cond, branch_target); break;
1695       default: ShouldNotReachHere(); break;
1696     }
1697     return;
1698   }
1699 
1700   if (x2 == 0) {
1701     switch (casenum) {
1702       case 0: z_ltr(r1, r1); break;
1703       case 1: z_ltr(r1, r1); break; // Caution: unsigned test only provides zero/notZero indication!
1704       case 2: z_ltgr(r1, r1); break;
1705       case 3: z_ltgr(r1, r1); break; // Caution: unsigned test only provides zero/notZero indication!
1706       default: ShouldNotReachHere(); break;
1707     }
1708   } else {
1709     if ((has_sign && Immediate::is_simm16(x2)) || (!has_sign && Immediate::is_uimm(x2, 15))) {
1710       switch (casenum) {
1711         case 0: z_chi(r1, x2); break;
1712         case 1: z_chi(r1, x2); break; // positive immediate < 2**15
1713         case 2: z_cghi(r1, x2); break;
1714         case 3: z_cghi(r1, x2); break; // positive immediate < 2**15
1715         default: break;
1716       }
1717     } else if ( (has_sign && Immediate::is_simm32(x2)) || (!has_sign && Immediate::is_uimm32(x2)) ) {
1718       switch (casenum) {
1719         case 0: z_cfi( r1, x2); break;
1720         case 1: z_clfi(r1, x2); break;
1721         case 2: z_cgfi(r1, x2); break;
1722         case 3: z_clgfi(r1, x2); break;
1723         default: ShouldNotReachHere(); break;
1724       }
1725     } else {
1726       // No instruction with immediate operand possible, so load into register.
1727       Register scratch = (r1 != Z_R0) ? Z_R0 : Z_R1;
1728       load_const_optimized(scratch, x2);
1729       switch (casenum) {
1730         case 0: z_cr( r1, scratch); break;
1731         case 1: z_clr(r1, scratch); break;
1732         case 2: z_cgr(r1, scratch); break;
1733         case 3: z_clgr(r1, scratch); break;
1734         default: ShouldNotReachHere(); break;
1735       }
1736     }
1737   }
1738   branch_optimized(cond, branch_target);
1739 }
1740 
1741 // Generate an optimal compare and branch to the branch target.
1742 // Optimal means that a relative branch (clgrj, brc or brcl) is used if the
1743 // branch distance is short enough. Loading the target address into a
1744 // register and branching via reg is used as fallback only.
1745 //
1746 // Input:
1747 //   r1 - left compare operand
1748 //   r2 - right compare operand
1749 void MacroAssembler::compare_and_branch_optimized(Register r1,
1750                                                   Register r2,
1751                                                   Assembler::branch_condition cond,
1752                                                   Label&   branch_target,
1753                                                   bool     len64,
1754                                                   bool     has_sign) {
1755   unsigned int casenum = (len64 ? 2 : 0) + (has_sign ? 0 : 1);
1756 
1757   if (branch_target.is_bound()) {
1758     address branch_addr = target(branch_target);
1759     compare_and_branch_optimized(r1, r2, cond, branch_addr, len64, has_sign);
1760   } else {
1761     if (VM_Version::has_CompareBranch() && branch_target.is_near()) {
1762       switch (casenum) {
1763         case 0: z_crj(  r1, r2, cond, branch_target); break;
1764         case 1: z_clrj( r1, r2, cond, branch_target); break;
1765         case 2: z_cgrj( r1, r2, cond, branch_target); break;
1766         case 3: z_clgrj(r1, r2, cond, branch_target); break;
1767         default: ShouldNotReachHere(); break;
1768       }
1769     } else {
1770       switch (casenum) {
1771         case 0: z_cr( r1, r2); break;
1772         case 1: z_clr(r1, r2); break;
1773         case 2: z_cgr(r1, r2); break;
1774         case 3: z_clgr(r1, r2); break;
1775         default: ShouldNotReachHere(); break;
1776       }
1777       branch_optimized(cond, branch_target);
1778     }
1779   }
1780 }
1781 
1782 //===========================================================================
1783 //===   END     H I G H E R   L E V E L   B R A N C H   E M I T T E R S   ===
1784 //===========================================================================
1785 
1786 AddressLiteral MacroAssembler::allocate_metadata_address(Metadata* obj) {
1787   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
1788   int index = oop_recorder()->allocate_metadata_index(obj);
1789   RelocationHolder rspec = metadata_Relocation::spec(index);
1790   return AddressLiteral((address)obj, rspec);
1791 }
1792 
1793 AddressLiteral MacroAssembler::constant_metadata_address(Metadata* obj) {
1794   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
1795   int index = oop_recorder()->find_index(obj);
1796   RelocationHolder rspec = metadata_Relocation::spec(index);
1797   return AddressLiteral((address)obj, rspec);
1798 }
1799 
1800 AddressLiteral MacroAssembler::allocate_oop_address(jobject obj) {
1801   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
1802   int oop_index = oop_recorder()->allocate_oop_index(obj);
1803   return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
1804 }
1805 
1806 AddressLiteral MacroAssembler::constant_oop_address(jobject obj) {
1807   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
1808   int oop_index = oop_recorder()->find_index(obj);
1809   return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
1810 }
1811 
1812 // NOTE: destroys r
1813 void MacroAssembler::c2bool(Register r, Register t) {
1814   z_lcr(t, r);   // t = -r
1815   z_or(r, t);    // r = -r OR r
1816   z_srl(r, 31);  // Yields 0 if r was 0, 1 otherwise.
1817 }
1818 
1819 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
1820                                                       Register tmp,
1821                                                       int offset) {
1822   intptr_t value = *delayed_value_addr;
1823   if (value != 0) {
1824     return RegisterOrConstant(value + offset);
1825   }
1826 
1827   BLOCK_COMMENT("delayed_value {");
1828   // Load indirectly to solve generation ordering problem.
1829   load_absolute_address(tmp, (address) delayed_value_addr); // tmp = a;
1830   z_lg(tmp, 0, tmp);                   // tmp = *tmp;
1831 
1832 #ifdef ASSERT
1833   NearLabel L;
1834   compare64_and_branch(tmp, (intptr_t)0L, Assembler::bcondNotEqual, L);
1835   z_illtrap();
1836   bind(L);
1837 #endif
1838 
1839   if (offset != 0) {
1840     z_agfi(tmp, offset);               // tmp = tmp + offset;
1841   }
1842 
1843   BLOCK_COMMENT("} delayed_value");
1844   return RegisterOrConstant(tmp);
1845 }
1846 
1847 // Patch instruction `inst' at offset `inst_pos' to refer to `dest_pos'
1848 // and return the resulting instruction.
1849 // Dest_pos and inst_pos are 32 bit only. These parms can only designate
1850 // relative positions.
1851 // Use correct argument types. Do not pre-calculate distance.
1852 unsigned long MacroAssembler::patched_branch(address dest_pos, unsigned long inst, address inst_pos) {
1853   int c = 0;
1854   unsigned long patched_inst = 0;
1855   if (is_call_pcrelative_short(inst) ||
1856       is_branch_pcrelative_short(inst) ||
1857       is_branchoncount_pcrelative_short(inst) ||
1858       is_branchonindex32_pcrelative_short(inst)) {
1859     c = 1;
1860     int m = fmask(15, 0);    // simm16(-1, 16, 32);
1861     int v = simm16(RelAddr::pcrel_off16(dest_pos, inst_pos), 16, 32);
1862     patched_inst = (inst & ~m) | v;
1863   } else if (is_compareandbranch_pcrelative_short(inst)) {
1864     c = 2;
1865     long m = fmask(31, 16);  // simm16(-1, 16, 48);
1866     long v = simm16(RelAddr::pcrel_off16(dest_pos, inst_pos), 16, 48);
1867     patched_inst = (inst & ~m) | v;
1868   } else if (is_branchonindex64_pcrelative_short(inst)) {
1869     c = 3;
1870     long m = fmask(31, 16);  // simm16(-1, 16, 48);
1871     long v = simm16(RelAddr::pcrel_off16(dest_pos, inst_pos), 16, 48);
1872     patched_inst = (inst & ~m) | v;
1873   } else if (is_call_pcrelative_long(inst) || is_branch_pcrelative_long(inst)) {
1874     c = 4;
1875     long m = fmask(31, 0);  // simm32(-1, 16, 48);
1876     long v = simm32(RelAddr::pcrel_off32(dest_pos, inst_pos), 16, 48);
1877     patched_inst = (inst & ~m) | v;
1878   } else if (is_pcrelative_long(inst)) { // These are the non-branch pc-relative instructions.
1879     c = 5;
1880     long m = fmask(31, 0);  // simm32(-1, 16, 48);
1881     long v = simm32(RelAddr::pcrel_off32(dest_pos, inst_pos), 16, 48);
1882     patched_inst = (inst & ~m) | v;
1883   } else {
1884     print_dbg_msg(tty, inst, "not a relative branch", 0);
1885     dump_code_range(tty, inst_pos, 32, "not a pcrelative branch");
1886     ShouldNotReachHere();
1887   }
1888 
1889   long new_off = get_pcrel_offset(patched_inst);
1890   if (new_off != (dest_pos-inst_pos)) {
1891     tty->print_cr("case %d: dest_pos = %p, inst_pos = %p, disp = %ld(%12.12lx)", c, dest_pos, inst_pos, new_off, new_off);
1892     print_dbg_msg(tty, inst,         "<- original instruction: branch patching error", 0);
1893     print_dbg_msg(tty, patched_inst, "<- patched  instruction: branch patching error", 0);
1894 #ifdef LUCY_DBG
1895     VM_Version::z_SIGSEGV();
1896 #endif
1897     ShouldNotReachHere();
1898   }
1899   return patched_inst;
1900 }
1901 
1902 // Only called when binding labels (share/vm/asm/assembler.cpp)
1903 // Pass arguments as intended. Do not pre-calculate distance.
1904 void MacroAssembler::pd_patch_instruction(address branch, address target, const char* file, int line) {
1905   unsigned long stub_inst;
1906   int           inst_len = get_instruction(branch, &stub_inst);
1907 
1908   set_instruction(branch, patched_branch(target, stub_inst, branch), inst_len);
1909 }
1910 
1911 
1912 // Extract relative address (aka offset).
1913 // inv_simm16 works for 4-byte instructions only.
1914 // compare and branch instructions are 6-byte and have a 16bit offset "in the middle".
1915 long MacroAssembler::get_pcrel_offset(unsigned long inst) {
1916 
1917   if (MacroAssembler::is_pcrelative_short(inst)) {
1918     if (((inst&0xFFFFffff00000000UL) == 0) && ((inst&0x00000000FFFF0000UL) != 0)) {
1919       return RelAddr::inv_pcrel_off16(inv_simm16(inst));
1920     } else {
1921       return RelAddr::inv_pcrel_off16(inv_simm16_48(inst));
1922     }
1923   }
1924 
1925   if (MacroAssembler::is_pcrelative_long(inst)) {
1926     return RelAddr::inv_pcrel_off32(inv_simm32(inst));
1927   }
1928 
1929   print_dbg_msg(tty, inst, "not a pcrelative instruction", 6);
1930 #ifdef LUCY_DBG
1931   VM_Version::z_SIGSEGV();
1932 #else
1933   ShouldNotReachHere();
1934 #endif
1935   return -1;
1936 }
1937 
1938 long MacroAssembler::get_pcrel_offset(address pc) {
1939   unsigned long inst;
1940   unsigned int  len = get_instruction(pc, &inst);
1941 
1942 #ifdef ASSERT
1943   long offset;
1944   if (MacroAssembler::is_pcrelative_short(inst) || MacroAssembler::is_pcrelative_long(inst)) {
1945     offset = get_pcrel_offset(inst);
1946   } else {
1947     offset = -1;
1948   }
1949 
1950   if (offset == -1) {
1951     dump_code_range(tty, pc, 32, "not a pcrelative instruction");
1952 #ifdef LUCY_DBG
1953     VM_Version::z_SIGSEGV();
1954 #else
1955     ShouldNotReachHere();
1956 #endif
1957   }
1958   return offset;
1959 #else
1960   return get_pcrel_offset(inst);
1961 #endif // ASSERT
1962 }
1963 
1964 // Get target address from pc-relative instructions.
1965 address MacroAssembler::get_target_addr_pcrel(address pc) {
1966   assert(is_pcrelative_long(pc), "not a pcrelative instruction");
1967   return pc + get_pcrel_offset(pc);
1968 }
1969 
1970 // Patch pc relative load address.
1971 void MacroAssembler::patch_target_addr_pcrel(address pc, address con) {
1972   unsigned long inst;
1973   // Offset is +/- 2**32 -> use long.
1974   ptrdiff_t distance = con - pc;
1975 
1976   get_instruction(pc, &inst);
1977 
1978   if (is_pcrelative_short(inst)) {
1979     *(short *)(pc+2) = RelAddr::pcrel_off16(con, pc);  // Instructions are at least 2-byte aligned, no test required.
1980 
1981     // Some extra safety net.
1982     if (!RelAddr::is_in_range_of_RelAddr16(distance)) {
1983       print_dbg_msg(tty, inst, "distance out of range (16bit)", 4);
1984       dump_code_range(tty, pc, 32, "distance out of range (16bit)");
1985       guarantee(RelAddr::is_in_range_of_RelAddr16(distance), "too far away (more than +/- 2**16");
1986     }
1987     return;
1988   }
1989 
1990   if (is_pcrelative_long(inst)) {
1991     *(int *)(pc+2)   = RelAddr::pcrel_off32(con, pc);
1992 
1993     // Some Extra safety net.
1994     if (!RelAddr::is_in_range_of_RelAddr32(distance)) {
1995       print_dbg_msg(tty, inst, "distance out of range (32bit)", 6);
1996       dump_code_range(tty, pc, 32, "distance out of range (32bit)");
1997       guarantee(RelAddr::is_in_range_of_RelAddr32(distance), "too far away (more than +/- 2**32");
1998     }
1999     return;
2000   }
2001 
2002   guarantee(false, "not a pcrelative instruction to patch!");
2003 }
2004 
2005 // "Current PC" here means the address just behind the basr instruction.
2006 address MacroAssembler::get_PC(Register result) {
2007   z_basr(result, Z_R0); // Don't branch, just save next instruction address in result.
2008   return pc();
2009 }
2010 
2011 // Get current PC + offset.
2012 // Offset given in bytes, must be even!
2013 // "Current PC" here means the address of the larl instruction plus the given offset.
2014 address MacroAssembler::get_PC(Register result, int64_t offset) {
2015   address here = pc();
2016   z_larl(result, offset/2); // Save target instruction address in result.
2017   return here + offset;
2018 }
2019 
2020 void MacroAssembler::instr_size(Register size, Register pc) {
2021   // Extract 2 most significant bits of current instruction.
2022   z_llgc(size, Address(pc));
2023   z_srl(size, 6);
2024   // Compute (x+3)&6 which translates 0->2, 1->4, 2->4, 3->6.
2025   z_ahi(size, 3);
2026   z_nill(size, 6);
2027 }
2028 
2029 // Resize_frame with SP(new) = SP(old) - [offset].
2030 void MacroAssembler::resize_frame_sub(Register offset, Register fp, bool load_fp)
2031 {
2032   assert_different_registers(offset, fp, Z_SP);
2033   if (load_fp) { z_lg(fp, _z_abi(callers_sp), Z_SP); }
2034 
2035   z_sgr(Z_SP, offset);
2036   z_stg(fp, _z_abi(callers_sp), Z_SP);
2037 }
2038 
2039 // Resize_frame with SP(new) = [newSP] + offset.
2040 //   This emitter is useful if we already have calculated a pointer
2041 //   into the to-be-allocated stack space, e.g. with special alignment properties,
2042 //   but need some additional space, e.g. for spilling.
2043 //   newSP    is the pre-calculated pointer. It must not be modified.
2044 //   fp       holds, or is filled with, the frame pointer.
2045 //   offset   is the additional increment which is added to addr to form the new SP.
2046 //            Note: specify a negative value to reserve more space!
2047 //   load_fp == true  only indicates that fp is not pre-filled with the frame pointer.
2048 //                    It does not guarantee that fp contains the frame pointer at the end.
2049 void MacroAssembler::resize_frame_abs_with_offset(Register newSP, Register fp, int offset, bool load_fp) {
2050   assert_different_registers(newSP, fp, Z_SP);
2051 
2052   if (load_fp) {
2053     z_lg(fp, _z_abi(callers_sp), Z_SP);
2054   }
2055 
2056   add2reg(Z_SP, offset, newSP);
2057   z_stg(fp, _z_abi(callers_sp), Z_SP);
2058 }
2059 
2060 // Resize_frame with SP(new) = [newSP].
2061 //   load_fp == true  only indicates that fp is not pre-filled with the frame pointer.
2062 //                    It does not guarantee that fp contains the frame pointer at the end.
2063 void MacroAssembler::resize_frame_absolute(Register newSP, Register fp, bool load_fp) {
2064   assert_different_registers(newSP, fp, Z_SP);
2065 
2066   if (load_fp) {
2067     z_lg(fp, _z_abi(callers_sp), Z_SP); // need to use load/store.
2068   }
2069 
2070   z_lgr(Z_SP, newSP);
2071   if (newSP != Z_R0) { // make sure we generate correct code, no matter what register newSP uses.
2072     z_stg(fp, _z_abi(callers_sp), newSP);
2073   } else {
2074     z_stg(fp, _z_abi(callers_sp), Z_SP);
2075   }
2076 }
2077 
2078 // Resize_frame with SP(new) = SP(old) + offset.
2079 void MacroAssembler::resize_frame(RegisterOrConstant offset, Register fp, bool load_fp) {
2080   assert_different_registers(fp, Z_SP);
2081 
2082   if (load_fp) {
2083     z_lg(fp, _z_abi(callers_sp), Z_SP);
2084   }
2085   add64(Z_SP, offset);
2086   z_stg(fp, _z_abi(callers_sp), Z_SP);
2087 }
2088 
2089 void MacroAssembler::push_frame(Register bytes, Register old_sp, bool copy_sp, bool bytes_with_inverted_sign) {
2090 #ifdef ASSERT
2091   assert_different_registers(bytes, old_sp, Z_SP);
2092   if (!copy_sp) {
2093     z_cgr(old_sp, Z_SP);
2094     asm_assert_eq("[old_sp]!=[Z_SP]", 0x211);
2095   }
2096 #endif
2097   if (copy_sp) { z_lgr(old_sp, Z_SP); }
2098   if (bytes_with_inverted_sign) {
2099     z_agr(Z_SP, bytes);
2100   } else {
2101     z_sgr(Z_SP, bytes); // Z_sgfr sufficient, but probably not faster.
2102   }
2103   z_stg(old_sp, _z_abi(callers_sp), Z_SP);
2104 }
2105 
2106 unsigned int MacroAssembler::push_frame(unsigned int bytes, Register scratch) {
2107   long offset = Assembler::align(bytes, frame::alignment_in_bytes);
2108   assert(offset > 0, "should push a frame with positive size, size = %ld.", offset);
2109   assert(Displacement::is_validDisp(-offset), "frame size out of range, size = %ld", offset);
2110 
2111   // We must not write outside the current stack bounds (given by Z_SP).
2112   // Thus, we have to first update Z_SP and then store the previous SP as stack linkage.
2113   // We rely on Z_R0 by default to be available as scratch.
2114   z_lgr(scratch, Z_SP);
2115   add2reg(Z_SP, -offset);
2116   z_stg(scratch, _z_abi(callers_sp), Z_SP);
2117 #ifdef ASSERT
2118   // Just make sure nobody uses the value in the default scratch register.
2119   // When another register is used, the caller might rely on it containing the frame pointer.
2120   if (scratch == Z_R0) {
2121     z_iihf(scratch, 0xbaadbabe);
2122     z_iilf(scratch, 0xdeadbeef);
2123   }
2124 #endif
2125   return offset;
2126 }
2127 
2128 // Push a frame of size `bytes' plus abi160 on top.
2129 unsigned int MacroAssembler::push_frame_abi160(unsigned int bytes) {
2130   BLOCK_COMMENT("push_frame_abi160 {");
2131   unsigned int res = push_frame(bytes + frame::z_abi_160_size);
2132   BLOCK_COMMENT("} push_frame_abi160");
2133   return res;
2134 }
2135 
2136 // Pop current C frame.
2137 void MacroAssembler::pop_frame() {
2138   BLOCK_COMMENT("pop_frame:");
2139   Assembler::z_lg(Z_SP, _z_abi(callers_sp), Z_SP);
2140 }
2141 
2142 // Pop current C frame and restore return PC register (Z_R14).
2143 void MacroAssembler::pop_frame_restore_retPC(int frame_size_in_bytes) {
2144   BLOCK_COMMENT("pop_frame_restore_retPC:");
2145   int retPC_offset = _z_abi16(return_pc) + frame_size_in_bytes;
2146   // If possible, pop frame by add instead of load (a penny saved is a penny got :-).
2147   if (Displacement::is_validDisp(retPC_offset)) {
2148     z_lg(Z_R14, retPC_offset, Z_SP);
2149     add2reg(Z_SP, frame_size_in_bytes);
2150   } else {
2151     add2reg(Z_SP, frame_size_in_bytes);
2152     restore_return_pc();
2153   }
2154 }
2155 
2156 void MacroAssembler::call_VM_leaf_base(address entry_point, bool allow_relocation) {
2157   if (allow_relocation) {
2158     call_c(entry_point);
2159   } else {
2160     call_c_static(entry_point);
2161   }
2162 }
2163 
2164 void MacroAssembler::call_VM_leaf_base(address entry_point) {
2165   bool allow_relocation = true;
2166   call_VM_leaf_base(entry_point, allow_relocation);
2167 }
2168 
2169 void MacroAssembler::call_VM_base(Register oop_result,
2170                                   Register last_java_sp,
2171                                   address  entry_point,
2172                                   bool     allow_relocation,
2173                                   bool     check_exceptions) { // Defaults to true.
2174   // Allow_relocation indicates, if true, that the generated code shall
2175   // be fit for code relocation or referenced data relocation. In other
2176   // words: all addresses must be considered variable. PC-relative addressing
2177   // is not possible then.
2178   // On the other hand, if (allow_relocation == false), addresses and offsets
2179   // may be considered stable, enabling us to take advantage of some PC-relative
2180   // addressing tweaks. These might improve performance and reduce code size.
2181 
2182   // Determine last_java_sp register.
2183   if (!last_java_sp->is_valid()) {
2184     last_java_sp = Z_SP;  // Load Z_SP as SP.
2185   }
2186 
2187   set_top_ijava_frame_at_SP_as_last_Java_frame(last_java_sp, Z_R1, allow_relocation);
2188 
2189   // ARG1 must hold thread address.
2190   z_lgr(Z_ARG1, Z_thread);
2191 
2192   address return_pc = NULL;
2193   if (allow_relocation) {
2194     return_pc = call_c(entry_point);
2195   } else {
2196     return_pc = call_c_static(entry_point);
2197   }
2198 
2199   reset_last_Java_frame(allow_relocation);
2200 
2201   // C++ interp handles this in the interpreter.
2202   check_and_handle_popframe(Z_thread);
2203   check_and_handle_earlyret(Z_thread);
2204 
2205   // Check for pending exceptions.
2206   if (check_exceptions) {
2207     // Check for pending exceptions (java_thread is set upon return).
2208     load_and_test_long(Z_R0_scratch, Address(Z_thread, Thread::pending_exception_offset()));
2209 
2210     // This used to conditionally jump to forward_exception however it is
2211     // possible if we relocate that the branch will not reach. So we must jump
2212     // around so we can always reach.
2213 
2214     Label ok;
2215     z_bre(ok); // Bcondequal is the same as bcondZero.
2216     call_stub(StubRoutines::forward_exception_entry());
2217     bind(ok);
2218   }
2219 
2220   // Get oop result if there is one and reset the value in the thread.
2221   if (oop_result->is_valid()) {
2222     get_vm_result(oop_result);
2223   }
2224 
2225   _last_calls_return_pc = return_pc;  // Wipe out other (error handling) calls.
2226 }
2227 
2228 void MacroAssembler::call_VM_base(Register oop_result,
2229                                   Register last_java_sp,
2230                                   address  entry_point,
2231                                   bool     check_exceptions) { // Defaults to true.
2232   bool allow_relocation = true;
2233   call_VM_base(oop_result, last_java_sp, entry_point, allow_relocation, check_exceptions);
2234 }
2235 
2236 // VM calls without explicit last_java_sp.
2237 
2238 void MacroAssembler::call_VM(Register oop_result, address entry_point, bool check_exceptions) {
2239   // Call takes possible detour via InterpreterMacroAssembler.
2240   call_VM_base(oop_result, noreg, entry_point, true, check_exceptions);
2241 }
2242 
2243 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, bool check_exceptions) {
2244   // Z_ARG1 is reserved for the thread.
2245   lgr_if_needed(Z_ARG2, arg_1);
2246   call_VM(oop_result, entry_point, check_exceptions);
2247 }
2248 
2249 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, bool check_exceptions) {
2250   // Z_ARG1 is reserved for the thread.
2251   lgr_if_needed(Z_ARG2, arg_1);
2252   assert(arg_2 != Z_ARG2, "smashed argument");
2253   lgr_if_needed(Z_ARG3, arg_2);
2254   call_VM(oop_result, entry_point, check_exceptions);
2255 }
2256 
2257 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2,
2258                              Register arg_3, bool check_exceptions) {
2259   // Z_ARG1 is reserved for the thread.
2260   lgr_if_needed(Z_ARG2, arg_1);
2261   assert(arg_2 != Z_ARG2, "smashed argument");
2262   lgr_if_needed(Z_ARG3, arg_2);
2263   assert(arg_3 != Z_ARG2 && arg_3 != Z_ARG3, "smashed argument");
2264   lgr_if_needed(Z_ARG4, arg_3);
2265   call_VM(oop_result, entry_point, check_exceptions);
2266 }
2267 
2268 // VM static calls without explicit last_java_sp.
2269 
2270 void MacroAssembler::call_VM_static(Register oop_result, address entry_point, bool check_exceptions) {
2271   // Call takes possible detour via InterpreterMacroAssembler.
2272   call_VM_base(oop_result, noreg, entry_point, false, check_exceptions);
2273 }
2274 
2275 void MacroAssembler::call_VM_static(Register oop_result, address entry_point, Register arg_1, Register arg_2,
2276                                     Register arg_3, bool check_exceptions) {
2277   // Z_ARG1 is reserved for the thread.
2278   lgr_if_needed(Z_ARG2, arg_1);
2279   assert(arg_2 != Z_ARG2, "smashed argument");
2280   lgr_if_needed(Z_ARG3, arg_2);
2281   assert(arg_3 != Z_ARG2 && arg_3 != Z_ARG3, "smashed argument");
2282   lgr_if_needed(Z_ARG4, arg_3);
2283   call_VM_static(oop_result, entry_point, check_exceptions);
2284 }
2285 
2286 // VM calls with explicit last_java_sp.
2287 
2288 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, bool check_exceptions) {
2289   // Call takes possible detour via InterpreterMacroAssembler.
2290   call_VM_base(oop_result, last_java_sp, entry_point, true, check_exceptions);
2291 }
2292 
2293 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, bool check_exceptions) {
2294    // Z_ARG1 is reserved for the thread.
2295    lgr_if_needed(Z_ARG2, arg_1);
2296    call_VM(oop_result, last_java_sp, entry_point, check_exceptions);
2297 }
2298 
2299 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1,
2300                              Register arg_2, bool check_exceptions) {
2301    // Z_ARG1 is reserved for the thread.
2302    lgr_if_needed(Z_ARG2, arg_1);
2303    assert(arg_2 != Z_ARG2, "smashed argument");
2304    lgr_if_needed(Z_ARG3, arg_2);
2305    call_VM(oop_result, last_java_sp, entry_point, check_exceptions);
2306 }
2307 
2308 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1,
2309                              Register arg_2, Register arg_3, bool check_exceptions) {
2310   // Z_ARG1 is reserved for the thread.
2311   lgr_if_needed(Z_ARG2, arg_1);
2312   assert(arg_2 != Z_ARG2, "smashed argument");
2313   lgr_if_needed(Z_ARG3, arg_2);
2314   assert(arg_3 != Z_ARG2 && arg_3 != Z_ARG3, "smashed argument");
2315   lgr_if_needed(Z_ARG4, arg_3);
2316   call_VM(oop_result, last_java_sp, entry_point, check_exceptions);
2317 }
2318 
2319 // VM leaf calls.
2320 
2321 void MacroAssembler::call_VM_leaf(address entry_point) {
2322   // Call takes possible detour via InterpreterMacroAssembler.
2323   call_VM_leaf_base(entry_point, true);
2324 }
2325 
2326 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1) {
2327   if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2328   call_VM_leaf(entry_point);
2329 }
2330 
2331 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2) {
2332   if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2333   assert(arg_2 != Z_ARG1, "smashed argument");
2334   if (arg_2 != noreg) lgr_if_needed(Z_ARG2, arg_2);
2335   call_VM_leaf(entry_point);
2336 }
2337 
2338 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2, Register arg_3) {
2339   if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2340   assert(arg_2 != Z_ARG1, "smashed argument");
2341   if (arg_2 != noreg) lgr_if_needed(Z_ARG2, arg_2);
2342   assert(arg_3 != Z_ARG1 && arg_3 != Z_ARG2, "smashed argument");
2343   if (arg_3 != noreg) lgr_if_needed(Z_ARG3, arg_3);
2344   call_VM_leaf(entry_point);
2345 }
2346 
2347 // Static VM leaf calls.
2348 // Really static VM leaf calls are never patched.
2349 
2350 void MacroAssembler::call_VM_leaf_static(address entry_point) {
2351   // Call takes possible detour via InterpreterMacroAssembler.
2352   call_VM_leaf_base(entry_point, false);
2353 }
2354 
2355 void MacroAssembler::call_VM_leaf_static(address entry_point, Register arg_1) {
2356   if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2357   call_VM_leaf_static(entry_point);
2358 }
2359 
2360 void MacroAssembler::call_VM_leaf_static(address entry_point, Register arg_1, Register arg_2) {
2361   if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2362   assert(arg_2 != Z_ARG1, "smashed argument");
2363   if (arg_2 != noreg) lgr_if_needed(Z_ARG2, arg_2);
2364   call_VM_leaf_static(entry_point);
2365 }
2366 
2367 void MacroAssembler::call_VM_leaf_static(address entry_point, Register arg_1, Register arg_2, Register arg_3) {
2368   if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2369   assert(arg_2 != Z_ARG1, "smashed argument");
2370   if (arg_2 != noreg) lgr_if_needed(Z_ARG2, arg_2);
2371   assert(arg_3 != Z_ARG1 && arg_3 != Z_ARG2, "smashed argument");
2372   if (arg_3 != noreg) lgr_if_needed(Z_ARG3, arg_3);
2373   call_VM_leaf_static(entry_point);
2374 }
2375 
2376 // Don't use detour via call_c(reg).
2377 address MacroAssembler::call_c(address function_entry) {
2378   load_const(Z_R1, function_entry);
2379   return call(Z_R1);
2380 }
2381 
2382 // Variant for really static (non-relocatable) calls which are never patched.
2383 address MacroAssembler::call_c_static(address function_entry) {
2384   load_absolute_address(Z_R1, function_entry);
2385 #if 0 // def ASSERT
2386   // Verify that call site did not move.
2387   load_const_optimized(Z_R0, function_entry);
2388   z_cgr(Z_R1, Z_R0);
2389   z_brc(bcondEqual, 3);
2390   z_illtrap(0xba);
2391 #endif
2392   return call(Z_R1);
2393 }
2394 
2395 address MacroAssembler::call_c_opt(address function_entry) {
2396   bool success = call_far_patchable(function_entry, -2 /* emit relocation + constant */);
2397   _last_calls_return_pc = success ? pc() : NULL;
2398   return _last_calls_return_pc;
2399 }
2400 
2401 // Identify a call_far_patchable instruction: LARL + LG + BASR
2402 //
2403 //    nop                   ; optionally, if required for alignment
2404 //    lgrl rx,A(TOC entry)  ; PC-relative access into constant pool
2405 //    basr Z_R14,rx         ; end of this instruction must be aligned to a word boundary
2406 //
2407 // Code pattern will eventually get patched into variant2 (see below for detection code).
2408 //
2409 bool MacroAssembler::is_call_far_patchable_variant0_at(address instruction_addr) {
2410   address iaddr = instruction_addr;
2411 
2412   // Check for the actual load instruction.
2413   if (!is_load_const_from_toc(iaddr)) { return false; }
2414   iaddr += load_const_from_toc_size();
2415 
2416   // Check for the call (BASR) instruction, finally.
2417   assert(iaddr-instruction_addr+call_byregister_size() == call_far_patchable_size(), "size mismatch");
2418   return is_call_byregister(iaddr);
2419 }
2420 
2421 // Identify a call_far_patchable instruction: BRASL
2422 //
2423 // Code pattern to suits atomic patching:
2424 //    nop                       ; Optionally, if required for alignment.
2425 //    nop    ...                ; Multiple filler nops to compensate for size difference (variant0 is longer).
2426 //    nop                       ; For code pattern detection: Prepend each BRASL with a nop.
2427 //    brasl  Z_R14,<reladdr>    ; End of code must be 4-byte aligned !
2428 bool MacroAssembler::is_call_far_patchable_variant2_at(address instruction_addr) {
2429   const address call_addr = (address)((intptr_t)instruction_addr + call_far_patchable_size() - call_far_pcrelative_size());
2430 
2431   // Check for correct number of leading nops.
2432   address iaddr;
2433   for (iaddr = instruction_addr; iaddr < call_addr; iaddr += nop_size()) {
2434     if (!is_z_nop(iaddr)) { return false; }
2435   }
2436   assert(iaddr == call_addr, "sanity");
2437 
2438   // --> Check for call instruction.
2439   if (is_call_far_pcrelative(call_addr)) {
2440     assert(call_addr-instruction_addr+call_far_pcrelative_size() == call_far_patchable_size(), "size mismatch");
2441     return true;
2442   }
2443 
2444   return false;
2445 }
2446 
2447 // Emit a NOT mt-safely patchable 64 bit absolute call.
2448 // If toc_offset == -2, then the destination of the call (= target) is emitted
2449 //                      to the constant pool and a runtime_call relocation is added
2450 //                      to the code buffer.
2451 // If toc_offset != -2, target must already be in the constant pool at
2452 //                      _ctableStart+toc_offset (a caller can retrieve toc_offset
2453 //                      from the runtime_call relocation).
2454 // Special handling of emitting to scratch buffer when there is no constant pool.
2455 // Slightly changed code pattern. We emit an additional nop if we would
2456 // not end emitting at a word aligned address. This is to ensure
2457 // an atomically patchable displacement in brasl instructions.
2458 //
2459 // A call_far_patchable comes in different flavors:
2460 //  - LARL(CP) / LG(CP) / BR (address in constant pool, access via CP register)
2461 //  - LGRL(CP) / BR          (address in constant pool, pc-relative accesss)
2462 //  - BRASL                  (relative address of call target coded in instruction)
2463 // All flavors occupy the same amount of space. Length differences are compensated
2464 // by leading nops, such that the instruction sequence always ends at the same
2465 // byte offset. This is required to keep the return offset constant.
2466 // Furthermore, the return address (the end of the instruction sequence) is forced
2467 // to be on a 4-byte boundary. This is required for atomic patching, should we ever
2468 // need to patch the call target of the BRASL flavor.
2469 // RETURN value: false, if no constant pool entry could be allocated, true otherwise.
2470 bool MacroAssembler::call_far_patchable(address target, int64_t tocOffset) {
2471   // Get current pc and ensure word alignment for end of instr sequence.
2472   const address start_pc = pc();
2473   const intptr_t       start_off = offset();
2474   assert(!call_far_patchable_requires_alignment_nop(start_pc), "call_far_patchable requires aligned address");
2475   const ptrdiff_t      dist      = (ptrdiff_t)(target - (start_pc + 2)); // Prepend each BRASL with a nop.
2476   const bool emit_target_to_pool = (tocOffset == -2) && !code_section()->scratch_emit();
2477   const bool emit_relative_call  = !emit_target_to_pool &&
2478                                    RelAddr::is_in_range_of_RelAddr32(dist) &&
2479                                    ReoptimizeCallSequences &&
2480                                    !code_section()->scratch_emit();
2481 
2482   if (emit_relative_call) {
2483     // Add padding to get the same size as below.
2484     const unsigned int padding = call_far_patchable_size() - call_far_pcrelative_size();
2485     unsigned int current_padding;
2486     for (current_padding = 0; current_padding < padding; current_padding += nop_size()) { z_nop(); }
2487     assert(current_padding == padding, "sanity");
2488 
2489     // relative call: len = 2(nop) + 6 (brasl)
2490     // CodeBlob resize cannot occur in this case because
2491     // this call is emitted into pre-existing space.
2492     z_nop(); // Prepend each BRASL with a nop.
2493     z_brasl(Z_R14, target);
2494   } else {
2495     // absolute call: Get address from TOC.
2496     // len = (load TOC){6|0} + (load from TOC){6} + (basr){2} = {14|8}
2497     if (emit_target_to_pool) {
2498       // When emitting the call for the first time, we do not need to use
2499       // the pc-relative version. It will be patched anyway, when the code
2500       // buffer is copied.
2501       // Relocation is not needed when !ReoptimizeCallSequences.
2502       relocInfo::relocType rt = ReoptimizeCallSequences ? relocInfo::runtime_call_w_cp_type : relocInfo::none;
2503       AddressLiteral dest(target, rt);
2504       // Store_oop_in_toc() adds dest to the constant table. As side effect, this kills
2505       // inst_mark(). Reset if possible.
2506       bool reset_mark = (inst_mark() == pc());
2507       tocOffset = store_oop_in_toc(dest);
2508       if (reset_mark) { set_inst_mark(); }
2509       if (tocOffset == -1) {
2510         return false; // Couldn't create constant pool entry.
2511       }
2512     }
2513     assert(offset() == start_off, "emit no code before this point!");
2514 
2515     address tocPos = pc() + tocOffset;
2516     if (emit_target_to_pool) {
2517       tocPos = code()->consts()->start() + tocOffset;
2518     }
2519     load_long_pcrelative(Z_R14, tocPos);
2520     z_basr(Z_R14, Z_R14);
2521   }
2522 
2523 #ifdef ASSERT
2524   // Assert that we can identify the emitted call.
2525   assert(is_call_far_patchable_at(addr_at(start_off)), "can't identify emitted call");
2526   assert(offset() == start_off+call_far_patchable_size(), "wrong size");
2527 
2528   if (emit_target_to_pool) {
2529     assert(get_dest_of_call_far_patchable_at(addr_at(start_off), code()->consts()->start()) == target,
2530            "wrong encoding of dest address");
2531   }
2532 #endif
2533   return true; // success
2534 }
2535 
2536 // Identify a call_far_patchable instruction.
2537 // For more detailed information see header comment of call_far_patchable.
2538 bool MacroAssembler::is_call_far_patchable_at(address instruction_addr) {
2539   return is_call_far_patchable_variant2_at(instruction_addr)  || // short version: BRASL
2540          is_call_far_patchable_variant0_at(instruction_addr);    // long version LARL + LG + BASR
2541 }
2542 
2543 // Does the call_far_patchable instruction use a pc-relative encoding
2544 // of the call destination?
2545 bool MacroAssembler::is_call_far_patchable_pcrelative_at(address instruction_addr) {
2546   // Variant 2 is pc-relative.
2547   return is_call_far_patchable_variant2_at(instruction_addr);
2548 }
2549 
2550 bool MacroAssembler::is_call_far_pcrelative(address instruction_addr) {
2551   // Prepend each BRASL with a nop.
2552   return is_z_nop(instruction_addr) && is_z_brasl(instruction_addr + nop_size());  // Match at position after one nop required.
2553 }
2554 
2555 // Set destination address of a call_far_patchable instruction.
2556 void MacroAssembler::set_dest_of_call_far_patchable_at(address instruction_addr, address dest, int64_t tocOffset) {
2557   ResourceMark rm;
2558 
2559   // Now that CP entry is verified, patch call to a pc-relative call (if circumstances permit).
2560   int code_size = MacroAssembler::call_far_patchable_size();
2561   CodeBuffer buf(instruction_addr, code_size);
2562   MacroAssembler masm(&buf);
2563   masm.call_far_patchable(dest, tocOffset);
2564   ICache::invalidate_range(instruction_addr, code_size); // Empty on z.
2565 }
2566 
2567 // Get dest address of a call_far_patchable instruction.
2568 address MacroAssembler::get_dest_of_call_far_patchable_at(address instruction_addr, address ctable) {
2569   // Dynamic TOC: absolute address in constant pool.
2570   // Check variant2 first, it is more frequent.
2571 
2572   // Relative address encoded in call instruction.
2573   if (is_call_far_patchable_variant2_at(instruction_addr)) {
2574     return MacroAssembler::get_target_addr_pcrel(instruction_addr + nop_size()); // Prepend each BRASL with a nop.
2575 
2576   // Absolute address in constant pool.
2577   } else if (is_call_far_patchable_variant0_at(instruction_addr)) {
2578     address iaddr = instruction_addr;
2579 
2580     long    tocOffset = get_load_const_from_toc_offset(iaddr);
2581     address tocLoc    = iaddr + tocOffset;
2582     return *(address *)(tocLoc);
2583   } else {
2584     fprintf(stderr, "MacroAssembler::get_dest_of_call_far_patchable_at has a problem at %p:\n", instruction_addr);
2585     fprintf(stderr, "not a call_far_patchable: %16.16lx %16.16lx, len = %d\n",
2586             *(unsigned long*)instruction_addr,
2587             *(unsigned long*)(instruction_addr+8),
2588             call_far_patchable_size());
2589     Disassembler::decode(instruction_addr, instruction_addr+call_far_patchable_size());
2590     ShouldNotReachHere();
2591     return NULL;
2592   }
2593 }
2594 
2595 void MacroAssembler::align_call_far_patchable(address pc) {
2596   if (call_far_patchable_requires_alignment_nop(pc)) { z_nop(); }
2597 }
2598 
2599 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2600 }
2601 
2602 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2603 }
2604 
2605 // Read from the polling page.
2606 // Use TM or TMY instruction, depending on read offset.
2607 //   offset = 0: Use TM, safepoint polling.
2608 //   offset < 0: Use TMY, profiling safepoint polling.
2609 void MacroAssembler::load_from_polling_page(Register polling_page_address, int64_t offset) {
2610   if (Immediate::is_uimm12(offset)) {
2611     z_tm(offset, polling_page_address, mask_safepoint);
2612   } else {
2613     z_tmy(offset, polling_page_address, mask_profiling);
2614   }
2615 }
2616 
2617 // Check whether z_instruction is a read access to the polling page
2618 // which was emitted by load_from_polling_page(..).
2619 bool MacroAssembler::is_load_from_polling_page(address instr_loc) {
2620   unsigned long z_instruction;
2621   unsigned int  ilen = get_instruction(instr_loc, &z_instruction);
2622 
2623   if (ilen == 2) { return false; } // It's none of the allowed instructions.
2624 
2625   if (ilen == 4) {
2626     if (!is_z_tm(z_instruction)) { return false; } // It's len=4, but not a z_tm. fail.
2627 
2628     int ms = inv_mask(z_instruction,8,32);  // mask
2629     int ra = inv_reg(z_instruction,16,32);  // base register
2630     int ds = inv_uimm12(z_instruction);     // displacement
2631 
2632     if (!(ds == 0 && ra != 0 && ms == mask_safepoint)) {
2633       return false; // It's not a z_tm(0, ra, mask_safepoint). Fail.
2634     }
2635 
2636   } else { /* if (ilen == 6) */
2637 
2638     assert(!is_z_lg(z_instruction), "old form (LG) polling page access. Please fix and use TM(Y).");
2639 
2640     if (!is_z_tmy(z_instruction)) { return false; } // It's len=6, but not a z_tmy. fail.
2641 
2642     int ms = inv_mask(z_instruction,8,48);  // mask
2643     int ra = inv_reg(z_instruction,16,48);  // base register
2644     int ds = inv_simm20(z_instruction);     // displacement
2645   }
2646 
2647   return true;
2648 }
2649 
2650 // Extract poll address from instruction and ucontext.
2651 address MacroAssembler::get_poll_address(address instr_loc, void* ucontext) {
2652   assert(ucontext != NULL, "must have ucontext");
2653   ucontext_t* uc = (ucontext_t*) ucontext;
2654   unsigned long z_instruction;
2655   unsigned int ilen = get_instruction(instr_loc, &z_instruction);
2656 
2657   if (ilen == 4 && is_z_tm(z_instruction)) {
2658     int ra = inv_reg(z_instruction, 16, 32);  // base register
2659     int ds = inv_uimm12(z_instruction);       // displacement
2660     address addr = (address)uc->uc_mcontext.gregs[ra];
2661     return addr + ds;
2662   } else if (ilen == 6 && is_z_tmy(z_instruction)) {
2663     int ra = inv_reg(z_instruction, 16, 48);  // base register
2664     int ds = inv_simm20(z_instruction);       // displacement
2665     address addr = (address)uc->uc_mcontext.gregs[ra];
2666     return addr + ds;
2667   }
2668 
2669   ShouldNotReachHere();
2670   return NULL;
2671 }
2672 
2673 // Extract poll register from instruction.
2674 uint MacroAssembler::get_poll_register(address instr_loc) {
2675   unsigned long z_instruction;
2676   unsigned int ilen = get_instruction(instr_loc, &z_instruction);
2677 
2678   if (ilen == 4 && is_z_tm(z_instruction)) {
2679     return (uint)inv_reg(z_instruction, 16, 32);  // base register
2680   } else if (ilen == 6 && is_z_tmy(z_instruction)) {
2681     return (uint)inv_reg(z_instruction, 16, 48);  // base register
2682   }
2683 
2684   ShouldNotReachHere();
2685   return 0;
2686 }
2687 
2688 void MacroAssembler::safepoint_poll(Label& slow_path, Register temp_reg) {
2689   if (SafepointMechanism::uses_thread_local_poll()) {
2690     const Address poll_byte_addr(Z_thread, in_bytes(Thread::polling_page_offset()) + 7 /* Big Endian */);
2691     // Armed page has poll_bit set.
2692     z_tm(poll_byte_addr, SafepointMechanism::poll_bit());
2693     z_brnaz(slow_path);
2694   } else {
2695     load_const_optimized(temp_reg, SafepointSynchronize::address_of_state());
2696     z_cli(/*SafepointSynchronize::sz_state()*/4-1, temp_reg, SafepointSynchronize::_not_synchronized);
2697     z_brne(slow_path);
2698   }
2699 }
2700 
2701 // Don't rely on register locking, always use Z_R1 as scratch register instead.
2702 void MacroAssembler::bang_stack_with_offset(int offset) {
2703   // Stack grows down, caller passes positive offset.
2704   assert(offset > 0, "must bang with positive offset");
2705   if (Displacement::is_validDisp(-offset)) {
2706     z_tmy(-offset, Z_SP, mask_stackbang);
2707   } else {
2708     add2reg(Z_R1, -offset, Z_SP);    // Do not destroy Z_SP!!!
2709     z_tm(0, Z_R1, mask_stackbang);  // Just banging.
2710   }
2711 }
2712 
2713 void MacroAssembler::reserved_stack_check(Register return_pc) {
2714   // Test if reserved zone needs to be enabled.
2715   Label no_reserved_zone_enabling;
2716   assert(return_pc == Z_R14, "Return pc must be in R14 before z_br() to StackOverflow stub.");
2717   BLOCK_COMMENT("reserved_stack_check {");
2718 
2719   z_clg(Z_SP, Address(Z_thread, JavaThread::reserved_stack_activation_offset()));
2720   z_brl(no_reserved_zone_enabling);
2721 
2722   // Enable reserved zone again, throw stack overflow exception.
2723   save_return_pc();
2724   push_frame_abi160(0);
2725   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), Z_thread);
2726   pop_frame();
2727   restore_return_pc();
2728 
2729   load_const_optimized(Z_R1, StubRoutines::throw_delayed_StackOverflowError_entry());
2730   // Don't use call() or z_basr(), they will invalidate Z_R14 which contains the return pc.
2731   z_br(Z_R1);
2732 
2733   should_not_reach_here();
2734 
2735   bind(no_reserved_zone_enabling);
2736   BLOCK_COMMENT("} reserved_stack_check");
2737 }
2738 
2739 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
2740 void MacroAssembler::tlab_allocate(Register obj,
2741                                    Register var_size_in_bytes,
2742                                    int con_size_in_bytes,
2743                                    Register t1,
2744                                    Label& slow_case) {
2745   assert_different_registers(obj, var_size_in_bytes, t1);
2746   Register end = t1;
2747   Register thread = Z_thread;
2748 
2749   z_lg(obj, Address(thread, JavaThread::tlab_top_offset()));
2750   if (var_size_in_bytes == noreg) {
2751     z_lay(end, Address(obj, con_size_in_bytes));
2752   } else {
2753     z_lay(end, Address(obj, var_size_in_bytes));
2754   }
2755   z_cg(end, Address(thread, JavaThread::tlab_end_offset()));
2756   branch_optimized(bcondHigh, slow_case);
2757 
2758   // Update the tlab top pointer.
2759   z_stg(end, Address(thread, JavaThread::tlab_top_offset()));
2760 
2761   // Recover var_size_in_bytes if necessary.
2762   if (var_size_in_bytes == end) {
2763     z_sgr(var_size_in_bytes, obj);
2764   }
2765 }
2766 
2767 // Emitter for interface method lookup.
2768 //   input: recv_klass, intf_klass, itable_index
2769 //   output: method_result
2770 //   kills: itable_index, temp1_reg, Z_R0, Z_R1
2771 // TODO: Temp2_reg is unused. we may use this emitter also in the itable stubs.
2772 // If the register is still not needed then, remove it.
2773 void MacroAssembler::lookup_interface_method(Register           recv_klass,
2774                                              Register           intf_klass,
2775                                              RegisterOrConstant itable_index,
2776                                              Register           method_result,
2777                                              Register           temp1_reg,
2778                                              Label&             no_such_interface,
2779                                              bool               return_method) {
2780 
2781   const Register vtable_len = temp1_reg;    // Used to compute itable_entry_addr.
2782   const Register itable_entry_addr = Z_R1_scratch;
2783   const Register itable_interface = Z_R0_scratch;
2784 
2785   BLOCK_COMMENT("lookup_interface_method {");
2786 
2787   // Load start of itable entries into itable_entry_addr.
2788   z_llgf(vtable_len, Address(recv_klass, Klass::vtable_length_offset()));
2789   z_sllg(vtable_len, vtable_len, exact_log2(vtableEntry::size_in_bytes()));
2790 
2791   // Loop over all itable entries until desired interfaceOop(Rinterface) found.
2792   const int vtable_base_offset = in_bytes(Klass::vtable_start_offset());
2793 
2794   add2reg_with_index(itable_entry_addr,
2795                      vtable_base_offset + itableOffsetEntry::interface_offset_in_bytes(),
2796                      recv_klass, vtable_len);
2797 
2798   const int itable_offset_search_inc = itableOffsetEntry::size() * wordSize;
2799   Label     search;
2800 
2801   bind(search);
2802 
2803   // Handle IncompatibleClassChangeError.
2804   // If the entry is NULL then we've reached the end of the table
2805   // without finding the expected interface, so throw an exception.
2806   load_and_test_long(itable_interface, Address(itable_entry_addr));
2807   z_bre(no_such_interface);
2808 
2809   add2reg(itable_entry_addr, itable_offset_search_inc);
2810   z_cgr(itable_interface, intf_klass);
2811   z_brne(search);
2812 
2813   // Entry found and itable_entry_addr points to it, get offset of vtable for interface.
2814   if (return_method) {
2815     const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
2816                                       itableOffsetEntry::interface_offset_in_bytes()) -
2817                                      itable_offset_search_inc;
2818 
2819     // Compute itableMethodEntry and get method and entry point
2820     // we use addressing with index and displacement, since the formula
2821     // for computing the entry's offset has a fixed and a dynamic part,
2822     // the latter depending on the matched interface entry and on the case,
2823     // that the itable index has been passed as a register, not a constant value.
2824     int method_offset = itableMethodEntry::method_offset_in_bytes();
2825                              // Fixed part (displacement), common operand.
2826     Register itable_offset = method_result;  // Dynamic part (index register).
2827 
2828     if (itable_index.is_register()) {
2829        // Compute the method's offset in that register, for the formula, see the
2830        // else-clause below.
2831        z_sllg(itable_offset, itable_index.as_register(), exact_log2(itableMethodEntry::size() * wordSize));
2832        z_agf(itable_offset, vtable_offset_offset, itable_entry_addr);
2833     } else {
2834       // Displacement increases.
2835       method_offset += itableMethodEntry::size() * wordSize * itable_index.as_constant();
2836 
2837       // Load index from itable.
2838       z_llgf(itable_offset, vtable_offset_offset, itable_entry_addr);
2839     }
2840 
2841     // Finally load the method's oop.
2842     z_lg(method_result, method_offset, itable_offset, recv_klass);
2843   }
2844   BLOCK_COMMENT("} lookup_interface_method");
2845 }
2846 
2847 // Lookup for virtual method invocation.
2848 void MacroAssembler::lookup_virtual_method(Register           recv_klass,
2849                                            RegisterOrConstant vtable_index,
2850                                            Register           method_result) {
2851   assert_different_registers(recv_klass, vtable_index.register_or_noreg());
2852   assert(vtableEntry::size() * wordSize == wordSize,
2853          "else adjust the scaling in the code below");
2854 
2855   BLOCK_COMMENT("lookup_virtual_method {");
2856 
2857   const int base = in_bytes(Klass::vtable_start_offset());
2858 
2859   if (vtable_index.is_constant()) {
2860     // Load with base + disp.
2861     Address vtable_entry_addr(recv_klass,
2862                               vtable_index.as_constant() * wordSize +
2863                               base +
2864                               vtableEntry::method_offset_in_bytes());
2865 
2866     z_lg(method_result, vtable_entry_addr);
2867   } else {
2868     // Shift index properly and load with base + index + disp.
2869     Register vindex = vtable_index.as_register();
2870     Address  vtable_entry_addr(recv_klass, vindex,
2871                                base + vtableEntry::method_offset_in_bytes());
2872 
2873     z_sllg(vindex, vindex, exact_log2(wordSize));
2874     z_lg(method_result, vtable_entry_addr);
2875   }
2876   BLOCK_COMMENT("} lookup_virtual_method");
2877 }
2878 
2879 // Factor out code to call ic_miss_handler.
2880 // Generate code to call the inline cache miss handler.
2881 //
2882 // In most cases, this code will be generated out-of-line.
2883 // The method parameters are intended to provide some variability.
2884 //   ICM          - Label which has to be bound to the start of useful code (past any traps).
2885 //   trapMarker   - Marking byte for the generated illtrap instructions (if any).
2886 //                  Any value except 0x00 is supported.
2887 //                  = 0x00 - do not generate illtrap instructions.
2888 //                         use nops to fill ununsed space.
2889 //   requiredSize - required size of the generated code. If the actually
2890 //                  generated code is smaller, use padding instructions to fill up.
2891 //                  = 0 - no size requirement, no padding.
2892 //   scratch      - scratch register to hold branch target address.
2893 //
2894 //  The method returns the code offset of the bound label.
2895 unsigned int MacroAssembler::call_ic_miss_handler(Label& ICM, int trapMarker, int requiredSize, Register scratch) {
2896   intptr_t startOffset = offset();
2897 
2898   // Prevent entry at content_begin().
2899   if (trapMarker != 0) {
2900     z_illtrap(trapMarker);
2901   }
2902 
2903   // Load address of inline cache miss code into scratch register
2904   // and branch to cache miss handler.
2905   BLOCK_COMMENT("IC miss handler {");
2906   BIND(ICM);
2907   unsigned int   labelOffset = offset();
2908   AddressLiteral icmiss(SharedRuntime::get_ic_miss_stub());
2909 
2910   load_const_optimized(scratch, icmiss);
2911   z_br(scratch);
2912 
2913   // Fill unused space.
2914   if (requiredSize > 0) {
2915     while ((offset() - startOffset) < requiredSize) {
2916       if (trapMarker == 0) {
2917         z_nop();
2918       } else {
2919         z_illtrap(trapMarker);
2920       }
2921     }
2922   }
2923   BLOCK_COMMENT("} IC miss handler");
2924   return labelOffset;
2925 }
2926 
2927 void MacroAssembler::nmethod_UEP(Label& ic_miss) {
2928   Register ic_reg       = as_Register(Matcher::inline_cache_reg_encode());
2929   int      klass_offset = oopDesc::klass_offset_in_bytes();
2930   if (!ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(klass_offset)) {
2931     if (VM_Version::has_CompareBranch()) {
2932       z_cgij(Z_ARG1, 0, Assembler::bcondEqual, ic_miss);
2933     } else {
2934       z_ltgr(Z_ARG1, Z_ARG1);
2935       z_bre(ic_miss);
2936     }
2937   }
2938   // Compare cached class against klass from receiver.
2939   compare_klass_ptr(ic_reg, klass_offset, Z_ARG1, false);
2940   z_brne(ic_miss);
2941 }
2942 
2943 void MacroAssembler::check_klass_subtype_fast_path(Register   sub_klass,
2944                                                    Register   super_klass,
2945                                                    Register   temp1_reg,
2946                                                    Label*     L_success,
2947                                                    Label*     L_failure,
2948                                                    Label*     L_slow_path,
2949                                                    RegisterOrConstant super_check_offset) {
2950 
2951   const int sc_offset  = in_bytes(Klass::secondary_super_cache_offset());
2952   const int sco_offset = in_bytes(Klass::super_check_offset_offset());
2953 
2954   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
2955   bool need_slow_path = (must_load_sco ||
2956                          super_check_offset.constant_or_zero() == sc_offset);
2957 
2958   // Input registers must not overlap.
2959   assert_different_registers(sub_klass, super_klass, temp1_reg);
2960   if (super_check_offset.is_register()) {
2961     assert_different_registers(sub_klass, super_klass,
2962                                super_check_offset.as_register());
2963   } else if (must_load_sco) {
2964     assert(temp1_reg != noreg, "supply either a temp or a register offset");
2965   }
2966 
2967   const Register Rsuper_check_offset = temp1_reg;
2968 
2969   NearLabel L_fallthrough;
2970   int label_nulls = 0;
2971   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
2972   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
2973   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
2974   assert(label_nulls <= 1 ||
2975          (L_slow_path == &L_fallthrough && label_nulls <= 2 && !need_slow_path),
2976          "at most one NULL in the batch, usually");
2977 
2978   BLOCK_COMMENT("check_klass_subtype_fast_path {");
2979   // If the pointers are equal, we are done (e.g., String[] elements).
2980   // This self-check enables sharing of secondary supertype arrays among
2981   // non-primary types such as array-of-interface. Otherwise, each such
2982   // type would need its own customized SSA.
2983   // We move this check to the front of the fast path because many
2984   // type checks are in fact trivially successful in this manner,
2985   // so we get a nicely predicted branch right at the start of the check.
2986   compare64_and_branch(sub_klass, super_klass, bcondEqual, *L_success);
2987 
2988   // Check the supertype display, which is uint.
2989   if (must_load_sco) {
2990     z_llgf(Rsuper_check_offset, sco_offset, super_klass);
2991     super_check_offset = RegisterOrConstant(Rsuper_check_offset);
2992   }
2993   Address super_check_addr(sub_klass, super_check_offset, 0);
2994   z_cg(super_klass, super_check_addr); // compare w/ displayed supertype
2995 
2996   // This check has worked decisively for primary supers.
2997   // Secondary supers are sought in the super_cache ('super_cache_addr').
2998   // (Secondary supers are interfaces and very deeply nested subtypes.)
2999   // This works in the same check above because of a tricky aliasing
3000   // between the super_cache and the primary super display elements.
3001   // (The 'super_check_addr' can address either, as the case requires.)
3002   // Note that the cache is updated below if it does not help us find
3003   // what we need immediately.
3004   // So if it was a primary super, we can just fail immediately.
3005   // Otherwise, it's the slow path for us (no success at this point).
3006 
3007   // Hacked jmp, which may only be used just before L_fallthrough.
3008 #define final_jmp(label)                                                \
3009   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
3010   else                            { branch_optimized(Assembler::bcondAlways, label); } /*omit semicolon*/
3011 
3012   if (super_check_offset.is_register()) {
3013     branch_optimized(Assembler::bcondEqual, *L_success);
3014     z_cfi(super_check_offset.as_register(), sc_offset);
3015     if (L_failure == &L_fallthrough) {
3016       branch_optimized(Assembler::bcondEqual, *L_slow_path);
3017     } else {
3018       branch_optimized(Assembler::bcondNotEqual, *L_failure);
3019       final_jmp(*L_slow_path);
3020     }
3021   } else if (super_check_offset.as_constant() == sc_offset) {
3022     // Need a slow path; fast failure is impossible.
3023     if (L_slow_path == &L_fallthrough) {
3024       branch_optimized(Assembler::bcondEqual, *L_success);
3025     } else {
3026       branch_optimized(Assembler::bcondNotEqual, *L_slow_path);
3027       final_jmp(*L_success);
3028     }
3029   } else {
3030     // No slow path; it's a fast decision.
3031     if (L_failure == &L_fallthrough) {
3032       branch_optimized(Assembler::bcondEqual, *L_success);
3033     } else {
3034       branch_optimized(Assembler::bcondNotEqual, *L_failure);
3035       final_jmp(*L_success);
3036     }
3037   }
3038 
3039   bind(L_fallthrough);
3040 #undef local_brc
3041 #undef final_jmp
3042   BLOCK_COMMENT("} check_klass_subtype_fast_path");
3043   // fallthru (to slow path)
3044 }
3045 
3046 void MacroAssembler::check_klass_subtype_slow_path(Register Rsubklass,
3047                                                    Register Rsuperklass,
3048                                                    Register Rarray_ptr,  // tmp
3049                                                    Register Rlength,     // tmp
3050                                                    Label* L_success,
3051                                                    Label* L_failure) {
3052   // Input registers must not overlap.
3053   // Also check for R1 which is explicitely used here.
3054   assert_different_registers(Z_R1, Rsubklass, Rsuperklass, Rarray_ptr, Rlength);
3055   NearLabel L_fallthrough;
3056   int label_nulls = 0;
3057   if (L_success == NULL) { L_success = &L_fallthrough; label_nulls++; }
3058   if (L_failure == NULL) { L_failure = &L_fallthrough; label_nulls++; }
3059   assert(label_nulls <= 1, "at most one NULL in the batch");
3060 
3061   const int ss_offset = in_bytes(Klass::secondary_supers_offset());
3062   const int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
3063 
3064   const int length_offset = Array<Klass*>::length_offset_in_bytes();
3065   const int base_offset   = Array<Klass*>::base_offset_in_bytes();
3066 
3067   // Hacked jmp, which may only be used just before L_fallthrough.
3068 #define final_jmp(label)                                                \
3069   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
3070   else                            branch_optimized(Assembler::bcondAlways, label) /*omit semicolon*/
3071 
3072   NearLabel loop_iterate, loop_count, match;
3073 
3074   BLOCK_COMMENT("check_klass_subtype_slow_path {");
3075   z_lg(Rarray_ptr, ss_offset, Rsubklass);
3076 
3077   load_and_test_int(Rlength, Address(Rarray_ptr, length_offset));
3078   branch_optimized(Assembler::bcondZero, *L_failure);
3079 
3080   // Oops in table are NO MORE compressed.
3081   z_cg(Rsuperklass, base_offset, Rarray_ptr); // Check array element for match.
3082   z_bre(match);                               // Shortcut for array length = 1.
3083 
3084   // No match yet, so we must walk the array's elements.
3085   z_lngfr(Rlength, Rlength);
3086   z_sllg(Rlength, Rlength, LogBytesPerWord); // -#bytes of cache array
3087   z_llill(Z_R1, BytesPerWord);               // Set increment/end index.
3088   add2reg(Rlength, 2 * BytesPerWord);        // start index  = -(n-2)*BytesPerWord
3089   z_slgr(Rarray_ptr, Rlength);               // start addr: +=  (n-2)*BytesPerWord
3090   z_bru(loop_count);
3091 
3092   BIND(loop_iterate);
3093   z_cg(Rsuperklass, base_offset, Rlength, Rarray_ptr); // Check array element for match.
3094   z_bre(match);
3095   BIND(loop_count);
3096   z_brxlg(Rlength, Z_R1, loop_iterate);
3097 
3098   // Rsuperklass not found among secondary super classes -> failure.
3099   branch_optimized(Assembler::bcondAlways, *L_failure);
3100 
3101   // Got a hit. Return success (zero result). Set cache.
3102   // Cache load doesn't happen here. For speed it is directly emitted by the compiler.
3103 
3104   BIND(match);
3105 
3106   z_stg(Rsuperklass, sc_offset, Rsubklass); // Save result to cache.
3107 
3108   final_jmp(*L_success);
3109 
3110   // Exit to the surrounding code.
3111   BIND(L_fallthrough);
3112 #undef local_brc
3113 #undef final_jmp
3114   BLOCK_COMMENT("} check_klass_subtype_slow_path");
3115 }
3116 
3117 // Emitter for combining fast and slow path.
3118 void MacroAssembler::check_klass_subtype(Register sub_klass,
3119                                          Register super_klass,
3120                                          Register temp1_reg,
3121                                          Register temp2_reg,
3122                                          Label&   L_success) {
3123   NearLabel failure;
3124   BLOCK_COMMENT(err_msg("check_klass_subtype(%s subclass of %s) {", sub_klass->name(), super_klass->name()));
3125   check_klass_subtype_fast_path(sub_klass, super_klass, temp1_reg,
3126                                 &L_success, &failure, NULL);
3127   check_klass_subtype_slow_path(sub_klass, super_klass,
3128                                 temp1_reg, temp2_reg, &L_success, NULL);
3129   BIND(failure);
3130   BLOCK_COMMENT("} check_klass_subtype");
3131 }
3132 
3133 void MacroAssembler::clinit_barrier(Register klass, Register thread, Label* L_fast_path, Label* L_slow_path) {
3134   assert(L_fast_path != NULL || L_slow_path != NULL, "at least one is required");
3135 
3136   Label L_fallthrough;
3137   if (L_fast_path == NULL) {
3138     L_fast_path = &L_fallthrough;
3139   } else if (L_slow_path == NULL) {
3140     L_slow_path = &L_fallthrough;
3141   }
3142 
3143   // Fast path check: class is fully initialized
3144   z_cli(Address(klass, InstanceKlass::init_state_offset()), InstanceKlass::fully_initialized);
3145   z_bre(*L_fast_path);
3146 
3147   // Fast path check: current thread is initializer thread
3148   z_cg(thread, Address(klass, InstanceKlass::init_thread_offset()));
3149   if (L_slow_path == &L_fallthrough) {
3150     z_bre(*L_fast_path);
3151   } else if (L_fast_path == &L_fallthrough) {
3152     z_brne(*L_slow_path);
3153   } else {
3154     Unimplemented();
3155   }
3156 
3157   bind(L_fallthrough);
3158 }
3159 
3160 // Increment a counter at counter_address when the eq condition code is
3161 // set. Kills registers tmp1_reg and tmp2_reg and preserves the condition code.
3162 void MacroAssembler::increment_counter_eq(address counter_address, Register tmp1_reg, Register tmp2_reg) {
3163   Label l;
3164   z_brne(l);
3165   load_const(tmp1_reg, counter_address);
3166   add2mem_32(Address(tmp1_reg), 1, tmp2_reg);
3167   z_cr(tmp1_reg, tmp1_reg); // Set cc to eq.
3168   bind(l);
3169 }
3170 
3171 // Semantics are dependent on the slow_case label:
3172 //   If the slow_case label is not NULL, failure to biased-lock the object
3173 //   transfers control to the location of the slow_case label. If the
3174 //   object could be biased-locked, control is transferred to the done label.
3175 //   The condition code is unpredictable.
3176 //
3177 //   If the slow_case label is NULL, failure to biased-lock the object results
3178 //   in a transfer of control to the done label with a condition code of not_equal.
3179 //   If the biased-lock could be successfully obtained, control is transfered to
3180 //   the done label with a condition code of equal.
3181 //   It is mandatory to react on the condition code At the done label.
3182 //
3183 void MacroAssembler::biased_locking_enter(Register  obj_reg,
3184                                           Register  mark_reg,
3185                                           Register  temp_reg,
3186                                           Register  temp2_reg,    // May be Z_RO!
3187                                           Label    &done,
3188                                           Label    *slow_case) {
3189   assert(UseBiasedLocking, "why call this otherwise?");
3190   assert_different_registers(obj_reg, mark_reg, temp_reg, temp2_reg);
3191 
3192   Label cas_label; // Try, if implemented, CAS locking. Fall thru to slow path otherwise.
3193 
3194   BLOCK_COMMENT("biased_locking_enter {");
3195 
3196   // Biased locking
3197   // See whether the lock is currently biased toward our thread and
3198   // whether the epoch is still valid.
3199   // Note that the runtime guarantees sufficient alignment of JavaThread
3200   // pointers to allow age to be placed into low bits.
3201   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits,
3202          "biased locking makes assumptions about bit layout");
3203   z_lr(temp_reg, mark_reg);
3204   z_nilf(temp_reg, markOopDesc::biased_lock_mask_in_place);
3205   z_chi(temp_reg, markOopDesc::biased_lock_pattern);
3206   z_brne(cas_label);  // Try cas if object is not biased, i.e. cannot be biased locked.
3207 
3208   load_prototype_header(temp_reg, obj_reg);
3209   load_const_optimized(temp2_reg, ~((int) markOopDesc::age_mask_in_place));
3210 
3211   z_ogr(temp_reg, Z_thread);
3212   z_xgr(temp_reg, mark_reg);
3213   z_ngr(temp_reg, temp2_reg);
3214   if (PrintBiasedLockingStatistics) {
3215     increment_counter_eq((address) BiasedLocking::biased_lock_entry_count_addr(), mark_reg, temp2_reg);
3216     // Restore mark_reg.
3217     z_lg(mark_reg, oopDesc::mark_offset_in_bytes(), obj_reg);
3218   }
3219   branch_optimized(Assembler::bcondEqual, done);  // Biased lock obtained, return success.
3220 
3221   Label try_revoke_bias;
3222   Label try_rebias;
3223   Address mark_addr = Address(obj_reg, oopDesc::mark_offset_in_bytes());
3224 
3225   //----------------------------------------------------------------------------
3226   // At this point we know that the header has the bias pattern and
3227   // that we are not the bias owner in the current epoch. We need to
3228   // figure out more details about the state of the header in order to
3229   // know what operations can be legally performed on the object's
3230   // header.
3231 
3232   // If the low three bits in the xor result aren't clear, that means
3233   // the prototype header is no longer biased and we have to revoke
3234   // the bias on this object.
3235   z_tmll(temp_reg, markOopDesc::biased_lock_mask_in_place);
3236   z_brnaz(try_revoke_bias);
3237 
3238   // Biasing is still enabled for this data type. See whether the
3239   // epoch of the current bias is still valid, meaning that the epoch
3240   // bits of the mark word are equal to the epoch bits of the
3241   // prototype header. (Note that the prototype header's epoch bits
3242   // only change at a safepoint.) If not, attempt to rebias the object
3243   // toward the current thread. Note that we must be absolutely sure
3244   // that the current epoch is invalid in order to do this because
3245   // otherwise the manipulations it performs on the mark word are
3246   // illegal.
3247   z_tmll(temp_reg, markOopDesc::epoch_mask_in_place);
3248   z_brnaz(try_rebias);
3249 
3250   //----------------------------------------------------------------------------
3251   // The epoch of the current bias is still valid but we know nothing
3252   // about the owner; it might be set or it might be clear. Try to
3253   // acquire the bias of the object using an atomic operation. If this
3254   // fails we will go in to the runtime to revoke the object's bias.
3255   // Note that we first construct the presumed unbiased header so we
3256   // don't accidentally blow away another thread's valid bias.
3257   z_nilf(mark_reg, markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place |
3258          markOopDesc::epoch_mask_in_place);
3259   z_lgr(temp_reg, Z_thread);
3260   z_llgfr(mark_reg, mark_reg);
3261   z_ogr(temp_reg, mark_reg);
3262 
3263   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
3264 
3265   z_csg(mark_reg, temp_reg, 0, obj_reg);
3266 
3267   // If the biasing toward our thread failed, this means that
3268   // another thread succeeded in biasing it toward itself and we
3269   // need to revoke that bias. The revocation will occur in the
3270   // interpreter runtime in the slow case.
3271 
3272   if (PrintBiasedLockingStatistics) {
3273     increment_counter_eq((address) BiasedLocking::anonymously_biased_lock_entry_count_addr(),
3274                          temp_reg, temp2_reg);
3275   }
3276   if (slow_case != NULL) {
3277     branch_optimized(Assembler::bcondNotEqual, *slow_case); // Biased lock not obtained, need to go the long way.
3278   }
3279   branch_optimized(Assembler::bcondAlways, done);           // Biased lock status given in condition code.
3280 
3281   //----------------------------------------------------------------------------
3282   bind(try_rebias);
3283   // At this point we know the epoch has expired, meaning that the
3284   // current "bias owner", if any, is actually invalid. Under these
3285   // circumstances _only_, we are allowed to use the current header's
3286   // value as the comparison value when doing the cas to acquire the
3287   // bias in the current epoch. In other words, we allow transfer of
3288   // the bias from one thread to another directly in this situation.
3289 
3290   z_nilf(mark_reg, markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
3291   load_prototype_header(temp_reg, obj_reg);
3292   z_llgfr(mark_reg, mark_reg);
3293 
3294   z_ogr(temp_reg, Z_thread);
3295 
3296   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
3297 
3298   z_csg(mark_reg, temp_reg, 0, obj_reg);
3299 
3300   // If the biasing toward our thread failed, this means that
3301   // another thread succeeded in biasing it toward itself and we
3302   // need to revoke that bias. The revocation will occur in the
3303   // interpreter runtime in the slow case.
3304 
3305   if (PrintBiasedLockingStatistics) {
3306     increment_counter_eq((address) BiasedLocking::rebiased_lock_entry_count_addr(), temp_reg, temp2_reg);
3307   }
3308   if (slow_case != NULL) {
3309     branch_optimized(Assembler::bcondNotEqual, *slow_case);  // Biased lock not obtained, need to go the long way.
3310   }
3311   z_bru(done);           // Biased lock status given in condition code.
3312 
3313   //----------------------------------------------------------------------------
3314   bind(try_revoke_bias);
3315   // The prototype mark in the klass doesn't have the bias bit set any
3316   // more, indicating that objects of this data type are not supposed
3317   // to be biased any more. We are going to try to reset the mark of
3318   // this object to the prototype value and fall through to the
3319   // CAS-based locking scheme. Note that if our CAS fails, it means
3320   // that another thread raced us for the privilege of revoking the
3321   // bias of this particular object, so it's okay to continue in the
3322   // normal locking code.
3323   load_prototype_header(temp_reg, obj_reg);
3324 
3325   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
3326 
3327   z_csg(mark_reg, temp_reg, 0, obj_reg);
3328 
3329   // Fall through to the normal CAS-based lock, because no matter what
3330   // the result of the above CAS, some thread must have succeeded in
3331   // removing the bias bit from the object's header.
3332   if (PrintBiasedLockingStatistics) {
3333     // z_cgr(mark_reg, temp2_reg);
3334     increment_counter_eq((address) BiasedLocking::revoked_lock_entry_count_addr(), temp_reg, temp2_reg);
3335   }
3336 
3337   bind(cas_label);
3338   BLOCK_COMMENT("} biased_locking_enter");
3339 }
3340 
3341 void MacroAssembler::biased_locking_exit(Register mark_addr, Register temp_reg, Label& done) {
3342   // Check for biased locking unlock case, which is a no-op
3343   // Note: we do not have to check the thread ID for two reasons.
3344   // First, the interpreter checks for IllegalMonitorStateException at
3345   // a higher level. Second, if the bias was revoked while we held the
3346   // lock, the object could not be rebiased toward another thread, so
3347   // the bias bit would be clear.
3348   BLOCK_COMMENT("biased_locking_exit {");
3349 
3350   z_lg(temp_reg, 0, mark_addr);
3351   z_nilf(temp_reg, markOopDesc::biased_lock_mask_in_place);
3352 
3353   z_chi(temp_reg, markOopDesc::biased_lock_pattern);
3354   z_bre(done);
3355   BLOCK_COMMENT("} biased_locking_exit");
3356 }
3357 
3358 void MacroAssembler::compiler_fast_lock_object(Register oop, Register box, Register temp1, Register temp2, bool try_bias) {
3359   Register displacedHeader = temp1;
3360   Register currentHeader = temp1;
3361   Register temp = temp2;
3362   NearLabel done, object_has_monitor;
3363 
3364   BLOCK_COMMENT("compiler_fast_lock_object {");
3365 
3366   // Load markOop from oop into mark.
3367   z_lg(displacedHeader, 0, oop);
3368 
3369   if (try_bias) {
3370     biased_locking_enter(oop, displacedHeader, temp, Z_R0, done);
3371   }
3372 
3373   // Handle existing monitor.
3374   // The object has an existing monitor iff (mark & monitor_value) != 0.
3375   guarantee(Immediate::is_uimm16(markOopDesc::monitor_value), "must be half-word");
3376   z_lr(temp, displacedHeader);
3377   z_nill(temp, markOopDesc::monitor_value);
3378   z_brne(object_has_monitor);
3379 
3380   // Set mark to markOop | markOopDesc::unlocked_value.
3381   z_oill(displacedHeader, markOopDesc::unlocked_value);
3382 
3383   // Load Compare Value application register.
3384 
3385   // Initialize the box (must happen before we update the object mark).
3386   z_stg(displacedHeader, BasicLock::displaced_header_offset_in_bytes(), box);
3387 
3388   // Memory Fence (in cmpxchgd)
3389   // Compare object markOop with mark and if equal exchange scratch1 with object markOop.
3390 
3391   // If the compare-and-swap succeeded, then we found an unlocked object and we
3392   // have now locked it.
3393   z_csg(displacedHeader, box, 0, oop);
3394   assert(currentHeader==displacedHeader, "must be same register"); // Identified two registers from z/Architecture.
3395   z_bre(done);
3396 
3397   // We did not see an unlocked object so try the fast recursive case.
3398 
3399   z_sgr(currentHeader, Z_SP);
3400   load_const_optimized(temp, (~(os::vm_page_size()-1) | markOopDesc::lock_mask_in_place));
3401 
3402   z_ngr(currentHeader, temp);
3403   //   z_brne(done);
3404   //   z_release();
3405   z_stg(currentHeader/*==0 or not 0*/, BasicLock::displaced_header_offset_in_bytes(), box);
3406 
3407   z_bru(done);
3408 
3409   Register zero = temp;
3410   Register monitor_tagged = displacedHeader; // Tagged with markOopDesc::monitor_value.
3411   bind(object_has_monitor);
3412   // The object's monitor m is unlocked iff m->owner == NULL,
3413   // otherwise m->owner may contain a thread or a stack address.
3414   //
3415   // Try to CAS m->owner from NULL to current thread.
3416   z_lghi(zero, 0);
3417   // If m->owner is null, then csg succeeds and sets m->owner=THREAD and CR=EQ.
3418   z_csg(zero, Z_thread, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), monitor_tagged);
3419   // Store a non-null value into the box.
3420   z_stg(box, BasicLock::displaced_header_offset_in_bytes(), box);
3421 #ifdef ASSERT
3422   z_brne(done);
3423   // We've acquired the monitor, check some invariants.
3424   // Invariant 1: _recursions should be 0.
3425   asm_assert_mem8_is_zero(OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions), monitor_tagged,
3426                           "monitor->_recursions should be 0", -1);
3427   z_ltgr(zero, zero); // Set CR=EQ.
3428 #endif
3429   bind(done);
3430 
3431   BLOCK_COMMENT("} compiler_fast_lock_object");
3432   // If locking was successful, CR should indicate 'EQ'.
3433   // The compiler or the native wrapper generates a branch to the runtime call
3434   // _complete_monitor_locking_Java.
3435 }
3436 
3437 void MacroAssembler::compiler_fast_unlock_object(Register oop, Register box, Register temp1, Register temp2, bool try_bias) {
3438   Register displacedHeader = temp1;
3439   Register currentHeader = temp2;
3440   Register temp = temp1;
3441   Register monitor = temp2;
3442 
3443   Label done, object_has_monitor;
3444 
3445   BLOCK_COMMENT("compiler_fast_unlock_object {");
3446 
3447   if (try_bias) {
3448     biased_locking_exit(oop, currentHeader, done);
3449   }
3450 
3451   // Find the lock address and load the displaced header from the stack.
3452   // if the displaced header is zero, we have a recursive unlock.
3453   load_and_test_long(displacedHeader, Address(box, BasicLock::displaced_header_offset_in_bytes()));
3454   z_bre(done);
3455 
3456   // Handle existing monitor.
3457   // The object has an existing monitor iff (mark & monitor_value) != 0.
3458   z_lg(currentHeader, oopDesc::mark_offset_in_bytes(), oop);
3459   guarantee(Immediate::is_uimm16(markOopDesc::monitor_value), "must be half-word");
3460   z_nill(currentHeader, markOopDesc::monitor_value);
3461   z_brne(object_has_monitor);
3462 
3463   // Check if it is still a light weight lock, this is true if we see
3464   // the stack address of the basicLock in the markOop of the object
3465   // copy box to currentHeader such that csg does not kill it.
3466   z_lgr(currentHeader, box);
3467   z_csg(currentHeader, displacedHeader, 0, oop);
3468   z_bru(done); // Csg sets CR as desired.
3469 
3470   // Handle existing monitor.
3471   bind(object_has_monitor);
3472   z_lg(currentHeader, oopDesc::mark_offset_in_bytes(), oop);    // CurrentHeader is tagged with monitor_value set.
3473   load_and_test_long(temp, Address(currentHeader, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
3474   z_brne(done);
3475   load_and_test_long(temp, Address(currentHeader, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
3476   z_brne(done);
3477   load_and_test_long(temp, Address(currentHeader, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
3478   z_brne(done);
3479   load_and_test_long(temp, Address(currentHeader, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
3480   z_brne(done);
3481   z_release();
3482   z_stg(temp/*=0*/, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), currentHeader);
3483 
3484   bind(done);
3485 
3486   BLOCK_COMMENT("} compiler_fast_unlock_object");
3487   // flag == EQ indicates success
3488   // flag == NE indicates failure
3489 }
3490 
3491 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
3492   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
3493   bs->resolve_jobject(this, value, tmp1, tmp2);
3494 }
3495 
3496 // Last_Java_sp must comply to the rules in frame_s390.hpp.
3497 void MacroAssembler::set_last_Java_frame(Register last_Java_sp, Register last_Java_pc, bool allow_relocation) {
3498   BLOCK_COMMENT("set_last_Java_frame {");
3499 
3500   // Always set last_Java_pc and flags first because once last_Java_sp
3501   // is visible has_last_Java_frame is true and users will look at the
3502   // rest of the fields. (Note: flags should always be zero before we
3503   // get here so doesn't need to be set.)
3504 
3505   // Verify that last_Java_pc was zeroed on return to Java.
3506   if (allow_relocation) {
3507     asm_assert_mem8_is_zero(in_bytes(JavaThread::last_Java_pc_offset()),
3508                             Z_thread,
3509                             "last_Java_pc not zeroed before leaving Java",
3510                             0x200);
3511   } else {
3512     asm_assert_mem8_is_zero_static(in_bytes(JavaThread::last_Java_pc_offset()),
3513                                    Z_thread,
3514                                    "last_Java_pc not zeroed before leaving Java",
3515                                    0x200);
3516   }
3517 
3518   // When returning from calling out from Java mode the frame anchor's
3519   // last_Java_pc will always be set to NULL. It is set here so that
3520   // if we are doing a call to native (not VM) that we capture the
3521   // known pc and don't have to rely on the native call having a
3522   // standard frame linkage where we can find the pc.
3523   if (last_Java_pc!=noreg) {
3524     z_stg(last_Java_pc, Address(Z_thread, JavaThread::last_Java_pc_offset()));
3525   }
3526 
3527   // This membar release is not required on z/Architecture, since the sequence of stores
3528   // in maintained. Nevertheless, we leave it in to document the required ordering.
3529   // The implementation of z_release() should be empty.
3530   // z_release();
3531 
3532   z_stg(last_Java_sp, Address(Z_thread, JavaThread::last_Java_sp_offset()));
3533   BLOCK_COMMENT("} set_last_Java_frame");
3534 }
3535 
3536 void MacroAssembler::reset_last_Java_frame(bool allow_relocation) {
3537   BLOCK_COMMENT("reset_last_Java_frame {");
3538 
3539   if (allow_relocation) {
3540     asm_assert_mem8_isnot_zero(in_bytes(JavaThread::last_Java_sp_offset()),
3541                                Z_thread,
3542                                "SP was not set, still zero",
3543                                0x202);
3544   } else {
3545     asm_assert_mem8_isnot_zero_static(in_bytes(JavaThread::last_Java_sp_offset()),
3546                                       Z_thread,
3547                                       "SP was not set, still zero",
3548                                       0x202);
3549   }
3550 
3551   // _last_Java_sp = 0
3552   // Clearing storage must be atomic here, so don't use clear_mem()!
3553   store_const(Address(Z_thread, JavaThread::last_Java_sp_offset()), 0);
3554 
3555   // _last_Java_pc = 0
3556   store_const(Address(Z_thread, JavaThread::last_Java_pc_offset()), 0);
3557 
3558   BLOCK_COMMENT("} reset_last_Java_frame");
3559   return;
3560 }
3561 
3562 void MacroAssembler::set_top_ijava_frame_at_SP_as_last_Java_frame(Register sp, Register tmp1, bool allow_relocation) {
3563   assert_different_registers(sp, tmp1);
3564 
3565   // We cannot trust that code generated by the C++ compiler saves R14
3566   // to z_abi_160.return_pc, because sometimes it spills R14 using stmg at
3567   // z_abi_160.gpr14 (e.g. InterpreterRuntime::_new()).
3568   // Therefore we load the PC into tmp1 and let set_last_Java_frame() save
3569   // it into the frame anchor.
3570   get_PC(tmp1);
3571   set_last_Java_frame(/*sp=*/sp, /*pc=*/tmp1, allow_relocation);
3572 }
3573 
3574 void MacroAssembler::set_thread_state(JavaThreadState new_state) {
3575   z_release();
3576 
3577   assert(Immediate::is_uimm16(_thread_max_state), "enum value out of range for instruction");
3578   assert(sizeof(JavaThreadState) == sizeof(int), "enum value must have base type int");
3579   store_const(Address(Z_thread, JavaThread::thread_state_offset()), new_state, Z_R0, false);
3580 }
3581 
3582 void MacroAssembler::get_vm_result(Register oop_result) {
3583   verify_thread();
3584 
3585   z_lg(oop_result, Address(Z_thread, JavaThread::vm_result_offset()));
3586   clear_mem(Address(Z_thread, JavaThread::vm_result_offset()), sizeof(void*));
3587 
3588   verify_oop(oop_result);
3589 }
3590 
3591 void MacroAssembler::get_vm_result_2(Register result) {
3592   verify_thread();
3593 
3594   z_lg(result, Address(Z_thread, JavaThread::vm_result_2_offset()));
3595   clear_mem(Address(Z_thread, JavaThread::vm_result_2_offset()), sizeof(void*));
3596 }
3597 
3598 // We require that C code which does not return a value in vm_result will
3599 // leave it undisturbed.
3600 void MacroAssembler::set_vm_result(Register oop_result) {
3601   z_stg(oop_result, Address(Z_thread, JavaThread::vm_result_offset()));
3602 }
3603 
3604 // Explicit null checks (used for method handle code).
3605 void MacroAssembler::null_check(Register reg, Register tmp, int64_t offset) {
3606   if (!ImplicitNullChecks) {
3607     NearLabel ok;
3608 
3609     compare64_and_branch(reg, (intptr_t) 0, Assembler::bcondNotEqual, ok);
3610 
3611     // We just put the address into reg if it was 0 (tmp==Z_R0 is allowed so we can't use it for the address).
3612     address exception_entry = Interpreter::throw_NullPointerException_entry();
3613     load_absolute_address(reg, exception_entry);
3614     z_br(reg);
3615 
3616     bind(ok);
3617   } else {
3618     if (needs_explicit_null_check((intptr_t)offset)) {
3619       // Provoke OS NULL exception if reg = NULL by
3620       // accessing M[reg] w/o changing any registers.
3621       z_lg(tmp, 0, reg);
3622     }
3623     // else
3624       // Nothing to do, (later) access of M[reg + offset]
3625       // will provoke OS NULL exception if reg = NULL.
3626   }
3627 }
3628 
3629 //-------------------------------------
3630 //  Compressed Klass Pointers
3631 //-------------------------------------
3632 
3633 // Klass oop manipulations if compressed.
3634 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3635   Register current = (src != noreg) ? src : dst; // Klass is in dst if no src provided. (dst == src) also possible.
3636   address  base    = CompressedKlassPointers::base();
3637   int      shift   = CompressedKlassPointers::shift();
3638   assert(UseCompressedClassPointers, "only for compressed klass ptrs");
3639 
3640   BLOCK_COMMENT("cKlass encoder {");
3641 
3642 #ifdef ASSERT
3643   Label ok;
3644   z_tmll(current, KlassAlignmentInBytes-1); // Check alignment.
3645   z_brc(Assembler::bcondAllZero, ok);
3646   // The plain disassembler does not recognize illtrap. It instead displays
3647   // a 32-bit value. Issueing two illtraps assures the disassembler finds
3648   // the proper beginning of the next instruction.
3649   z_illtrap(0xee);
3650   z_illtrap(0xee);
3651   bind(ok);
3652 #endif
3653 
3654   if (base != NULL) {
3655     unsigned int base_h = ((unsigned long)base)>>32;
3656     unsigned int base_l = (unsigned int)((unsigned long)base);
3657     if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
3658       lgr_if_needed(dst, current);
3659       z_aih(dst, -((int)base_h));     // Base has no set bits in lower half.
3660     } else if ((base_h == 0) && (base_l != 0)) {
3661       lgr_if_needed(dst, current);
3662       z_agfi(dst, -(int)base_l);
3663     } else {
3664       load_const(Z_R0, base);
3665       lgr_if_needed(dst, current);
3666       z_sgr(dst, Z_R0);
3667     }
3668     current = dst;
3669   }
3670   if (shift != 0) {
3671     assert (LogKlassAlignmentInBytes == shift, "decode alg wrong");
3672     z_srlg(dst, current, shift);
3673     current = dst;
3674   }
3675   lgr_if_needed(dst, current); // Move may be required (if neither base nor shift != 0).
3676 
3677   BLOCK_COMMENT("} cKlass encoder");
3678 }
3679 
3680 // This function calculates the size of the code generated by
3681 //   decode_klass_not_null(register dst, Register src)
3682 // when (Universe::heap() != NULL). Hence, if the instructions
3683 // it generates change, then this method needs to be updated.
3684 int MacroAssembler::instr_size_for_decode_klass_not_null() {
3685   address  base    = CompressedKlassPointers::base();
3686   int shift_size   = CompressedKlassPointers::shift() == 0 ? 0 : 6; /* sllg */
3687   int addbase_size = 0;
3688   assert(UseCompressedClassPointers, "only for compressed klass ptrs");
3689 
3690   if (base != NULL) {
3691     unsigned int base_h = ((unsigned long)base)>>32;
3692     unsigned int base_l = (unsigned int)((unsigned long)base);
3693     if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
3694       addbase_size += 6; /* aih */
3695     } else if ((base_h == 0) && (base_l != 0)) {
3696       addbase_size += 6; /* algfi */
3697     } else {
3698       addbase_size += load_const_size();
3699       addbase_size += 4; /* algr */
3700     }
3701   }
3702 #ifdef ASSERT
3703   addbase_size += 10;
3704   addbase_size += 2; // Extra sigill.
3705 #endif
3706   return addbase_size + shift_size;
3707 }
3708 
3709 // !!! If the instructions that get generated here change
3710 //     then function instr_size_for_decode_klass_not_null()
3711 //     needs to get updated.
3712 // This variant of decode_klass_not_null() must generate predictable code!
3713 // The code must only depend on globally known parameters.
3714 void MacroAssembler::decode_klass_not_null(Register dst) {
3715   address  base    = CompressedKlassPointers::base();
3716   int      shift   = CompressedKlassPointers::shift();
3717   int      beg_off = offset();
3718   assert(UseCompressedClassPointers, "only for compressed klass ptrs");
3719 
3720   BLOCK_COMMENT("cKlass decoder (const size) {");
3721 
3722   if (shift != 0) { // Shift required?
3723     z_sllg(dst, dst, shift);
3724   }
3725   if (base != NULL) {
3726     unsigned int base_h = ((unsigned long)base)>>32;
3727     unsigned int base_l = (unsigned int)((unsigned long)base);
3728     if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
3729       z_aih(dst, base_h);     // Base has no set bits in lower half.
3730     } else if ((base_h == 0) && (base_l != 0)) {
3731       z_algfi(dst, base_l);   // Base has no set bits in upper half.
3732     } else {
3733       load_const(Z_R0, base); // Base has set bits everywhere.
3734       z_algr(dst, Z_R0);
3735     }
3736   }
3737 
3738 #ifdef ASSERT
3739   Label ok;
3740   z_tmll(dst, KlassAlignmentInBytes-1); // Check alignment.
3741   z_brc(Assembler::bcondAllZero, ok);
3742   // The plain disassembler does not recognize illtrap. It instead displays
3743   // a 32-bit value. Issueing two illtraps assures the disassembler finds
3744   // the proper beginning of the next instruction.
3745   z_illtrap(0xd1);
3746   z_illtrap(0xd1);
3747   bind(ok);
3748 #endif
3749   assert(offset() == beg_off + instr_size_for_decode_klass_not_null(), "Code gen mismatch.");
3750 
3751   BLOCK_COMMENT("} cKlass decoder (const size)");
3752 }
3753 
3754 // This variant of decode_klass_not_null() is for cases where
3755 //  1) the size of the generated instructions may vary
3756 //  2) the result is (potentially) stored in a register different from the source.
3757 void MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3758   address base  = CompressedKlassPointers::base();
3759   int     shift = CompressedKlassPointers::shift();
3760   assert(UseCompressedClassPointers, "only for compressed klass ptrs");
3761 
3762   BLOCK_COMMENT("cKlass decoder {");
3763 
3764   if (src == noreg) src = dst;
3765 
3766   if (shift != 0) { // Shift or at least move required?
3767     z_sllg(dst, src, shift);
3768   } else {
3769     lgr_if_needed(dst, src);
3770   }
3771 
3772   if (base != NULL) {
3773     unsigned int base_h = ((unsigned long)base)>>32;
3774     unsigned int base_l = (unsigned int)((unsigned long)base);
3775     if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
3776       z_aih(dst, base_h);     // Base has not set bits in lower half.
3777     } else if ((base_h == 0) && (base_l != 0)) {
3778       z_algfi(dst, base_l);   // Base has no set bits in upper half.
3779     } else {
3780       load_const_optimized(Z_R0, base); // Base has set bits everywhere.
3781       z_algr(dst, Z_R0);
3782     }
3783   }
3784 
3785 #ifdef ASSERT
3786   Label ok;
3787   z_tmll(dst, KlassAlignmentInBytes-1); // Check alignment.
3788   z_brc(Assembler::bcondAllZero, ok);
3789   // The plain disassembler does not recognize illtrap. It instead displays
3790   // a 32-bit value. Issueing two illtraps assures the disassembler finds
3791   // the proper beginning of the next instruction.
3792   z_illtrap(0xd2);
3793   z_illtrap(0xd2);
3794   bind(ok);
3795 #endif
3796   BLOCK_COMMENT("} cKlass decoder");
3797 }
3798 
3799 void MacroAssembler::load_klass(Register klass, Address mem) {
3800   if (UseCompressedClassPointers) {
3801     z_llgf(klass, mem);
3802     // Attention: no null check here!
3803     decode_klass_not_null(klass);
3804   } else {
3805     z_lg(klass, mem);
3806   }
3807 }
3808 
3809 void MacroAssembler::load_klass(Register klass, Register src_oop) {
3810   if (UseCompressedClassPointers) {
3811     z_llgf(klass, oopDesc::klass_offset_in_bytes(), src_oop);
3812     // Attention: no null check here!
3813     decode_klass_not_null(klass);
3814   } else {
3815     z_lg(klass, oopDesc::klass_offset_in_bytes(), src_oop);
3816   }
3817 }
3818 
3819 void MacroAssembler::load_prototype_header(Register Rheader, Register Rsrc_oop) {
3820   assert_different_registers(Rheader, Rsrc_oop);
3821   load_klass(Rheader, Rsrc_oop);
3822   z_lg(Rheader, Address(Rheader, Klass::prototype_header_offset()));
3823 }
3824 
3825 void MacroAssembler::store_klass(Register klass, Register dst_oop, Register ck) {
3826   if (UseCompressedClassPointers) {
3827     assert_different_registers(dst_oop, klass, Z_R0);
3828     if (ck == noreg) ck = klass;
3829     encode_klass_not_null(ck, klass);
3830     z_st(ck, Address(dst_oop, oopDesc::klass_offset_in_bytes()));
3831   } else {
3832     z_stg(klass, Address(dst_oop, oopDesc::klass_offset_in_bytes()));
3833   }
3834 }
3835 
3836 void MacroAssembler::store_klass_gap(Register s, Register d) {
3837   if (UseCompressedClassPointers) {
3838     assert(s != d, "not enough registers");
3839     // Support s = noreg.
3840     if (s != noreg) {
3841       z_st(s, Address(d, oopDesc::klass_gap_offset_in_bytes()));
3842     } else {
3843       z_mvhi(Address(d, oopDesc::klass_gap_offset_in_bytes()), 0);
3844     }
3845   }
3846 }
3847 
3848 // Compare klass ptr in memory against klass ptr in register.
3849 //
3850 // Rop1            - klass in register, always uncompressed.
3851 // disp            - Offset of klass in memory, compressed/uncompressed, depending on runtime flag.
3852 // Rbase           - Base address of cKlass in memory.
3853 // maybeNULL       - True if Rop1 possibly is a NULL.
3854 void MacroAssembler::compare_klass_ptr(Register Rop1, int64_t disp, Register Rbase, bool maybeNULL) {
3855 
3856   BLOCK_COMMENT("compare klass ptr {");
3857 
3858   if (UseCompressedClassPointers) {
3859     const int shift = CompressedKlassPointers::shift();
3860     address   base  = CompressedKlassPointers::base();
3861 
3862     assert((shift == 0) || (shift == LogKlassAlignmentInBytes), "cKlass encoder detected bad shift");
3863     assert_different_registers(Rop1, Z_R0);
3864     assert_different_registers(Rop1, Rbase, Z_R1);
3865 
3866     // First encode register oop and then compare with cOop in memory.
3867     // This sequence saves an unnecessary cOop load and decode.
3868     if (base == NULL) {
3869       if (shift == 0) {
3870         z_cl(Rop1, disp, Rbase);     // Unscaled
3871       } else {
3872         z_srlg(Z_R0, Rop1, shift);   // ZeroBased
3873         z_cl(Z_R0, disp, Rbase);
3874       }
3875     } else {                         // HeapBased
3876 #ifdef ASSERT
3877       bool     used_R0 = true;
3878       bool     used_R1 = true;
3879 #endif
3880       Register current = Rop1;
3881       Label    done;
3882 
3883       if (maybeNULL) {       // NULL ptr must be preserved!
3884         z_ltgr(Z_R0, current);
3885         z_bre(done);
3886         current = Z_R0;
3887       }
3888 
3889       unsigned int base_h = ((unsigned long)base)>>32;
3890       unsigned int base_l = (unsigned int)((unsigned long)base);
3891       if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
3892         lgr_if_needed(Z_R0, current);
3893         z_aih(Z_R0, -((int)base_h));     // Base has no set bits in lower half.
3894       } else if ((base_h == 0) && (base_l != 0)) {
3895         lgr_if_needed(Z_R0, current);
3896         z_agfi(Z_R0, -(int)base_l);
3897       } else {
3898         int pow2_offset = get_oop_base_complement(Z_R1, ((uint64_t)(intptr_t)base));
3899         add2reg_with_index(Z_R0, pow2_offset, Z_R1, Rop1); // Subtract base by adding complement.
3900       }
3901 
3902       if (shift != 0) {
3903         z_srlg(Z_R0, Z_R0, shift);
3904       }
3905       bind(done);
3906       z_cl(Z_R0, disp, Rbase);
3907 #ifdef ASSERT
3908       if (used_R0) preset_reg(Z_R0, 0xb05bUL, 2);
3909       if (used_R1) preset_reg(Z_R1, 0xb06bUL, 2);
3910 #endif
3911     }
3912   } else {
3913     z_clg(Rop1, disp, Z_R0, Rbase);
3914   }
3915   BLOCK_COMMENT("} compare klass ptr");
3916 }
3917 
3918 //---------------------------
3919 //  Compressed oops
3920 //---------------------------
3921 
3922 void MacroAssembler::encode_heap_oop(Register oop) {
3923   oop_encoder(oop, oop, true /*maybe null*/);
3924 }
3925 
3926 void MacroAssembler::encode_heap_oop_not_null(Register oop) {
3927   oop_encoder(oop, oop, false /*not null*/);
3928 }
3929 
3930 // Called with something derived from the oop base. e.g. oop_base>>3.
3931 int MacroAssembler::get_oop_base_pow2_offset(uint64_t oop_base) {
3932   unsigned int oop_base_ll = ((unsigned int)(oop_base >>  0)) & 0xffff;
3933   unsigned int oop_base_lh = ((unsigned int)(oop_base >> 16)) & 0xffff;
3934   unsigned int oop_base_hl = ((unsigned int)(oop_base >> 32)) & 0xffff;
3935   unsigned int oop_base_hh = ((unsigned int)(oop_base >> 48)) & 0xffff;
3936   unsigned int n_notzero_parts = (oop_base_ll == 0 ? 0:1)
3937                                + (oop_base_lh == 0 ? 0:1)
3938                                + (oop_base_hl == 0 ? 0:1)
3939                                + (oop_base_hh == 0 ? 0:1);
3940 
3941   assert(oop_base != 0, "This is for HeapBased cOops only");
3942 
3943   if (n_notzero_parts != 1) { //  Check if oop_base is just a few pages shy of a power of 2.
3944     uint64_t pow2_offset = 0x10000 - oop_base_ll;
3945     if (pow2_offset < 0x8000) {  // This might not be necessary.
3946       uint64_t oop_base2 = oop_base + pow2_offset;
3947 
3948       oop_base_ll = ((unsigned int)(oop_base2 >>  0)) & 0xffff;
3949       oop_base_lh = ((unsigned int)(oop_base2 >> 16)) & 0xffff;
3950       oop_base_hl = ((unsigned int)(oop_base2 >> 32)) & 0xffff;
3951       oop_base_hh = ((unsigned int)(oop_base2 >> 48)) & 0xffff;
3952       n_notzero_parts = (oop_base_ll == 0 ? 0:1) +
3953                         (oop_base_lh == 0 ? 0:1) +
3954                         (oop_base_hl == 0 ? 0:1) +
3955                         (oop_base_hh == 0 ? 0:1);
3956       if (n_notzero_parts == 1) {
3957         assert(-(int64_t)pow2_offset != (int64_t)-1, "We use -1 to signal uninitialized base register");
3958         return -pow2_offset;
3959       }
3960     }
3961   }
3962   return 0;
3963 }
3964 
3965 // If base address is offset from a straight power of two by just a few pages,
3966 // return this offset to the caller for a possible later composite add.
3967 // TODO/FIX: will only work correctly for 4k pages.
3968 int MacroAssembler::get_oop_base(Register Rbase, uint64_t oop_base) {
3969   int pow2_offset = get_oop_base_pow2_offset(oop_base);
3970 
3971   load_const_optimized(Rbase, oop_base - pow2_offset); // Best job possible.
3972 
3973   return pow2_offset;
3974 }
3975 
3976 int MacroAssembler::get_oop_base_complement(Register Rbase, uint64_t oop_base) {
3977   int offset = get_oop_base(Rbase, oop_base);
3978   z_lcgr(Rbase, Rbase);
3979   return -offset;
3980 }
3981 
3982 // Compare compressed oop in memory against oop in register.
3983 // Rop1            - Oop in register.
3984 // disp            - Offset of cOop in memory.
3985 // Rbase           - Base address of cOop in memory.
3986 // maybeNULL       - True if Rop1 possibly is a NULL.
3987 // maybeNULLtarget - Branch target for Rop1 == NULL, if flow control shall NOT continue with compare instruction.
3988 void MacroAssembler::compare_heap_oop(Register Rop1, Address mem, bool maybeNULL) {
3989   Register Rbase  = mem.baseOrR0();
3990   Register Rindex = mem.indexOrR0();
3991   int64_t  disp   = mem.disp();
3992 
3993   const int shift = CompressedOops::shift();
3994   address   base  = CompressedOops::base();
3995 
3996   assert(UseCompressedOops, "must be on to call this method");
3997   assert(Universe::heap() != NULL, "java heap must be initialized to call this method");
3998   assert((shift == 0) || (shift == LogMinObjAlignmentInBytes), "cOop encoder detected bad shift");
3999   assert_different_registers(Rop1, Z_R0);
4000   assert_different_registers(Rop1, Rbase, Z_R1);
4001   assert_different_registers(Rop1, Rindex, Z_R1);
4002 
4003   BLOCK_COMMENT("compare heap oop {");
4004 
4005   // First encode register oop and then compare with cOop in memory.
4006   // This sequence saves an unnecessary cOop load and decode.
4007   if (base == NULL) {
4008     if (shift == 0) {
4009       z_cl(Rop1, disp, Rindex, Rbase);  // Unscaled
4010     } else {
4011       z_srlg(Z_R0, Rop1, shift);        // ZeroBased
4012       z_cl(Z_R0, disp, Rindex, Rbase);
4013     }
4014   } else {                              // HeapBased
4015 #ifdef ASSERT
4016     bool  used_R0 = true;
4017     bool  used_R1 = true;
4018 #endif
4019     Label done;
4020     int   pow2_offset = get_oop_base_complement(Z_R1, ((uint64_t)(intptr_t)base));
4021 
4022     if (maybeNULL) {       // NULL ptr must be preserved!
4023       z_ltgr(Z_R0, Rop1);
4024       z_bre(done);
4025     }
4026 
4027     add2reg_with_index(Z_R0, pow2_offset, Z_R1, Rop1);
4028     z_srlg(Z_R0, Z_R0, shift);
4029 
4030     bind(done);
4031     z_cl(Z_R0, disp, Rindex, Rbase);
4032 #ifdef ASSERT
4033     if (used_R0) preset_reg(Z_R0, 0xb05bUL, 2);
4034     if (used_R1) preset_reg(Z_R1, 0xb06bUL, 2);
4035 #endif
4036   }
4037   BLOCK_COMMENT("} compare heap oop");
4038 }
4039 
4040 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
4041                                      const Address& addr, Register val,
4042                                      Register tmp1, Register tmp2, Register tmp3) {
4043   assert((decorators & ~(AS_RAW | IN_HEAP | IN_NATIVE | IS_ARRAY | IS_NOT_NULL |
4044                          ON_UNKNOWN_OOP_REF)) == 0, "unsupported decorator");
4045   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4046   decorators = AccessInternal::decorator_fixup(decorators);
4047   bool as_raw = (decorators & AS_RAW) != 0;
4048   if (as_raw) {
4049     bs->BarrierSetAssembler::store_at(this, decorators, type,
4050                                       addr, val,
4051                                       tmp1, tmp2, tmp3);
4052   } else {
4053     bs->store_at(this, decorators, type,
4054                  addr, val,
4055                  tmp1, tmp2, tmp3);
4056   }
4057 }
4058 
4059 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
4060                                     const Address& addr, Register dst,
4061                                     Register tmp1, Register tmp2, Label *is_null) {
4062   assert((decorators & ~(AS_RAW | IN_HEAP | IN_NATIVE | IS_ARRAY | IS_NOT_NULL |
4063                          ON_PHANTOM_OOP_REF | ON_WEAK_OOP_REF)) == 0, "unsupported decorator");
4064   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4065   decorators = AccessInternal::decorator_fixup(decorators);
4066   bool as_raw = (decorators & AS_RAW) != 0;
4067   if (as_raw) {
4068     bs->BarrierSetAssembler::load_at(this, decorators, type,
4069                                      addr, dst,
4070                                      tmp1, tmp2, is_null);
4071   } else {
4072     bs->load_at(this, decorators, type,
4073                 addr, dst,
4074                 tmp1, tmp2, is_null);
4075   }
4076 }
4077 
4078 void MacroAssembler::load_heap_oop(Register dest, const Address &a,
4079                                    Register tmp1, Register tmp2,
4080                                    DecoratorSet decorators, Label *is_null) {
4081   access_load_at(T_OBJECT, IN_HEAP | decorators, a, dest, tmp1, tmp2, is_null);
4082 }
4083 
4084 void MacroAssembler::store_heap_oop(Register Roop, const Address &a,
4085                                     Register tmp1, Register tmp2, Register tmp3,
4086                                     DecoratorSet decorators) {
4087   access_store_at(T_OBJECT, IN_HEAP | decorators, a, Roop, tmp1, tmp2, tmp3);
4088 }
4089 
4090 //-------------------------------------------------
4091 // Encode compressed oop. Generally usable encoder.
4092 //-------------------------------------------------
4093 // Rsrc - contains regular oop on entry. It remains unchanged.
4094 // Rdst - contains compressed oop on exit.
4095 // Rdst and Rsrc may indicate same register, in which case Rsrc does not remain unchanged.
4096 //
4097 // Rdst must not indicate scratch register Z_R1 (Z_R1_scratch) for functionality.
4098 // Rdst should not indicate scratch register Z_R0 (Z_R0_scratch) for performance.
4099 //
4100 // only32bitValid is set, if later code only uses the lower 32 bits. In this
4101 // case we must not fix the upper 32 bits.
4102 void MacroAssembler::oop_encoder(Register Rdst, Register Rsrc, bool maybeNULL,
4103                                  Register Rbase, int pow2_offset, bool only32bitValid) {
4104 
4105   const address oop_base  = CompressedOops::base();
4106   const int     oop_shift = CompressedOops::shift();
4107   const bool    disjoint  = CompressedOops::base_disjoint();
4108 
4109   assert(UseCompressedOops, "must be on to call this method");
4110   assert(Universe::heap() != NULL, "java heap must be initialized to call this encoder");
4111   assert((oop_shift == 0) || (oop_shift == LogMinObjAlignmentInBytes), "cOop encoder detected bad shift");
4112 
4113   if (disjoint || (oop_base == NULL)) {
4114     BLOCK_COMMENT("cOop encoder zeroBase {");
4115     if (oop_shift == 0) {
4116       if (oop_base != NULL && !only32bitValid) {
4117         z_llgfr(Rdst, Rsrc); // Clear upper bits in case the register will be decoded again.
4118       } else {
4119         lgr_if_needed(Rdst, Rsrc);
4120       }
4121     } else {
4122       z_srlg(Rdst, Rsrc, oop_shift);
4123       if (oop_base != NULL && !only32bitValid) {
4124         z_llgfr(Rdst, Rdst); // Clear upper bits in case the register will be decoded again.
4125       }
4126     }
4127     BLOCK_COMMENT("} cOop encoder zeroBase");
4128     return;
4129   }
4130 
4131   bool used_R0 = false;
4132   bool used_R1 = false;
4133 
4134   BLOCK_COMMENT("cOop encoder general {");
4135   assert_different_registers(Rdst, Z_R1);
4136   assert_different_registers(Rsrc, Rbase);
4137   if (maybeNULL) {
4138     Label done;
4139     // We reorder shifting and subtracting, so that we can compare
4140     // and shift in parallel:
4141     //
4142     // cycle 0:  potential LoadN, base = <const>
4143     // cycle 1:  base = !base     dst = src >> 3,    cmp cr = (src != 0)
4144     // cycle 2:  if (cr) br,      dst = dst + base + offset
4145 
4146     // Get oop_base components.
4147     if (pow2_offset == -1) {
4148       if (Rdst == Rbase) {
4149         if (Rdst == Z_R1 || Rsrc == Z_R1) {
4150           Rbase = Z_R0;
4151           used_R0 = true;
4152         } else {
4153           Rdst = Z_R1;
4154           used_R1 = true;
4155         }
4156       }
4157       if (Rbase == Z_R1) {
4158         used_R1 = true;
4159       }
4160       pow2_offset = get_oop_base_complement(Rbase, ((uint64_t)(intptr_t)oop_base) >> oop_shift);
4161     }
4162     assert_different_registers(Rdst, Rbase);
4163 
4164     // Check for NULL oop (must be left alone) and shift.
4165     if (oop_shift != 0) {  // Shift out alignment bits
4166       if (((intptr_t)oop_base&0xc000000000000000L) == 0L) { // We are sure: no single address will have the leftmost bit set.
4167         z_srag(Rdst, Rsrc, oop_shift);  // Arithmetic shift sets the condition code.
4168       } else {
4169         z_srlg(Rdst, Rsrc, oop_shift);
4170         z_ltgr(Rsrc, Rsrc);  // This is the recommended way of testing for zero.
4171         // This probably is faster, as it does not write a register. No!
4172         // z_cghi(Rsrc, 0);
4173       }
4174     } else {
4175       z_ltgr(Rdst, Rsrc);   // Move NULL to result register.
4176     }
4177     z_bre(done);
4178 
4179     // Subtract oop_base components.
4180     if ((Rdst == Z_R0) || (Rbase == Z_R0)) {
4181       z_algr(Rdst, Rbase);
4182       if (pow2_offset != 0) { add2reg(Rdst, pow2_offset); }
4183     } else {
4184       add2reg_with_index(Rdst, pow2_offset, Rbase, Rdst);
4185     }
4186     if (!only32bitValid) {
4187       z_llgfr(Rdst, Rdst); // Clear upper bits in case the register will be decoded again.
4188     }
4189     bind(done);
4190 
4191   } else {  // not null
4192     // Get oop_base components.
4193     if (pow2_offset == -1) {
4194       pow2_offset = get_oop_base_complement(Rbase, (uint64_t)(intptr_t)oop_base);
4195     }
4196 
4197     // Subtract oop_base components and shift.
4198     if (Rdst == Z_R0 || Rsrc == Z_R0 || Rbase == Z_R0) {
4199       // Don't use lay instruction.
4200       if (Rdst == Rsrc) {
4201         z_algr(Rdst, Rbase);
4202       } else {
4203         lgr_if_needed(Rdst, Rbase);
4204         z_algr(Rdst, Rsrc);
4205       }
4206       if (pow2_offset != 0) add2reg(Rdst, pow2_offset);
4207     } else {
4208       add2reg_with_index(Rdst, pow2_offset, Rbase, Rsrc);
4209     }
4210     if (oop_shift != 0) {   // Shift out alignment bits.
4211       z_srlg(Rdst, Rdst, oop_shift);
4212     }
4213     if (!only32bitValid) {
4214       z_llgfr(Rdst, Rdst); // Clear upper bits in case the register will be decoded again.
4215     }
4216   }
4217 #ifdef ASSERT
4218   if (used_R0 && Rdst != Z_R0 && Rsrc != Z_R0) { preset_reg(Z_R0, 0xb01bUL, 2); }
4219   if (used_R1 && Rdst != Z_R1 && Rsrc != Z_R1) { preset_reg(Z_R1, 0xb02bUL, 2); }
4220 #endif
4221   BLOCK_COMMENT("} cOop encoder general");
4222 }
4223 
4224 //-------------------------------------------------
4225 // decode compressed oop. Generally usable decoder.
4226 //-------------------------------------------------
4227 // Rsrc - contains compressed oop on entry.
4228 // Rdst - contains regular oop on exit.
4229 // Rdst and Rsrc may indicate same register.
4230 // Rdst must not be the same register as Rbase, if Rbase was preloaded (before call).
4231 // Rdst can be the same register as Rbase. Then, either Z_R0 or Z_R1 must be available as scratch.
4232 // Rbase - register to use for the base
4233 // pow2_offset - offset of base to nice value. If -1, base must be loaded.
4234 // For performance, it is good to
4235 //  - avoid Z_R0 for any of the argument registers.
4236 //  - keep Rdst and Rsrc distinct from Rbase. Rdst == Rsrc is ok for performance.
4237 //  - avoid Z_R1 for Rdst if Rdst == Rbase.
4238 void MacroAssembler::oop_decoder(Register Rdst, Register Rsrc, bool maybeNULL, Register Rbase, int pow2_offset) {
4239 
4240   const address oop_base  = CompressedOops::base();
4241   const int     oop_shift = CompressedOops::shift();
4242   const bool    disjoint  = CompressedOops::base_disjoint();
4243 
4244   assert(UseCompressedOops, "must be on to call this method");
4245   assert(Universe::heap() != NULL, "java heap must be initialized to call this decoder");
4246   assert((oop_shift == 0) || (oop_shift == LogMinObjAlignmentInBytes),
4247          "cOop encoder detected bad shift");
4248 
4249   // cOops are always loaded zero-extended from memory. No explicit zero-extension necessary.
4250 
4251   if (oop_base != NULL) {
4252     unsigned int oop_base_hl = ((unsigned int)((uint64_t)(intptr_t)oop_base >> 32)) & 0xffff;
4253     unsigned int oop_base_hh = ((unsigned int)((uint64_t)(intptr_t)oop_base >> 48)) & 0xffff;
4254     unsigned int oop_base_hf = ((unsigned int)((uint64_t)(intptr_t)oop_base >> 32)) & 0xFFFFffff;
4255     if (disjoint && (oop_base_hl == 0 || oop_base_hh == 0)) {
4256       BLOCK_COMMENT("cOop decoder disjointBase {");
4257       // We do not need to load the base. Instead, we can install the upper bits
4258       // with an OR instead of an ADD.
4259       Label done;
4260 
4261       // Rsrc contains a narrow oop. Thus we are sure the leftmost <oop_shift> bits will never be set.
4262       if (maybeNULL) {  // NULL ptr must be preserved!
4263         z_slag(Rdst, Rsrc, oop_shift);  // Arithmetic shift sets the condition code.
4264         z_bre(done);
4265       } else {
4266         z_sllg(Rdst, Rsrc, oop_shift);  // Logical shift leaves condition code alone.
4267       }
4268       if ((oop_base_hl != 0) && (oop_base_hh != 0)) {
4269         z_oihf(Rdst, oop_base_hf);
4270       } else if (oop_base_hl != 0) {
4271         z_oihl(Rdst, oop_base_hl);
4272       } else {
4273         assert(oop_base_hh != 0, "not heapbased mode");
4274         z_oihh(Rdst, oop_base_hh);
4275       }
4276       bind(done);
4277       BLOCK_COMMENT("} cOop decoder disjointBase");
4278     } else {
4279       BLOCK_COMMENT("cOop decoder general {");
4280       // There are three decode steps:
4281       //   scale oop offset (shift left)
4282       //   get base (in reg) and pow2_offset (constant)
4283       //   add base, pow2_offset, and oop offset
4284       // The following register overlap situations may exist:
4285       // Rdst == Rsrc,  Rbase any other
4286       //   not a problem. Scaling in-place leaves Rbase undisturbed.
4287       //   Loading Rbase does not impact the scaled offset.
4288       // Rdst == Rbase, Rsrc  any other
4289       //   scaling would destroy a possibly preloaded Rbase. Loading Rbase
4290       //   would destroy the scaled offset.
4291       //   Remedy: use Rdst_tmp if Rbase has been preloaded.
4292       //           use Rbase_tmp if base has to be loaded.
4293       // Rsrc == Rbase, Rdst  any other
4294       //   Only possible without preloaded Rbase.
4295       //   Loading Rbase does not destroy compressed oop because it was scaled into Rdst before.
4296       // Rsrc == Rbase, Rdst == Rbase
4297       //   Only possible without preloaded Rbase.
4298       //   Loading Rbase would destroy compressed oop. Scaling in-place is ok.
4299       //   Remedy: use Rbase_tmp.
4300       //
4301       Label    done;
4302       Register Rdst_tmp       = Rdst;
4303       Register Rbase_tmp      = Rbase;
4304       bool     used_R0        = false;
4305       bool     used_R1        = false;
4306       bool     base_preloaded = pow2_offset >= 0;
4307       guarantee(!(base_preloaded && (Rsrc == Rbase)), "Register clash, check caller");
4308       assert(oop_shift != 0, "room for optimization");
4309 
4310       // Check if we need to use scratch registers.
4311       if (Rdst == Rbase) {
4312         assert(!(((Rdst == Z_R0) && (Rsrc == Z_R1)) || ((Rdst == Z_R1) && (Rsrc == Z_R0))), "need a scratch reg");
4313         if (Rdst != Rsrc) {
4314           if (base_preloaded) { Rdst_tmp  = (Rdst == Z_R1) ? Z_R0 : Z_R1; }
4315           else                { Rbase_tmp = (Rdst == Z_R1) ? Z_R0 : Z_R1; }
4316         } else {
4317           Rbase_tmp = (Rdst == Z_R1) ? Z_R0 : Z_R1;
4318         }
4319       }
4320       if (base_preloaded) lgr_if_needed(Rbase_tmp, Rbase);
4321 
4322       // Scale oop and check for NULL.
4323       // Rsrc contains a narrow oop. Thus we are sure the leftmost <oop_shift> bits will never be set.
4324       if (maybeNULL) {  // NULL ptr must be preserved!
4325         z_slag(Rdst_tmp, Rsrc, oop_shift);  // Arithmetic shift sets the condition code.
4326         z_bre(done);
4327       } else {
4328         z_sllg(Rdst_tmp, Rsrc, oop_shift);  // Logical shift leaves condition code alone.
4329       }
4330 
4331       // Get oop_base components.
4332       if (!base_preloaded) {
4333         pow2_offset = get_oop_base(Rbase_tmp, (uint64_t)(intptr_t)oop_base);
4334       }
4335 
4336       // Add up all components.
4337       if ((Rbase_tmp == Z_R0) || (Rdst_tmp == Z_R0)) {
4338         z_algr(Rdst_tmp, Rbase_tmp);
4339         if (pow2_offset != 0) { add2reg(Rdst_tmp, pow2_offset); }
4340       } else {
4341         add2reg_with_index(Rdst_tmp, pow2_offset, Rbase_tmp, Rdst_tmp);
4342       }
4343 
4344       bind(done);
4345       lgr_if_needed(Rdst, Rdst_tmp);
4346 #ifdef ASSERT
4347       if (used_R0 && Rdst != Z_R0 && Rsrc != Z_R0) { preset_reg(Z_R0, 0xb03bUL, 2); }
4348       if (used_R1 && Rdst != Z_R1 && Rsrc != Z_R1) { preset_reg(Z_R1, 0xb04bUL, 2); }
4349 #endif
4350       BLOCK_COMMENT("} cOop decoder general");
4351     }
4352   } else {
4353     BLOCK_COMMENT("cOop decoder zeroBase {");
4354     if (oop_shift == 0) {
4355       lgr_if_needed(Rdst, Rsrc);
4356     } else {
4357       z_sllg(Rdst, Rsrc, oop_shift);
4358     }
4359     BLOCK_COMMENT("} cOop decoder zeroBase");
4360   }
4361 }
4362 
4363 // ((OopHandle)result).resolve();
4364 void MacroAssembler::resolve_oop_handle(Register result) {
4365   // OopHandle::resolve is an indirection.
4366   z_lg(result, 0, result);
4367 }
4368 
4369 void MacroAssembler::load_mirror_from_const_method(Register mirror, Register const_method) {
4370   mem2reg_opt(mirror, Address(const_method, ConstMethod::constants_offset()));
4371   mem2reg_opt(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
4372   mem2reg_opt(mirror, Address(mirror, Klass::java_mirror_offset()));
4373   resolve_oop_handle(mirror);
4374 }
4375 
4376 void MacroAssembler::load_method_holder(Register holder, Register method) {
4377   mem2reg_opt(holder, Address(method, Method::const_offset()));
4378   mem2reg_opt(holder, Address(holder, ConstMethod::constants_offset()));
4379   mem2reg_opt(holder, Address(holder, ConstantPool::pool_holder_offset_in_bytes()));
4380 }
4381 
4382 //---------------------------------------------------------------
4383 //---  Operations on arrays.
4384 //---------------------------------------------------------------
4385 
4386 // Compiler ensures base is doubleword aligned and cnt is #doublewords.
4387 // Emitter does not KILL cnt and base arguments, since they need to be copied to
4388 // work registers anyway.
4389 // Actually, only r0, r1, and r5 are killed.
4390 unsigned int MacroAssembler::Clear_Array(Register cnt_arg, Register base_pointer_arg, Register odd_tmp_reg) {
4391 
4392   int      block_start = offset();
4393   Register dst_len  = Z_R1;    // Holds dst len  for MVCLE.
4394   Register dst_addr = Z_R0;    // Holds dst addr for MVCLE.
4395 
4396   Label doXC, doMVCLE, done;
4397 
4398   BLOCK_COMMENT("Clear_Array {");
4399 
4400   // Check for zero len and convert to long.
4401   z_ltgfr(odd_tmp_reg, cnt_arg);
4402   z_bre(done);                    // Nothing to do if len == 0.
4403 
4404   // Prefetch data to be cleared.
4405   if (VM_Version::has_Prefetch()) {
4406     z_pfd(0x02,   0, Z_R0, base_pointer_arg);
4407     z_pfd(0x02, 256, Z_R0, base_pointer_arg);
4408   }
4409 
4410   z_sllg(dst_len, odd_tmp_reg, 3); // #bytes to clear.
4411   z_cghi(odd_tmp_reg, 32);         // Check for len <= 256 bytes (<=32 DW).
4412   z_brnh(doXC);                    // If so, use executed XC to clear.
4413 
4414   // MVCLE: initialize long arrays (general case).
4415   bind(doMVCLE);
4416   z_lgr(dst_addr, base_pointer_arg);
4417   // Pass 0 as source length to MVCLE: destination will be filled with padding byte 0.
4418   // The even register of the register pair is not killed.
4419   clear_reg(odd_tmp_reg, true, false);
4420   MacroAssembler::move_long_ext(dst_addr, as_Register(odd_tmp_reg->encoding()-1), 0);
4421   z_bru(done);
4422 
4423   // XC: initialize short arrays.
4424   Label XC_template; // Instr template, never exec directly!
4425     bind(XC_template);
4426     z_xc(0,0,base_pointer_arg,0,base_pointer_arg);
4427 
4428   bind(doXC);
4429     add2reg(dst_len, -1);               // Get #bytes-1 for EXECUTE.
4430     if (VM_Version::has_ExecuteExtensions()) {
4431       z_exrl(dst_len, XC_template);     // Execute XC with var. len.
4432     } else {
4433       z_larl(odd_tmp_reg, XC_template);
4434       z_ex(dst_len,0,Z_R0,odd_tmp_reg); // Execute XC with var. len.
4435     }
4436     // z_bru(done);      // fallthru
4437 
4438   bind(done);
4439 
4440   BLOCK_COMMENT("} Clear_Array");
4441 
4442   int block_end = offset();
4443   return block_end - block_start;
4444 }
4445 
4446 // Compiler ensures base is doubleword aligned and cnt is count of doublewords.
4447 // Emitter does not KILL any arguments nor work registers.
4448 // Emitter generates up to 16 XC instructions, depending on the array length.
4449 unsigned int MacroAssembler::Clear_Array_Const(long cnt, Register base) {
4450   int  block_start    = offset();
4451   int  off;
4452   int  lineSize_Bytes = AllocatePrefetchStepSize;
4453   int  lineSize_DW    = AllocatePrefetchStepSize>>LogBytesPerWord;
4454   bool doPrefetch     = VM_Version::has_Prefetch();
4455   int  XC_maxlen      = 256;
4456   int  numXCInstr     = cnt > 0 ? (cnt*BytesPerWord-1)/XC_maxlen+1 : 0;
4457 
4458   BLOCK_COMMENT("Clear_Array_Const {");
4459   assert(cnt*BytesPerWord <= 4096, "ClearArrayConst can handle 4k only");
4460 
4461   // Do less prefetching for very short arrays.
4462   if (numXCInstr > 0) {
4463     // Prefetch only some cache lines, then begin clearing.
4464     if (doPrefetch) {
4465       if (cnt*BytesPerWord <= lineSize_Bytes/4) {  // If less than 1/4 of a cache line to clear,
4466         z_pfd(0x02, 0, Z_R0, base);                // prefetch just the first cache line.
4467       } else {
4468         assert(XC_maxlen == lineSize_Bytes, "ClearArrayConst needs 256B cache lines");
4469         for (off = 0; (off < AllocatePrefetchLines) && (off <= numXCInstr); off ++) {
4470           z_pfd(0x02, off*lineSize_Bytes, Z_R0, base);
4471         }
4472       }
4473     }
4474 
4475     for (off=0; off<(numXCInstr-1); off++) {
4476       z_xc(off*XC_maxlen, XC_maxlen-1, base, off*XC_maxlen, base);
4477 
4478       // Prefetch some cache lines in advance.
4479       if (doPrefetch && (off <= numXCInstr-AllocatePrefetchLines)) {
4480         z_pfd(0x02, (off+AllocatePrefetchLines)*lineSize_Bytes, Z_R0, base);
4481       }
4482     }
4483     if (off*XC_maxlen < cnt*BytesPerWord) {
4484       z_xc(off*XC_maxlen, (cnt*BytesPerWord-off*XC_maxlen)-1, base, off*XC_maxlen, base);
4485     }
4486   }
4487   BLOCK_COMMENT("} Clear_Array_Const");
4488 
4489   int block_end = offset();
4490   return block_end - block_start;
4491 }
4492 
4493 // Compiler ensures base is doubleword aligned and cnt is #doublewords.
4494 // Emitter does not KILL cnt and base arguments, since they need to be copied to
4495 // work registers anyway.
4496 // Actually, only r0, r1, (which are work registers) and odd_tmp_reg are killed.
4497 //
4498 // For very large arrays, exploit MVCLE H/W support.
4499 // MVCLE instruction automatically exploits H/W-optimized page mover.
4500 // - Bytes up to next page boundary are cleared with a series of XC to self.
4501 // - All full pages are cleared with the page mover H/W assist.
4502 // - Remaining bytes are again cleared by a series of XC to self.
4503 //
4504 unsigned int MacroAssembler::Clear_Array_Const_Big(long cnt, Register base_pointer_arg, Register odd_tmp_reg) {
4505 
4506   int      block_start = offset();
4507   Register dst_len  = Z_R1;      // Holds dst len  for MVCLE.
4508   Register dst_addr = Z_R0;      // Holds dst addr for MVCLE.
4509 
4510   BLOCK_COMMENT("Clear_Array_Const_Big {");
4511 
4512   // Get len to clear.
4513   load_const_optimized(dst_len, (long)cnt*8L);  // in Bytes = #DW*8
4514 
4515   // Prepare other args to MVCLE.
4516   z_lgr(dst_addr, base_pointer_arg);
4517   // Pass 0 as source length to MVCLE: destination will be filled with padding byte 0.
4518   // The even register of the register pair is not killed.
4519   (void) clear_reg(odd_tmp_reg, true, false);  // Src len of MVCLE is zero.
4520   MacroAssembler::move_long_ext(dst_addr, as_Register(odd_tmp_reg->encoding() - 1), 0);
4521   BLOCK_COMMENT("} Clear_Array_Const_Big");
4522 
4523   int block_end = offset();
4524   return block_end - block_start;
4525 }
4526 
4527 // Allocator.
4528 unsigned int MacroAssembler::CopyRawMemory_AlignedDisjoint(Register src_reg, Register dst_reg,
4529                                                            Register cnt_reg,
4530                                                            Register tmp1_reg, Register tmp2_reg) {
4531   // Tmp1 is oddReg.
4532   // Tmp2 is evenReg.
4533 
4534   int block_start = offset();
4535   Label doMVC, doMVCLE, done, MVC_template;
4536 
4537   BLOCK_COMMENT("CopyRawMemory_AlignedDisjoint {");
4538 
4539   // Check for zero len and convert to long.
4540   z_ltgfr(cnt_reg, cnt_reg);      // Remember casted value for doSTG case.
4541   z_bre(done);                    // Nothing to do if len == 0.
4542 
4543   z_sllg(Z_R1, cnt_reg, 3);       // Dst len in bytes. calc early to have the result ready.
4544 
4545   z_cghi(cnt_reg, 32);            // Check for len <= 256 bytes (<=32 DW).
4546   z_brnh(doMVC);                  // If so, use executed MVC to clear.
4547 
4548   bind(doMVCLE);                  // A lot of data (more than 256 bytes).
4549   // Prep dest reg pair.
4550   z_lgr(Z_R0, dst_reg);           // dst addr
4551   // Dst len already in Z_R1.
4552   // Prep src reg pair.
4553   z_lgr(tmp2_reg, src_reg);       // src addr
4554   z_lgr(tmp1_reg, Z_R1);          // Src len same as dst len.
4555 
4556   // Do the copy.
4557   move_long_ext(Z_R0, tmp2_reg, 0xb0); // Bypass cache.
4558   z_bru(done);                         // All done.
4559 
4560   bind(MVC_template);             // Just some data (not more than 256 bytes).
4561   z_mvc(0, 0, dst_reg, 0, src_reg);
4562 
4563   bind(doMVC);
4564 
4565   if (VM_Version::has_ExecuteExtensions()) {
4566     add2reg(Z_R1, -1);
4567   } else {
4568     add2reg(tmp1_reg, -1, Z_R1);
4569     z_larl(Z_R1, MVC_template);
4570   }
4571 
4572   if (VM_Version::has_Prefetch()) {
4573     z_pfd(1,  0,Z_R0,src_reg);
4574     z_pfd(2,  0,Z_R0,dst_reg);
4575     //    z_pfd(1,256,Z_R0,src_reg);    // Assume very short copy.
4576     //    z_pfd(2,256,Z_R0,dst_reg);
4577   }
4578 
4579   if (VM_Version::has_ExecuteExtensions()) {
4580     z_exrl(Z_R1, MVC_template);
4581   } else {
4582     z_ex(tmp1_reg, 0, Z_R0, Z_R1);
4583   }
4584 
4585   bind(done);
4586 
4587   BLOCK_COMMENT("} CopyRawMemory_AlignedDisjoint");
4588 
4589   int block_end = offset();
4590   return block_end - block_start;
4591 }
4592 
4593 //------------------------------------------------------
4594 //   Special String Intrinsics. Implementation
4595 //------------------------------------------------------
4596 
4597 // Intrinsics for CompactStrings
4598 
4599 // Compress char[] to byte[].
4600 //   Restores: src, dst
4601 //   Uses:     cnt
4602 //   Kills:    tmp, Z_R0, Z_R1.
4603 //   Early clobber: result.
4604 // Note:
4605 //   cnt is signed int. Do not rely on high word!
4606 //       counts # characters, not bytes.
4607 // The result is the number of characters copied before the first incompatible character was found.
4608 // If precise is true, the processing stops exactly at this point. Otherwise, the result may be off
4609 // by a few bytes. The result always indicates the number of copied characters.
4610 // When used as a character index, the returned value points to the first incompatible character.
4611 //
4612 // Note: Does not behave exactly like package private StringUTF16 compress java implementation in case of failure:
4613 // - Different number of characters may have been written to dead array (if precise is false).
4614 // - Returns a number <cnt instead of 0. (Result gets compared with cnt.)
4615 unsigned int MacroAssembler::string_compress(Register result, Register src, Register dst, Register cnt,
4616                                              Register tmp,    bool precise) {
4617   assert_different_registers(Z_R0, Z_R1, result, src, dst, cnt, tmp);
4618 
4619   if (precise) {
4620     BLOCK_COMMENT("encode_iso_array {");
4621   } else {
4622     BLOCK_COMMENT("string_compress {");
4623   }
4624   int  block_start = offset();
4625 
4626   Register       Rsrc  = src;
4627   Register       Rdst  = dst;
4628   Register       Rix   = tmp;
4629   Register       Rcnt  = cnt;
4630   Register       Rmask = result;  // holds incompatibility check mask until result value is stored.
4631   Label          ScalarShortcut, AllDone;
4632 
4633   z_iilf(Rmask, 0xFF00FF00);
4634   z_iihf(Rmask, 0xFF00FF00);
4635 
4636 #if 0  // Sacrifice shortcuts for code compactness
4637   {
4638     //---<  shortcuts for short strings (very frequent)   >---
4639     //   Strings with 4 and 8 characters were fond to occur very frequently.
4640     //   Therefore, we handle them right away with minimal overhead.
4641     Label     skipShortcut, skip4Shortcut, skip8Shortcut;
4642     Register  Rout = Z_R0;
4643     z_chi(Rcnt, 4);
4644     z_brne(skip4Shortcut);                 // 4 characters are very frequent
4645       z_lg(Z_R0, 0, Rsrc);                 // Treat exactly 4 characters specially.
4646       if (VM_Version::has_DistinctOpnds()) {
4647         Rout = Z_R0;
4648         z_ngrk(Rix, Z_R0, Rmask);
4649       } else {
4650         Rout = Rix;
4651         z_lgr(Rix, Z_R0);
4652         z_ngr(Z_R0, Rmask);
4653       }
4654       z_brnz(skipShortcut);
4655       z_stcmh(Rout, 5, 0, Rdst);
4656       z_stcm(Rout,  5, 2, Rdst);
4657       z_lgfr(result, Rcnt);
4658       z_bru(AllDone);
4659     bind(skip4Shortcut);
4660 
4661     z_chi(Rcnt, 8);
4662     z_brne(skip8Shortcut);                 // There's more to do...
4663       z_lmg(Z_R0, Z_R1, 0, Rsrc);          // Treat exactly 8 characters specially.
4664       if (VM_Version::has_DistinctOpnds()) {
4665         Rout = Z_R0;
4666         z_ogrk(Rix, Z_R0, Z_R1);
4667         z_ngr(Rix, Rmask);
4668       } else {
4669         Rout = Rix;
4670         z_lgr(Rix, Z_R0);
4671         z_ogr(Z_R0, Z_R1);
4672         z_ngr(Z_R0, Rmask);
4673       }
4674       z_brnz(skipShortcut);
4675       z_stcmh(Rout, 5, 0, Rdst);
4676       z_stcm(Rout,  5, 2, Rdst);
4677       z_stcmh(Z_R1, 5, 4, Rdst);
4678       z_stcm(Z_R1,  5, 6, Rdst);
4679       z_lgfr(result, Rcnt);
4680       z_bru(AllDone);
4681 
4682     bind(skip8Shortcut);
4683     clear_reg(Z_R0, true, false);          // #characters already processed (none). Precond for scalar loop.
4684     z_brl(ScalarShortcut);                 // Just a few characters
4685 
4686     bind(skipShortcut);
4687   }
4688 #endif
4689   clear_reg(Z_R0);                         // make sure register is properly initialized.
4690 
4691   if (VM_Version::has_VectorFacility()) {
4692     const int  min_vcnt     = 32;          // Minimum #characters required to use vector instructions.
4693                                            // Otherwise just do nothing in vector mode.
4694                                            // Must be multiple of 2*(vector register length in chars (8 HW = 128 bits)).
4695     const int  log_min_vcnt = exact_log2(min_vcnt);
4696     Label      VectorLoop, VectorDone, VectorBreak;
4697 
4698     VectorRegister Vtmp1      = Z_V16;
4699     VectorRegister Vtmp2      = Z_V17;
4700     VectorRegister Vmask      = Z_V18;
4701     VectorRegister Vzero      = Z_V19;
4702     VectorRegister Vsrc_first = Z_V20;
4703     VectorRegister Vsrc_last  = Z_V23;
4704 
4705     assert((Vsrc_last->encoding() - Vsrc_first->encoding() + 1) == min_vcnt/8, "logic error");
4706     assert(VM_Version::has_DistinctOpnds(), "Assumption when has_VectorFacility()");
4707     z_srak(Rix, Rcnt, log_min_vcnt);       // # vector loop iterations
4708     z_brz(VectorDone);                     // not enough data for vector loop
4709 
4710     z_vzero(Vzero);                        // all zeroes
4711     z_vgmh(Vmask, 0, 7);                   // generate 0xff00 mask for all 2-byte elements
4712     z_sllg(Z_R0, Rix, log_min_vcnt);       // remember #chars that will be processed by vector loop
4713 
4714     bind(VectorLoop);
4715       z_vlm(Vsrc_first, Vsrc_last, 0, Rsrc);
4716       add2reg(Rsrc, min_vcnt*2);
4717 
4718       //---<  check for incompatible character  >---
4719       z_vo(Vtmp1, Z_V20, Z_V21);
4720       z_vo(Vtmp2, Z_V22, Z_V23);
4721       z_vo(Vtmp1, Vtmp1, Vtmp2);
4722       z_vn(Vtmp1, Vtmp1, Vmask);
4723       z_vceqhs(Vtmp1, Vtmp1, Vzero);       // high half of all chars must be zero for successful compress.
4724       z_bvnt(VectorBreak);                 // break vector loop if not all vector elements compare eq -> incompatible character found.
4725                                            // re-process data from current iteration in break handler.
4726 
4727       //---<  pack & store characters  >---
4728       z_vpkh(Vtmp1, Z_V20, Z_V21);         // pack (src1, src2) -> tmp1
4729       z_vpkh(Vtmp2, Z_V22, Z_V23);         // pack (src3, src4) -> tmp2
4730       z_vstm(Vtmp1, Vtmp2, 0, Rdst);       // store packed string
4731       add2reg(Rdst, min_vcnt);
4732 
4733       z_brct(Rix, VectorLoop);
4734 
4735     z_bru(VectorDone);
4736 
4737     bind(VectorBreak);
4738       add2reg(Rsrc, -min_vcnt*2);          // Fix Rsrc. Rsrc was already updated, but Rdst and Rix are not.
4739       z_sll(Rix, log_min_vcnt);            // # chars processed so far in VectorLoop, excl. current iteration.
4740       z_sr(Z_R0, Rix);                     // correct # chars processed in total.
4741 
4742     bind(VectorDone);
4743   }
4744 
4745   {
4746     const int  min_cnt     =  8;           // Minimum #characters required to use unrolled loop.
4747                                            // Otherwise just do nothing in unrolled loop.
4748                                            // Must be multiple of 8.
4749     const int  log_min_cnt = exact_log2(min_cnt);
4750     Label      UnrolledLoop, UnrolledDone, UnrolledBreak;
4751 
4752     if (VM_Version::has_DistinctOpnds()) {
4753       z_srk(Rix, Rcnt, Z_R0);              // remaining # chars to compress in unrolled loop
4754     } else {
4755       z_lr(Rix, Rcnt);
4756       z_sr(Rix, Z_R0);
4757     }
4758     z_sra(Rix, log_min_cnt);             // unrolled loop count
4759     z_brz(UnrolledDone);
4760 
4761     bind(UnrolledLoop);
4762       z_lmg(Z_R0, Z_R1, 0, Rsrc);
4763       if (precise) {
4764         z_ogr(Z_R1, Z_R0);                 // check all 8 chars for incompatibility
4765         z_ngr(Z_R1, Rmask);
4766         z_brnz(UnrolledBreak);
4767 
4768         z_lg(Z_R1, 8, Rsrc);               // reload destroyed register
4769         z_stcmh(Z_R0, 5, 0, Rdst);
4770         z_stcm(Z_R0,  5, 2, Rdst);
4771       } else {
4772         z_stcmh(Z_R0, 5, 0, Rdst);
4773         z_stcm(Z_R0,  5, 2, Rdst);
4774 
4775         z_ogr(Z_R0, Z_R1);
4776         z_ngr(Z_R0, Rmask);
4777         z_brnz(UnrolledBreak);
4778       }
4779       z_stcmh(Z_R1, 5, 4, Rdst);
4780       z_stcm(Z_R1,  5, 6, Rdst);
4781 
4782       add2reg(Rsrc, min_cnt*2);
4783       add2reg(Rdst, min_cnt);
4784       z_brct(Rix, UnrolledLoop);
4785 
4786     z_lgfr(Z_R0, Rcnt);                    // # chars processed in total after unrolled loop.
4787     z_nilf(Z_R0, ~(min_cnt-1));
4788     z_tmll(Rcnt, min_cnt-1);
4789     z_brnaz(ScalarShortcut);               // if all bits zero, there is nothing left to do for scalar loop.
4790                                            // Rix == 0 in all cases.
4791     z_sllg(Z_R1, Rcnt, 1);                 // # src bytes already processed. Only lower 32 bits are valid!
4792                                            //   Z_R1 contents must be treated as unsigned operand! For huge strings,
4793                                            //   (Rcnt >= 2**30), the value may spill into the sign bit by sllg.
4794     z_lgfr(result, Rcnt);                  // all characters processed.
4795     z_slgfr(Rdst, Rcnt);                   // restore ptr
4796     z_slgfr(Rsrc, Z_R1);                   // restore ptr, double the element count for Rsrc restore
4797     z_bru(AllDone);
4798 
4799     bind(UnrolledBreak);
4800     z_lgfr(Z_R0, Rcnt);                    // # chars processed in total after unrolled loop
4801     z_nilf(Z_R0, ~(min_cnt-1));
4802     z_sll(Rix, log_min_cnt);               // # chars not yet processed in UnrolledLoop (due to break), broken iteration not included.
4803     z_sr(Z_R0, Rix);                       // fix # chars processed OK so far.
4804     if (!precise) {
4805       z_lgfr(result, Z_R0);
4806       z_sllg(Z_R1, Z_R0, 1);               // # src bytes already processed. Only lower 32 bits are valid!
4807                                            //   Z_R1 contents must be treated as unsigned operand! For huge strings,
4808                                            //   (Rcnt >= 2**30), the value may spill into the sign bit by sllg.
4809       z_aghi(result, min_cnt/2);           // min_cnt/2 characters have already been written
4810                                            // but ptrs were not updated yet.
4811       z_slgfr(Rdst, Z_R0);                 // restore ptr
4812       z_slgfr(Rsrc, Z_R1);                 // restore ptr, double the element count for Rsrc restore
4813       z_bru(AllDone);
4814     }
4815     bind(UnrolledDone);
4816   }
4817 
4818   {
4819     Label     ScalarLoop, ScalarDone, ScalarBreak;
4820 
4821     bind(ScalarShortcut);
4822     z_ltgfr(result, Rcnt);
4823     z_brz(AllDone);
4824 
4825 #if 0  // Sacrifice shortcuts for code compactness
4826     {
4827       //---<  Special treatment for very short strings (one or two characters)  >---
4828       //   For these strings, we are sure that the above code was skipped.
4829       //   Thus, no registers were modified, register restore is not required.
4830       Label     ScalarDoit, Scalar2Char;
4831       z_chi(Rcnt, 2);
4832       z_brh(ScalarDoit);
4833       z_llh(Z_R1,  0, Z_R0, Rsrc);
4834       z_bre(Scalar2Char);
4835       z_tmll(Z_R1, 0xff00);
4836       z_lghi(result, 0);                   // cnt == 1, first char invalid, no chars successfully processed
4837       z_brnaz(AllDone);
4838       z_stc(Z_R1,  0, Z_R0, Rdst);
4839       z_lghi(result, 1);
4840       z_bru(AllDone);
4841 
4842       bind(Scalar2Char);
4843       z_llh(Z_R0,  2, Z_R0, Rsrc);
4844       z_tmll(Z_R1, 0xff00);
4845       z_lghi(result, 0);                   // cnt == 2, first char invalid, no chars successfully processed
4846       z_brnaz(AllDone);
4847       z_stc(Z_R1,  0, Z_R0, Rdst);
4848       z_tmll(Z_R0, 0xff00);
4849       z_lghi(result, 1);                   // cnt == 2, second char invalid, one char successfully processed
4850       z_brnaz(AllDone);
4851       z_stc(Z_R0,  1, Z_R0, Rdst);
4852       z_lghi(result, 2);
4853       z_bru(AllDone);
4854 
4855       bind(ScalarDoit);
4856     }
4857 #endif
4858 
4859     if (VM_Version::has_DistinctOpnds()) {
4860       z_srk(Rix, Rcnt, Z_R0);              // remaining # chars to compress in unrolled loop
4861     } else {
4862       z_lr(Rix, Rcnt);
4863       z_sr(Rix, Z_R0);
4864     }
4865     z_lgfr(result, Rcnt);                  // # processed characters (if all runs ok).
4866     z_brz(ScalarDone);                     // uses CC from Rix calculation
4867 
4868     bind(ScalarLoop);
4869       z_llh(Z_R1, 0, Z_R0, Rsrc);
4870       z_tmll(Z_R1, 0xff00);
4871       z_brnaz(ScalarBreak);
4872       z_stc(Z_R1, 0, Z_R0, Rdst);
4873       add2reg(Rsrc, 2);
4874       add2reg(Rdst, 1);
4875       z_brct(Rix, ScalarLoop);
4876 
4877     z_bru(ScalarDone);
4878 
4879     bind(ScalarBreak);
4880     z_sr(result, Rix);
4881 
4882     bind(ScalarDone);
4883     z_sgfr(Rdst, result);                  // restore ptr
4884     z_sgfr(Rsrc, result);                  // restore ptr, double the element count for Rsrc restore
4885     z_sgfr(Rsrc, result);
4886   }
4887   bind(AllDone);
4888 
4889   if (precise) {
4890     BLOCK_COMMENT("} encode_iso_array");
4891   } else {
4892     BLOCK_COMMENT("} string_compress");
4893   }
4894   return offset() - block_start;
4895 }
4896 
4897 // Inflate byte[] to char[].
4898 unsigned int MacroAssembler::string_inflate_trot(Register src, Register dst, Register cnt, Register tmp) {
4899   int block_start = offset();
4900 
4901   BLOCK_COMMENT("string_inflate {");
4902 
4903   Register stop_char = Z_R0;
4904   Register table     = Z_R1;
4905   Register src_addr  = tmp;
4906 
4907   assert_different_registers(Z_R0, Z_R1, tmp, src, dst, cnt);
4908   assert(dst->encoding()%2 == 0, "must be even reg");
4909   assert(cnt->encoding()%2 == 1, "must be odd reg");
4910   assert(cnt->encoding() - dst->encoding() == 1, "must be even/odd pair");
4911 
4912   StubRoutines::zarch::generate_load_trot_table_addr(this, table);  // kills Z_R0 (if ASSERT)
4913   clear_reg(stop_char);  // Stop character. Not used here, but initialized to have a defined value.
4914   lgr_if_needed(src_addr, src);
4915   z_llgfr(cnt, cnt);     // # src characters, must be a positive simm32.
4916 
4917   translate_ot(dst, src_addr, /* mask = */ 0x0001);
4918 
4919   BLOCK_COMMENT("} string_inflate");
4920 
4921   return offset() - block_start;
4922 }
4923 
4924 // Inflate byte[] to char[].
4925 //   Restores: src, dst
4926 //   Uses:     cnt
4927 //   Kills:    tmp, Z_R0, Z_R1.
4928 // Note:
4929 //   cnt is signed int. Do not rely on high word!
4930 //       counts # characters, not bytes.
4931 unsigned int MacroAssembler::string_inflate(Register src, Register dst, Register cnt, Register tmp) {
4932   assert_different_registers(Z_R0, Z_R1, src, dst, cnt, tmp);
4933 
4934   BLOCK_COMMENT("string_inflate {");
4935   int block_start = offset();
4936 
4937   Register   Rcnt = cnt;   // # characters (src: bytes, dst: char (2-byte)), remaining after current loop.
4938   Register   Rix  = tmp;   // loop index
4939   Register   Rsrc = src;   // addr(src array)
4940   Register   Rdst = dst;   // addr(dst array)
4941   Label      ScalarShortcut, AllDone;
4942 
4943 #if 0  // Sacrifice shortcuts for code compactness
4944   {
4945     //---<  shortcuts for short strings (very frequent)   >---
4946     Label   skipShortcut, skip4Shortcut;
4947     z_ltr(Rcnt, Rcnt);                     // absolutely nothing to do for strings of len == 0.
4948     z_brz(AllDone);
4949     clear_reg(Z_R0);                       // make sure registers are properly initialized.
4950     clear_reg(Z_R1);
4951     z_chi(Rcnt, 4);
4952     z_brne(skip4Shortcut);                 // 4 characters are very frequent
4953       z_icm(Z_R0, 5,    0, Rsrc);          // Treat exactly 4 characters specially.
4954       z_icm(Z_R1, 5,    2, Rsrc);
4955       z_stm(Z_R0, Z_R1, 0, Rdst);
4956       z_bru(AllDone);
4957     bind(skip4Shortcut);
4958 
4959     z_chi(Rcnt, 8);
4960     z_brh(skipShortcut);                   // There's a lot to do...
4961     z_lgfr(Z_R0, Rcnt);                    // remaining #characters (<= 8). Precond for scalar loop.
4962                                            // This does not destroy the "register cleared" state of Z_R0.
4963     z_brl(ScalarShortcut);                 // Just a few characters
4964       z_icmh(Z_R0, 5, 0, Rsrc);            // Treat exactly 8 characters specially.
4965       z_icmh(Z_R1, 5, 4, Rsrc);
4966       z_icm(Z_R0,  5, 2, Rsrc);
4967       z_icm(Z_R1,  5, 6, Rsrc);
4968       z_stmg(Z_R0, Z_R1, 0, Rdst);
4969       z_bru(AllDone);
4970     bind(skipShortcut);
4971   }
4972 #endif
4973   clear_reg(Z_R0);                         // make sure register is properly initialized.
4974 
4975   if (VM_Version::has_VectorFacility()) {
4976     const int  min_vcnt     = 32;          // Minimum #characters required to use vector instructions.
4977                                            // Otherwise just do nothing in vector mode.
4978                                            // Must be multiple of vector register length (16 bytes = 128 bits).
4979     const int  log_min_vcnt = exact_log2(min_vcnt);
4980     Label      VectorLoop, VectorDone;
4981 
4982     assert(VM_Version::has_DistinctOpnds(), "Assumption when has_VectorFacility()");
4983     z_srak(Rix, Rcnt, log_min_vcnt);       // calculate # vector loop iterations
4984     z_brz(VectorDone);                     // skip if none
4985 
4986     z_sllg(Z_R0, Rix, log_min_vcnt);       // remember #chars that will be processed by vector loop
4987 
4988     bind(VectorLoop);
4989       z_vlm(Z_V20, Z_V21, 0, Rsrc);        // get next 32 characters (single-byte)
4990       add2reg(Rsrc, min_vcnt);
4991 
4992       z_vuplhb(Z_V22, Z_V20);              // V2 <- (expand) V0(high)
4993       z_vupllb(Z_V23, Z_V20);              // V3 <- (expand) V0(low)
4994       z_vuplhb(Z_V24, Z_V21);              // V4 <- (expand) V1(high)
4995       z_vupllb(Z_V25, Z_V21);              // V5 <- (expand) V1(low)
4996       z_vstm(Z_V22, Z_V25, 0, Rdst);       // store next 32 bytes
4997       add2reg(Rdst, min_vcnt*2);
4998 
4999       z_brct(Rix, VectorLoop);
5000 
5001     bind(VectorDone);
5002   }
5003 
5004   const int  min_cnt     =  8;             // Minimum #characters required to use unrolled scalar loop.
5005                                            // Otherwise just do nothing in unrolled scalar mode.
5006                                            // Must be multiple of 8.
5007   {
5008     const int  log_min_cnt = exact_log2(min_cnt);
5009     Label      UnrolledLoop, UnrolledDone;
5010 
5011 
5012     if (VM_Version::has_DistinctOpnds()) {
5013       z_srk(Rix, Rcnt, Z_R0);              // remaining # chars to process in unrolled loop
5014     } else {
5015       z_lr(Rix, Rcnt);
5016       z_sr(Rix, Z_R0);
5017     }
5018     z_sra(Rix, log_min_cnt);               // unrolled loop count
5019     z_brz(UnrolledDone);
5020 
5021     clear_reg(Z_R0);
5022     clear_reg(Z_R1);
5023 
5024     bind(UnrolledLoop);
5025       z_icmh(Z_R0, 5, 0, Rsrc);
5026       z_icmh(Z_R1, 5, 4, Rsrc);
5027       z_icm(Z_R0,  5, 2, Rsrc);
5028       z_icm(Z_R1,  5, 6, Rsrc);
5029       add2reg(Rsrc, min_cnt);
5030 
5031       z_stmg(Z_R0, Z_R1, 0, Rdst);
5032 
5033       add2reg(Rdst, min_cnt*2);
5034       z_brct(Rix, UnrolledLoop);
5035 
5036     bind(UnrolledDone);
5037     z_lgfr(Z_R0, Rcnt);                    // # chars left over after unrolled loop.
5038     z_nilf(Z_R0, min_cnt-1);
5039     z_brnz(ScalarShortcut);                // if zero, there is nothing left to do for scalar loop.
5040                                            // Rix == 0 in all cases.
5041     z_sgfr(Z_R0, Rcnt);                    // negative # characters the ptrs have been advanced previously.
5042     z_agr(Rdst, Z_R0);                     // restore ptr, double the element count for Rdst restore.
5043     z_agr(Rdst, Z_R0);
5044     z_agr(Rsrc, Z_R0);                     // restore ptr.
5045     z_bru(AllDone);
5046   }
5047 
5048   {
5049     bind(ScalarShortcut);
5050     // Z_R0 must contain remaining # characters as 64-bit signed int here.
5051     //      register contents is preserved over scalar processing (for register fixup).
5052 
5053 #if 0  // Sacrifice shortcuts for code compactness
5054     {
5055       Label      ScalarDefault;
5056       z_chi(Rcnt, 2);
5057       z_brh(ScalarDefault);
5058       z_llc(Z_R0,  0, Z_R0, Rsrc);     // 6 bytes
5059       z_sth(Z_R0,  0, Z_R0, Rdst);     // 4 bytes
5060       z_brl(AllDone);
5061       z_llc(Z_R0,  1, Z_R0, Rsrc);     // 6 bytes
5062       z_sth(Z_R0,  2, Z_R0, Rdst);     // 4 bytes
5063       z_bru(AllDone);
5064       bind(ScalarDefault);
5065     }
5066 #endif
5067 
5068     Label   CodeTable;
5069     // Some comments on Rix calculation:
5070     //  - Rcnt is small, therefore no bits shifted out of low word (sll(g) instructions).
5071     //  - high word of both Rix and Rcnt may contain garbage
5072     //  - the final lngfr takes care of that garbage, extending the sign to high word
5073     z_sllg(Rix, Z_R0, 2);                // calculate 10*Rix = (4*Rix + Rix)*2
5074     z_ar(Rix, Z_R0);
5075     z_larl(Z_R1, CodeTable);
5076     z_sll(Rix, 1);
5077     z_lngfr(Rix, Rix);      // ix range: [0..7], after inversion & mult: [-(7*12)..(0*12)].
5078     z_bc(Assembler::bcondAlways, 0, Rix, Z_R1);
5079 
5080     z_llc(Z_R1,  6, Z_R0, Rsrc);  // 6 bytes
5081     z_sth(Z_R1, 12, Z_R0, Rdst);  // 4 bytes
5082 
5083     z_llc(Z_R1,  5, Z_R0, Rsrc);
5084     z_sth(Z_R1, 10, Z_R0, Rdst);
5085 
5086     z_llc(Z_R1,  4, Z_R0, Rsrc);
5087     z_sth(Z_R1,  8, Z_R0, Rdst);
5088 
5089     z_llc(Z_R1,  3, Z_R0, Rsrc);
5090     z_sth(Z_R1,  6, Z_R0, Rdst);
5091 
5092     z_llc(Z_R1,  2, Z_R0, Rsrc);
5093     z_sth(Z_R1,  4, Z_R0, Rdst);
5094 
5095     z_llc(Z_R1,  1, Z_R0, Rsrc);
5096     z_sth(Z_R1,  2, Z_R0, Rdst);
5097 
5098     z_llc(Z_R1,  0, Z_R0, Rsrc);
5099     z_sth(Z_R1,  0, Z_R0, Rdst);
5100     bind(CodeTable);
5101 
5102     z_chi(Rcnt, 8);                        // no fixup for small strings. Rdst, Rsrc were not modified.
5103     z_brl(AllDone);
5104 
5105     z_sgfr(Z_R0, Rcnt);                    // # characters the ptrs have been advanced previously.
5106     z_agr(Rdst, Z_R0);                     // restore ptr, double the element count for Rdst restore.
5107     z_agr(Rdst, Z_R0);
5108     z_agr(Rsrc, Z_R0);                     // restore ptr.
5109   }
5110   bind(AllDone);
5111 
5112   BLOCK_COMMENT("} string_inflate");
5113   return offset() - block_start;
5114 }
5115 
5116 // Inflate byte[] to char[], length known at compile time.
5117 //   Restores: src, dst
5118 //   Kills:    tmp, Z_R0, Z_R1.
5119 // Note:
5120 //   len is signed int. Counts # characters, not bytes.
5121 unsigned int MacroAssembler::string_inflate_const(Register src, Register dst, Register tmp, int len) {
5122   assert_different_registers(Z_R0, Z_R1, src, dst, tmp);
5123 
5124   BLOCK_COMMENT("string_inflate_const {");
5125   int block_start = offset();
5126 
5127   Register   Rix  = tmp;   // loop index
5128   Register   Rsrc = src;   // addr(src array)
5129   Register   Rdst = dst;   // addr(dst array)
5130   Label      ScalarShortcut, AllDone;
5131   int        nprocessed = 0;
5132   int        src_off    = 0;  // compensate for saved (optimized away) ptr advancement.
5133   int        dst_off    = 0;  // compensate for saved (optimized away) ptr advancement.
5134   bool       restore_inputs = false;
5135   bool       workreg_clear  = false;
5136 
5137   if ((len >= 32) && VM_Version::has_VectorFacility()) {
5138     const int  min_vcnt     = 32;          // Minimum #characters required to use vector instructions.
5139                                            // Otherwise just do nothing in vector mode.
5140                                            // Must be multiple of vector register length (16 bytes = 128 bits).
5141     const int  log_min_vcnt = exact_log2(min_vcnt);
5142     const int  iterations   = (len - nprocessed) >> log_min_vcnt;
5143     nprocessed             += iterations << log_min_vcnt;
5144     Label      VectorLoop;
5145 
5146     if (iterations == 1) {
5147       z_vlm(Z_V20, Z_V21, 0+src_off, Rsrc);  // get next 32 characters (single-byte)
5148       z_vuplhb(Z_V22, Z_V20);                // V2 <- (expand) V0(high)
5149       z_vupllb(Z_V23, Z_V20);                // V3 <- (expand) V0(low)
5150       z_vuplhb(Z_V24, Z_V21);                // V4 <- (expand) V1(high)
5151       z_vupllb(Z_V25, Z_V21);                // V5 <- (expand) V1(low)
5152       z_vstm(Z_V22, Z_V25, 0+dst_off, Rdst); // store next 32 bytes
5153 
5154       src_off += min_vcnt;
5155       dst_off += min_vcnt*2;
5156     } else {
5157       restore_inputs = true;
5158 
5159       z_lgfi(Rix, len>>log_min_vcnt);
5160       bind(VectorLoop);
5161         z_vlm(Z_V20, Z_V21, 0, Rsrc);        // get next 32 characters (single-byte)
5162         add2reg(Rsrc, min_vcnt);
5163 
5164         z_vuplhb(Z_V22, Z_V20);              // V2 <- (expand) V0(high)
5165         z_vupllb(Z_V23, Z_V20);              // V3 <- (expand) V0(low)
5166         z_vuplhb(Z_V24, Z_V21);              // V4 <- (expand) V1(high)
5167         z_vupllb(Z_V25, Z_V21);              // V5 <- (expand) V1(low)
5168         z_vstm(Z_V22, Z_V25, 0, Rdst);       // store next 32 bytes
5169         add2reg(Rdst, min_vcnt*2);
5170 
5171         z_brct(Rix, VectorLoop);
5172     }
5173   }
5174 
5175   if (((len-nprocessed) >= 16) && VM_Version::has_VectorFacility()) {
5176     const int  min_vcnt     = 16;          // Minimum #characters required to use vector instructions.
5177                                            // Otherwise just do nothing in vector mode.
5178                                            // Must be multiple of vector register length (16 bytes = 128 bits).
5179     const int  log_min_vcnt = exact_log2(min_vcnt);
5180     const int  iterations   = (len - nprocessed) >> log_min_vcnt;
5181     nprocessed             += iterations << log_min_vcnt;
5182     assert(iterations == 1, "must be!");
5183 
5184     z_vl(Z_V20, 0+src_off, Z_R0, Rsrc);    // get next 16 characters (single-byte)
5185     z_vuplhb(Z_V22, Z_V20);                // V2 <- (expand) V0(high)
5186     z_vupllb(Z_V23, Z_V20);                // V3 <- (expand) V0(low)
5187     z_vstm(Z_V22, Z_V23, 0+dst_off, Rdst); // store next 32 bytes
5188 
5189     src_off += min_vcnt;
5190     dst_off += min_vcnt*2;
5191   }
5192 
5193   if ((len-nprocessed) > 8) {
5194     const int  min_cnt     =  8;           // Minimum #characters required to use unrolled scalar loop.
5195                                            // Otherwise just do nothing in unrolled scalar mode.
5196                                            // Must be multiple of 8.
5197     const int  log_min_cnt = exact_log2(min_cnt);
5198     const int  iterations  = (len - nprocessed) >> log_min_cnt;
5199     nprocessed     += iterations << log_min_cnt;
5200 
5201     //---<  avoid loop overhead/ptr increment for small # iterations  >---
5202     if (iterations <= 2) {
5203       clear_reg(Z_R0);
5204       clear_reg(Z_R1);
5205       workreg_clear = true;
5206 
5207       z_icmh(Z_R0, 5, 0+src_off, Rsrc);
5208       z_icmh(Z_R1, 5, 4+src_off, Rsrc);
5209       z_icm(Z_R0,  5, 2+src_off, Rsrc);
5210       z_icm(Z_R1,  5, 6+src_off, Rsrc);
5211       z_stmg(Z_R0, Z_R1, 0+dst_off, Rdst);
5212 
5213       src_off += min_cnt;
5214       dst_off += min_cnt*2;
5215     }
5216 
5217     if (iterations == 2) {
5218       z_icmh(Z_R0, 5, 0+src_off, Rsrc);
5219       z_icmh(Z_R1, 5, 4+src_off, Rsrc);
5220       z_icm(Z_R0,  5, 2+src_off, Rsrc);
5221       z_icm(Z_R1,  5, 6+src_off, Rsrc);
5222       z_stmg(Z_R0, Z_R1, 0+dst_off, Rdst);
5223 
5224       src_off += min_cnt;
5225       dst_off += min_cnt*2;
5226     }
5227 
5228     if (iterations > 2) {
5229       Label      UnrolledLoop;
5230       restore_inputs  = true;
5231 
5232       clear_reg(Z_R0);
5233       clear_reg(Z_R1);
5234       workreg_clear = true;
5235 
5236       z_lgfi(Rix, iterations);
5237       bind(UnrolledLoop);
5238         z_icmh(Z_R0, 5, 0, Rsrc);
5239         z_icmh(Z_R1, 5, 4, Rsrc);
5240         z_icm(Z_R0,  5, 2, Rsrc);
5241         z_icm(Z_R1,  5, 6, Rsrc);
5242         add2reg(Rsrc, min_cnt);
5243 
5244         z_stmg(Z_R0, Z_R1, 0, Rdst);
5245         add2reg(Rdst, min_cnt*2);
5246 
5247         z_brct(Rix, UnrolledLoop);
5248     }
5249   }
5250 
5251   if ((len-nprocessed) > 0) {
5252     switch (len-nprocessed) {
5253       case 8:
5254         if (!workreg_clear) {
5255           clear_reg(Z_R0);
5256           clear_reg(Z_R1);
5257         }
5258         z_icmh(Z_R0, 5, 0+src_off, Rsrc);
5259         z_icmh(Z_R1, 5, 4+src_off, Rsrc);
5260         z_icm(Z_R0,  5, 2+src_off, Rsrc);
5261         z_icm(Z_R1,  5, 6+src_off, Rsrc);
5262         z_stmg(Z_R0, Z_R1, 0+dst_off, Rdst);
5263         break;
5264       case 7:
5265         if (!workreg_clear) {
5266           clear_reg(Z_R0);
5267           clear_reg(Z_R1);
5268         }
5269         clear_reg(Rix);
5270         z_icm(Z_R0,  5, 0+src_off, Rsrc);
5271         z_icm(Z_R1,  5, 2+src_off, Rsrc);
5272         z_icm(Rix,   5, 4+src_off, Rsrc);
5273         z_stm(Z_R0,  Z_R1, 0+dst_off, Rdst);
5274         z_llc(Z_R0,  6+src_off, Z_R0, Rsrc);
5275         z_st(Rix,    8+dst_off, Z_R0, Rdst);
5276         z_sth(Z_R0, 12+dst_off, Z_R0, Rdst);
5277         break;
5278       case 6:
5279         if (!workreg_clear) {
5280           clear_reg(Z_R0);
5281           clear_reg(Z_R1);
5282         }
5283         clear_reg(Rix);
5284         z_icm(Z_R0, 5, 0+src_off, Rsrc);
5285         z_icm(Z_R1, 5, 2+src_off, Rsrc);
5286         z_icm(Rix,  5, 4+src_off, Rsrc);
5287         z_stm(Z_R0, Z_R1, 0+dst_off, Rdst);
5288         z_st(Rix,   8+dst_off, Z_R0, Rdst);
5289         break;
5290       case 5:
5291         if (!workreg_clear) {
5292           clear_reg(Z_R0);
5293           clear_reg(Z_R1);
5294         }
5295         z_icm(Z_R0, 5, 0+src_off, Rsrc);
5296         z_icm(Z_R1, 5, 2+src_off, Rsrc);
5297         z_llc(Rix,  4+src_off, Z_R0, Rsrc);
5298         z_stm(Z_R0, Z_R1, 0+dst_off, Rdst);
5299         z_sth(Rix,  8+dst_off, Z_R0, Rdst);
5300         break;
5301       case 4:
5302         if (!workreg_clear) {
5303           clear_reg(Z_R0);
5304           clear_reg(Z_R1);
5305         }
5306         z_icm(Z_R0, 5, 0+src_off, Rsrc);
5307         z_icm(Z_R1, 5, 2+src_off, Rsrc);
5308         z_stm(Z_R0, Z_R1, 0+dst_off, Rdst);
5309         break;
5310       case 3:
5311         if (!workreg_clear) {
5312           clear_reg(Z_R0);
5313         }
5314         z_llc(Z_R1, 2+src_off, Z_R0, Rsrc);
5315         z_icm(Z_R0, 5, 0+src_off, Rsrc);
5316         z_sth(Z_R1, 4+dst_off, Z_R0, Rdst);
5317         z_st(Z_R0,  0+dst_off, Rdst);
5318         break;
5319       case 2:
5320         z_llc(Z_R0, 0+src_off, Z_R0, Rsrc);
5321         z_llc(Z_R1, 1+src_off, Z_R0, Rsrc);
5322         z_sth(Z_R0, 0+dst_off, Z_R0, Rdst);
5323         z_sth(Z_R1, 2+dst_off, Z_R0, Rdst);
5324         break;
5325       case 1:
5326         z_llc(Z_R0, 0+src_off, Z_R0, Rsrc);
5327         z_sth(Z_R0, 0+dst_off, Z_R0, Rdst);
5328         break;
5329       default:
5330         guarantee(false, "Impossible");
5331         break;
5332     }
5333     src_off   +=  len-nprocessed;
5334     dst_off   += (len-nprocessed)*2;
5335     nprocessed = len;
5336   }
5337 
5338   //---< restore modified input registers  >---
5339   if ((nprocessed > 0) && restore_inputs) {
5340     z_agfi(Rsrc, -(nprocessed-src_off));
5341     if (nprocessed < 1000000000) { // avoid int overflow
5342       z_agfi(Rdst, -(nprocessed*2-dst_off));
5343     } else {
5344       z_agfi(Rdst, -(nprocessed-dst_off));
5345       z_agfi(Rdst, -nprocessed);
5346     }
5347   }
5348 
5349   BLOCK_COMMENT("} string_inflate_const");
5350   return offset() - block_start;
5351 }
5352 
5353 // Kills src.
5354 unsigned int MacroAssembler::has_negatives(Register result, Register src, Register cnt,
5355                                            Register odd_reg, Register even_reg, Register tmp) {
5356   int block_start = offset();
5357   Label Lloop1, Lloop2, Lslow, Lnotfound, Ldone;
5358   const Register addr = src, mask = tmp;
5359 
5360   BLOCK_COMMENT("has_negatives {");
5361 
5362   z_llgfr(Z_R1, cnt);      // Number of bytes to read. (Must be a positive simm32.)
5363   z_llilf(mask, 0x80808080);
5364   z_lhi(result, 1);        // Assume true.
5365   // Last possible addr for fast loop.
5366   z_lay(odd_reg, -16, Z_R1, src);
5367   z_chi(cnt, 16);
5368   z_brl(Lslow);
5369 
5370   // ind1: index, even_reg: index increment, odd_reg: index limit
5371   z_iihf(mask, 0x80808080);
5372   z_lghi(even_reg, 16);
5373 
5374   bind(Lloop1); // 16 bytes per iteration.
5375   z_lg(Z_R0, Address(addr));
5376   z_lg(Z_R1, Address(addr, 8));
5377   z_ogr(Z_R0, Z_R1);
5378   z_ngr(Z_R0, mask);
5379   z_brne(Ldone);           // If found return 1.
5380   z_brxlg(addr, even_reg, Lloop1);
5381 
5382   bind(Lslow);
5383   z_aghi(odd_reg, 16-1);   // Last possible addr for slow loop.
5384   z_lghi(even_reg, 1);
5385   z_cgr(addr, odd_reg);
5386   z_brh(Lnotfound);
5387 
5388   bind(Lloop2); // 1 byte per iteration.
5389   z_cli(Address(addr), 0x80);
5390   z_brnl(Ldone);           // If found return 1.
5391   z_brxlg(addr, even_reg, Lloop2);
5392 
5393   bind(Lnotfound);
5394   z_lhi(result, 0);
5395 
5396   bind(Ldone);
5397 
5398   BLOCK_COMMENT("} has_negatives");
5399 
5400   return offset() - block_start;
5401 }
5402 
5403 // kill: cnt1, cnt2, odd_reg, even_reg; early clobber: result
5404 unsigned int MacroAssembler::string_compare(Register str1, Register str2,
5405                                             Register cnt1, Register cnt2,
5406                                             Register odd_reg, Register even_reg, Register result, int ae) {
5407   int block_start = offset();
5408 
5409   assert_different_registers(str1, cnt1, cnt2, odd_reg, even_reg, result);
5410   assert_different_registers(str2, cnt1, cnt2, odd_reg, even_reg, result);
5411 
5412   // If strings are equal up to min length, return the length difference.
5413   const Register diff = result, // Pre-set result with length difference.
5414                  min  = cnt1,   // min number of bytes
5415                  tmp  = cnt2;
5416 
5417   // Note: Making use of the fact that compareTo(a, b) == -compareTo(b, a)
5418   // we interchange str1 and str2 in the UL case and negate the result.
5419   // Like this, str1 is always latin1 encoded, except for the UU case.
5420   // In addition, we need 0 (or sign which is 0) extend when using 64 bit register.
5421   const bool used_as_LU = (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL);
5422 
5423   BLOCK_COMMENT("string_compare {");
5424 
5425   if (used_as_LU) {
5426     z_srl(cnt2, 1);
5427   }
5428 
5429   // See if the lengths are different, and calculate min in cnt1.
5430   // Save diff in case we need it for a tie-breaker.
5431 
5432   // diff = cnt1 - cnt2
5433   if (VM_Version::has_DistinctOpnds()) {
5434     z_srk(diff, cnt1, cnt2);
5435   } else {
5436     z_lr(diff, cnt1);
5437     z_sr(diff, cnt2);
5438   }
5439   if (str1 != str2) {
5440     if (VM_Version::has_LoadStoreConditional()) {
5441       z_locr(min, cnt2, Assembler::bcondHigh);
5442     } else {
5443       Label Lskip;
5444       z_brl(Lskip);    // min ok if cnt1 < cnt2
5445       z_lr(min, cnt2); // min = cnt2
5446       bind(Lskip);
5447     }
5448   }
5449 
5450   if (ae == StrIntrinsicNode::UU) {
5451     z_sra(diff, 1);
5452   }
5453   if (str1 != str2) {
5454     Label Ldone;
5455     if (used_as_LU) {
5456       // Loop which searches the first difference character by character.
5457       Label Lloop;
5458       const Register ind1 = Z_R1,
5459                      ind2 = min;
5460       int stride1 = 1, stride2 = 2; // See comment above.
5461 
5462       // ind1: index, even_reg: index increment, odd_reg: index limit
5463       z_llilf(ind1, (unsigned int)(-stride1));
5464       z_lhi(even_reg, stride1);
5465       add2reg(odd_reg, -stride1, min);
5466       clear_reg(ind2); // kills min
5467 
5468       bind(Lloop);
5469       z_brxh(ind1, even_reg, Ldone);
5470       z_llc(tmp, Address(str1, ind1));
5471       z_llh(Z_R0, Address(str2, ind2));
5472       z_ahi(ind2, stride2);
5473       z_sr(tmp, Z_R0);
5474       z_bre(Lloop);
5475 
5476       z_lr(result, tmp);
5477 
5478     } else {
5479       // Use clcle in fast loop (only for same encoding).
5480       z_lgr(Z_R0, str1);
5481       z_lgr(even_reg, str2);
5482       z_llgfr(Z_R1, min);
5483       z_llgfr(odd_reg, min);
5484 
5485       if (ae == StrIntrinsicNode::LL) {
5486         compare_long_ext(Z_R0, even_reg, 0);
5487       } else {
5488         compare_long_uni(Z_R0, even_reg, 0);
5489       }
5490       z_bre(Ldone);
5491       z_lgr(Z_R1, Z_R0);
5492       if (ae == StrIntrinsicNode::LL) {
5493         z_llc(Z_R0, Address(even_reg));
5494         z_llc(result, Address(Z_R1));
5495       } else {
5496         z_llh(Z_R0, Address(even_reg));
5497         z_llh(result, Address(Z_R1));
5498       }
5499       z_sr(result, Z_R0);
5500     }
5501 
5502     // Otherwise, return the difference between the first mismatched chars.
5503     bind(Ldone);
5504   }
5505 
5506   if (ae == StrIntrinsicNode::UL) {
5507     z_lcr(result, result); // Negate result (see note above).
5508   }
5509 
5510   BLOCK_COMMENT("} string_compare");
5511 
5512   return offset() - block_start;
5513 }
5514 
5515 unsigned int MacroAssembler::array_equals(bool is_array_equ, Register ary1, Register ary2, Register limit,
5516                                           Register odd_reg, Register even_reg, Register result, bool is_byte) {
5517   int block_start = offset();
5518 
5519   BLOCK_COMMENT("array_equals {");
5520 
5521   assert_different_registers(ary1, limit, odd_reg, even_reg);
5522   assert_different_registers(ary2, limit, odd_reg, even_reg);
5523 
5524   Label Ldone, Ldone_true, Ldone_false, Lclcle, CLC_template;
5525   int base_offset = 0;
5526 
5527   if (ary1 != ary2) {
5528     if (is_array_equ) {
5529       base_offset = arrayOopDesc::base_offset_in_bytes(is_byte ? T_BYTE : T_CHAR);
5530 
5531       // Return true if the same array.
5532       compareU64_and_branch(ary1, ary2, Assembler::bcondEqual, Ldone_true);
5533 
5534       // Return false if one of them is NULL.
5535       compareU64_and_branch(ary1, (intptr_t)0, Assembler::bcondEqual, Ldone_false);
5536       compareU64_and_branch(ary2, (intptr_t)0, Assembler::bcondEqual, Ldone_false);
5537 
5538       // Load the lengths of arrays.
5539       z_llgf(odd_reg, Address(ary1, arrayOopDesc::length_offset_in_bytes()));
5540 
5541       // Return false if the two arrays are not equal length.
5542       z_c(odd_reg, Address(ary2, arrayOopDesc::length_offset_in_bytes()));
5543       z_brne(Ldone_false);
5544 
5545       // string len in bytes (right operand)
5546       if (!is_byte) {
5547         z_chi(odd_reg, 128);
5548         z_sll(odd_reg, 1); // preserves flags
5549         z_brh(Lclcle);
5550       } else {
5551         compareU32_and_branch(odd_reg, (intptr_t)256, Assembler::bcondHigh, Lclcle);
5552       }
5553     } else {
5554       z_llgfr(odd_reg, limit); // Need to zero-extend prior to using the value.
5555       compareU32_and_branch(limit, (intptr_t)256, Assembler::bcondHigh, Lclcle);
5556     }
5557 
5558 
5559     // Use clc instruction for up to 256 bytes.
5560     {
5561       Register str1_reg = ary1,
5562           str2_reg = ary2;
5563       if (is_array_equ) {
5564         str1_reg = Z_R1;
5565         str2_reg = even_reg;
5566         add2reg(str1_reg, base_offset, ary1); // string addr (left operand)
5567         add2reg(str2_reg, base_offset, ary2); // string addr (right operand)
5568       }
5569       z_ahi(odd_reg, -1); // Clc uses decremented limit. Also compare result to 0.
5570       z_brl(Ldone_true);
5571       // Note: We could jump to the template if equal.
5572 
5573       assert(VM_Version::has_ExecuteExtensions(), "unsupported hardware");
5574       z_exrl(odd_reg, CLC_template);
5575       z_bre(Ldone_true);
5576       // fall through
5577 
5578       bind(Ldone_false);
5579       clear_reg(result);
5580       z_bru(Ldone);
5581 
5582       bind(CLC_template);
5583       z_clc(0, 0, str1_reg, 0, str2_reg);
5584     }
5585 
5586     // Use clcle instruction.
5587     {
5588       bind(Lclcle);
5589       add2reg(even_reg, base_offset, ary2); // string addr (right operand)
5590       add2reg(Z_R0, base_offset, ary1);     // string addr (left operand)
5591 
5592       z_lgr(Z_R1, odd_reg); // string len in bytes (left operand)
5593       if (is_byte) {
5594         compare_long_ext(Z_R0, even_reg, 0);
5595       } else {
5596         compare_long_uni(Z_R0, even_reg, 0);
5597       }
5598       z_lghi(result, 0); // Preserve flags.
5599       z_brne(Ldone);
5600     }
5601   }
5602   // fall through
5603 
5604   bind(Ldone_true);
5605   z_lghi(result, 1); // All characters are equal.
5606   bind(Ldone);
5607 
5608   BLOCK_COMMENT("} array_equals");
5609 
5610   return offset() - block_start;
5611 }
5612 
5613 // kill: haycnt, needlecnt, odd_reg, even_reg; early clobber: result
5614 unsigned int MacroAssembler::string_indexof(Register result, Register haystack, Register haycnt,
5615                                             Register needle, Register needlecnt, int needlecntval,
5616                                             Register odd_reg, Register even_reg, int ae) {
5617   int block_start = offset();
5618 
5619   // Ensure 0<needlecnt<=haycnt in ideal graph as prerequisite!
5620   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
5621   const int h_csize = (ae == StrIntrinsicNode::LL) ? 1 : 2;
5622   const int n_csize = (ae == StrIntrinsicNode::UU) ? 2 : 1;
5623   Label L_needle1, L_Found, L_NotFound;
5624 
5625   BLOCK_COMMENT("string_indexof {");
5626 
5627   if (needle == haystack) {
5628     z_lhi(result, 0);
5629   } else {
5630 
5631   // Load first character of needle (R0 used by search_string instructions).
5632   if (n_csize == 2) { z_llgh(Z_R0, Address(needle)); } else { z_llgc(Z_R0, Address(needle)); }
5633 
5634   // Compute last haystack addr to use if no match gets found.
5635   if (needlecnt != noreg) { // variable needlecnt
5636     z_ahi(needlecnt, -1); // Remaining characters after first one.
5637     z_sr(haycnt, needlecnt); // Compute index succeeding last element to compare.
5638     if (n_csize == 2) { z_sll(needlecnt, 1); } // In bytes.
5639   } else { // constant needlecnt
5640     assert((needlecntval & 0x7fff) == needlecntval, "must be positive simm16 immediate");
5641     // Compute index succeeding last element to compare.
5642     if (needlecntval != 1) { z_ahi(haycnt, 1 - needlecntval); }
5643   }
5644 
5645   z_llgfr(haycnt, haycnt); // Clear high half.
5646   z_lgr(result, haystack); // Final result will be computed from needle start pointer.
5647   if (h_csize == 2) { z_sll(haycnt, 1); } // Scale to number of bytes.
5648   z_agr(haycnt, haystack); // Point to address succeeding last element (haystack+scale*(haycnt-needlecnt+1)).
5649 
5650   if (h_csize != n_csize) {
5651     assert(ae == StrIntrinsicNode::UL, "Invalid encoding");
5652 
5653     if (needlecnt != noreg || needlecntval != 1) {
5654       if (needlecnt != noreg) {
5655         compare32_and_branch(needlecnt, (intptr_t)0, Assembler::bcondEqual, L_needle1);
5656       }
5657 
5658       // Main Loop: UL version (now we have at least 2 characters).
5659       Label L_OuterLoop, L_InnerLoop, L_Skip;
5660       bind(L_OuterLoop); // Search for 1st 2 characters.
5661       z_lgr(Z_R1, haycnt);
5662       MacroAssembler::search_string_uni(Z_R1, result);
5663       z_brc(Assembler::bcondNotFound, L_NotFound);
5664       z_lgr(result, Z_R1);
5665 
5666       z_lghi(Z_R1, n_csize);
5667       z_lghi(even_reg, h_csize);
5668       bind(L_InnerLoop);
5669       z_llgc(odd_reg, Address(needle, Z_R1));
5670       z_ch(odd_reg, Address(result, even_reg));
5671       z_brne(L_Skip);
5672       if (needlecnt != noreg) { z_cr(Z_R1, needlecnt); } else { z_chi(Z_R1, needlecntval - 1); }
5673       z_brnl(L_Found);
5674       z_aghi(Z_R1, n_csize);
5675       z_aghi(even_reg, h_csize);
5676       z_bru(L_InnerLoop);
5677 
5678       bind(L_Skip);
5679       z_aghi(result, h_csize); // This is the new address we want to use for comparing.
5680       z_bru(L_OuterLoop);
5681     }
5682 
5683   } else {
5684     const intptr_t needle_bytes = (n_csize == 2) ? ((needlecntval - 1) << 1) : (needlecntval - 1);
5685     Label L_clcle;
5686 
5687     if (needlecnt != noreg || (needlecntval != 1 && needle_bytes <= 256)) {
5688       if (needlecnt != noreg) {
5689         compare32_and_branch(needlecnt, 256, Assembler::bcondHigh, L_clcle);
5690         z_ahi(needlecnt, -1); // remaining bytes -1 (for CLC)
5691         z_brl(L_needle1);
5692       }
5693 
5694       // Main Loop: clc version (now we have at least 2 characters).
5695       Label L_OuterLoop, CLC_template;
5696       bind(L_OuterLoop); // Search for 1st 2 characters.
5697       z_lgr(Z_R1, haycnt);
5698       if (h_csize == 1) {
5699         MacroAssembler::search_string(Z_R1, result);
5700       } else {
5701         MacroAssembler::search_string_uni(Z_R1, result);
5702       }
5703       z_brc(Assembler::bcondNotFound, L_NotFound);
5704       z_lgr(result, Z_R1);
5705 
5706       if (needlecnt != noreg) {
5707         assert(VM_Version::has_ExecuteExtensions(), "unsupported hardware");
5708         z_exrl(needlecnt, CLC_template);
5709       } else {
5710         z_clc(h_csize, needle_bytes -1, Z_R1, n_csize, needle);
5711       }
5712       z_bre(L_Found);
5713       z_aghi(result, h_csize); // This is the new address we want to use for comparing.
5714       z_bru(L_OuterLoop);
5715 
5716       if (needlecnt != noreg) {
5717         bind(CLC_template);
5718         z_clc(h_csize, 0, Z_R1, n_csize, needle);
5719       }
5720     }
5721 
5722     if (needlecnt != noreg || needle_bytes > 256) {
5723       bind(L_clcle);
5724 
5725       // Main Loop: clcle version (now we have at least 256 bytes).
5726       Label L_OuterLoop, CLC_template;
5727       bind(L_OuterLoop); // Search for 1st 2 characters.
5728       z_lgr(Z_R1, haycnt);
5729       if (h_csize == 1) {
5730         MacroAssembler::search_string(Z_R1, result);
5731       } else {
5732         MacroAssembler::search_string_uni(Z_R1, result);
5733       }
5734       z_brc(Assembler::bcondNotFound, L_NotFound);
5735 
5736       add2reg(Z_R0, n_csize, needle);
5737       add2reg(even_reg, h_csize, Z_R1);
5738       z_lgr(result, Z_R1);
5739       if (needlecnt != noreg) {
5740         z_llgfr(Z_R1, needlecnt); // needle len in bytes (left operand)
5741         z_llgfr(odd_reg, needlecnt);
5742       } else {
5743         load_const_optimized(Z_R1, needle_bytes);
5744         if (Immediate::is_simm16(needle_bytes)) { z_lghi(odd_reg, needle_bytes); } else { z_lgr(odd_reg, Z_R1); }
5745       }
5746       if (h_csize == 1) {
5747         compare_long_ext(Z_R0, even_reg, 0);
5748       } else {
5749         compare_long_uni(Z_R0, even_reg, 0);
5750       }
5751       z_bre(L_Found);
5752 
5753       if (n_csize == 2) { z_llgh(Z_R0, Address(needle)); } else { z_llgc(Z_R0, Address(needle)); } // Reload.
5754       z_aghi(result, h_csize); // This is the new address we want to use for comparing.
5755       z_bru(L_OuterLoop);
5756     }
5757   }
5758 
5759   if (needlecnt != noreg || needlecntval == 1) {
5760     bind(L_needle1);
5761 
5762     // Single needle character version.
5763     if (h_csize == 1) {
5764       MacroAssembler::search_string(haycnt, result);
5765     } else {
5766       MacroAssembler::search_string_uni(haycnt, result);
5767     }
5768     z_lgr(result, haycnt);
5769     z_brc(Assembler::bcondFound, L_Found);
5770   }
5771 
5772   bind(L_NotFound);
5773   add2reg(result, -1, haystack); // Return -1.
5774 
5775   bind(L_Found); // Return index (or -1 in fallthrough case).
5776   z_sgr(result, haystack);
5777   if (h_csize == 2) { z_srag(result, result, exact_log2(sizeof(jchar))); }
5778   }
5779   BLOCK_COMMENT("} string_indexof");
5780 
5781   return offset() - block_start;
5782 }
5783 
5784 // early clobber: result
5785 unsigned int MacroAssembler::string_indexof_char(Register result, Register haystack, Register haycnt,
5786                                                  Register needle, jchar needleChar, Register odd_reg, Register even_reg, bool is_byte) {
5787   int block_start = offset();
5788 
5789   BLOCK_COMMENT("string_indexof_char {");
5790 
5791   if (needle == haystack) {
5792     z_lhi(result, 0);
5793   } else {
5794 
5795   Label Ldone;
5796 
5797   z_llgfr(odd_reg, haycnt);  // Preset loop ctr/searchrange end.
5798   if (needle == noreg) {
5799     load_const_optimized(Z_R0, (unsigned long)needleChar);
5800   } else {
5801     if (is_byte) {
5802       z_llgcr(Z_R0, needle); // First (and only) needle char.
5803     } else {
5804       z_llghr(Z_R0, needle); // First (and only) needle char.
5805     }
5806   }
5807 
5808   if (!is_byte) {
5809     z_agr(odd_reg, odd_reg); // Calc #bytes to be processed with SRSTU.
5810   }
5811 
5812   z_lgr(even_reg, haystack); // haystack addr
5813   z_agr(odd_reg, haystack);  // First char after range end.
5814   z_lghi(result, -1);
5815 
5816   if (is_byte) {
5817     MacroAssembler::search_string(odd_reg, even_reg);
5818   } else {
5819     MacroAssembler::search_string_uni(odd_reg, even_reg);
5820   }
5821   z_brc(Assembler::bcondNotFound, Ldone);
5822   if (is_byte) {
5823     if (VM_Version::has_DistinctOpnds()) {
5824       z_sgrk(result, odd_reg, haystack);
5825     } else {
5826       z_sgr(odd_reg, haystack);
5827       z_lgr(result, odd_reg);
5828     }
5829   } else {
5830     z_slgr(odd_reg, haystack);
5831     z_srlg(result, odd_reg, exact_log2(sizeof(jchar)));
5832   }
5833 
5834   bind(Ldone);
5835   }
5836   BLOCK_COMMENT("} string_indexof_char");
5837 
5838   return offset() - block_start;
5839 }
5840 
5841 
5842 //-------------------------------------------------
5843 //   Constants (scalar and oop) in constant pool
5844 //-------------------------------------------------
5845 
5846 // Add a non-relocated constant to the CP.
5847 int MacroAssembler::store_const_in_toc(AddressLiteral& val) {
5848   long    value  = val.value();
5849   address tocPos = long_constant(value);
5850 
5851   if (tocPos != NULL) {
5852     int tocOffset = (int)(tocPos - code()->consts()->start());
5853     return tocOffset;
5854   }
5855   // Address_constant returned NULL, so no constant entry has been created.
5856   // In that case, we return a "fatal" offset, just in case that subsequently
5857   // generated access code is executed.
5858   return -1;
5859 }
5860 
5861 // Returns the TOC offset where the address is stored.
5862 // Add a relocated constant to the CP.
5863 int MacroAssembler::store_oop_in_toc(AddressLiteral& oop) {
5864   // Use RelocationHolder::none for the constant pool entry.
5865   // Otherwise we will end up with a failing NativeCall::verify(x),
5866   // where x is the address of the constant pool entry.
5867   address tocPos = address_constant((address)oop.value(), RelocationHolder::none);
5868 
5869   if (tocPos != NULL) {
5870     int              tocOffset = (int)(tocPos - code()->consts()->start());
5871     RelocationHolder rsp = oop.rspec();
5872     Relocation      *rel = rsp.reloc();
5873 
5874     // Store toc_offset in relocation, used by call_far_patchable.
5875     if ((relocInfo::relocType)rel->type() == relocInfo::runtime_call_w_cp_type) {
5876       ((runtime_call_w_cp_Relocation *)(rel))->set_constant_pool_offset(tocOffset);
5877     }
5878     // Relocate at the load's pc.
5879     relocate(rsp);
5880 
5881     return tocOffset;
5882   }
5883   // Address_constant returned NULL, so no constant entry has been created
5884   // in that case, we return a "fatal" offset, just in case that subsequently
5885   // generated access code is executed.
5886   return -1;
5887 }
5888 
5889 bool MacroAssembler::load_const_from_toc(Register dst, AddressLiteral& a, Register Rtoc) {
5890   int     tocOffset = store_const_in_toc(a);
5891   if (tocOffset == -1) return false;
5892   address tocPos    = tocOffset + code()->consts()->start();
5893   assert((address)code()->consts()->start() != NULL, "Please add CP address");
5894 
5895   load_long_pcrelative(dst, tocPos);
5896   return true;
5897 }
5898 
5899 bool MacroAssembler::load_oop_from_toc(Register dst, AddressLiteral& a, Register Rtoc) {
5900   int     tocOffset = store_oop_in_toc(a);
5901   if (tocOffset == -1) return false;
5902   address tocPos    = tocOffset + code()->consts()->start();
5903   assert((address)code()->consts()->start() != NULL, "Please add CP address");
5904 
5905   load_addr_pcrelative(dst, tocPos);
5906   return true;
5907 }
5908 
5909 // If the instruction sequence at the given pc is a load_const_from_toc
5910 // sequence, return the value currently stored at the referenced position
5911 // in the TOC.
5912 intptr_t MacroAssembler::get_const_from_toc(address pc) {
5913 
5914   assert(is_load_const_from_toc(pc), "must be load_const_from_pool");
5915 
5916   long    offset  = get_load_const_from_toc_offset(pc);
5917   address dataLoc = NULL;
5918   if (is_load_const_from_toc_pcrelative(pc)) {
5919     dataLoc = pc + offset;
5920   } else {
5921     CodeBlob* cb = CodeCache::find_blob_unsafe(pc);   // Else we get assertion if nmethod is zombie.
5922     assert(cb && cb->is_nmethod(), "sanity");
5923     nmethod* nm = (nmethod*)cb;
5924     dataLoc = nm->ctable_begin() + offset;
5925   }
5926   return *(intptr_t *)dataLoc;
5927 }
5928 
5929 // If the instruction sequence at the given pc is a load_const_from_toc
5930 // sequence, copy the passed-in new_data value into the referenced
5931 // position in the TOC.
5932 void MacroAssembler::set_const_in_toc(address pc, unsigned long new_data, CodeBlob *cb) {
5933   assert(is_load_const_from_toc(pc), "must be load_const_from_pool");
5934 
5935   long    offset = MacroAssembler::get_load_const_from_toc_offset(pc);
5936   address dataLoc = NULL;
5937   if (is_load_const_from_toc_pcrelative(pc)) {
5938     dataLoc = pc+offset;
5939   } else {
5940     nmethod* nm = CodeCache::find_nmethod(pc);
5941     assert((cb == NULL) || (nm == (nmethod*)cb), "instruction address should be in CodeBlob");
5942     dataLoc = nm->ctable_begin() + offset;
5943   }
5944   if (*(unsigned long *)dataLoc != new_data) { // Prevent cache invalidation: update only if necessary.
5945     *(unsigned long *)dataLoc = new_data;
5946   }
5947 }
5948 
5949 // Dynamic TOC. Getter must only be called if "a" is a load_const_from_toc
5950 // site. Verify by calling is_load_const_from_toc() before!!
5951 // Offset is +/- 2**32 -> use long.
5952 long MacroAssembler::get_load_const_from_toc_offset(address a) {
5953   assert(is_load_const_from_toc_pcrelative(a), "expected pc relative load");
5954   //  expected code sequence:
5955   //    z_lgrl(t, simm32);    len = 6
5956   unsigned long inst;
5957   unsigned int  len = get_instruction(a, &inst);
5958   return get_pcrel_offset(inst);
5959 }
5960 
5961 //**********************************************************************************
5962 //  inspection of generated instruction sequences for a particular pattern
5963 //**********************************************************************************
5964 
5965 bool MacroAssembler::is_load_const_from_toc_pcrelative(address a) {
5966 #ifdef ASSERT
5967   unsigned long inst;
5968   unsigned int  len = get_instruction(a+2, &inst);
5969   if ((len == 6) && is_load_pcrelative_long(a) && is_call_pcrelative_long(inst)) {
5970     const int range = 128;
5971     Assembler::dump_code_range(tty, a, range, "instr(a) == z_lgrl && instr(a+2) == z_brasl");
5972     VM_Version::z_SIGSEGV();
5973   }
5974 #endif
5975   // expected code sequence:
5976   //   z_lgrl(t, relAddr32);    len = 6
5977   //TODO: verify accessed data is in CP, if possible.
5978   return is_load_pcrelative_long(a);  // TODO: might be too general. Currently, only lgrl is used.
5979 }
5980 
5981 bool MacroAssembler::is_load_const_from_toc_call(address a) {
5982   return is_load_const_from_toc(a) && is_call_byregister(a + load_const_from_toc_size());
5983 }
5984 
5985 bool MacroAssembler::is_load_const_call(address a) {
5986   return is_load_const(a) && is_call_byregister(a + load_const_size());
5987 }
5988 
5989 //-------------------------------------------------
5990 //   Emitters for some really CICS instructions
5991 //-------------------------------------------------
5992 
5993 void MacroAssembler::move_long_ext(Register dst, Register src, unsigned int pad) {
5994   assert(dst->encoding()%2==0, "must be an even/odd register pair");
5995   assert(src->encoding()%2==0, "must be an even/odd register pair");
5996   assert(pad<256, "must be a padding BYTE");
5997 
5998   Label retry;
5999   bind(retry);
6000   Assembler::z_mvcle(dst, src, pad);
6001   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6002 }
6003 
6004 void MacroAssembler::compare_long_ext(Register left, Register right, unsigned int pad) {
6005   assert(left->encoding() % 2 == 0, "must be an even/odd register pair");
6006   assert(right->encoding() % 2 == 0, "must be an even/odd register pair");
6007   assert(pad<256, "must be a padding BYTE");
6008 
6009   Label retry;
6010   bind(retry);
6011   Assembler::z_clcle(left, right, pad, Z_R0);
6012   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6013 }
6014 
6015 void MacroAssembler::compare_long_uni(Register left, Register right, unsigned int pad) {
6016   assert(left->encoding() % 2 == 0, "must be an even/odd register pair");
6017   assert(right->encoding() % 2 == 0, "must be an even/odd register pair");
6018   assert(pad<=0xfff, "must be a padding HALFWORD");
6019   assert(VM_Version::has_ETF2(), "instruction must be available");
6020 
6021   Label retry;
6022   bind(retry);
6023   Assembler::z_clclu(left, right, pad, Z_R0);
6024   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6025 }
6026 
6027 void MacroAssembler::search_string(Register end, Register start) {
6028   assert(end->encoding() != 0, "end address must not be in R0");
6029   assert(start->encoding() != 0, "start address must not be in R0");
6030 
6031   Label retry;
6032   bind(retry);
6033   Assembler::z_srst(end, start);
6034   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6035 }
6036 
6037 void MacroAssembler::search_string_uni(Register end, Register start) {
6038   assert(end->encoding() != 0, "end address must not be in R0");
6039   assert(start->encoding() != 0, "start address must not be in R0");
6040   assert(VM_Version::has_ETF3(), "instruction must be available");
6041 
6042   Label retry;
6043   bind(retry);
6044   Assembler::z_srstu(end, start);
6045   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6046 }
6047 
6048 void MacroAssembler::kmac(Register srcBuff) {
6049   assert(srcBuff->encoding()     != 0, "src buffer address can't be in Z_R0");
6050   assert(srcBuff->encoding() % 2 == 0, "src buffer/len must be an even/odd register pair");
6051 
6052   Label retry;
6053   bind(retry);
6054   Assembler::z_kmac(Z_R0, srcBuff);
6055   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6056 }
6057 
6058 void MacroAssembler::kimd(Register srcBuff) {
6059   assert(srcBuff->encoding()     != 0, "src buffer address can't be in Z_R0");
6060   assert(srcBuff->encoding() % 2 == 0, "src buffer/len must be an even/odd register pair");
6061 
6062   Label retry;
6063   bind(retry);
6064   Assembler::z_kimd(Z_R0, srcBuff);
6065   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6066 }
6067 
6068 void MacroAssembler::klmd(Register srcBuff) {
6069   assert(srcBuff->encoding()     != 0, "src buffer address can't be in Z_R0");
6070   assert(srcBuff->encoding() % 2 == 0, "src buffer/len must be an even/odd register pair");
6071 
6072   Label retry;
6073   bind(retry);
6074   Assembler::z_klmd(Z_R0, srcBuff);
6075   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6076 }
6077 
6078 void MacroAssembler::km(Register dstBuff, Register srcBuff) {
6079   // DstBuff and srcBuff are allowed to be the same register (encryption in-place).
6080   // DstBuff and srcBuff storage must not overlap destructively, and neither must overlap the parameter block.
6081   assert(srcBuff->encoding()     != 0, "src buffer address can't be in Z_R0");
6082   assert(dstBuff->encoding() % 2 == 0, "dst buffer addr must be an even register");
6083   assert(srcBuff->encoding() % 2 == 0, "src buffer addr/len must be an even/odd register pair");
6084 
6085   Label retry;
6086   bind(retry);
6087   Assembler::z_km(dstBuff, srcBuff);
6088   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6089 }
6090 
6091 void MacroAssembler::kmc(Register dstBuff, Register srcBuff) {
6092   // DstBuff and srcBuff are allowed to be the same register (encryption in-place).
6093   // DstBuff and srcBuff storage must not overlap destructively, and neither must overlap the parameter block.
6094   assert(srcBuff->encoding()     != 0, "src buffer address can't be in Z_R0");
6095   assert(dstBuff->encoding() % 2 == 0, "dst buffer addr must be an even register");
6096   assert(srcBuff->encoding() % 2 == 0, "src buffer addr/len must be an even/odd register pair");
6097 
6098   Label retry;
6099   bind(retry);
6100   Assembler::z_kmc(dstBuff, srcBuff);
6101   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6102 }
6103 
6104 void MacroAssembler::cksm(Register crcBuff, Register srcBuff) {
6105   assert(srcBuff->encoding() % 2 == 0, "src buffer addr/len must be an even/odd register pair");
6106 
6107   Label retry;
6108   bind(retry);
6109   Assembler::z_cksm(crcBuff, srcBuff);
6110   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6111 }
6112 
6113 void MacroAssembler::translate_oo(Register r1, Register r2, uint m3) {
6114   assert(r1->encoding() % 2 == 0, "dst addr/src len must be an even/odd register pair");
6115   assert((m3 & 0b1110) == 0, "Unused mask bits must be zero");
6116 
6117   Label retry;
6118   bind(retry);
6119   Assembler::z_troo(r1, r2, m3);
6120   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6121 }
6122 
6123 void MacroAssembler::translate_ot(Register r1, Register r2, uint m3) {
6124   assert(r1->encoding() % 2 == 0, "dst addr/src len must be an even/odd register pair");
6125   assert((m3 & 0b1110) == 0, "Unused mask bits must be zero");
6126 
6127   Label retry;
6128   bind(retry);
6129   Assembler::z_trot(r1, r2, m3);
6130   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6131 }
6132 
6133 void MacroAssembler::translate_to(Register r1, Register r2, uint m3) {
6134   assert(r1->encoding() % 2 == 0, "dst addr/src len must be an even/odd register pair");
6135   assert((m3 & 0b1110) == 0, "Unused mask bits must be zero");
6136 
6137   Label retry;
6138   bind(retry);
6139   Assembler::z_trto(r1, r2, m3);
6140   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6141 }
6142 
6143 void MacroAssembler::translate_tt(Register r1, Register r2, uint m3) {
6144   assert(r1->encoding() % 2 == 0, "dst addr/src len must be an even/odd register pair");
6145   assert((m3 & 0b1110) == 0, "Unused mask bits must be zero");
6146 
6147   Label retry;
6148   bind(retry);
6149   Assembler::z_trtt(r1, r2, m3);
6150   Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
6151 }
6152 
6153 
6154 void MacroAssembler::generate_type_profiling(const Register Rdata,
6155                                              const Register Rreceiver_klass,
6156                                              const Register Rwanted_receiver_klass,
6157                                              const Register Rmatching_row,
6158                                              bool is_virtual_call) {
6159   const int row_size = in_bytes(ReceiverTypeData::receiver_offset(1)) -
6160                        in_bytes(ReceiverTypeData::receiver_offset(0));
6161   const int num_rows = ReceiverTypeData::row_limit();
6162   NearLabel found_free_row;
6163   NearLabel do_increment;
6164   NearLabel found_no_slot;
6165 
6166   BLOCK_COMMENT("type profiling {");
6167 
6168   // search for:
6169   //    a) The type given in Rwanted_receiver_klass.
6170   //    b) The *first* empty row.
6171 
6172   // First search for a) only, just running over b) with no regard.
6173   // This is possible because
6174   //    wanted_receiver_class == receiver_class  &&  wanted_receiver_class == 0
6175   // is never true (receiver_class can't be zero).
6176   for (int row_num = 0; row_num < num_rows; row_num++) {
6177     // Row_offset should be a well-behaved positive number. The generated code relies
6178     // on that wrt constant code size. Add2reg can handle all row_offset values, but
6179     // will have to vary generated code size.
6180     int row_offset = in_bytes(ReceiverTypeData::receiver_offset(row_num));
6181     assert(Displacement::is_shortDisp(row_offset), "Limitation of generated code");
6182 
6183     // Is Rwanted_receiver_klass in this row?
6184     if (VM_Version::has_CompareBranch()) {
6185       z_lg(Rwanted_receiver_klass, row_offset, Z_R0, Rdata);
6186       // Rmatching_row = Rdata + row_offset;
6187       add2reg(Rmatching_row, row_offset, Rdata);
6188       // if (*row_recv == (intptr_t) receiver_klass) goto fill_existing_slot;
6189       compare64_and_branch(Rwanted_receiver_klass, Rreceiver_klass, Assembler::bcondEqual, do_increment);
6190     } else {
6191       add2reg(Rmatching_row, row_offset, Rdata);
6192       z_cg(Rreceiver_klass, row_offset, Z_R0, Rdata);
6193       z_bre(do_increment);
6194     }
6195   }
6196 
6197   // Now that we did not find a match, let's search for b).
6198 
6199   // We could save the first calculation of Rmatching_row if we woud search for a) in reverse order.
6200   // We would then end up here with Rmatching_row containing the value for row_num == 0.
6201   // We would not see much benefit, if any at all, because the CPU can schedule
6202   // two instructions together with a branch anyway.
6203   for (int row_num = 0; row_num < num_rows; row_num++) {
6204     int row_offset = in_bytes(ReceiverTypeData::receiver_offset(row_num));
6205 
6206     // Has this row a zero receiver_klass, i.e. is it empty?
6207     if (VM_Version::has_CompareBranch()) {
6208       z_lg(Rwanted_receiver_klass, row_offset, Z_R0, Rdata);
6209       // Rmatching_row = Rdata + row_offset
6210       add2reg(Rmatching_row, row_offset, Rdata);
6211       // if (*row_recv == (intptr_t) 0) goto found_free_row
6212       compare64_and_branch(Rwanted_receiver_klass, (intptr_t)0, Assembler::bcondEqual, found_free_row);
6213     } else {
6214       add2reg(Rmatching_row, row_offset, Rdata);
6215       load_and_test_long(Rwanted_receiver_klass, Address(Rdata, row_offset));
6216       z_bre(found_free_row);  // zero -> Found a free row.
6217     }
6218   }
6219 
6220   // No match, no empty row found.
6221   // Increment total counter to indicate polymorphic case.
6222   if (is_virtual_call) {
6223     add2mem_64(Address(Rdata, CounterData::count_offset()), 1, Rmatching_row);
6224   }
6225   z_bru(found_no_slot);
6226 
6227   // Here we found an empty row, but we have not found Rwanted_receiver_klass.
6228   // Rmatching_row holds the address to the first empty row.
6229   bind(found_free_row);
6230   // Store receiver_klass into empty slot.
6231   z_stg(Rreceiver_klass, 0, Z_R0, Rmatching_row);
6232 
6233   // Increment the counter of Rmatching_row.
6234   bind(do_increment);
6235   ByteSize counter_offset = ReceiverTypeData::receiver_count_offset(0) - ReceiverTypeData::receiver_offset(0);
6236   add2mem_64(Address(Rmatching_row, counter_offset), 1, Rdata);
6237 
6238   bind(found_no_slot);
6239 
6240   BLOCK_COMMENT("} type profiling");
6241 }
6242 
6243 //---------------------------------------
6244 // Helpers for Intrinsic Emitters
6245 //---------------------------------------
6246 
6247 /**
6248  * uint32_t crc;
6249  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
6250  */
6251 void MacroAssembler::fold_byte_crc32(Register crc, Register val, Register table, Register tmp) {
6252   assert_different_registers(crc, table, tmp);
6253   assert_different_registers(val, table);
6254   if (crc == val) {      // Must rotate first to use the unmodified value.
6255     rotate_then_insert(tmp, val, 56-2, 63-2, 2, true);  // Insert byte 7 of val, shifted left by 2, into byte 6..7 of tmp, clear the rest.
6256     z_srl(crc, 8);       // Unsigned shift, clear leftmost 8 bits.
6257   } else {
6258     z_srl(crc, 8);       // Unsigned shift, clear leftmost 8 bits.
6259     rotate_then_insert(tmp, val, 56-2, 63-2, 2, true);  // Insert byte 7 of val, shifted left by 2, into byte 6..7 of tmp, clear the rest.
6260   }
6261   z_x(crc, Address(table, tmp, 0));
6262 }
6263 
6264 /**
6265  * uint32_t crc;
6266  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
6267  */
6268 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
6269   fold_byte_crc32(crc, crc, table, tmp);
6270 }
6271 
6272 /**
6273  * Emits code to update CRC-32 with a byte value according to constants in table.
6274  *
6275  * @param [in,out]crc Register containing the crc.
6276  * @param [in]val     Register containing the byte to fold into the CRC.
6277  * @param [in]table   Register containing the table of crc constants.
6278  *
6279  * uint32_t crc;
6280  * val = crc_table[(val ^ crc) & 0xFF];
6281  * crc = val ^ (crc >> 8);
6282  */
6283 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
6284   z_xr(val, crc);
6285   fold_byte_crc32(crc, val, table, val);
6286 }
6287 
6288 
6289 /**
6290  * @param crc   register containing existing CRC (32-bit)
6291  * @param buf   register pointing to input byte buffer (byte*)
6292  * @param len   register containing number of bytes
6293  * @param table register pointing to CRC table
6294  */
6295 void MacroAssembler::update_byteLoop_crc32(Register crc, Register buf, Register len, Register table, Register data) {
6296   assert_different_registers(crc, buf, len, table, data);
6297 
6298   Label L_mainLoop, L_done;
6299   const int mainLoop_stepping = 1;
6300 
6301   // Process all bytes in a single-byte loop.
6302   z_ltr(len, len);
6303   z_brnh(L_done);
6304 
6305   bind(L_mainLoop);
6306     z_llgc(data, Address(buf, (intptr_t)0));// Current byte of input buffer (zero extended). Avoids garbage in upper half of register.
6307     add2reg(buf, mainLoop_stepping);        // Advance buffer position.
6308     update_byte_crc32(crc, data, table);
6309     z_brct(len, L_mainLoop);                // Iterate.
6310 
6311   bind(L_done);
6312 }
6313 
6314 /**
6315  * Emits code to update CRC-32 with a 4-byte value according to constants in table.
6316  * Implementation according to jdk/src/share/native/java/util/zip/zlib-1.2.8/crc32.c.
6317  *
6318  */
6319 void MacroAssembler::update_1word_crc32(Register crc, Register buf, Register table, int bufDisp, int bufInc,
6320                                         Register t0,  Register t1,  Register t2,    Register t3) {
6321   // This is what we implement (the DOBIG4 part):
6322   //
6323   // #define DOBIG4 c ^= *++buf4; \
6324   //         c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
6325   //             crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
6326   // #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
6327   // Pre-calculate (constant) column offsets, use columns 4..7 for big-endian.
6328   const int ix0 = 4*(4*CRC32_COLUMN_SIZE);
6329   const int ix1 = 5*(4*CRC32_COLUMN_SIZE);
6330   const int ix2 = 6*(4*CRC32_COLUMN_SIZE);
6331   const int ix3 = 7*(4*CRC32_COLUMN_SIZE);
6332 
6333   // XOR crc with next four bytes of buffer.
6334   lgr_if_needed(t0, crc);
6335   z_x(t0, Address(buf, bufDisp));
6336   if (bufInc != 0) {
6337     add2reg(buf, bufInc);
6338   }
6339 
6340   // Chop crc into 4 single-byte pieces, shifted left 2 bits, to form the table indices.
6341   rotate_then_insert(t3, t0, 56-2, 63-2, 2,    true);  // ((c >>  0) & 0xff) << 2
6342   rotate_then_insert(t2, t0, 56-2, 63-2, 2-8,  true);  // ((c >>  8) & 0xff) << 2
6343   rotate_then_insert(t1, t0, 56-2, 63-2, 2-16, true);  // ((c >> 16) & 0xff) << 2
6344   rotate_then_insert(t0, t0, 56-2, 63-2, 2-24, true);  // ((c >> 24) & 0xff) << 2
6345 
6346   // XOR indexed table values to calculate updated crc.
6347   z_ly(t2, Address(table, t2, (intptr_t)ix1));
6348   z_ly(t0, Address(table, t0, (intptr_t)ix3));
6349   z_xy(t2, Address(table, t3, (intptr_t)ix0));
6350   z_xy(t0, Address(table, t1, (intptr_t)ix2));
6351   z_xr(t0, t2);           // Now t0 contains the updated CRC value.
6352   lgr_if_needed(crc, t0);
6353 }
6354 
6355 /**
6356  * @param crc   register containing existing CRC (32-bit)
6357  * @param buf   register pointing to input byte buffer (byte*)
6358  * @param len   register containing number of bytes
6359  * @param table register pointing to CRC table
6360  *
6361  * uses Z_R10..Z_R13 as work register. Must be saved/restored by caller!
6362  */
6363 void MacroAssembler::kernel_crc32_1word(Register crc, Register buf, Register len, Register table,
6364                                         Register t0,  Register t1,  Register t2,  Register t3,
6365                                         bool invertCRC) {
6366   assert_different_registers(crc, buf, len, table);
6367 
6368   Label L_mainLoop, L_tail;
6369   Register  data = t0;
6370   Register  ctr  = Z_R0;
6371   const int mainLoop_stepping = 4;
6372   const int log_stepping      = exact_log2(mainLoop_stepping);
6373 
6374   // Don't test for len <= 0 here. This pathological case should not occur anyway.
6375   // Optimizing for it by adding a test and a branch seems to be a waste of CPU cycles.
6376   // The situation itself is detected and handled correctly by the conditional branches
6377   // following aghi(len, -stepping) and aghi(len, +stepping).
6378 
6379   if (invertCRC) {
6380     not_(crc, noreg, false);           // 1s complement of crc
6381   }
6382 
6383   // Check for short (<4 bytes) buffer.
6384   z_srag(ctr, len, log_stepping);
6385   z_brnh(L_tail);
6386 
6387   z_lrvr(crc, crc);          // Revert byte order because we are dealing with big-endian data.
6388   rotate_then_insert(len, len, 64-log_stepping, 63, 0, true); // #bytes for tailLoop
6389 
6390   BIND(L_mainLoop);
6391     update_1word_crc32(crc, buf, table, 0, mainLoop_stepping, crc, t1, t2, t3);
6392     z_brct(ctr, L_mainLoop); // Iterate.
6393 
6394   z_lrvr(crc, crc);          // Revert byte order back to original.
6395 
6396   // Process last few (<8) bytes of buffer.
6397   BIND(L_tail);
6398   update_byteLoop_crc32(crc, buf, len, table, data);
6399 
6400   if (invertCRC) {
6401     not_(crc, noreg, false);           // 1s complement of crc
6402   }
6403 }
6404 
6405 /**
6406  * @param crc   register containing existing CRC (32-bit)
6407  * @param buf   register pointing to input byte buffer (byte*)
6408  * @param len   register containing number of bytes
6409  * @param table register pointing to CRC table
6410  */
6411 void MacroAssembler::kernel_crc32_1byte(Register crc, Register buf, Register len, Register table,
6412                                         Register t0,  Register t1,  Register t2,  Register t3,
6413                                         bool invertCRC) {
6414   assert_different_registers(crc, buf, len, table);
6415   Register data = t0;
6416 
6417   if (invertCRC) {
6418     not_(crc, noreg, false);           // 1s complement of crc
6419   }
6420 
6421   update_byteLoop_crc32(crc, buf, len, table, data);
6422 
6423   if (invertCRC) {
6424     not_(crc, noreg, false);           // 1s complement of crc
6425   }
6426 }
6427 
6428 void MacroAssembler::kernel_crc32_singleByte(Register crc, Register buf, Register len, Register table, Register tmp,
6429                                              bool invertCRC) {
6430   assert_different_registers(crc, buf, len, table, tmp);
6431 
6432   if (invertCRC) {
6433     not_(crc, noreg, false);           // 1s complement of crc
6434   }
6435 
6436   z_llgc(tmp, Address(buf, (intptr_t)0));  // Current byte of input buffer (zero extended). Avoids garbage in upper half of register.
6437   update_byte_crc32(crc, tmp, table);
6438 
6439   if (invertCRC) {
6440     not_(crc, noreg, false);           // 1s complement of crc
6441   }
6442 }
6443 
6444 void MacroAssembler::kernel_crc32_singleByteReg(Register crc, Register val, Register table,
6445                                                 bool invertCRC) {
6446   assert_different_registers(crc, val, table);
6447 
6448   if (invertCRC) {
6449     not_(crc, noreg, false);           // 1s complement of crc
6450   }
6451 
6452   update_byte_crc32(crc, val, table);
6453 
6454   if (invertCRC) {
6455     not_(crc, noreg, false);           // 1s complement of crc
6456   }
6457 }
6458 
6459 //
6460 // Code for BigInteger::multiplyToLen() intrinsic.
6461 //
6462 
6463 // dest_lo += src1 + src2
6464 // dest_hi += carry1 + carry2
6465 // Z_R7 is destroyed !
6466 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo,
6467                                      Register src1, Register src2) {
6468   clear_reg(Z_R7);
6469   z_algr(dest_lo, src1);
6470   z_alcgr(dest_hi, Z_R7);
6471   z_algr(dest_lo, src2);
6472   z_alcgr(dest_hi, Z_R7);
6473 }
6474 
6475 // Multiply 64 bit by 64 bit first loop.
6476 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart,
6477                                            Register x_xstart,
6478                                            Register y, Register y_idx,
6479                                            Register z,
6480                                            Register carry,
6481                                            Register product,
6482                                            Register idx, Register kdx) {
6483   // jlong carry, x[], y[], z[];
6484   // for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx--, kdx--) {
6485   //   huge_128 product = y[idx] * x[xstart] + carry;
6486   //   z[kdx] = (jlong)product;
6487   //   carry  = (jlong)(product >>> 64);
6488   // }
6489   // z[xstart] = carry;
6490 
6491   Label L_first_loop, L_first_loop_exit;
6492   Label L_one_x, L_one_y, L_multiply;
6493 
6494   z_aghi(xstart, -1);
6495   z_brl(L_one_x);   // Special case: length of x is 1.
6496 
6497   // Load next two integers of x.
6498   z_sllg(Z_R1_scratch, xstart, LogBytesPerInt);
6499   mem2reg_opt(x_xstart, Address(x, Z_R1_scratch, 0));
6500 
6501 
6502   bind(L_first_loop);
6503 
6504   z_aghi(idx, -1);
6505   z_brl(L_first_loop_exit);
6506   z_aghi(idx, -1);
6507   z_brl(L_one_y);
6508 
6509   // Load next two integers of y.
6510   z_sllg(Z_R1_scratch, idx, LogBytesPerInt);
6511   mem2reg_opt(y_idx, Address(y, Z_R1_scratch, 0));
6512 
6513 
6514   bind(L_multiply);
6515 
6516   Register multiplicand = product->successor();
6517   Register product_low = multiplicand;
6518 
6519   lgr_if_needed(multiplicand, x_xstart);
6520   z_mlgr(product, y_idx);     // multiplicand * y_idx -> product::multiplicand
6521   clear_reg(Z_R7);
6522   z_algr(product_low, carry); // Add carry to result.
6523   z_alcgr(product, Z_R7);     // Add carry of the last addition.
6524   add2reg(kdx, -2);
6525 
6526   // Store result.
6527   z_sllg(Z_R7, kdx, LogBytesPerInt);
6528   reg2mem_opt(product_low, Address(z, Z_R7, 0));
6529   lgr_if_needed(carry, product);
6530   z_bru(L_first_loop);
6531 
6532 
6533   bind(L_one_y); // Load one 32 bit portion of y as (0,value).
6534 
6535   clear_reg(y_idx);
6536   mem2reg_opt(y_idx, Address(y, (intptr_t) 0), false);
6537   z_bru(L_multiply);
6538 
6539 
6540   bind(L_one_x); // Load one 32 bit portion of x as (0,value).
6541 
6542   clear_reg(x_xstart);
6543   mem2reg_opt(x_xstart, Address(x, (intptr_t) 0), false);
6544   z_bru(L_first_loop);
6545 
6546   bind(L_first_loop_exit);
6547 }
6548 
6549 // Multiply 64 bit by 64 bit and add 128 bit.
6550 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y,
6551                                             Register z,
6552                                             Register yz_idx, Register idx,
6553                                             Register carry, Register product,
6554                                             int offset) {
6555   // huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
6556   // z[kdx] = (jlong)product;
6557 
6558   Register multiplicand = product->successor();
6559   Register product_low = multiplicand;
6560 
6561   z_sllg(Z_R7, idx, LogBytesPerInt);
6562   mem2reg_opt(yz_idx, Address(y, Z_R7, offset));
6563 
6564   lgr_if_needed(multiplicand, x_xstart);
6565   z_mlgr(product, yz_idx); // multiplicand * yz_idx -> product::multiplicand
6566   mem2reg_opt(yz_idx, Address(z, Z_R7, offset));
6567 
6568   add2_with_carry(product, product_low, carry, yz_idx);
6569 
6570   z_sllg(Z_R7, idx, LogBytesPerInt);
6571   reg2mem_opt(product_low, Address(z, Z_R7, offset));
6572 
6573 }
6574 
6575 // Multiply 128 bit by 128 bit. Unrolled inner loop.
6576 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart,
6577                                              Register y, Register z,
6578                                              Register yz_idx, Register idx,
6579                                              Register jdx,
6580                                              Register carry, Register product,
6581                                              Register carry2) {
6582   // jlong carry, x[], y[], z[];
6583   // int kdx = ystart+1;
6584   // for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
6585   //   huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
6586   //   z[kdx+idx+1] = (jlong)product;
6587   //   jlong carry2 = (jlong)(product >>> 64);
6588   //   product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
6589   //   z[kdx+idx] = (jlong)product;
6590   //   carry = (jlong)(product >>> 64);
6591   // }
6592   // idx += 2;
6593   // if (idx > 0) {
6594   //   product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
6595   //   z[kdx+idx] = (jlong)product;
6596   //   carry = (jlong)(product >>> 64);
6597   // }
6598 
6599   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
6600 
6601   // scale the index
6602   lgr_if_needed(jdx, idx);
6603   and_imm(jdx, 0xfffffffffffffffcL);
6604   rshift(jdx, 2);
6605 
6606 
6607   bind(L_third_loop);
6608 
6609   z_aghi(jdx, -1);
6610   z_brl(L_third_loop_exit);
6611   add2reg(idx, -4);
6612 
6613   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
6614   lgr_if_needed(carry2, product);
6615 
6616   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
6617   lgr_if_needed(carry, product);
6618   z_bru(L_third_loop);
6619 
6620 
6621   bind(L_third_loop_exit);  // Handle any left-over operand parts.
6622 
6623   and_imm(idx, 0x3);
6624   z_brz(L_post_third_loop_done);
6625 
6626   Label L_check_1;
6627 
6628   z_aghi(idx, -2);
6629   z_brl(L_check_1);
6630 
6631   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
6632   lgr_if_needed(carry, product);
6633 
6634 
6635   bind(L_check_1);
6636 
6637   add2reg(idx, 0x2);
6638   and_imm(idx, 0x1);
6639   z_aghi(idx, -1);
6640   z_brl(L_post_third_loop_done);
6641 
6642   Register   multiplicand = product->successor();
6643   Register   product_low = multiplicand;
6644 
6645   z_sllg(Z_R7, idx, LogBytesPerInt);
6646   clear_reg(yz_idx);
6647   mem2reg_opt(yz_idx, Address(y, Z_R7, 0), false);
6648   lgr_if_needed(multiplicand, x_xstart);
6649   z_mlgr(product, yz_idx); // multiplicand * yz_idx -> product::multiplicand
6650   clear_reg(yz_idx);
6651   mem2reg_opt(yz_idx, Address(z, Z_R7, 0), false);
6652 
6653   add2_with_carry(product, product_low, yz_idx, carry);
6654 
6655   z_sllg(Z_R7, idx, LogBytesPerInt);
6656   reg2mem_opt(product_low, Address(z, Z_R7, 0), false);
6657   rshift(product_low, 32);
6658 
6659   lshift(product, 32);
6660   z_ogr(product_low, product);
6661   lgr_if_needed(carry, product_low);
6662 
6663   bind(L_post_third_loop_done);
6664 }
6665 
6666 void MacroAssembler::multiply_to_len(Register x, Register xlen,
6667                                      Register y, Register ylen,
6668                                      Register z,
6669                                      Register tmp1, Register tmp2,
6670                                      Register tmp3, Register tmp4,
6671                                      Register tmp5) {
6672   ShortBranchVerifier sbv(this);
6673 
6674   assert_different_registers(x, xlen, y, ylen, z,
6675                              tmp1, tmp2, tmp3, tmp4, tmp5, Z_R1_scratch, Z_R7);
6676   assert_different_registers(x, xlen, y, ylen, z,
6677                              tmp1, tmp2, tmp3, tmp4, tmp5, Z_R8);
6678 
6679   z_stmg(Z_R7, Z_R13, _z_abi(gpr7), Z_SP);
6680 
6681   // In openJdk, we store the argument as 32-bit value to slot.
6682   Address zlen(Z_SP, _z_abi(remaining_cargs));  // Int in long on big endian.
6683 
6684   const Register idx = tmp1;
6685   const Register kdx = tmp2;
6686   const Register xstart = tmp3;
6687 
6688   const Register y_idx = tmp4;
6689   const Register carry = tmp5;
6690   const Register product  = Z_R0_scratch;
6691   const Register x_xstart = Z_R8;
6692 
6693   // First Loop.
6694   //
6695   //   final static long LONG_MASK = 0xffffffffL;
6696   //   int xstart = xlen - 1;
6697   //   int ystart = ylen - 1;
6698   //   long carry = 0;
6699   //   for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
6700   //     long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
6701   //     z[kdx] = (int)product;
6702   //     carry = product >>> 32;
6703   //   }
6704   //   z[xstart] = (int)carry;
6705   //
6706 
6707   lgr_if_needed(idx, ylen);  // idx = ylen
6708   z_llgf(kdx, zlen);         // C2 does not respect int to long conversion for stub calls, thus load zero-extended.
6709   clear_reg(carry);          // carry = 0
6710 
6711   Label L_done;
6712 
6713   lgr_if_needed(xstart, xlen);
6714   z_aghi(xstart, -1);
6715   z_brl(L_done);
6716 
6717   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
6718 
6719   NearLabel L_second_loop;
6720   compare64_and_branch(kdx, RegisterOrConstant((intptr_t) 0), bcondEqual, L_second_loop);
6721 
6722   NearLabel L_carry;
6723   z_aghi(kdx, -1);
6724   z_brz(L_carry);
6725 
6726   // Store lower 32 bits of carry.
6727   z_sllg(Z_R1_scratch, kdx, LogBytesPerInt);
6728   reg2mem_opt(carry, Address(z, Z_R1_scratch, 0), false);
6729   rshift(carry, 32);
6730   z_aghi(kdx, -1);
6731 
6732 
6733   bind(L_carry);
6734 
6735   // Store upper 32 bits of carry.
6736   z_sllg(Z_R1_scratch, kdx, LogBytesPerInt);
6737   reg2mem_opt(carry, Address(z, Z_R1_scratch, 0), false);
6738 
6739   // Second and third (nested) loops.
6740   //
6741   // for (int i = xstart-1; i >= 0; i--) { // Second loop
6742   //   carry = 0;
6743   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
6744   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
6745   //                    (z[k] & LONG_MASK) + carry;
6746   //     z[k] = (int)product;
6747   //     carry = product >>> 32;
6748   //   }
6749   //   z[i] = (int)carry;
6750   // }
6751   //
6752   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
6753 
6754   const Register jdx = tmp1;
6755 
6756   bind(L_second_loop);
6757 
6758   clear_reg(carry);           // carry = 0;
6759   lgr_if_needed(jdx, ylen);   // j = ystart+1
6760 
6761   z_aghi(xstart, -1);         // i = xstart-1;
6762   z_brl(L_done);
6763 
6764   // Use free slots in the current stackframe instead of push/pop.
6765   Address zsave(Z_SP, _z_abi(carg_1));
6766   reg2mem_opt(z, zsave);
6767 
6768 
6769   Label L_last_x;
6770 
6771   z_sllg(Z_R1_scratch, xstart, LogBytesPerInt);
6772   load_address(z, Address(z, Z_R1_scratch, 4)); // z = z + k - j
6773   z_aghi(xstart, -1);                           // i = xstart-1;
6774   z_brl(L_last_x);
6775 
6776   z_sllg(Z_R1_scratch, xstart, LogBytesPerInt);
6777   mem2reg_opt(x_xstart, Address(x, Z_R1_scratch, 0));
6778 
6779 
6780   Label L_third_loop_prologue;
6781 
6782   bind(L_third_loop_prologue);
6783 
6784   Address xsave(Z_SP, _z_abi(carg_2));
6785   Address xlensave(Z_SP, _z_abi(carg_3));
6786   Address ylensave(Z_SP, _z_abi(carg_4));
6787 
6788   reg2mem_opt(x, xsave);
6789   reg2mem_opt(xstart, xlensave);
6790   reg2mem_opt(ylen, ylensave);
6791 
6792 
6793   multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
6794 
6795   mem2reg_opt(z, zsave);
6796   mem2reg_opt(x, xsave);
6797   mem2reg_opt(xlen, xlensave);   // This is the decrement of the loop counter!
6798   mem2reg_opt(ylen, ylensave);
6799 
6800   add2reg(tmp3, 1, xlen);
6801   z_sllg(Z_R1_scratch, tmp3, LogBytesPerInt);
6802   reg2mem_opt(carry, Address(z, Z_R1_scratch, 0), false);
6803   z_aghi(tmp3, -1);
6804   z_brl(L_done);
6805 
6806   rshift(carry, 32);
6807   z_sllg(Z_R1_scratch, tmp3, LogBytesPerInt);
6808   reg2mem_opt(carry, Address(z, Z_R1_scratch, 0), false);
6809   z_bru(L_second_loop);
6810 
6811   // Next infrequent code is moved outside loops.
6812   bind(L_last_x);
6813 
6814   clear_reg(x_xstart);
6815   mem2reg_opt(x_xstart, Address(x, (intptr_t) 0), false);
6816   z_bru(L_third_loop_prologue);
6817 
6818   bind(L_done);
6819 
6820   z_lmg(Z_R7, Z_R13, _z_abi(gpr7), Z_SP);
6821 }
6822 
6823 #ifndef PRODUCT
6824 // Assert if CC indicates "not equal" (check_equal==true) or "equal" (check_equal==false).
6825 void MacroAssembler::asm_assert(bool check_equal, const char *msg, int id) {
6826   Label ok;
6827   if (check_equal) {
6828     z_bre(ok);
6829   } else {
6830     z_brne(ok);
6831   }
6832   stop(msg, id);
6833   bind(ok);
6834 }
6835 
6836 // Assert if CC indicates "low".
6837 void MacroAssembler::asm_assert_low(const char *msg, int id) {
6838   Label ok;
6839   z_brnl(ok);
6840   stop(msg, id);
6841   bind(ok);
6842 }
6843 
6844 // Assert if CC indicates "high".
6845 void MacroAssembler::asm_assert_high(const char *msg, int id) {
6846   Label ok;
6847   z_brnh(ok);
6848   stop(msg, id);
6849   bind(ok);
6850 }
6851 
6852 // Assert if CC indicates "not equal" (check_equal==true) or "equal" (check_equal==false)
6853 // generate non-relocatable code.
6854 void MacroAssembler::asm_assert_static(bool check_equal, const char *msg, int id) {
6855   Label ok;
6856   if (check_equal) { z_bre(ok); }
6857   else             { z_brne(ok); }
6858   stop_static(msg, id);
6859   bind(ok);
6860 }
6861 
6862 void MacroAssembler::asm_assert_mems_zero(bool check_equal, bool allow_relocation, int size, int64_t mem_offset,
6863                                           Register mem_base, const char* msg, int id) {
6864   switch (size) {
6865     case 4:
6866       load_and_test_int(Z_R0, Address(mem_base, mem_offset));
6867       break;
6868     case 8:
6869       load_and_test_long(Z_R0,  Address(mem_base, mem_offset));
6870       break;
6871     default:
6872       ShouldNotReachHere();
6873   }
6874   if (allow_relocation) { asm_assert(check_equal, msg, id); }
6875   else                  { asm_assert_static(check_equal, msg, id); }
6876 }
6877 
6878 // Check the condition
6879 //   expected_size == FP - SP
6880 // after transformation:
6881 //   expected_size - FP + SP == 0
6882 // Destroys Register expected_size if no tmp register is passed.
6883 void MacroAssembler::asm_assert_frame_size(Register expected_size, Register tmp, const char* msg, int id) {
6884   if (tmp == noreg) {
6885     tmp = expected_size;
6886   } else {
6887     if (tmp != expected_size) {
6888       z_lgr(tmp, expected_size);
6889     }
6890     z_algr(tmp, Z_SP);
6891     z_slg(tmp, 0, Z_R0, Z_SP);
6892     asm_assert_eq(msg, id);
6893   }
6894 }
6895 #endif // !PRODUCT
6896 
6897 void MacroAssembler::verify_thread() {
6898   if (VerifyThread) {
6899     unimplemented("", 117);
6900   }
6901 }
6902 
6903 // Plausibility check for oops.
6904 void MacroAssembler::verify_oop(Register oop, const char* msg) {
6905   if (!VerifyOops) return;
6906 
6907   BLOCK_COMMENT("verify_oop {");
6908   Register tmp = Z_R0;
6909   unsigned int nbytes_save = 5*BytesPerWord;
6910   address entry = StubRoutines::verify_oop_subroutine_entry_address();
6911 
6912   save_return_pc();
6913   push_frame_abi160(nbytes_save);
6914   z_stmg(Z_R1, Z_R5, frame::z_abi_160_size, Z_SP);
6915 
6916   z_lgr(Z_ARG2, oop);
6917   load_const(Z_ARG1, (address) msg);
6918   load_const(Z_R1, entry);
6919   z_lg(Z_R1, 0, Z_R1);
6920   call_c(Z_R1);
6921 
6922   z_lmg(Z_R1, Z_R5, frame::z_abi_160_size, Z_SP);
6923   pop_frame();
6924   restore_return_pc();
6925 
6926   BLOCK_COMMENT("} verify_oop ");
6927 }
6928 
6929 const char* MacroAssembler::stop_types[] = {
6930   "stop",
6931   "untested",
6932   "unimplemented",
6933   "shouldnotreachhere"
6934 };
6935 
6936 static void stop_on_request(const char* tp, const char* msg) {
6937   tty->print("Z assembly code requires stop: (%s) %s\n", tp, msg);
6938   guarantee(false, "Z assembly code requires stop: %s", msg);
6939 }
6940 
6941 void MacroAssembler::stop(int type, const char* msg, int id) {
6942   BLOCK_COMMENT(err_msg("stop: %s {", msg));
6943 
6944   // Setup arguments.
6945   load_const(Z_ARG1, (void*) stop_types[type%stop_end]);
6946   load_const(Z_ARG2, (void*) msg);
6947   get_PC(Z_R14);     // Following code pushes a frame without entering a new function. Use current pc as return address.
6948   save_return_pc();  // Saves return pc Z_R14.
6949   push_frame_abi160(0);
6950   call_VM_leaf(CAST_FROM_FN_PTR(address, stop_on_request), Z_ARG1, Z_ARG2);
6951   // The plain disassembler does not recognize illtrap. It instead displays
6952   // a 32-bit value. Issueing two illtraps assures the disassembler finds
6953   // the proper beginning of the next instruction.
6954   z_illtrap(); // Illegal instruction.
6955   z_illtrap(); // Illegal instruction.
6956 
6957   BLOCK_COMMENT(" } stop");
6958 }
6959 
6960 // Special version of stop() for code size reduction.
6961 // Reuses the previously generated call sequence, if any.
6962 // Generates the call sequence on its own, if necessary.
6963 // Note: This code will work only in non-relocatable code!
6964 //       The relative address of the data elements (arg1, arg2) must not change.
6965 //       The reentry point must not move relative to it's users. This prerequisite
6966 //       should be given for "hand-written" code, if all chain calls are in the same code blob.
6967 //       Generated code must not undergo any transformation, e.g. ShortenBranches, to be safe.
6968 address MacroAssembler::stop_chain(address reentry, int type, const char* msg, int id, bool allow_relocation) {
6969   BLOCK_COMMENT(err_msg("stop_chain(%s,%s): %s {", reentry==NULL?"init":"cont", allow_relocation?"reloc ":"static", msg));
6970 
6971   // Setup arguments.
6972   if (allow_relocation) {
6973     // Relocatable version (for comparison purposes). Remove after some time.
6974     load_const(Z_ARG1, (void*) stop_types[type%stop_end]);
6975     load_const(Z_ARG2, (void*) msg);
6976   } else {
6977     load_absolute_address(Z_ARG1, (address)stop_types[type%stop_end]);
6978     load_absolute_address(Z_ARG2, (address)msg);
6979   }
6980   if ((reentry != NULL) && RelAddr::is_in_range_of_RelAddr16(reentry, pc())) {
6981     BLOCK_COMMENT("branch to reentry point:");
6982     z_brc(bcondAlways, reentry);
6983   } else {
6984     BLOCK_COMMENT("reentry point:");
6985     reentry = pc();      // Re-entry point for subsequent stop calls.
6986     save_return_pc();    // Saves return pc Z_R14.
6987     push_frame_abi160(0);
6988     if (allow_relocation) {
6989       reentry = NULL;    // Prevent reentry if code relocation is allowed.
6990       call_VM_leaf(CAST_FROM_FN_PTR(address, stop_on_request), Z_ARG1, Z_ARG2);
6991     } else {
6992       call_VM_leaf_static(CAST_FROM_FN_PTR(address, stop_on_request), Z_ARG1, Z_ARG2);
6993     }
6994     z_illtrap(); // Illegal instruction as emergency stop, should the above call return.
6995   }
6996   BLOCK_COMMENT(" } stop_chain");
6997 
6998   return reentry;
6999 }
7000 
7001 // Special version of stop() for code size reduction.
7002 // Assumes constant relative addresses for data and runtime call.
7003 void MacroAssembler::stop_static(int type, const char* msg, int id) {
7004   stop_chain(NULL, type, msg, id, false);
7005 }
7006 
7007 void MacroAssembler::stop_subroutine() {
7008   unimplemented("stop_subroutine", 710);
7009 }
7010 
7011 // Prints msg to stdout from within generated code..
7012 void MacroAssembler::warn(const char* msg) {
7013   RegisterSaver::save_live_registers(this, RegisterSaver::all_registers, Z_R14);
7014   load_absolute_address(Z_R1, (address) warning);
7015   load_absolute_address(Z_ARG1, (address) msg);
7016   (void) call(Z_R1);
7017   RegisterSaver::restore_live_registers(this, RegisterSaver::all_registers);
7018 }
7019 
7020 #ifndef PRODUCT
7021 
7022 // Write pattern 0x0101010101010101 in region [low-before, high+after].
7023 void MacroAssembler::zap_from_to(Register low, Register high, Register val, Register addr, int before, int after) {
7024   if (!ZapEmptyStackFields) return;
7025   BLOCK_COMMENT("zap memory region {");
7026   load_const_optimized(val, 0x0101010101010101);
7027   int size = before + after;
7028   if (low == high && size < 5 && size > 0) {
7029     int offset = -before*BytesPerWord;
7030     for (int i = 0; i < size; ++i) {
7031       z_stg(val, Address(low, offset));
7032       offset +=(1*BytesPerWord);
7033     }
7034   } else {
7035     add2reg(addr, -before*BytesPerWord, low);
7036     if (after) {
7037 #ifdef ASSERT
7038       jlong check = after * BytesPerWord;
7039       assert(Immediate::is_simm32(check) && Immediate::is_simm32(-check), "value not encodable !");
7040 #endif
7041       add2reg(high, after * BytesPerWord);
7042     }
7043     NearLabel loop;
7044     bind(loop);
7045     z_stg(val, Address(addr));
7046     add2reg(addr, 8);
7047     compare64_and_branch(addr, high, bcondNotHigh, loop);
7048     if (after) {
7049       add2reg(high, -after * BytesPerWord);
7050     }
7051   }
7052   BLOCK_COMMENT("} zap memory region");
7053 }
7054 #endif // !PRODUCT
7055 
7056 SkipIfEqual::SkipIfEqual(MacroAssembler* masm, const bool* flag_addr, bool value, Register _rscratch) {
7057   _masm = masm;
7058   _masm->load_absolute_address(_rscratch, (address)flag_addr);
7059   _masm->load_and_test_int(_rscratch, Address(_rscratch));
7060   if (value) {
7061     _masm->z_brne(_label); // Skip if true, i.e. != 0.
7062   } else {
7063     _masm->z_bre(_label);  // Skip if false, i.e. == 0.
7064   }
7065 }
7066 
7067 SkipIfEqual::~SkipIfEqual() {
7068   _masm->bind(_label);
7069 }