1 /*
   2  * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2016, 2024 SAP SE. All rights reserved.
   4  * Copyright (c) 2026 IBM Corporation. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "code/debugInfoRec.hpp"
  29 #include "code/vtableStubs.hpp"
  30 #include "code/compiledIC.hpp"
  31 #include "compiler/oopMap.hpp"
  32 #include "gc/shared/barrierSetAssembler.hpp"
  33 #include "gc/shared/gcLocker.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "interpreter/interp_masm.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "nativeInst_s390.hpp"
  38 #include "oops/klass.inline.hpp"
  39 #include "prims/methodHandles.hpp"
  40 #include "registerSaver_s390.hpp"
  41 #include "runtime/continuation.hpp"
  42 #include "runtime/continuationEntry.inline.hpp"
  43 #include "runtime/jniHandles.hpp"
  44 #include "runtime/safepointMechanism.hpp"
  45 #include "runtime/sharedRuntime.hpp"
  46 #include "runtime/signature.hpp"
  47 #include "runtime/stubRoutines.hpp"
  48 #include "runtime/timerTrace.hpp"
  49 #include "runtime/vframeArray.hpp"
  50 #include "utilities/align.hpp"
  51 #include "utilities/macros.hpp"
  52 #include "vmreg_s390.inline.hpp"
  53 #ifdef COMPILER1
  54 #include "c1/c1_Runtime1.hpp"
  55 #endif
  56 #ifdef COMPILER2
  57 #include "opto/ad.hpp"
  58 #include "opto/runtime.hpp"
  59 #endif
  60 
  61 #ifdef PRODUCT
  62 #define __ masm->
  63 #else
  64 #define __ (Verbose ? (masm->block_comment(FILE_AND_LINE),masm):masm)->
  65 #endif
  66 
  67 #define BLOCK_COMMENT(str) __ block_comment(str)
  68 #define BIND(label)        bind(label); BLOCK_COMMENT(#label ":")
  69 
  70 #define RegisterSaver_LiveIntReg(regname) \
  71   { RegisterSaver::int_reg,   regname->encoding(), regname->as_VMReg() }
  72 
  73 #define RegisterSaver_LiveFloatReg(regname) \
  74   { RegisterSaver::float_reg, regname->encoding(), regname->as_VMReg() }
  75 
  76 // Registers which are not saved/restored, but still they have got a frame slot.
  77 // Used to get same frame size for RegisterSaver_LiveRegs and RegisterSaver_LiveRegsWithoutR2
  78 #define RegisterSaver_ExcludedIntReg(regname) \
  79   { RegisterSaver::excluded_reg, regname->encoding(), regname->as_VMReg() }
  80 
  81 // Registers which are not saved/restored, but still they have got a frame slot.
  82 // Used to get same frame size for RegisterSaver_LiveRegs and RegisterSaver_LiveRegsWithoutR2.
  83 #define RegisterSaver_ExcludedFloatReg(regname) \
  84   { RegisterSaver::excluded_reg, regname->encoding(), regname->as_VMReg() }
  85 
  86 #define RegisterSaver_LiveVReg(regname) \
  87   { RegisterSaver::v_reg,      regname->encoding(), regname->as_VMReg() }
  88 
  89 static const RegisterSaver::LiveRegType RegisterSaver_LiveRegs[] = {
  90   // Live registers which get spilled to the stack. Register positions
  91   // in this array correspond directly to the stack layout.
  92   //
  93   // live float registers:
  94   //
  95   RegisterSaver_LiveFloatReg(Z_F0 ),
  96   // RegisterSaver_ExcludedFloatReg(Z_F1 ), // scratch (Z_fscratch_1)
  97   RegisterSaver_LiveFloatReg(Z_F2 ),
  98   RegisterSaver_LiveFloatReg(Z_F3 ),
  99   RegisterSaver_LiveFloatReg(Z_F4 ),
 100   RegisterSaver_LiveFloatReg(Z_F5 ),
 101   RegisterSaver_LiveFloatReg(Z_F6 ),
 102   RegisterSaver_LiveFloatReg(Z_F7 ),
 103   RegisterSaver_LiveFloatReg(Z_F8 ),
 104   RegisterSaver_LiveFloatReg(Z_F9 ),
 105   RegisterSaver_LiveFloatReg(Z_F10),
 106   RegisterSaver_LiveFloatReg(Z_F11),
 107   RegisterSaver_LiveFloatReg(Z_F12),
 108   RegisterSaver_LiveFloatReg(Z_F13),
 109   RegisterSaver_LiveFloatReg(Z_F14),
 110   RegisterSaver_LiveFloatReg(Z_F15),
 111   //
 112   // RegisterSaver_ExcludedIntReg(Z_R0), // scratch
 113   // RegisterSaver_ExcludedIntReg(Z_R1), // scratch
 114   RegisterSaver_LiveIntReg(Z_R2 ),
 115   RegisterSaver_LiveIntReg(Z_R3 ),
 116   RegisterSaver_LiveIntReg(Z_R4 ),
 117   RegisterSaver_LiveIntReg(Z_R5 ),
 118   RegisterSaver_LiveIntReg(Z_R6 ),
 119   RegisterSaver_LiveIntReg(Z_R7 ),
 120   RegisterSaver_LiveIntReg(Z_R8 ),
 121   RegisterSaver_LiveIntReg(Z_R9 ),
 122   RegisterSaver_LiveIntReg(Z_R10),
 123   RegisterSaver_LiveIntReg(Z_R11),
 124   RegisterSaver_LiveIntReg(Z_R12),
 125   RegisterSaver_LiveIntReg(Z_R13),
 126   // RegisterSaver_ExcludedIntReg(Z_R14), // return pc (Saved in caller frame.)
 127   // RegisterSaver_ExcludedIntReg(Z_R15)  // stack pointer
 128 };
 129 
 130 static const RegisterSaver::LiveRegType RegisterSaver_LiveIntRegs[] = {
 131   // Live registers which get spilled to the stack. Register positions
 132   // in this array correspond directly to the stack layout.
 133   //
 134   // live float registers: All excluded, but still they get a stack slot to get same frame size.
 135   //
 136   RegisterSaver_ExcludedFloatReg(Z_F0 ),
 137   // RegisterSaver_ExcludedFloatReg(Z_F1 ), // scratch (Z_fscratch_1)
 138   RegisterSaver_ExcludedFloatReg(Z_F2 ),
 139   RegisterSaver_ExcludedFloatReg(Z_F3 ),
 140   RegisterSaver_ExcludedFloatReg(Z_F4 ),
 141   RegisterSaver_ExcludedFloatReg(Z_F5 ),
 142   RegisterSaver_ExcludedFloatReg(Z_F6 ),
 143   RegisterSaver_ExcludedFloatReg(Z_F7 ),
 144   RegisterSaver_ExcludedFloatReg(Z_F8 ),
 145   RegisterSaver_ExcludedFloatReg(Z_F9 ),
 146   RegisterSaver_ExcludedFloatReg(Z_F10),
 147   RegisterSaver_ExcludedFloatReg(Z_F11),
 148   RegisterSaver_ExcludedFloatReg(Z_F12),
 149   RegisterSaver_ExcludedFloatReg(Z_F13),
 150   RegisterSaver_ExcludedFloatReg(Z_F14),
 151   RegisterSaver_ExcludedFloatReg(Z_F15),
 152   //
 153   // RegisterSaver_ExcludedIntReg(Z_R0), // scratch
 154   // RegisterSaver_ExcludedIntReg(Z_R1), // scratch
 155   RegisterSaver_LiveIntReg(Z_R2 ),
 156   RegisterSaver_LiveIntReg(Z_R3 ),
 157   RegisterSaver_LiveIntReg(Z_R4 ),
 158   RegisterSaver_LiveIntReg(Z_R5 ),
 159   RegisterSaver_LiveIntReg(Z_R6 ),
 160   RegisterSaver_LiveIntReg(Z_R7 ),
 161   RegisterSaver_LiveIntReg(Z_R8 ),
 162   RegisterSaver_LiveIntReg(Z_R9 ),
 163   RegisterSaver_LiveIntReg(Z_R10),
 164   RegisterSaver_LiveIntReg(Z_R11),
 165   RegisterSaver_LiveIntReg(Z_R12),
 166   RegisterSaver_LiveIntReg(Z_R13),
 167   // RegisterSaver_ExcludedIntReg(Z_R14), // return pc (Saved in caller frame.)
 168   // RegisterSaver_ExcludedIntReg(Z_R15)  // stack pointer
 169 };
 170 
 171 static const RegisterSaver::LiveRegType RegisterSaver_LiveRegsWithoutR2[] = {
 172   // Live registers which get spilled to the stack. Register positions
 173   // in this array correspond directly to the stack layout.
 174   //
 175   // live float registers:
 176   //
 177   RegisterSaver_LiveFloatReg(Z_F0 ),
 178   // RegisterSaver_ExcludedFloatReg(Z_F1 ), // scratch (Z_fscratch_1)
 179   RegisterSaver_LiveFloatReg(Z_F2 ),
 180   RegisterSaver_LiveFloatReg(Z_F3 ),
 181   RegisterSaver_LiveFloatReg(Z_F4 ),
 182   RegisterSaver_LiveFloatReg(Z_F5 ),
 183   RegisterSaver_LiveFloatReg(Z_F6 ),
 184   RegisterSaver_LiveFloatReg(Z_F7 ),
 185   RegisterSaver_LiveFloatReg(Z_F8 ),
 186   RegisterSaver_LiveFloatReg(Z_F9 ),
 187   RegisterSaver_LiveFloatReg(Z_F10),
 188   RegisterSaver_LiveFloatReg(Z_F11),
 189   RegisterSaver_LiveFloatReg(Z_F12),
 190   RegisterSaver_LiveFloatReg(Z_F13),
 191   RegisterSaver_LiveFloatReg(Z_F14),
 192   RegisterSaver_LiveFloatReg(Z_F15),
 193   //
 194   // RegisterSaver_ExcludedIntReg(Z_R0), // scratch
 195   // RegisterSaver_ExcludedIntReg(Z_R1), // scratch
 196   RegisterSaver_ExcludedIntReg(Z_R2), // Omit saving R2.
 197   RegisterSaver_LiveIntReg(Z_R3 ),
 198   RegisterSaver_LiveIntReg(Z_R4 ),
 199   RegisterSaver_LiveIntReg(Z_R5 ),
 200   RegisterSaver_LiveIntReg(Z_R6 ),
 201   RegisterSaver_LiveIntReg(Z_R7 ),
 202   RegisterSaver_LiveIntReg(Z_R8 ),
 203   RegisterSaver_LiveIntReg(Z_R9 ),
 204   RegisterSaver_LiveIntReg(Z_R10),
 205   RegisterSaver_LiveIntReg(Z_R11),
 206   RegisterSaver_LiveIntReg(Z_R12),
 207   RegisterSaver_LiveIntReg(Z_R13),
 208   // RegisterSaver_ExcludedIntReg(Z_R14), // return pc (Saved in caller frame.)
 209   // RegisterSaver_ExcludedIntReg(Z_R15)  // stack pointer
 210 };
 211 
 212 // Live argument registers which get spilled to the stack.
 213 static const RegisterSaver::LiveRegType RegisterSaver_LiveArgRegs[] = {
 214   RegisterSaver_LiveFloatReg(Z_FARG1),
 215   RegisterSaver_LiveFloatReg(Z_FARG2),
 216   RegisterSaver_LiveFloatReg(Z_FARG3),
 217   RegisterSaver_LiveFloatReg(Z_FARG4),
 218   RegisterSaver_LiveIntReg(Z_ARG1),
 219   RegisterSaver_LiveIntReg(Z_ARG2),
 220   RegisterSaver_LiveIntReg(Z_ARG3),
 221   RegisterSaver_LiveIntReg(Z_ARG4),
 222   RegisterSaver_LiveIntReg(Z_ARG5)
 223 };
 224 
 225 static const RegisterSaver::LiveRegType RegisterSaver_LiveVolatileRegs[] = {
 226   // Live registers which get spilled to the stack. Register positions
 227   // in this array correspond directly to the stack layout.
 228   //
 229   // live float registers:
 230   //
 231   RegisterSaver_LiveFloatReg(Z_F0 ),
 232   // RegisterSaver_ExcludedFloatReg(Z_F1 ), // scratch (Z_fscratch_1)
 233   RegisterSaver_LiveFloatReg(Z_F2 ),
 234   RegisterSaver_LiveFloatReg(Z_F3 ),
 235   RegisterSaver_LiveFloatReg(Z_F4 ),
 236   RegisterSaver_LiveFloatReg(Z_F5 ),
 237   RegisterSaver_LiveFloatReg(Z_F6 ),
 238   RegisterSaver_LiveFloatReg(Z_F7 ),
 239   // RegisterSaver_LiveFloatReg(Z_F8 ), // non-volatile
 240   // RegisterSaver_LiveFloatReg(Z_F9 ), // non-volatile
 241   // RegisterSaver_LiveFloatReg(Z_F10), // non-volatile
 242   // RegisterSaver_LiveFloatReg(Z_F11), // non-volatile
 243   // RegisterSaver_LiveFloatReg(Z_F12), // non-volatile
 244   // RegisterSaver_LiveFloatReg(Z_F13), // non-volatile
 245   // RegisterSaver_LiveFloatReg(Z_F14), // non-volatile
 246   // RegisterSaver_LiveFloatReg(Z_F15), // non-volatile
 247   //
 248   // RegisterSaver_ExcludedIntReg(Z_R0), // scratch
 249   // RegisterSaver_ExcludedIntReg(Z_R1), // scratch
 250   RegisterSaver_LiveIntReg(Z_R2 ),
 251   RegisterSaver_LiveIntReg(Z_R3 ),
 252   RegisterSaver_LiveIntReg(Z_R4 ),
 253   RegisterSaver_LiveIntReg(Z_R5 ),
 254   // RegisterSaver_LiveIntReg(Z_R6 ), // non-volatile
 255   // RegisterSaver_LiveIntReg(Z_R7 ), // non-volatile
 256   // RegisterSaver_LiveIntReg(Z_R8 ), // non-volatile
 257   // RegisterSaver_LiveIntReg(Z_R9 ), // non-volatile
 258   // RegisterSaver_LiveIntReg(Z_R10), // non-volatile
 259   // RegisterSaver_LiveIntReg(Z_R11), // non-volatile
 260   // RegisterSaver_LiveIntReg(Z_R12), // non-volatile
 261   // RegisterSaver_LiveIntReg(Z_R13), // non-volatile
 262   // RegisterSaver_ExcludedIntReg(Z_R14), // return pc (Saved in caller frame.)
 263   // RegisterSaver_ExcludedIntReg(Z_R15)  // stack pointer
 264 };
 265 
 266 static const RegisterSaver::LiveRegType RegisterSaver_LiveVRegs[] = {
 267   // live vector registers (optional, only these are used by C2):
 268   RegisterSaver_LiveVReg( Z_V16 ),
 269   RegisterSaver_LiveVReg( Z_V17 ),
 270   RegisterSaver_LiveVReg( Z_V18 ),
 271   RegisterSaver_LiveVReg( Z_V19 ),
 272   RegisterSaver_LiveVReg( Z_V20 ),
 273   RegisterSaver_LiveVReg( Z_V21 ),
 274   RegisterSaver_LiveVReg( Z_V22 ),
 275   RegisterSaver_LiveVReg( Z_V23 ),
 276   RegisterSaver_LiveVReg( Z_V24 ),
 277   RegisterSaver_LiveVReg( Z_V25 ),
 278   RegisterSaver_LiveVReg( Z_V26 ),
 279   RegisterSaver_LiveVReg( Z_V27 ),
 280   RegisterSaver_LiveVReg( Z_V28 ),
 281   RegisterSaver_LiveVReg( Z_V29 ),
 282   RegisterSaver_LiveVReg( Z_V30 ),
 283   RegisterSaver_LiveVReg( Z_V31 )
 284 };
 285 
 286 int RegisterSaver::live_reg_save_size(RegisterSet reg_set) {
 287   int reg_space = -1;
 288   switch (reg_set) {
 289     case all_registers:           reg_space = sizeof(RegisterSaver_LiveRegs); break;
 290     case all_registers_except_r2: reg_space = sizeof(RegisterSaver_LiveRegsWithoutR2); break;
 291     case all_integer_registers:   reg_space = sizeof(RegisterSaver_LiveIntRegs); break;
 292     case all_volatile_registers:  reg_space = sizeof(RegisterSaver_LiveVolatileRegs); break;
 293     case arg_registers:           reg_space = sizeof(RegisterSaver_LiveArgRegs); break;
 294     default: ShouldNotReachHere();
 295   }
 296   return (reg_space / sizeof(RegisterSaver::LiveRegType)) * reg_size;
 297 }
 298 
 299 int RegisterSaver::calculate_vregstosave_num() {
 300   return (sizeof(RegisterSaver_LiveVRegs) / sizeof(RegisterSaver::LiveRegType));
 301 }
 302 
 303 int RegisterSaver::live_reg_frame_size(RegisterSet reg_set, bool save_vectors) {
 304   const int vregstosave_num = save_vectors ? calculate_vregstosave_num() : 0;
 305   return live_reg_save_size(reg_set) + vregstosave_num * v_reg_size + frame::z_abi_160_size;
 306 }
 307 
 308 
 309 // return_pc: Specify the register that should be stored as the return pc in the current frame.
 310 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, RegisterSet reg_set, Register return_pc, bool save_vectors) {
 311   // Record volatile registers as callee-save values in an OopMap so
 312   // their save locations will be propagated to the caller frame's
 313   // RegisterMap during StackFrameStream construction (needed for
 314   // deoptimization; see compiledVFrame::create_stack_value).
 315 
 316   // Calculate frame size.
 317   const int frame_size_in_bytes  = live_reg_frame_size(reg_set, save_vectors);
 318   const int frame_size_in_slots  = frame_size_in_bytes / sizeof(jint);
 319   const int vregstosave_num = save_vectors ? calculate_vregstosave_num() : 0;
 320   const int register_save_offset = frame_size_in_bytes - (live_reg_save_size(reg_set) + vregstosave_num * v_reg_size);
 321 
 322   // OopMap frame size is in c2 stack slots (sizeof(jint)) not bytes or words.
 323   OopMap* map = new OopMap(frame_size_in_slots, 0);
 324 
 325   int regstosave_num = 0;
 326   const RegisterSaver::LiveRegType* live_regs = nullptr;
 327 
 328   switch (reg_set) {
 329     case all_registers:
 330       regstosave_num = sizeof(RegisterSaver_LiveRegs)/sizeof(RegisterSaver::LiveRegType);
 331       live_regs      = RegisterSaver_LiveRegs;
 332       break;
 333     case all_registers_except_r2:
 334       regstosave_num = sizeof(RegisterSaver_LiveRegsWithoutR2)/sizeof(RegisterSaver::LiveRegType);;
 335       live_regs      = RegisterSaver_LiveRegsWithoutR2;
 336       break;
 337     case all_integer_registers:
 338       regstosave_num = sizeof(RegisterSaver_LiveIntRegs)/sizeof(RegisterSaver::LiveRegType);
 339       live_regs      = RegisterSaver_LiveIntRegs;
 340       break;
 341     case all_volatile_registers:
 342       regstosave_num = sizeof(RegisterSaver_LiveVolatileRegs)/sizeof(RegisterSaver::LiveRegType);
 343       live_regs      = RegisterSaver_LiveVolatileRegs;
 344       break;
 345     case arg_registers:
 346       regstosave_num = sizeof(RegisterSaver_LiveArgRegs)/sizeof(RegisterSaver::LiveRegType);;
 347       live_regs      = RegisterSaver_LiveArgRegs;
 348       break;
 349     default: ShouldNotReachHere();
 350   }
 351 
 352   // Save return pc in old frame.
 353   __ save_return_pc(return_pc);
 354 
 355   // Push a new frame (includes stack linkage).
 356   // Use return_pc as scratch for push_frame. Z_R0_scratch (the default) and Z_R1_scratch are
 357   // illegally used to pass parameters by RangeCheckStub::emit_code().
 358   __ push_frame(frame_size_in_bytes, return_pc);
 359   // We have to restore return_pc right away.
 360   // Nobody else will. Furthermore, return_pc isn't necessarily the default (Z_R14).
 361   // Nobody else knows which register we saved.
 362   __ z_lg(return_pc, _z_common_abi(return_pc) + frame_size_in_bytes, Z_SP);
 363 
 364   // Register save area in new frame starts above z_abi_160 area.
 365   int offset = register_save_offset;
 366 
 367   Register first = noreg;
 368   Register last  = noreg;
 369   int      first_offset = -1;
 370   bool     float_spilled = false;
 371 
 372   for (int i = 0; i < regstosave_num; i++, offset += reg_size) {
 373     int reg_num  = live_regs[i].reg_num;
 374     int reg_type = live_regs[i].reg_type;
 375 
 376     switch (reg_type) {
 377       case RegisterSaver::int_reg: {
 378         Register reg = as_Register(reg_num);
 379         if (last != reg->predecessor()) {
 380           if (first != noreg) {
 381             __ z_stmg(first, last, first_offset, Z_SP);
 382           }
 383           first = reg;
 384           first_offset = offset;
 385           DEBUG_ONLY(float_spilled = false);
 386         }
 387         last = reg;
 388         assert(last != Z_R0, "r0 would require special treatment");
 389         assert(!float_spilled, "for simplicity, do not mix up ints and floats in RegisterSaver_LiveRegs[]");
 390         break;
 391       }
 392 
 393       case RegisterSaver::excluded_reg: // Not saved/restored, but with dedicated slot.
 394         continue; // Continue with next loop iteration.
 395 
 396       case RegisterSaver::float_reg: {
 397         FloatRegister freg = as_FloatRegister(reg_num);
 398         __ z_std(freg, offset, Z_SP);
 399         DEBUG_ONLY(float_spilled = true);
 400         break;
 401       }
 402 
 403       default:
 404         ShouldNotReachHere();
 405         break;
 406     }
 407 
 408     map->set_callee_saved(VMRegImpl::stack2reg(offset >> 2), live_regs[i].vmreg);
 409   }
 410   assert(first != noreg, "Should spill at least one int reg.");
 411   __ z_stmg(first, last, first_offset, Z_SP);
 412 
 413   for (int i = 0; i < vregstosave_num; i++, offset += v_reg_size) {
 414     int reg_num  = RegisterSaver_LiveVRegs[i].reg_num;
 415 
 416     __ z_vst(as_VectorRegister(reg_num), Address(Z_SP, offset));
 417 
 418     map->set_callee_saved(VMRegImpl::stack2reg(offset>>2),
 419                    RegisterSaver_LiveVRegs[i].vmreg);
 420   }
 421 
 422   assert(offset == frame_size_in_bytes, "consistency check");
 423 
 424   // And we're done.
 425   return map;
 426 }
 427 
 428 
 429 // Generate the OopMap (again, regs where saved before).
 430 OopMap* RegisterSaver::generate_oop_map(MacroAssembler* masm, RegisterSet reg_set) {
 431   // Calculate frame size.
 432   const int frame_size_in_bytes  = live_reg_frame_size(reg_set);
 433   const int frame_size_in_slots  = frame_size_in_bytes / sizeof(jint);
 434   const int register_save_offset = frame_size_in_bytes - live_reg_save_size(reg_set);
 435 
 436   // OopMap frame size is in c2 stack slots (sizeof(jint)) not bytes or words.
 437   OopMap* map = new OopMap(frame_size_in_slots, 0);
 438 
 439   int regstosave_num = 0;
 440   const RegisterSaver::LiveRegType* live_regs = nullptr;
 441 
 442   switch (reg_set) {
 443     case all_registers:
 444       regstosave_num = sizeof(RegisterSaver_LiveRegs)/sizeof(RegisterSaver::LiveRegType);
 445       live_regs      = RegisterSaver_LiveRegs;
 446       break;
 447     case all_registers_except_r2:
 448       regstosave_num = sizeof(RegisterSaver_LiveRegsWithoutR2)/sizeof(RegisterSaver::LiveRegType);;
 449       live_regs      = RegisterSaver_LiveRegsWithoutR2;
 450       break;
 451     case all_integer_registers:
 452       regstosave_num = sizeof(RegisterSaver_LiveIntRegs)/sizeof(RegisterSaver::LiveRegType);
 453       live_regs      = RegisterSaver_LiveIntRegs;
 454       break;
 455     case all_volatile_registers:
 456       regstosave_num = sizeof(RegisterSaver_LiveVolatileRegs)/sizeof(RegisterSaver::LiveRegType);
 457       live_regs      = RegisterSaver_LiveVolatileRegs;
 458       break;
 459     case arg_registers:
 460       regstosave_num = sizeof(RegisterSaver_LiveArgRegs)/sizeof(RegisterSaver::LiveRegType);;
 461       live_regs      = RegisterSaver_LiveArgRegs;
 462       break;
 463     default: ShouldNotReachHere();
 464   }
 465 
 466   // Register save area in new frame starts above z_abi_160 area.
 467   int offset = register_save_offset;
 468   for (int i = 0; i < regstosave_num; i++) {
 469     if (live_regs[i].reg_type < RegisterSaver::excluded_reg) {
 470       map->set_callee_saved(VMRegImpl::stack2reg(offset>>2), live_regs[i].vmreg);
 471     }
 472     offset += reg_size;
 473   }
 474 #ifdef ASSERT
 475   assert(offset == frame_size_in_bytes, "consistency check");
 476 #endif
 477   return map;
 478 }
 479 
 480 
 481 // Pop the current frame and restore all the registers that we saved.
 482 void RegisterSaver::restore_live_registers(MacroAssembler* masm, RegisterSet reg_set, bool save_vectors) {
 483   int offset;
 484   const int vregstosave_num = save_vectors ? calculate_vregstosave_num() : 0;
 485   const int register_save_offset = live_reg_frame_size(reg_set, save_vectors) - (live_reg_save_size(reg_set) + vregstosave_num * v_reg_size);
 486 
 487   Register first = noreg;
 488   Register last = noreg;
 489   int      first_offset = -1;
 490   bool     float_spilled = false;
 491 
 492   int regstosave_num = 0;
 493   const RegisterSaver::LiveRegType* live_regs = nullptr;
 494 
 495   switch (reg_set) {
 496     case all_registers:
 497       regstosave_num = sizeof(RegisterSaver_LiveRegs)/sizeof(RegisterSaver::LiveRegType);;
 498       live_regs      = RegisterSaver_LiveRegs;
 499       break;
 500     case all_registers_except_r2:
 501       regstosave_num = sizeof(RegisterSaver_LiveRegsWithoutR2)/sizeof(RegisterSaver::LiveRegType);;
 502       live_regs      = RegisterSaver_LiveRegsWithoutR2;
 503       break;
 504     case all_integer_registers:
 505       regstosave_num = sizeof(RegisterSaver_LiveIntRegs)/sizeof(RegisterSaver::LiveRegType);
 506       live_regs      = RegisterSaver_LiveIntRegs;
 507       break;
 508     case all_volatile_registers:
 509       regstosave_num = sizeof(RegisterSaver_LiveVolatileRegs)/sizeof(RegisterSaver::LiveRegType);;
 510       live_regs      = RegisterSaver_LiveVolatileRegs;
 511       break;
 512     case arg_registers:
 513       regstosave_num = sizeof(RegisterSaver_LiveArgRegs)/sizeof(RegisterSaver::LiveRegType);;
 514       live_regs      = RegisterSaver_LiveArgRegs;
 515       break;
 516     default: ShouldNotReachHere();
 517   }
 518 
 519   // Restore all registers (ints and floats).
 520 
 521   // Register save area in new frame starts above z_abi_160 area.
 522   offset = register_save_offset;
 523 
 524   for (int i = 0; i < regstosave_num; i++, offset += reg_size) {
 525     int reg_num  = live_regs[i].reg_num;
 526     int reg_type = live_regs[i].reg_type;
 527 
 528     switch (reg_type) {
 529       case RegisterSaver::excluded_reg:
 530         continue; // Continue with next loop iteration.
 531 
 532       case RegisterSaver::int_reg: {
 533         Register reg = as_Register(reg_num);
 534         if (last != reg->predecessor()) {
 535           if (first != noreg) {
 536             __ z_lmg(first, last, first_offset, Z_SP);
 537           }
 538           first = reg;
 539           first_offset = offset;
 540           DEBUG_ONLY(float_spilled = false);
 541         }
 542         last = reg;
 543         assert(last != Z_R0, "r0 would require special treatment");
 544         assert(!float_spilled, "for simplicity, do not mix up ints and floats in RegisterSaver_LiveRegs[]");
 545         break;
 546       }
 547 
 548       case RegisterSaver::float_reg: {
 549         FloatRegister freg = as_FloatRegister(reg_num);
 550         __ z_ld(freg, offset, Z_SP);
 551         DEBUG_ONLY(float_spilled = true);
 552         break;
 553       }
 554 
 555       default:
 556         ShouldNotReachHere();
 557     }
 558   }
 559   assert(first != noreg, "Should spill at least one int reg.");
 560   __ z_lmg(first, last, first_offset, Z_SP);
 561 
 562   for (int i = 0; i < vregstosave_num; i++, offset += v_reg_size) {
 563     int reg_num  = RegisterSaver_LiveVRegs[i].reg_num;
 564 
 565     __ z_vl(as_VectorRegister(reg_num), Address(Z_SP, offset));
 566   }
 567 
 568   // Pop the frame.
 569   __ pop_frame();
 570 
 571   // Restore the flags.
 572   __ restore_return_pc();
 573 }
 574 
 575 
 576 // Pop the current frame and restore the registers that might be holding a result.
 577 void RegisterSaver::restore_result_registers(MacroAssembler* masm, bool save_vectors) {
 578   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 579                                    sizeof(RegisterSaver::LiveRegType);
 580   const int vecregstosave_num    = save_vectors ?  calculate_vregstosave_num() : 0;
 581   const int vreg_save_size   = vecregstosave_num * v_reg_size;
 582   const int register_save_offset = live_reg_frame_size(all_registers, save_vectors) - (live_reg_save_size(all_registers) + vreg_save_size);
 583 
 584   // Restore all result registers (ints and floats).
 585   int offset = register_save_offset;
 586   for (int i = 0; i < regstosave_num; i++, offset += reg_size) {
 587     int reg_num = RegisterSaver_LiveRegs[i].reg_num;
 588     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 589     switch (reg_type) {
 590       case RegisterSaver::excluded_reg:
 591         continue; // Continue with next loop iteration.
 592       case RegisterSaver::int_reg: {
 593         if (as_Register(reg_num) == Z_RET) { // int result_reg
 594           __ z_lg(as_Register(reg_num), offset, Z_SP);
 595         }
 596         break;
 597       }
 598       case RegisterSaver::float_reg: {
 599         if (as_FloatRegister(reg_num) == Z_FRET) { // float result_reg
 600           __ z_ld(as_FloatRegister(reg_num), offset, Z_SP);
 601         }
 602         break;
 603       }
 604       default:
 605         ShouldNotReachHere();
 606     }
 607   }
 608   assert(offset == live_reg_frame_size(all_registers, save_vectors) - (save_vectors ? vreg_save_size : 0) , "consistency check");
 609 }
 610 
 611 // ---------------------------------------------------------------------------
 612 void SharedRuntime::save_native_result(MacroAssembler * masm,
 613                                        BasicType ret_type,
 614                                        int frame_slots) {
 615   Address memaddr(Z_SP, frame_slots * VMRegImpl::stack_slot_size);
 616 
 617   switch (ret_type) {
 618     case T_BOOLEAN:  // Save shorter types as int. Do we need sign extension at restore??
 619     case T_BYTE:
 620     case T_CHAR:
 621     case T_SHORT:
 622     case T_INT:
 623       __ reg2mem_opt(Z_RET, memaddr, false);
 624       break;
 625     case T_OBJECT:   // Save pointer types as long.
 626     case T_ARRAY:
 627     case T_ADDRESS:
 628     case T_VOID:
 629     case T_LONG:
 630       __ reg2mem_opt(Z_RET, memaddr);
 631       break;
 632     case T_FLOAT:
 633       __ freg2mem_opt(Z_FRET, memaddr, false);
 634       break;
 635     case T_DOUBLE:
 636       __ freg2mem_opt(Z_FRET, memaddr);
 637       break;
 638     default:
 639       ShouldNotReachHere();
 640       break;
 641   }
 642 }
 643 
 644 void SharedRuntime::restore_native_result(MacroAssembler *masm,
 645                                           BasicType       ret_type,
 646                                           int             frame_slots) {
 647   Address memaddr(Z_SP, frame_slots * VMRegImpl::stack_slot_size);
 648 
 649   switch (ret_type) {
 650     case T_BOOLEAN:  // Restore shorter types as int. Do we need sign extension at restore??
 651     case T_BYTE:
 652     case T_CHAR:
 653     case T_SHORT:
 654     case T_INT:
 655       __ mem2reg_opt(Z_RET, memaddr, false);
 656       break;
 657     case T_OBJECT:   // Restore pointer types as long.
 658     case T_ARRAY:
 659     case T_ADDRESS:
 660     case T_VOID:
 661     case T_LONG:
 662       __ mem2reg_opt(Z_RET, memaddr);
 663       break;
 664     case T_FLOAT:
 665       __ mem2freg_opt(Z_FRET, memaddr, false);
 666       break;
 667     case T_DOUBLE:
 668       __ mem2freg_opt(Z_FRET, memaddr);
 669       break;
 670     default:
 671       ShouldNotReachHere();
 672       break;
 673   }
 674 }
 675 
 676 // ---------------------------------------------------------------------------
 677 // Read the array of BasicTypes from a signature, and compute where the
 678 // arguments should go. Values in the VMRegPair regs array refer to 4-byte
 679 // quantities. Values less than VMRegImpl::stack0 are registers, those above
 680 // refer to 4-byte stack slots. All stack slots are based off of the stack pointer
 681 // as framesizes are fixed.
 682 // VMRegImpl::stack0 refers to the first slot 0(sp).
 683 // VMRegImpl::stack0+1 refers to the memory word 4-byes higher. Registers
 684 // up to Register::number_of_registers are the 64-bit integer registers.
 685 
 686 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 687 // either 32-bit or 64-bit depending on the build. The OUTPUTS are in 32-bit
 688 // units regardless of build.
 689 
 690 // The Java calling convention is a "shifted" version of the C ABI.
 691 // By skipping the first C ABI register we can call non-static jni methods
 692 // with small numbers of arguments without having to shuffle the arguments
 693 // at all. Since we control the java ABI we ought to at least get some
 694 // advantage out of it.
 695 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 696                                            VMRegPair *regs,
 697                                            int total_args_passed) {
 698   // c2c calling conventions for compiled-compiled calls.
 699 
 700   // An int/float occupies 1 slot here.
 701   const int inc_stk_for_intfloat   = 1; // 1 slots for ints and floats.
 702   const int inc_stk_for_longdouble = 2; // 2 slots for longs and doubles.
 703 
 704   const VMReg z_iarg_reg[5] = {
 705     Z_R2->as_VMReg(),
 706     Z_R3->as_VMReg(),
 707     Z_R4->as_VMReg(),
 708     Z_R5->as_VMReg(),
 709     Z_R6->as_VMReg()
 710   };
 711   const VMReg z_farg_reg[4] = {
 712     Z_F0->as_VMReg(),
 713     Z_F2->as_VMReg(),
 714     Z_F4->as_VMReg(),
 715     Z_F6->as_VMReg()
 716   };
 717   const int z_num_iarg_registers = sizeof(z_iarg_reg) / sizeof(z_iarg_reg[0]);
 718   const int z_num_farg_registers = sizeof(z_farg_reg) / sizeof(z_farg_reg[0]);
 719 
 720   assert(Register::number_of_arg_registers == z_num_iarg_registers, "iarg reg count mismatch");
 721   assert(FloatRegister::number_of_arg_registers == z_num_farg_registers, "farg reg count mismatch");
 722 
 723   int i;
 724   int stk = 0;
 725   int ireg = 0;
 726   int freg = 0;
 727 
 728   for (int i = 0; i < total_args_passed; ++i) {
 729     switch (sig_bt[i]) {
 730       case T_BOOLEAN:
 731       case T_CHAR:
 732       case T_BYTE:
 733       case T_SHORT:
 734       case T_INT:
 735         if (ireg < z_num_iarg_registers) {
 736           // Put int/ptr in register.
 737           regs[i].set1(z_iarg_reg[ireg]);
 738           ++ireg;
 739         } else {
 740           // Put int/ptr on stack.
 741           regs[i].set1(VMRegImpl::stack2reg(stk));
 742           stk += inc_stk_for_intfloat;
 743         }
 744         break;
 745       case T_LONG:
 746         assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 747         if (ireg < z_num_iarg_registers) {
 748           // Put long in register.
 749           regs[i].set2(z_iarg_reg[ireg]);
 750           ++ireg;
 751         } else {
 752           // Put long on stack and align to 2 slots.
 753           if (stk & 0x1) { ++stk; }
 754           regs[i].set2(VMRegImpl::stack2reg(stk));
 755           stk += inc_stk_for_longdouble;
 756         }
 757         break;
 758       case T_OBJECT:
 759       case T_ARRAY:
 760       case T_ADDRESS:
 761         if (ireg < z_num_iarg_registers) {
 762           // Put ptr in register.
 763           regs[i].set2(z_iarg_reg[ireg]);
 764           ++ireg;
 765         } else {
 766           // Put ptr on stack and align to 2 slots, because
 767           // "64-bit pointers record oop-ishness on 2 aligned adjacent
 768           // registers." (see OopFlow::build_oop_map).
 769           if (stk & 0x1) { ++stk; }
 770           regs[i].set2(VMRegImpl::stack2reg(stk));
 771           stk += inc_stk_for_longdouble;
 772         }
 773         break;
 774       case T_FLOAT:
 775         if (freg < z_num_farg_registers) {
 776           // Put float in register.
 777           regs[i].set1(z_farg_reg[freg]);
 778           ++freg;
 779         } else {
 780           // Put float on stack.
 781           regs[i].set1(VMRegImpl::stack2reg(stk));
 782           stk += inc_stk_for_intfloat;
 783         }
 784         break;
 785       case T_DOUBLE:
 786         assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 787         if (freg < z_num_farg_registers) {
 788           // Put double in register.
 789           regs[i].set2(z_farg_reg[freg]);
 790           ++freg;
 791         } else {
 792           // Put double on stack and align to 2 slots.
 793           if (stk & 0x1) { ++stk; }
 794           regs[i].set2(VMRegImpl::stack2reg(stk));
 795           stk += inc_stk_for_longdouble;
 796         }
 797         break;
 798       case T_VOID:
 799         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 800         // Do not count halves.
 801         regs[i].set_bad();
 802         break;
 803       default:
 804         ShouldNotReachHere();
 805     }
 806   }
 807   return stk;
 808 }
 809 
 810 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 811                                         VMRegPair *regs,
 812                                         int total_args_passed) {
 813 
 814   // Calling conventions for C runtime calls and calls to JNI native methods.
 815   const VMReg z_iarg_reg[5] = {
 816     Z_R2->as_VMReg(),
 817     Z_R3->as_VMReg(),
 818     Z_R4->as_VMReg(),
 819     Z_R5->as_VMReg(),
 820     Z_R6->as_VMReg()
 821   };
 822   const VMReg z_farg_reg[4] = {
 823     Z_F0->as_VMReg(),
 824     Z_F2->as_VMReg(),
 825     Z_F4->as_VMReg(),
 826     Z_F6->as_VMReg()
 827   };
 828   const int z_num_iarg_registers = sizeof(z_iarg_reg) / sizeof(z_iarg_reg[0]);
 829   const int z_num_farg_registers = sizeof(z_farg_reg) / sizeof(z_farg_reg[0]);
 830 
 831   // Check calling conventions consistency.
 832   assert(Register::number_of_arg_registers == z_num_iarg_registers, "iarg reg count mismatch");
 833   assert(FloatRegister::number_of_arg_registers == z_num_farg_registers, "farg reg count mismatch");
 834 
 835   // Avoid passing C arguments in the wrong stack slots.
 836 
 837   // 'Stk' counts stack slots. Due to alignment, 32 bit values occupy
 838   // 2 such slots, like 64 bit values do.
 839   const int inc_stk_for_intfloat   = 2; // 2 slots for ints and floats.
 840   const int inc_stk_for_longdouble = 2; // 2 slots for longs and doubles.
 841 
 842   int i;
 843   // Leave room for C-compatible ABI
 844   int stk = (frame::z_abi_160_size - frame::z_jit_out_preserve_size) / VMRegImpl::stack_slot_size;
 845   int freg = 0;
 846   int ireg = 0;
 847 
 848   // We put the first 5 arguments into registers and the rest on the
 849   // stack. Float arguments are already in their argument registers
 850   // due to c2c calling conventions (see calling_convention).
 851   for (int i = 0; i < total_args_passed; ++i) {
 852     switch (sig_bt[i]) {
 853       case T_BOOLEAN:
 854       case T_CHAR:
 855       case T_BYTE:
 856       case T_SHORT:
 857       case T_INT:
 858         // Fall through, handle as long.
 859       case T_LONG:
 860       case T_OBJECT:
 861       case T_ARRAY:
 862       case T_ADDRESS:
 863       case T_METADATA:
 864         // Oops are already boxed if required (JNI).
 865         if (ireg < z_num_iarg_registers) {
 866           regs[i].set2(z_iarg_reg[ireg]);
 867           ++ireg;
 868         } else {
 869           regs[i].set2(VMRegImpl::stack2reg(stk));
 870           stk += inc_stk_for_longdouble;
 871         }
 872         break;
 873       case T_FLOAT:
 874         if (freg < z_num_farg_registers) {
 875           regs[i].set1(z_farg_reg[freg]);
 876           ++freg;
 877         } else {
 878           regs[i].set1(VMRegImpl::stack2reg(stk+1));
 879           stk +=  inc_stk_for_intfloat;
 880         }
 881         break;
 882       case T_DOUBLE:
 883         assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 884         if (freg < z_num_farg_registers) {
 885           regs[i].set2(z_farg_reg[freg]);
 886           ++freg;
 887         } else {
 888           // Put double on stack.
 889           regs[i].set2(VMRegImpl::stack2reg(stk));
 890           stk += inc_stk_for_longdouble;
 891         }
 892         break;
 893       case T_VOID:
 894         // Do not count halves.
 895         regs[i].set_bad();
 896         break;
 897       default:
 898         ShouldNotReachHere();
 899     }
 900   }
 901   return align_up(stk, 2);
 902 }
 903 
 904 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
 905                                              uint num_bits,
 906                                              uint total_args_passed) {
 907   Unimplemented();
 908   return 0;
 909 }
 910 
 911 ////////////////////////////////////////////////////////////////////////
 912 //
 913 //  Argument shufflers
 914 //
 915 ////////////////////////////////////////////////////////////////////////
 916 
 917 //----------------------------------------------------------------------
 918 // The java_calling_convention describes stack locations as ideal slots on
 919 // a frame with no abi restrictions. Since we must observe abi restrictions
 920 // (like the placement of the register window) the slots must be biased by
 921 // the following value.
 922 //----------------------------------------------------------------------
 923 static int reg2slot(VMReg r) {
 924   return r->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 925 }
 926 
 927 static int reg2offset(VMReg r) {
 928   return reg2slot(r) * VMRegImpl::stack_slot_size;
 929 }
 930 
 931 static void verify_oop_args(MacroAssembler *masm,
 932                             int total_args_passed,
 933                             const BasicType *sig_bt,
 934                             const VMRegPair *regs) {
 935   if (!VerifyOops) { return; }
 936 
 937   for (int i = 0; i < total_args_passed; i++) {
 938     if (is_reference_type(sig_bt[i])) {
 939       VMReg r = regs[i].first();
 940       assert(r->is_valid(), "bad oop arg");
 941 
 942       if (r->is_stack()) {
 943         __ z_lg(Z_R0_scratch,
 944                 Address(Z_SP, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
 945         __ verify_oop(Z_R0_scratch, FILE_AND_LINE);
 946       } else {
 947         __ verify_oop(r->as_Register(), FILE_AND_LINE);
 948       }
 949     }
 950   }
 951 }
 952 
 953 static void gen_special_dispatch(MacroAssembler *masm,
 954                                  int total_args_passed,
 955                                  vmIntrinsics::ID special_dispatch,
 956                                  const BasicType *sig_bt,
 957                                  const VMRegPair *regs) {
 958   verify_oop_args(masm, total_args_passed, sig_bt, regs);
 959 
 960   // Now write the args into the outgoing interpreter space.
 961   bool     has_receiver   = false;
 962   Register receiver_reg   = noreg;
 963   int      member_arg_pos = -1;
 964   Register member_reg     = noreg;
 965   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(special_dispatch);
 966 
 967   if (ref_kind != 0) {
 968     member_arg_pos = total_args_passed - 1;  // trailing MemberName argument
 969     member_reg = Z_R9;                       // Known to be free at this point.
 970     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
 971   } else if (special_dispatch == vmIntrinsics::_linkToNative) {
 972     member_arg_pos = total_args_passed - 1;  // trailing NativeEntryPoint argument
 973     member_reg = Z_R9;  // known to be free at this point
 974   } else {
 975     guarantee(special_dispatch == vmIntrinsics::_invokeBasic,
 976               "special_dispatch=%d", vmIntrinsics::as_int(special_dispatch));
 977     has_receiver = true;
 978   }
 979 
 980   if (member_reg != noreg) {
 981     // Load the member_arg into register, if necessary.
 982     assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob");
 983     assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object");
 984 
 985     VMReg r = regs[member_arg_pos].first();
 986     assert(r->is_valid(), "bad member arg");
 987 
 988     if (r->is_stack()) {
 989       __ z_lg(member_reg, Address(Z_SP, reg2offset(r)));
 990     } else {
 991       // No data motion is needed.
 992       member_reg = r->as_Register();
 993     }
 994   }
 995 
 996   if (has_receiver) {
 997     // Make sure the receiver is loaded into a register.
 998     assert(total_args_passed > 0, "oob");
 999     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1000 
1001     VMReg r = regs[0].first();
1002     assert(r->is_valid(), "bad receiver arg");
1003 
1004     if (r->is_stack()) {
1005       // Porting note: This assumes that compiled calling conventions always
1006       // pass the receiver oop in a register. If this is not true on some
1007       // platform, pick a temp and load the receiver from stack.
1008       assert(false, "receiver always in a register");
1009       receiver_reg = Z_R13;  // Known to be free at this point.
1010       __ z_lg(receiver_reg, Address(Z_SP, reg2offset(r)));
1011     } else {
1012       // No data motion is needed.
1013       receiver_reg = r->as_Register();
1014     }
1015   }
1016 
1017   // Figure out which address we are really jumping to:
1018   MethodHandles::generate_method_handle_dispatch(masm, special_dispatch,
1019                                                  receiver_reg, member_reg,
1020                                                  /*for_compiler_entry:*/ true);
1021 }
1022 
1023 ////////////////////////////////////////////////////////////////////////
1024 //
1025 //  Argument shufflers
1026 //
1027 ////////////////////////////////////////////////////////////////////////
1028 
1029 // Is the size of a vector size (in bytes) bigger than a size saved by default?
1030 // 8 bytes registers are saved by default on z/Architecture.
1031 bool SharedRuntime::is_wide_vector(int size) {
1032   // Note, MaxVectorSize == 8/16 on this platform.
1033   assert(size <= (SuperwordUseVX ? 16 : 8), "%d bytes vectors are not supported", size);
1034   return size > 8;
1035 }
1036 
1037 //----------------------------------------------------------------------
1038 // An oop arg. Must pass a handle not the oop itself
1039 //----------------------------------------------------------------------
1040 static void object_move(MacroAssembler *masm,
1041                         OopMap *map,
1042                         int oop_handle_offset,
1043                         int framesize_in_slots,
1044                         VMRegPair src,
1045                         VMRegPair dst,
1046                         bool is_receiver,
1047                         int *receiver_offset) {
1048   int frame_offset = framesize_in_slots*VMRegImpl::stack_slot_size;
1049 
1050   assert(!is_receiver || (is_receiver && (*receiver_offset == -1)), "only one receiving object per call, please.");
1051 
1052   // Must pass a handle. First figure out the location we use as a handle.
1053 
1054   if (src.first()->is_stack()) {
1055     // Oop is already on the stack, put handle on stack or in register
1056     // If handle will be on the stack, use temp reg to calculate it.
1057     Register rHandle = dst.first()->is_stack() ? Z_R1 : dst.first()->as_Register();
1058     Label    skip;
1059     int      slot_in_older_frame = reg2slot(src.first());
1060 
1061     guarantee(!is_receiver, "expecting receiver in register");
1062     map->set_oop(VMRegImpl::stack2reg(slot_in_older_frame + framesize_in_slots));
1063 
1064     __ add2reg(rHandle, reg2offset(src.first())+frame_offset, Z_SP);
1065     __ load_and_test_long(Z_R0, Address(rHandle));
1066     __ z_brne(skip);
1067     // Use a null handle if oop is null.
1068     __ clear_reg(rHandle, true, false);
1069     __ bind(skip);
1070 
1071     // Copy handle to the right place (register or stack).
1072     if (dst.first()->is_stack()) {
1073       __ z_stg(rHandle, reg2offset(dst.first()), Z_SP);
1074     } // else
1075       // nothing to do. rHandle uses the correct register
1076   } else {
1077     // Oop is passed in an input register. We must flush it to the stack.
1078     const Register rOop = src.first()->as_Register();
1079     const Register rHandle = dst.first()->is_stack() ? Z_R1 : dst.first()->as_Register();
1080     int            oop_slot = (rOop->encoding()-Z_ARG1->encoding()) * VMRegImpl::slots_per_word + oop_handle_offset;
1081     int            oop_slot_offset = oop_slot*VMRegImpl::stack_slot_size;
1082     NearLabel skip;
1083 
1084     if (is_receiver) {
1085       *receiver_offset = oop_slot_offset;
1086     }
1087     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1088 
1089     // Flush Oop to stack, calculate handle.
1090     __ z_stg(rOop, oop_slot_offset, Z_SP);
1091     __ add2reg(rHandle, oop_slot_offset, Z_SP);
1092 
1093     // If Oop is null, use a null handle.
1094     __ compare64_and_branch(rOop, (RegisterOrConstant)0L, Assembler::bcondNotEqual, skip);
1095     __ clear_reg(rHandle, true, false);
1096     __ bind(skip);
1097 
1098     // Copy handle to the right place (register or stack).
1099     if (dst.first()->is_stack()) {
1100       __ z_stg(rHandle, reg2offset(dst.first()), Z_SP);
1101     } // else
1102       // nothing to do here, since rHandle = dst.first()->as_Register in this case.
1103   }
1104 }
1105 
1106 //----------------------------------------------------------------------
1107 // A float arg. May have to do float reg to int reg conversion
1108 //----------------------------------------------------------------------
1109 static void float_move(MacroAssembler *masm,
1110                        VMRegPair src,
1111                        VMRegPair dst,
1112                        int framesize_in_slots,
1113                        int workspace_slot_offset) {
1114   int frame_offset = framesize_in_slots * VMRegImpl::stack_slot_size;
1115   int workspace_offset = workspace_slot_offset * VMRegImpl::stack_slot_size;
1116 
1117   // We do not accept an argument in a VMRegPair to be spread over two slots,
1118   // no matter what physical location (reg or stack) the slots may have.
1119   // We just check for the unaccepted slot to be invalid.
1120   assert(!src.second()->is_valid(), "float in arg spread over two slots");
1121   assert(!dst.second()->is_valid(), "float out arg spread over two slots");
1122 
1123   if (src.first()->is_stack()) {
1124     if (dst.first()->is_stack()) {
1125       // stack -> stack. The easiest of the bunch.
1126       __ z_mvc(Address(Z_SP, reg2offset(dst.first())),
1127                Address(Z_SP, reg2offset(src.first()) + frame_offset), sizeof(float));
1128     } else {
1129       // stack to reg
1130       Address memaddr(Z_SP, reg2offset(src.first()) + frame_offset);
1131       if (dst.first()->is_Register()) {
1132         __ mem2reg_opt(dst.first()->as_Register(), memaddr, false);
1133       } else {
1134         __ mem2freg_opt(dst.first()->as_FloatRegister(), memaddr, false);
1135       }
1136     }
1137   } else if (src.first()->is_Register()) {
1138     if (dst.first()->is_stack()) {
1139       // gpr -> stack
1140       __ reg2mem_opt(src.first()->as_Register(),
1141                      Address(Z_SP, reg2offset(dst.first()), false ));
1142     } else {
1143       if (dst.first()->is_Register()) {
1144         // gpr -> gpr
1145         __ move_reg_if_needed(dst.first()->as_Register(), T_INT,
1146                               src.first()->as_Register(), T_INT);
1147       } else {
1148         if (VM_Version::has_FPSupportEnhancements()) {
1149           // gpr -> fpr. Exploit z10 capability of direct transfer.
1150           __ z_ldgr(dst.first()->as_FloatRegister(), src.first()->as_Register());
1151         } else {
1152           // gpr -> fpr. Use work space on stack to transfer data.
1153           Address   stackaddr(Z_SP, workspace_offset);
1154 
1155           __ reg2mem_opt(src.first()->as_Register(), stackaddr, false);
1156           __ mem2freg_opt(dst.first()->as_FloatRegister(), stackaddr, false);
1157         }
1158       }
1159     }
1160   } else {
1161     if (dst.first()->is_stack()) {
1162       // fpr -> stack
1163       __ freg2mem_opt(src.first()->as_FloatRegister(),
1164                       Address(Z_SP, reg2offset(dst.first())), false);
1165     } else {
1166       if (dst.first()->is_Register()) {
1167         if (VM_Version::has_FPSupportEnhancements()) {
1168           // fpr -> gpr.
1169           __ z_lgdr(dst.first()->as_Register(), src.first()->as_FloatRegister());
1170         } else {
1171           // fpr -> gpr. Use work space on stack to transfer data.
1172           Address   stackaddr(Z_SP, workspace_offset);
1173 
1174           __ freg2mem_opt(src.first()->as_FloatRegister(), stackaddr, false);
1175           __ mem2reg_opt(dst.first()->as_Register(), stackaddr, false);
1176         }
1177       } else {
1178         // fpr -> fpr
1179         __ move_freg_if_needed(dst.first()->as_FloatRegister(), T_FLOAT,
1180                                src.first()->as_FloatRegister(), T_FLOAT);
1181       }
1182     }
1183   }
1184 }
1185 
1186 //----------------------------------------------------------------------
1187 // A double arg. May have to do double reg to long reg conversion
1188 //----------------------------------------------------------------------
1189 static void double_move(MacroAssembler *masm,
1190                         VMRegPair src,
1191                         VMRegPair dst,
1192                         int framesize_in_slots,
1193                         int workspace_slot_offset) {
1194   int frame_offset = framesize_in_slots*VMRegImpl::stack_slot_size;
1195   int workspace_offset = workspace_slot_offset*VMRegImpl::stack_slot_size;
1196 
1197   // Since src is always a java calling convention we know that the
1198   // src pair is always either all registers or all stack (and aligned?)
1199 
1200   if (src.first()->is_stack()) {
1201     if (dst.first()->is_stack()) {
1202       // stack -> stack. The easiest of the bunch.
1203       __ z_mvc(Address(Z_SP, reg2offset(dst.first())),
1204                Address(Z_SP, reg2offset(src.first()) + frame_offset), sizeof(double));
1205     } else {
1206       // stack to reg
1207       Address stackaddr(Z_SP, reg2offset(src.first()) + frame_offset);
1208 
1209       if (dst.first()->is_Register()) {
1210         __ mem2reg_opt(dst.first()->as_Register(), stackaddr);
1211       } else {
1212         __ mem2freg_opt(dst.first()->as_FloatRegister(), stackaddr);
1213       }
1214     }
1215   } else if (src.first()->is_Register()) {
1216     if (dst.first()->is_stack()) {
1217       // gpr -> stack
1218       __ reg2mem_opt(src.first()->as_Register(),
1219                      Address(Z_SP, reg2offset(dst.first())));
1220     } else {
1221       if (dst.first()->is_Register()) {
1222         // gpr -> gpr
1223         __ move_reg_if_needed(dst.first()->as_Register(), T_LONG,
1224                               src.first()->as_Register(), T_LONG);
1225       } else {
1226         if (VM_Version::has_FPSupportEnhancements()) {
1227           // gpr -> fpr. Exploit z10 capability of direct transfer.
1228           __ z_ldgr(dst.first()->as_FloatRegister(), src.first()->as_Register());
1229         } else {
1230           // gpr -> fpr. Use work space on stack to transfer data.
1231           Address stackaddr(Z_SP, workspace_offset);
1232           __ reg2mem_opt(src.first()->as_Register(), stackaddr);
1233           __ mem2freg_opt(dst.first()->as_FloatRegister(), stackaddr);
1234         }
1235       }
1236     }
1237   } else {
1238     if (dst.first()->is_stack()) {
1239       // fpr -> stack
1240       __ freg2mem_opt(src.first()->as_FloatRegister(),
1241                       Address(Z_SP, reg2offset(dst.first())));
1242     } else {
1243       if (dst.first()->is_Register()) {
1244         if (VM_Version::has_FPSupportEnhancements()) {
1245           // fpr -> gpr. Exploit z10 capability of direct transfer.
1246           __ z_lgdr(dst.first()->as_Register(), src.first()->as_FloatRegister());
1247         } else {
1248           // fpr -> gpr. Use work space on stack to transfer data.
1249           Address stackaddr(Z_SP, workspace_offset);
1250 
1251           __ freg2mem_opt(src.first()->as_FloatRegister(), stackaddr);
1252           __ mem2reg_opt(dst.first()->as_Register(), stackaddr);
1253         }
1254       } else {
1255         // fpr -> fpr
1256         // In theory these overlap but the ordering is such that this is likely a nop.
1257         __ move_freg_if_needed(dst.first()->as_FloatRegister(), T_DOUBLE,
1258                                src.first()->as_FloatRegister(), T_DOUBLE);
1259       }
1260     }
1261   }
1262 }
1263 
1264 //----------------------------------------------------------------------
1265 // A long arg.
1266 //----------------------------------------------------------------------
1267 static void long_move(MacroAssembler *masm,
1268                       VMRegPair src,
1269                       VMRegPair dst,
1270                       int framesize_in_slots) {
1271   int frame_offset = framesize_in_slots*VMRegImpl::stack_slot_size;
1272 
1273   if (src.first()->is_stack()) {
1274     if (dst.first()->is_stack()) {
1275       // stack -> stack. The easiest of the bunch.
1276       __ z_mvc(Address(Z_SP, reg2offset(dst.first())),
1277                Address(Z_SP, reg2offset(src.first()) + frame_offset), sizeof(long));
1278     } else {
1279       // stack to reg
1280       assert(dst.first()->is_Register(), "long dst value must be in GPR");
1281       __ mem2reg_opt(dst.first()->as_Register(),
1282                       Address(Z_SP, reg2offset(src.first()) + frame_offset));
1283     }
1284   } else {
1285     // reg to reg
1286     assert(src.first()->is_Register(), "long src value must be in GPR");
1287     if (dst.first()->is_stack()) {
1288       // reg -> stack
1289       __ reg2mem_opt(src.first()->as_Register(),
1290                      Address(Z_SP, reg2offset(dst.first())));
1291     } else {
1292       // reg -> reg
1293       assert(dst.first()->is_Register(), "long dst value must be in GPR");
1294       __ move_reg_if_needed(dst.first()->as_Register(),
1295                             T_LONG, src.first()->as_Register(), T_LONG);
1296     }
1297   }
1298 }
1299 
1300 
1301 //----------------------------------------------------------------------
1302 // A int-like arg.
1303 //----------------------------------------------------------------------
1304 // On z/Architecture we will store integer like items to the stack as 64 bit
1305 // items, according to the z/Architecture ABI, even though Java would only store
1306 // 32 bits for a parameter.
1307 // We do sign extension for all base types. That is ok since the only
1308 // unsigned base type is T_CHAR, and T_CHAR uses only 16 bits of an int.
1309 // Sign extension 32->64 bit will thus not affect the value.
1310 //----------------------------------------------------------------------
1311 static void move32_64(MacroAssembler *masm,
1312                       VMRegPair src,
1313                       VMRegPair dst,
1314                       int framesize_in_slots) {
1315   int frame_offset = framesize_in_slots * VMRegImpl::stack_slot_size;
1316 
1317   if (src.first()->is_stack()) {
1318     Address memaddr(Z_SP, reg2offset(src.first()) + frame_offset);
1319     if (dst.first()->is_stack()) {
1320       // stack -> stack. MVC not possible due to sign extension.
1321       Address firstaddr(Z_SP, reg2offset(dst.first()));
1322       __ mem2reg_signed_opt(Z_R0_scratch, memaddr);
1323       __ reg2mem_opt(Z_R0_scratch, firstaddr);
1324     } else {
1325       // stack -> reg, sign extended
1326       __ mem2reg_signed_opt(dst.first()->as_Register(), memaddr);
1327     }
1328   } else {
1329     if (dst.first()->is_stack()) {
1330       // reg -> stack, sign extended
1331       Address firstaddr(Z_SP, reg2offset(dst.first()));
1332       __ z_lgfr(src.first()->as_Register(), src.first()->as_Register());
1333       __ reg2mem_opt(src.first()->as_Register(), firstaddr);
1334     } else {
1335       // reg -> reg, sign extended
1336       __ z_lgfr(dst.first()->as_Register(), src.first()->as_Register());
1337     }
1338   }
1339 }
1340 
1341 //----------------------------------------------------------------------
1342 // Wrap a JNI call.
1343 //----------------------------------------------------------------------
1344 #undef USE_RESIZE_FRAME
1345 
1346 static void check_continuation_enter_argument(VMReg actual_vmreg,
1347                                               Register expected_reg,
1348                                               const char* name) {
1349   assert(!actual_vmreg->is_stack(), "%s cannot be on stack", name);
1350   assert(actual_vmreg->as_Register() == expected_reg,
1351          "%s is in unexpected register: %s instead of %s",
1352          name, actual_vmreg->as_Register()->name(), expected_reg->name());
1353 }
1354 
1355 //---------------------------- continuation_enter_setup ---------------------------
1356 //
1357 // Frame setup.
1358 //
1359 // Arguments:
1360 //   None.
1361 //
1362 // Results:
1363 //   Z_SP: pointer to blank ContinuationEntry in the pushed frame.
1364 //
1365 // Kills:
1366 //   Nothing
1367 //
1368 static OopMap* continuation_enter_setup(MacroAssembler* masm, int& framesize_words) {
1369 
1370   assert(ContinuationEntry::size() % VMRegImpl::stack_slot_size == 0, "");
1371   assert(in_bytes(ContinuationEntry::cont_offset())  % VMRegImpl::stack_slot_size == 0, "");
1372   assert(in_bytes(ContinuationEntry::chunk_offset()) % VMRegImpl::stack_slot_size == 0, "");
1373 
1374   const int frame_size_in_bytes = (int)ContinuationEntry::size();
1375   assert(is_aligned(frame_size_in_bytes, frame::alignment_in_bytes), "alignment error");
1376 
1377   framesize_words = frame_size_in_bytes / wordSize;
1378 
1379   DEBUG_ONLY(__ block_comment("continuation_enter_setup {"));
1380   __ save_return_pc(); // preserve current Z_R14
1381   __ push_frame(frame_size_in_bytes);
1382 
1383   OopMap* map = new OopMap((int)frame_size_in_bytes / VMRegImpl::stack_slot_size, 0 /* arg_slots*/);
1384   __ z_mvc(Address(Z_SP, ContinuationEntry::parent_offset()), /* move to */
1385            Address(Z_thread, JavaThread::cont_entry_offset()), /* move from */
1386            sizeof(ContinuationEntry*) /* size of data to be moved */
1387            );
1388   __ z_stg(Z_SP, Address(Z_thread, JavaThread::cont_entry_offset()));
1389   DEBUG_ONLY(__ block_comment("} continuation_enter_setup"));
1390   return map;
1391 }
1392 
1393 //---------------------------- fill_continuation_entry ---------------------------
1394 //
1395 // Initialize the new ContinuationEntry.
1396 //
1397 // Arguments:
1398 //   Z_SP         : pointer to blank Continuation entry
1399 //   reg_cont_obj : pointer to the continuation
1400 //   reg_flags    : flags / isVirtualThread
1401 //
1402 // Results:
1403 //   Z_SP : pointer to filled out ContinuationEntry
1404 //
1405 // Kills:
1406 //   This is peace driven method, doesn't kill anyone.
1407 //
1408 static void fill_continuation_entry(MacroAssembler* masm, Register reg_cont_obj, Register reg_flags) {
1409   assert_different_registers(reg_cont_obj, reg_flags);
1410   DEBUG_ONLY(__ block_comment("fill_continuation_entry {"));
1411 #ifdef ASSERT
1412   assert(Immediate::is_simm16(ContinuationEntry::cookie_value()), "update below instruction");
1413   __ z_mvhi(Address(Z_SP, ContinuationEntry::cookie_offset()), ContinuationEntry::cookie_value());
1414 #endif //ASSERT
1415   __ z_stg(reg_cont_obj, Address(Z_SP, ContinuationEntry::cont_offset()));
1416   __ z_st(reg_flags,    Address(Z_SP, ContinuationEntry::flags_offset()));
1417   __ z_mvghi(Address(Z_SP, ContinuationEntry::chunk_offset()), 0);
1418   __ z_mvhi( Address(Z_SP, ContinuationEntry::argsize_offset()), 0);
1419   __ z_mvhi( Address(Z_SP, ContinuationEntry::pin_count_offset()), 0);
1420 
1421   __ z_mvc(Address(Z_SP, ContinuationEntry::parent_cont_fastpath_offset()), /* move to */
1422            Address(Z_thread, JavaThread::cont_fastpath_offset()), /* move from */
1423            sizeof(ContinuationEntry*) /* size of data to be moved */
1424   );
1425 
1426   __ z_mvghi(Address(Z_thread, JavaThread::cont_fastpath_offset()), 0);
1427 
1428   DEBUG_ONLY(__ block_comment("} fill_continuation_entry"));
1429 }
1430 
1431 //---------------------------- continuation_enter_cleanup ---------------------------
1432 //
1433 // Copy corresponding attributes from the top ContinuationEntry to the JavaThread
1434 // before deleting it.
1435 //
1436 // Arguments:
1437 //   Z_SP: pointer to the ContinuationEntry
1438 //
1439 // Results:
1440 //   None.
1441 //
1442 // Kills:
1443 //   Z_R0_scratch (in debug builds)
1444 //   Z_R10 (when CheckJNICalls is enabled)
1445 //
1446 static void continuation_enter_cleanup(MacroAssembler* masm) {
1447   __ block_comment("continuation_enter_cleanup {");
1448 
1449 #ifdef ASSERT
1450   __ z_cg(Z_SP, Address(Z_thread, JavaThread::cont_entry_offset()));
1451   __ asm_assert(Assembler::bcondEqual, FILE_AND_LINE ": incorrect Z_SP", 0x1bb);
1452 
1453   __ z_lgf(Z_R0, Address(Z_SP, ContinuationEntry::cookie_offset()));
1454   __ z_cfi(Z_R0, ContinuationEntry::cookie_value());
1455   __ asm_assert(Assembler::bcondEqual, FILE_AND_LINE ": incorrect cookie value", 0x1cc);
1456 #endif // ASSERT
1457 
1458   __ z_mvc(Address(Z_thread, JavaThread::cont_fastpath_offset()), /* move to */
1459            Address(Z_SP, ContinuationEntry::parent_cont_fastpath_offset()), /* move from */
1460            sizeof(ContinuationEntry*) /* size of data to be moved */
1461   );
1462 
1463   __ z_mvc(Address(Z_thread, JavaThread::cont_entry_offset()), /* move to */
1464            Address(Z_SP, ContinuationEntry::parent_offset()), /* move from */
1465            sizeof(ContinuationEntry*) /* size of data to be moved */
1466   );
1467 
1468   __ block_comment("} continuation_enter_cleanup");
1469 }
1470 static void gen_continuation_enter(MacroAssembler* masm,
1471                                    const VMRegPair* regs,
1472                                    int& exception_offset,
1473                                    OopMapSet* oop_maps,
1474                                    int& frame_complete,
1475                                    int& framesize_words,
1476                                    int& interpreted_entry_offset,
1477                                    int& compiled_entry_offset) {
1478   // enterSpecial(Continuation c, boolean isContinue, boolean isVirtualThread)
1479   int pos_cont_obj   = 0;
1480   int pos_is_cont    = 1;
1481   int pos_is_virtual = 2;
1482 
1483   // The platform-specific calling convention may present the arguments in various registers.
1484   // To simplify the rest of the code, we expect the arguments to reside at these known
1485   // registers, and we additionally check the placement here in case calling convention ever
1486   // changes.
1487   Register reg_cont_obj   = Z_ARG1;
1488   Register reg_is_cont    = Z_ARG2;
1489   Register reg_is_virtual = Z_ARG3;
1490 
1491   check_continuation_enter_argument(regs[pos_cont_obj].first(),   reg_cont_obj,   "Continuation object");
1492   check_continuation_enter_argument(regs[pos_is_cont].first(),    reg_is_cont,    "isContinue");
1493   check_continuation_enter_argument(regs[pos_is_virtual].first(), reg_is_virtual, "isVirtualThread");
1494 
1495   address resolve_static_call = SharedRuntime::get_resolve_static_call_stub();
1496 
1497   address start = __ pc();
1498 
1499   Label L_thaw, L_exit;
1500 
1501   // i2i entry used at interp_only_mode only
1502   interpreted_entry_offset = __ pc() - start;
1503   {
1504 #ifdef ASSERT
1505     NearLabel is_interp_only;
1506     __ load_and_test_int(Z_R0_scratch, Address(Z_thread, JavaThread::interp_only_mode_offset()));
1507     __ z_brnz(is_interp_only);
1508     __ stop("enterSpecial interpreter entry called when not in interp_only_mode");
1509     __ bind(is_interp_only);
1510 #endif
1511 
1512     // Read interpreter arguments into registers (this is an ad-hoc i2c adapter)
1513     // s390x stores frame pointer in the slot 0, so argument will be loaded from slot 1
1514     __ z_lg(reg_cont_obj,     Address(Z_esp, Interpreter::stackElementSize*3));
1515     __ z_llgf(reg_is_cont,    Address(Z_esp, Interpreter::stackElementSize*2));
1516     __ z_llgf(reg_is_virtual, Address(Z_esp, Interpreter::stackElementSize*1));
1517 
1518     __ push_cont_fastpath();
1519 
1520     OopMap* map = continuation_enter_setup(masm, framesize_words);
1521 
1522     // The frame is complete here, but we only record it for the compiled entry, so the frame would appear unsafe,
1523     // but that's okay because at the very worst we'll miss an async sample, but we're in interp_only_mode anyway.
1524 
1525     __ verify_oop(reg_cont_obj);
1526 
1527     fill_continuation_entry(masm, reg_cont_obj, reg_is_virtual);
1528 
1529     // If isContinue, call to thaw. Otherwise, call Continuation.enter(Continuation c, boolean isContinue)
1530     __ compare32_and_branch(reg_is_cont, 0, Assembler::bcondNotZero, L_thaw);
1531 
1532     // --- call Continuation.enter(Continuation c, boolean isContinue)
1533 
1534     // Emit compiled static call. The call will be always resolved to the c2i
1535     // entry of Continuation.enter(Continuation c, boolean isContinue).
1536     // There are special cases in SharedRuntime::resolve_static_call_C() and
1537     // SharedRuntime::resolve_sub_helper_internal() to achieve this
1538     // See also corresponding call below.
1539     // Make sure the call is patchable
1540 
1541     __ align(NativeCall::call_far_pcrelative_displacement_alignment,
1542         __ offset() + NativeCall::call_far_pcrelative_displacement_offset);
1543 
1544     // Emit stub for static call
1545     address stub = CompiledDirectCall::emit_to_interp_stub(masm, __ pc());
1546     if (stub == nullptr) {
1547       fatal("CodeCache is full at gen_continuation_enter");
1548     }
1549     __ relocate(relocInfo::static_call_type);
1550     __ z_nop();
1551     __ z_brasl(Z_R14, resolve_static_call);
1552     oop_maps->add_gc_map(__ pc() - start, map);
1553     __ post_call_nop();
1554     __ branch_optimized(Assembler::bcondAlways, L_exit);
1555   }
1556 
1557   // compiled entry
1558   __ align(CodeEntryAlignment);
1559   compiled_entry_offset = __ pc() - start;
1560 
1561   OopMap* map = continuation_enter_setup(masm, framesize_words);
1562 
1563   // Frame is now completed as far as size and linkage.
1564 
1565   frame_complete =__ pc() - start;
1566 
1567   __ verify_oop(reg_cont_obj);
1568 
1569   fill_continuation_entry(masm, reg_cont_obj, reg_is_virtual);
1570 
1571   // If isContinue, call to thaw. Otherwise, call Continuation.enter(Continuation c, boolean isContinue)
1572   __ z_ltr(reg_is_cont, reg_is_cont);
1573   __ branch_optimized(Assembler::bcondNotEqual, L_thaw); // was reg_is_cont equal to 0 ?
1574 
1575   // --- call Continuation.enter(Continuation c, boolean isContinue)
1576 
1577   // Make sure the call is patchable
1578   __ align(NativeCall::call_far_pcrelative_displacement_alignment,
1579       __ offset() + NativeCall::call_far_pcrelative_displacement_offset);
1580 
1581   // Emit stub for static call
1582   address stub = CompiledDirectCall::emit_to_interp_stub(masm, __ pc());
1583   guarantee(stub != nullptr, "CodeCache is full at gen_continuation_enter");
1584 
1585   assert((__ offset() + NativeCall::call_far_pcrelative_displacement_offset) % NativeCall::call_far_pcrelative_displacement_alignment == 0,
1586          "must be aligned (offset=%d)", __ offset());
1587 
1588   // The call needs to be resolved. There's a special case for this in
1589   // SharedRuntime::find_callee_info_helper() which calls
1590   // LinkResolver::resolve_continuation_enter() which resolves the call to
1591   // Continuation.enter(Continuation c, boolean isContinue).
1592   __ relocate(relocInfo::static_call_type);
1593   __ z_nop();
1594   __ z_brasl(Z_R14, resolve_static_call);
1595   oop_maps->add_gc_map(__ pc() - start, map);
1596   __ post_call_nop();
1597 
1598   __ branch_optimized(Assembler::bcondAlways, L_exit);
1599 
1600   // --- Thawing path
1601 
1602   __ bind(L_thaw);
1603   ContinuationEntry::_thaw_call_pc_offset = __ pc() - start;
1604   __ load_const_optimized(Z_R1_scratch, StubRoutines::cont_thaw());
1605   __ call(Z_R1_scratch);
1606   oop_maps->add_gc_map(__ pc() - start, map->deep_copy());
1607   ContinuationEntry::_return_pc_offset = __ pc() - start;
1608   __ post_call_nop();
1609 
1610   // --- Normal exit (resolve/thawing)
1611   __ bind(L_exit);
1612   ContinuationEntry::_cleanup_offset = __ pc() - start;
1613   continuation_enter_cleanup(masm);
1614 
1615   // Pop frame and return
1616   DEBUG_ONLY(__ z_lg(Z_R0, Address(Z_SP, 0)));
1617   __ add2reg(Z_SP, framesize_words * wordSize);
1618 
1619 #ifdef ASSERT
1620   NearLabel ok;
1621   __ z_cgr(Z_R0, Z_SP);
1622   __ z_bre(ok);
1623   __ stop("inconsistent frame size");
1624   __ bind(ok);
1625 #endif // ASSERT
1626 
1627   __ restore_return_pc();
1628   __ z_br(Z_R14);
1629 
1630   // --- Exception handling path
1631   exception_offset = __ pc() - start;
1632 
1633   continuation_enter_cleanup(masm);
1634 
1635   // Load caller's return pc
1636   __ z_lg(Z_ARG2, _z_common_abi(callers_sp), Z_SP);
1637   __ z_lg(Z_ARG2, _z_common_abi(return_pc), Z_ARG2);
1638 
1639   __ save_return_pc();
1640   __ push_frame_abi160(0 + 2 * BytesPerWord);
1641 
1642   __ z_stg(Z_ARG1, 0 * BytesPerWord + frame::z_abi_160_size, Z_SP); // save return value containing the exception oop
1643   __ z_stg(Z_ARG2, 1 * BytesPerWord + frame::z_abi_160_size, Z_SP); // save exception_pc
1644 
1645   // Find exception handler.
1646   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
1647                   Z_thread,
1648                   Z_ARG2);
1649 
1650   // Copy handler's address.
1651   __ z_lgr(Z_R1, Z_RET);
1652 
1653   // Set up the arguments for the exception handler:
1654   // - Z_ARG1: exception oop
1655   // - Z_ARG2: exception pc
1656   __ z_lg(Z_ARG1, 0 * BytesPerWord + frame::z_abi_160_size, Z_SP); // load the exception oop
1657   __ z_lg(Z_ARG2, 1 * BytesPerWord + frame::z_abi_160_size, Z_SP); // load the exception pc
1658 
1659   __ pop_frame(); // pop frame pushed before runtime call
1660   // __ restore_return_pc(); // can be skipped
1661 
1662   __ pop_frame(); // pop enterSpecial frame
1663   __ restore_return_pc();
1664 
1665   // Jump to exception handler
1666   __ z_br(Z_R1 /*handler address*/);
1667 }
1668 
1669 static void gen_continuation_yield(MacroAssembler* masm,
1670                                    const VMRegPair* regs,
1671                                    OopMapSet* oop_maps,
1672                                    int& frame_complete,
1673                                    int& framesize_words,
1674                                    int& compiled_entry_offset) {
1675   const int framesize_bytes = (int)align_up((int)frame::z_abi_160_size, frame::alignment_in_bytes);
1676   framesize_words = framesize_bytes / wordSize;
1677 
1678   Register Rtmp = Z_R1_scratch;
1679 
1680   address start = __ pc();
1681   compiled_entry_offset = __ pc() - start;
1682 
1683   // Save return pc and push entry frame
1684   __ save_return_pc();
1685   __ push_frame(framesize_bytes);
1686 
1687     DEBUG_ONLY(__ block_comment("Frame Complete (gen_continuation_yield):"));
1688     frame_complete = __ pc() - start;
1689     address last_java_pc = __ pc();
1690 
1691 
1692     // This nop must be exactly at the PC we push into the frame info.
1693     // We use this nop for fast CodeBlob lookup, associate the OopMap
1694     // with it right away.
1695     __ post_call_nop();
1696     OopMap* map = new OopMap(framesize_bytes / VMRegImpl::stack_slot_size, 1);
1697     oop_maps->add_gc_map(last_java_pc - start, map);
1698 
1699     __ z_larl(Rtmp, last_java_pc);
1700     __ set_last_Java_frame(Z_SP, Rtmp);
1701     __ call_VM_leaf(Continuation::freeze_entry(), Z_thread, Z_SP);
1702     __ reset_last_Java_frame();
1703 
1704     NearLabel L_pinned;
1705     __ z_cij(Z_RET, 0, Assembler::bcondNotEqual, L_pinned);
1706 
1707     // Pop frames of continuation including this stub's frame
1708     __ z_lg(Z_SP, Address(Z_thread, JavaThread::cont_entry_offset()));
1709     // The frame pushed by gen_continuation_enter() is on top now again
1710     continuation_enter_cleanup(masm);
1711     // Pop frame and return
1712     Label L_return;
1713     __ bind(L_return);
1714     __ pop_frame();
1715     __ restore_return_pc();
1716     __ z_br(Z_R14);
1717 
1718     // yield failed - continuation is pinned
1719     __ bind(L_pinned);
1720 
1721     // handle pending exception thrown by freeze
1722     __ load_and_test_long(Rtmp, Address(Z_thread, Thread::pending_exception_offset()));
1723     __ z_bre(L_return); // return if no exception is pending
1724     __ pop_frame();
1725     __ restore_return_pc();
1726     __ load_const_optimized(Z_R1_scratch, StubRoutines::forward_exception_entry());
1727     __ z_br(Z_R1_scratch);
1728 }
1729 
1730 void SharedRuntime::continuation_enter_cleanup(MacroAssembler* masm) {
1731   ::continuation_enter_cleanup(masm);
1732 }
1733 
1734 nmethod *SharedRuntime::generate_native_wrapper(MacroAssembler *masm,
1735                                                 const methodHandle& method,
1736                                                 int compile_id,
1737                                                 BasicType *in_sig_bt,
1738                                                 VMRegPair *in_regs,
1739                                                 BasicType ret_type) {
1740   int total_in_args = method->size_of_parameters();
1741   if (method->is_continuation_native_intrinsic()) {
1742     int exception_offset = -1;
1743     OopMapSet* oop_maps = new OopMapSet();
1744     int frame_complete = -1;
1745     int stack_slots = -1;
1746     int interpreted_entry_offset = -1;
1747     int vep_offset = -1; // verified entry point offset
1748     if (method->is_continuation_enter_intrinsic()) {
1749       gen_continuation_enter(masm,
1750                              in_regs,
1751                              exception_offset,
1752                              oop_maps,
1753                              frame_complete,
1754                              stack_slots,
1755                              interpreted_entry_offset,
1756                              vep_offset);
1757     } else if(method->is_continuation_yield_intrinsic()) {
1758       gen_continuation_yield(masm,
1759                              in_regs,
1760                              oop_maps,
1761                              frame_complete,
1762                              stack_slots,
1763                              vep_offset);
1764     } else {
1765       guarantee(false, "Unknown Continuation native intrinsic");
1766     }
1767 
1768 #ifdef ASSERT
1769     if (method->is_continuation_enter_intrinsic()) {
1770       assert(interpreted_entry_offset != -1, "Must be set");
1771       assert(exception_offset != -1,         "Must be set");
1772     } else {
1773       assert(interpreted_entry_offset == -1, "Must be unset");
1774       assert(exception_offset == -1,         "Must be unset");
1775     }
1776     assert(frame_complete != -1,    "Must be set");
1777     assert(stack_slots != -1,       "Must be set");
1778     assert(vep_offset != -1,        "Must be set");
1779 #endif
1780 
1781     __ flush();
1782     nmethod* nm = nmethod::new_native_nmethod(method,
1783                                               compile_id,
1784                                               masm->code(),
1785                                               vep_offset,
1786                                               frame_complete,
1787                                               stack_slots,
1788                                               in_ByteSize(-1),
1789                                               in_ByteSize(-1),
1790                                               oop_maps,
1791                                               exception_offset);
1792     if (nm == nullptr) return nm;
1793     if (method->is_continuation_enter_intrinsic()) {
1794       ContinuationEntry::set_enter_code(nm, interpreted_entry_offset);
1795     } else if (method->is_continuation_yield_intrinsic()) {
1796       _cont_doYield_stub = nm;
1797     }
1798     return nm;
1799   }
1800 
1801   if (method->is_method_handle_intrinsic()) {
1802     vmIntrinsics::ID iid = method->intrinsic_id();
1803     intptr_t start = (intptr_t) __ pc();
1804     int vep_offset = ((intptr_t) __ pc()) - start;
1805 
1806     gen_special_dispatch(masm, total_in_args,
1807                          method->intrinsic_id(), in_sig_bt, in_regs);
1808 
1809     int frame_complete = ((intptr_t)__ pc()) - start; // Not complete, period.
1810 
1811     __ flush();
1812 
1813     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // No out slots at all, actually.
1814 
1815     return nmethod::new_native_nmethod(method,
1816                                        compile_id,
1817                                        masm->code(),
1818                                        vep_offset,
1819                                        frame_complete,
1820                                        stack_slots / VMRegImpl::slots_per_word,
1821                                        in_ByteSize(-1),
1822                                        in_ByteSize(-1),
1823                                        (OopMapSet *) nullptr);
1824   }
1825 
1826 
1827   ///////////////////////////////////////////////////////////////////////
1828   //
1829   //  Precalculations before generating any code
1830   //
1831   ///////////////////////////////////////////////////////////////////////
1832 
1833   address native_func = method->native_function();
1834   assert(native_func != nullptr, "must have function");
1835 
1836   //---------------------------------------------------------------------
1837   // We have received a description of where all the java args are located
1838   // on entry to the wrapper. We need to convert these args to where
1839   // the jni function will expect them. To figure out where they go
1840   // we convert the java signature to a C signature by inserting
1841   // the hidden arguments as arg[0] and possibly arg[1] (static method).
1842   //
1843   // The first hidden argument arg[0] is a pointer to the JNI environment.
1844   // It is generated for every call.
1845   // The second argument arg[1] to the JNI call, which is hidden for static
1846   // methods, is the boxed lock object. For static calls, the lock object
1847   // is the static method itself. The oop is constructed here. for instance
1848   // calls, the lock is performed on the object itself, the pointer of
1849   // which is passed as the first visible argument.
1850   //---------------------------------------------------------------------
1851 
1852   // Additionally, on z/Architecture we must convert integers
1853   // to longs in the C signature. We do this in advance in order to have
1854   // no trouble with indexes into the bt-arrays.
1855   // So convert the signature and registers now, and adjust the total number
1856   // of in-arguments accordingly.
1857   bool method_is_static = method->is_static();
1858   int  total_c_args     = total_in_args + (method_is_static ? 2 : 1);
1859 
1860   BasicType *out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1861   VMRegPair *out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1862 
1863   // Create the signature for the C call:
1864   //   1) add the JNIEnv*
1865   //   2) add the class if the method is static
1866   //   3) copy the rest of the incoming signature (shifted by the number of
1867   //      hidden arguments)
1868 
1869   int argc = 0;
1870   out_sig_bt[argc++] = T_ADDRESS;
1871   if (method->is_static()) {
1872     out_sig_bt[argc++] = T_OBJECT;
1873   }
1874 
1875   for (int i = 0; i < total_in_args; i++) {
1876     out_sig_bt[argc++] = in_sig_bt[i];
1877   }
1878 
1879   ///////////////////////////////////////////////////////////////////////
1880   // Now figure out where the args must be stored and how much stack space
1881   // they require (neglecting out_preserve_stack_slots but providing space
1882   // for storing the first five register arguments).
1883   // It's weird, see int_stk_helper.
1884   ///////////////////////////////////////////////////////////////////////
1885 
1886   //---------------------------------------------------------------------
1887   // Compute framesize for the wrapper.
1888   //
1889   // - We need to handlize all oops passed in registers.
1890   // - We must create space for them here that is disjoint from the save area.
1891   // - We always just allocate 5 words for storing down these object.
1892   //   This allows us to simply record the base and use the Ireg number to
1893   //   decide which slot to use.
1894   // - Note that the reg number used to index the stack slot is the inbound
1895   //   number, not the outbound number.
1896   // - We must shuffle args to match the native convention,
1897   //   and to include var-args space.
1898   //---------------------------------------------------------------------
1899 
1900   //---------------------------------------------------------------------
1901   // Calculate the total number of stack slots we will need:
1902   // - 1) abi requirements
1903   // - 2) outgoing args
1904   // - 3) space for inbound oop handle area
1905   // - 4) space for handlizing a klass if static method
1906   // - 5) space for a lock if synchronized method
1907   // - 6) workspace (save rtn value, int<->float reg moves, ...)
1908   // - 7) filler slots for alignment
1909   //---------------------------------------------------------------------
1910   // Here is how the space we have allocated will look like.
1911   // Since we use resize_frame, we do not create a new stack frame,
1912   // but just extend the one we got with our own data area.
1913   //
1914   // If an offset or pointer name points to a separator line, it is
1915   // assumed that addressing with offset 0 selects storage starting
1916   // at the first byte above the separator line.
1917   //
1918   //
1919   //     ...                   ...
1920   //      | caller's frame      |
1921   // FP-> |---------------------|
1922   //      | filler slots, if any|
1923   //     7| #slots == mult of 2 |
1924   //      |---------------------|
1925   //      | work space          |
1926   //     6| 2 slots = 8 bytes   |
1927   //      |---------------------|
1928   //     5| lock box (if sync)  |
1929   //      |---------------------| <- lock_slot_offset
1930   //     4| klass (if static)   |
1931   //      |---------------------| <- klass_slot_offset
1932   //     3| oopHandle area      |
1933   //      |                     |
1934   //      |                     |
1935   //      |---------------------| <- oop_handle_offset
1936   //     2| outbound memory     |
1937   //     ...                   ...
1938   //      | based arguments     |
1939   //      |---------------------|
1940   //      | vararg              |
1941   //     ...                   ...
1942   //      | area                |
1943   //      |---------------------| <- out_arg_slot_offset
1944   //     1| out_preserved_slots |
1945   //     ...                   ...
1946   //      | (z_abi spec)        |
1947   // SP-> |---------------------| <- FP_slot_offset (back chain)
1948   //     ...                   ...
1949   //
1950   //---------------------------------------------------------------------
1951 
1952   // *_slot_offset indicates offset from SP in #stack slots
1953   // *_offset      indicates offset from SP in #bytes
1954 
1955   int stack_slots = c_calling_convention(out_sig_bt, out_regs, total_c_args) + // 1+2
1956                     SharedRuntime::out_preserve_stack_slots(); // see c_calling_convention
1957 
1958   // Now the space for the inbound oop handle area.
1959   int total_save_slots = Register::number_of_arg_registers * VMRegImpl::slots_per_word;
1960 
1961   int oop_handle_slot_offset = stack_slots;
1962   stack_slots += total_save_slots;                                        // 3)
1963 
1964   int klass_slot_offset = 0;
1965   int klass_offset      = -1;
1966   if (method_is_static) {                                                 // 4)
1967     klass_slot_offset  = stack_slots;
1968     klass_offset       = klass_slot_offset * VMRegImpl::stack_slot_size;
1969     stack_slots       += VMRegImpl::slots_per_word;
1970   }
1971 
1972   int lock_slot_offset = 0;
1973   int lock_offset      = -1;
1974   if (method->is_synchronized()) {                                        // 5)
1975     lock_slot_offset   = stack_slots;
1976     lock_offset        = lock_slot_offset * VMRegImpl::stack_slot_size;
1977     stack_slots       += VMRegImpl::slots_per_word;
1978   }
1979 
1980   int workspace_slot_offset= stack_slots;                                 // 6)
1981   stack_slots         += 2;
1982 
1983   // Now compute actual number of stack words we need.
1984   // Round to align stack properly.
1985   stack_slots = align_up(stack_slots,                                     // 7)
1986                          frame::alignment_in_bytes / VMRegImpl::stack_slot_size);
1987   int frame_size_in_bytes = stack_slots * VMRegImpl::stack_slot_size;
1988 
1989 
1990   ///////////////////////////////////////////////////////////////////////
1991   // Now we can start generating code
1992   ///////////////////////////////////////////////////////////////////////
1993 
1994   unsigned int wrapper_CodeStart  = __ offset();
1995   unsigned int wrapper_UEPStart;
1996   unsigned int wrapper_VEPStart;
1997   unsigned int wrapper_FrameDone;
1998   unsigned int wrapper_CRegsSet;
1999   Label     handle_pending_exception;
2000   Label     last_java_pc;
2001 
2002   //---------------------------------------------------------------------
2003   // Unverified entry point (UEP)
2004   //---------------------------------------------------------------------
2005 
2006   // check ic: object class <-> cached class
2007   if (!method_is_static) {
2008     wrapper_UEPStart = __ ic_check(CodeEntryAlignment /* end_alignment */);
2009   }
2010 
2011   //---------------------------------------------------------------------
2012   // Verified entry point (VEP)
2013   //---------------------------------------------------------------------
2014   wrapper_VEPStart = __ offset();
2015 
2016   if (method->needs_clinit_barrier()) {
2017     assert(VM_Version::supports_fast_class_init_checks(), "sanity");
2018     Label L_skip_barrier;
2019     Register klass = Z_R1_scratch;
2020     // Notify OOP recorder (don't need the relocation)
2021     AddressLiteral md = __ constant_metadata_address(method->method_holder());
2022     __ load_const_optimized(klass, md.value());
2023     __ clinit_barrier(klass, Z_thread, &L_skip_barrier /*L_fast_path*/);
2024 
2025     __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub());
2026     __ z_br(klass);
2027 
2028     __ bind(L_skip_barrier);
2029   }
2030 
2031   __ save_return_pc();
2032   __ generate_stack_overflow_check(frame_size_in_bytes);  // Check before creating frame.
2033 #ifndef USE_RESIZE_FRAME
2034   __ push_frame(frame_size_in_bytes);                     // Create a new frame for the wrapper.
2035 #else
2036   __ resize_frame(-frame_size_in_bytes, Z_R0_scratch);    // No new frame for the wrapper.
2037                                                           // Just resize the existing one.
2038 #endif
2039 
2040   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2041   bs->nmethod_entry_barrier(masm);
2042 
2043   wrapper_FrameDone = __ offset();
2044 
2045   // Native nmethod wrappers never take possession of the oop arguments.
2046   // So the caller will gc the arguments.
2047   // The only thing we need an oopMap for is if the call is static.
2048   //
2049   // An OopMap for lock (and class if static), and one for the VM call itself
2050   OopMapSet  *oop_maps        = new OopMapSet();
2051   OopMap     *map             = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
2052 
2053   //////////////////////////////////////////////////////////////////////
2054   //
2055   // The Grand Shuffle
2056   //
2057   //////////////////////////////////////////////////////////////////////
2058   //
2059   // We immediately shuffle the arguments so that for any vm call we have
2060   // to make from here on out (sync slow path, jvmti, etc.) we will have
2061   // captured the oops from our caller and have a valid oopMap for them.
2062   //
2063   //--------------------------------------------------------------------
2064   // Natives require 1 or 2 extra arguments over the normal ones: the JNIEnv*
2065   // (derived from JavaThread* which is in Z_thread) and, if static,
2066   // the class mirror instead of a receiver. This pretty much guarantees that
2067   // register layout will not match. We ignore these extra arguments during
2068   // the shuffle. The shuffle is described by the two calling convention
2069   // vectors we have in our possession. We simply walk the java vector to
2070   // get the source locations and the c vector to get the destinations.
2071   //
2072   // This is a trick. We double the stack slots so we can claim
2073   // the oops in the caller's frame. Since we are sure to have
2074   // more args than the caller doubling is enough to make
2075   // sure we can capture all the incoming oop args from the caller.
2076   //--------------------------------------------------------------------
2077 
2078   // Record sp-based slot for receiver on stack for non-static methods.
2079   int receiver_offset = -1;
2080 
2081   //--------------------------------------------------------------------
2082   // We move the arguments backwards because the floating point registers
2083   // destination will always be to a register with a greater or equal
2084   // register number or the stack.
2085   //   jix is the index of the incoming Java arguments.
2086   //   cix is the index of the outgoing C arguments.
2087   //--------------------------------------------------------------------
2088 
2089 #ifdef ASSERT
2090   bool reg_destroyed[Register::number_of_registers];
2091   bool freg_destroyed[FloatRegister::number_of_registers];
2092   for (int r = 0; r < Register::number_of_registers; r++) {
2093     reg_destroyed[r] = false;
2094   }
2095   for (int f = 0; f < FloatRegister::number_of_registers; f++) {
2096     freg_destroyed[f] = false;
2097   }
2098 #endif // ASSERT
2099 
2100   for (int jix = total_in_args - 1, cix = total_c_args - 1; jix >= 0; jix--, cix--) {
2101 #ifdef ASSERT
2102     if (in_regs[jix].first()->is_Register()) {
2103       assert(!reg_destroyed[in_regs[jix].first()->as_Register()->encoding()], "ack!");
2104     } else {
2105       if (in_regs[jix].first()->is_FloatRegister()) {
2106         assert(!freg_destroyed[in_regs[jix].first()->as_FloatRegister()->encoding()], "ack!");
2107       }
2108     }
2109     if (out_regs[cix].first()->is_Register()) {
2110       reg_destroyed[out_regs[cix].first()->as_Register()->encoding()] = true;
2111     } else {
2112       if (out_regs[cix].first()->is_FloatRegister()) {
2113         freg_destroyed[out_regs[cix].first()->as_FloatRegister()->encoding()] = true;
2114       }
2115     }
2116 #endif // ASSERT
2117 
2118     switch (in_sig_bt[jix]) {
2119       // Due to casting, small integers should only occur in pairs with type T_LONG.
2120       case T_BOOLEAN:
2121       case T_CHAR:
2122       case T_BYTE:
2123       case T_SHORT:
2124       case T_INT:
2125         // Move int and do sign extension.
2126         move32_64(masm, in_regs[jix], out_regs[cix], stack_slots);
2127         break;
2128 
2129       case T_LONG :
2130         long_move(masm, in_regs[jix], out_regs[cix], stack_slots);
2131         break;
2132 
2133       case T_ARRAY:
2134       case T_OBJECT:
2135         object_move(masm, map, oop_handle_slot_offset, stack_slots, in_regs[jix], out_regs[cix],
2136                     ((jix == 0) && (!method_is_static)),
2137                     &receiver_offset);
2138         break;
2139       case T_VOID:
2140         break;
2141 
2142       case T_FLOAT:
2143         float_move(masm, in_regs[jix], out_regs[cix], stack_slots, workspace_slot_offset);
2144         break;
2145 
2146       case T_DOUBLE:
2147         assert(jix+1 <  total_in_args && in_sig_bt[jix+1]  == T_VOID && out_sig_bt[cix+1] == T_VOID, "bad arg list");
2148         double_move(masm, in_regs[jix], out_regs[cix], stack_slots, workspace_slot_offset);
2149         break;
2150 
2151       case T_ADDRESS:
2152         assert(false, "found T_ADDRESS in java args");
2153         break;
2154 
2155       default:
2156         ShouldNotReachHere();
2157     }
2158   }
2159 
2160   //--------------------------------------------------------------------
2161   // Pre-load a static method's oop into ARG2.
2162   // Used both by locking code and the normal JNI call code.
2163   //--------------------------------------------------------------------
2164   if (method_is_static) {
2165     __ set_oop_constant(JNIHandles::make_local(method->method_holder()->java_mirror()), Z_ARG2);
2166 
2167     // Now handlize the static class mirror in ARG2. It's known not-null.
2168     __ z_stg(Z_ARG2, klass_offset, Z_SP);
2169     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
2170     __ add2reg(Z_ARG2, klass_offset, Z_SP);
2171   }
2172 
2173   // Get JNIEnv* which is first argument to native.
2174   __ add2reg(Z_ARG1, in_bytes(JavaThread::jni_environment_offset()), Z_thread);
2175 
2176   //////////////////////////////////////////////////////////////////////
2177   // We have all of the arguments setup at this point.
2178   // We MUST NOT touch any outgoing regs from this point on.
2179   // So if we must call out we must push a new frame.
2180   //////////////////////////////////////////////////////////////////////
2181 
2182   // The last java pc will also be used as resume pc if this is the wrapper for wait0.
2183   // For this purpose the precise location matters but not for oopmap lookup.
2184   __ z_larl(Z_R10, last_java_pc);
2185 
2186   // Lock a synchronized method.
2187 
2188   if (method->is_synchronized()) {
2189 
2190     // ATTENTION: args and Z_R10 must be preserved.
2191     Register r_oop  = Z_R11;
2192     Register r_box  = Z_R12;
2193     Register r_tmp1 = Z_R13;
2194     Register r_tmp2 = Z_R7;
2195     Label done;
2196 
2197     // Load the oop for the object or class. R_carg2_classorobject contains
2198     // either the handlized oop from the incoming arguments or the handlized
2199     // class mirror (if the method is static).
2200     __ z_lg(r_oop, 0, Z_ARG2);
2201 
2202     lock_offset = (lock_slot_offset * VMRegImpl::stack_slot_size);
2203     // Get the lock box slot's address.
2204     __ add2reg(r_box, lock_offset, Z_SP);
2205 
2206     // Try fastpath for locking.
2207     // Fast_lock kills r_temp_1, r_temp_2.
2208     __ compiler_fast_lock_object(r_oop, r_box, r_tmp1, r_tmp2);
2209     __ z_bre(done);
2210 
2211     //-------------------------------------------------------------------------
2212     // None of the above fast optimizations worked so we have to get into the
2213     // slow case of monitor enter. Inline a special case of call_VM that
2214     // disallows any pending_exception.
2215     //-------------------------------------------------------------------------
2216 
2217     Register oldSP = Z_R11;
2218 
2219     __ z_lgr(oldSP, Z_SP);
2220 
2221     RegisterSaver::save_live_registers(masm, RegisterSaver::arg_registers);
2222 
2223     // Prepare arguments for call.
2224     __ z_lg(Z_ARG1, 0, Z_ARG2); // Ynboxed class mirror or unboxed object.
2225     __ add2reg(Z_ARG2, lock_offset, oldSP);
2226     __ z_lgr(Z_ARG3, Z_thread);
2227 
2228     __ set_last_Java_frame(oldSP, Z_R10 /* gc map pc */);
2229     assert(Z_R10->is_nonvolatile(), "Z_R10 needs to be preserved accross complete_monitor_locking_C call");
2230 
2231     // Do the call.
2232     __ push_cont_fastpath();
2233     __ load_const_optimized(Z_R1_scratch, CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C));
2234     __ call(Z_R1_scratch);
2235     __ pop_cont_fastpath();
2236 
2237     __ reset_last_Java_frame();
2238 
2239     RegisterSaver::restore_live_registers(masm, RegisterSaver::arg_registers);
2240 #ifdef ASSERT
2241     { Label L;
2242       __ load_and_test_long(Z_R0, Address(Z_thread, Thread::pending_exception_offset()));
2243       __ z_bre(L);
2244       __ stop("no pending exception allowed on exit from IR::monitorenter");
2245       __ bind(L);
2246     }
2247 #endif
2248     __ bind(done);
2249   } // lock for synchronized methods
2250 
2251 
2252   //////////////////////////////////////////////////////////////////////
2253   // Finally just about ready to make the JNI call.
2254   //////////////////////////////////////////////////////////////////////
2255 
2256   // Use that pc we placed in Z_R10 a while back as the current frame anchor.
2257   __ set_last_Java_frame(Z_SP, Z_R10);
2258 
2259   // Transition from _thread_in_Java to _thread_in_native.
2260   __ set_thread_state(_thread_in_native);
2261 
2262   //////////////////////////////////////////////////////////////////////
2263   // This is the JNI call.
2264   //////////////////////////////////////////////////////////////////////
2265 
2266   __ call_c(native_func);
2267 
2268 
2269   //////////////////////////////////////////////////////////////////////
2270   // We have survived the call once we reach here.
2271   //////////////////////////////////////////////////////////////////////
2272 
2273 
2274   //--------------------------------------------------------------------
2275   // Unpack native results.
2276   //--------------------------------------------------------------------
2277   // For int-types, we do any needed sign-extension required.
2278   // Care must be taken that the return value (in Z_ARG1 = Z_RET = Z_R2
2279   // or in Z_FARG0 = Z_FRET = Z_F0) will survive any VM calls for
2280   // blocking or unlocking.
2281   // An OOP result (handle) is done specially in the slow-path code.
2282   //--------------------------------------------------------------------
2283   switch (ret_type) {
2284     case T_VOID:    break;         // Nothing to do!
2285     case T_FLOAT:   break;         // Got it where we want it (unless slow-path)
2286     case T_DOUBLE:  break;         // Got it where we want it (unless slow-path)
2287     case T_LONG:    break;         // Got it where we want it (unless slow-path)
2288     case T_OBJECT:  break;         // Really a handle.
2289                                    // Cannot de-handlize until after reclaiming jvm_lock.
2290     case T_ARRAY:   break;
2291 
2292     case T_BOOLEAN:                // 0 -> false(0); !0 -> true(1)
2293       __ z_lngfr(Z_RET, Z_RET);    // Force sign bit on except for zero.
2294       __ z_srlg(Z_RET, Z_RET, 63); // Shift sign bit into least significant pos.
2295       break;
2296     case T_BYTE:    __ z_lgbr(Z_RET, Z_RET);  break; // sign extension
2297     case T_CHAR:    __ z_llghr(Z_RET, Z_RET); break; // unsigned result
2298     case T_SHORT:   __ z_lghr(Z_RET, Z_RET);  break; // sign extension
2299     case T_INT:     __ z_lgfr(Z_RET, Z_RET);  break; // sign-extend for beauty.
2300 
2301     default:
2302       ShouldNotReachHere();
2303       break;
2304   }
2305 
2306   // Switch thread to "native transition" state before reading the synchronization state.
2307   // This additional state is necessary because reading and testing the synchronization
2308   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2309   //   - Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2310   //   - VM thread changes sync state to synchronizing and suspends threads for GC.
2311   //   - Thread A is resumed to finish this native method, but doesn't block here since it
2312   //     didn't see any synchronization in progress, and escapes.
2313 
2314   // Transition from _thread_in_native to _thread_in_native_trans.
2315   __ set_thread_state(_thread_in_native_trans);
2316 
2317   // Safepoint synchronization
2318   //--------------------------------------------------------------------
2319   // Must we block?
2320   //--------------------------------------------------------------------
2321   // Block, if necessary, before resuming in _thread_in_Java state.
2322   // In order for GC to work, don't clear the last_Java_sp until after blocking.
2323   //--------------------------------------------------------------------
2324   {
2325     Label no_block, sync;
2326 
2327     save_native_result(masm, ret_type, workspace_slot_offset); // Make Z_R2 available as work reg.
2328 
2329     // Force this write out before the read below.
2330     if (!UseSystemMemoryBarrier) {
2331       __ z_fence();
2332     }
2333 
2334     __ safepoint_poll(sync, Z_R1);
2335 
2336     __ load_and_test_int(Z_R0, Address(Z_thread, JavaThread::suspend_flags_offset()));
2337     __ z_bre(no_block);
2338 
2339     // Block. Save any potential method result value before the operation and
2340     // use a leaf call to leave the last_Java_frame setup undisturbed. Doing this
2341     // lets us share the oopMap we used when we went native rather than create
2342     // a distinct one for this pc.
2343     //
2344     __ bind(sync);
2345     __ z_acquire();
2346 
2347     address entry_point = CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans);
2348 
2349     __ call_VM_leaf(entry_point, Z_thread);
2350 
2351     __ bind(no_block);
2352     restore_native_result(masm, ret_type, workspace_slot_offset);
2353   }
2354 
2355   //--------------------------------------------------------------------
2356   // Thread state is thread_in_native_trans. Any safepoint blocking has
2357   // already happened so we can now change state to _thread_in_Java.
2358   //--------------------------------------------------------------------
2359   // Transition from _thread_in_native_trans to _thread_in_Java.
2360   __ set_thread_state(_thread_in_Java);
2361 
2362   // Check preemption for Object.wait()
2363   if (method->is_object_wait0()) {
2364     NearLabel not_preempted;
2365     __ z_ltg(Z_R1_scratch, Address(Z_thread, JavaThread::preempt_alternate_return_offset()));
2366     __ z_brz(not_preempted); // if 0, jump to not_preempted
2367     __ z_mvghi(Address(Z_thread, JavaThread::preempt_alternate_return_offset()), 0);
2368     __ z_br(Z_R1_scratch);
2369     __ bind(not_preempted);
2370   }
2371   __ bind(last_java_pc);
2372 
2373   // Calc the current pc into wrapper_CRegsSet.
2374   wrapper_CRegsSet = __ offset();  // and into into variable.
2375 
2376   // We use the same pc/oopMap repeatedly when we call out.
2377   oop_maps->add_gc_map((int)(wrapper_CRegsSet-wrapper_CodeStart), map);
2378 
2379   //--------------------------------------------------------------------
2380   // Reguard any pages if necessary.
2381   // Protect native result from being destroyed.
2382   //--------------------------------------------------------------------
2383 
2384   Label no_reguard;
2385 
2386   __ z_cli(Address(Z_thread, JavaThread::stack_guard_state_offset() + in_ByteSize(sizeof(StackOverflow::StackGuardState) - 1)),
2387            StackOverflow::stack_guard_yellow_reserved_disabled);
2388 
2389   __ z_bre(no_reguard);
2390 
2391   save_native_result(masm, ret_type, workspace_slot_offset);
2392   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages), Z_method);
2393   restore_native_result(masm, ret_type, workspace_slot_offset);
2394 
2395   __ bind(no_reguard);
2396 
2397 
2398   // Synchronized methods (slow path only)
2399   // No pending exceptions for now.
2400   //--------------------------------------------------------------------
2401   // Handle possibly pending exception (will unlock if necessary).
2402   // Native result is, if any is live, in Z_FRES or Z_RES.
2403   //--------------------------------------------------------------------
2404   // Unlock
2405   //--------------------------------------------------------------------
2406   if (method->is_synchronized()) {
2407     const Register r_oop        = Z_R11;
2408     const Register r_box        = Z_R12;
2409     const Register r_tmp1       = Z_R13;
2410     const Register r_tmp2       = Z_R7;
2411     Label done;
2412 
2413     // Get unboxed oop of class mirror or object ...
2414     int   offset = method_is_static ? klass_offset : receiver_offset;
2415 
2416     assert(offset != -1, "");
2417     __ z_lg(r_oop, offset, Z_SP);
2418 
2419     // ... and address of lock object box.
2420     __ add2reg(r_box, lock_offset, Z_SP);
2421 
2422     // Try fastpath for unlocking.
2423     // Fast_unlock kills r_tmp1, r_tmp2.
2424     __ compiler_fast_unlock_object(r_oop, r_box, r_tmp1, r_tmp2);
2425     __ z_bre(done);
2426 
2427     // Slow path for unlocking.
2428     // Save and restore any potential method result value around the unlocking operation.
2429     const Register R_exc = Z_R11;
2430 
2431     save_native_result(masm, ret_type, workspace_slot_offset);
2432 
2433     // Must save pending exception around the slow-path VM call. Since it's a
2434     // leaf call, the pending exception (if any) can be kept in a register.
2435     __ z_lg(R_exc, Address(Z_thread, Thread::pending_exception_offset()));
2436     assert(R_exc->is_nonvolatile(), "exception register must be non-volatile");
2437 
2438     // Must clear pending-exception before re-entering the VM. Since this is
2439     // a leaf call, pending-exception-oop can be safely kept in a register.
2440     __ clear_mem(Address(Z_thread, Thread::pending_exception_offset()), sizeof(intptr_t));
2441 
2442     // Inline a special case of call_VM that disallows any pending_exception.
2443 
2444     // Get locked oop from the handle we passed to jni.
2445     __ z_lg(Z_ARG1, offset, Z_SP);
2446     __ add2reg(Z_ARG2, lock_offset, Z_SP);
2447     __ z_lgr(Z_ARG3, Z_thread);
2448 
2449     __ load_const_optimized(Z_R1_scratch, CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
2450 
2451     __ call(Z_R1_scratch);
2452 
2453 #ifdef ASSERT
2454     {
2455       Label L;
2456       __ load_and_test_long(Z_R0, Address(Z_thread, Thread::pending_exception_offset()));
2457       __ z_bre(L);
2458       __ stop("no pending exception allowed on exit from IR::monitorexit");
2459       __ bind(L);
2460     }
2461 #endif
2462 
2463     // Check_forward_pending_exception jump to forward_exception if any pending
2464     // exception is set. The forward_exception routine expects to see the
2465     // exception in pending_exception and not in a register. Kind of clumsy,
2466     // since all folks who branch to forward_exception must have tested
2467     // pending_exception first and hence have it in a register already.
2468     __ z_stg(R_exc, Address(Z_thread, Thread::pending_exception_offset()));
2469     restore_native_result(masm, ret_type, workspace_slot_offset);
2470     __ z_bru(done);
2471     __ z_illtrap(0x66);
2472 
2473     __ bind(done);
2474   }
2475 
2476 
2477   //--------------------------------------------------------------------
2478   // Clear "last Java frame" SP and PC.
2479   //--------------------------------------------------------------------
2480 
2481 
2482   // Last java frame won't be set if we're resuming after preemption
2483   bool maybe_preempted = method->is_object_wait0();
2484   __ reset_last_Java_frame(/* check_last_java_sp = */ !maybe_preempted);
2485 
2486   // Unpack oop result, e.g. JNIHandles::resolve result.
2487   if (is_reference_type(ret_type)) {
2488     __ resolve_jobject(Z_RET, /* tmp1 */ Z_R13, /* tmp2 */ Z_R7);
2489   }
2490 
2491   if (CheckJNICalls) {
2492     // clear_pending_jni_exception_check
2493     __ clear_mem(Address(Z_thread, JavaThread::pending_jni_exception_check_fn_offset()), sizeof(oop));
2494   }
2495 
2496   // Reset handle block.
2497   __ z_lg(Z_R1_scratch, Address(Z_thread, JavaThread::active_handles_offset()));
2498   __ clear_mem(Address(Z_R1_scratch, JNIHandleBlock::top_offset()), 4);
2499 
2500   // Check for pending exceptions.
2501   __ load_and_test_long(Z_R0, Address(Z_thread, Thread::pending_exception_offset()));
2502   __ z_brne(handle_pending_exception);
2503 
2504 
2505   //////////////////////////////////////////////////////////////////////
2506   // Return
2507   //////////////////////////////////////////////////////////////////////
2508 
2509 
2510 #ifndef USE_RESIZE_FRAME
2511   __ pop_frame();                     // Pop wrapper frame.
2512 #else
2513   __ resize_frame(frame_size_in_bytes, Z_R0_scratch);  // Revert stack extension.
2514 #endif
2515   __ restore_return_pc();             // This is the way back to the caller.
2516   __ z_br(Z_R14);
2517 
2518 
2519   //////////////////////////////////////////////////////////////////////
2520   // Out-of-line calls to the runtime.
2521   //////////////////////////////////////////////////////////////////////
2522 
2523 
2524   //---------------------------------------------------------------------
2525   // Handler for pending exceptions (out-of-line).
2526   //---------------------------------------------------------------------
2527   // Since this is a native call, we know the proper exception handler
2528   // is the empty function. We just pop this frame and then jump to
2529   // forward_exception_entry. Z_R14 will contain the native caller's
2530   // return PC.
2531   __ bind(handle_pending_exception);
2532   __ pop_frame();
2533   __ load_const_optimized(Z_R1_scratch, StubRoutines::forward_exception_entry());
2534   __ restore_return_pc();
2535   __ z_br(Z_R1_scratch);
2536 
2537   __ flush();
2538   //////////////////////////////////////////////////////////////////////
2539   // end of code generation
2540   //////////////////////////////////////////////////////////////////////
2541 
2542 
2543   nmethod *nm = nmethod::new_native_nmethod(method,
2544                                             compile_id,
2545                                             masm->code(),
2546                                             (int)(wrapper_VEPStart-wrapper_CodeStart),
2547                                             (int)(wrapper_FrameDone-wrapper_CodeStart),
2548                                             stack_slots / VMRegImpl::slots_per_word,
2549                                             (method_is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2550                                             in_ByteSize(lock_offset),
2551                                             oop_maps);
2552 
2553   return nm;
2554 }
2555 
2556 static address gen_c2i_adapter(MacroAssembler  *masm,
2557                                int comp_args_on_stack,
2558                                const GrowableArray<SigEntry>* sig,
2559                                const VMRegPair *regs,
2560                                Label &skip_fixup) {
2561   // Before we get into the guts of the C2I adapter, see if we should be here
2562   // at all. We've come from compiled code and are attempting to jump to the
2563   // interpreter, which means the caller made a static call to get here
2564   // (vcalls always get a compiled target if there is one). Check for a
2565   // compiled target. If there is one, we need to patch the caller's call.
2566 
2567   // These two defs MUST MATCH code in gen_i2c2i_adapter!
2568   const Register ientry = Z_R11;
2569   const Register code   = Z_R11;
2570 
2571   address c2i_entrypoint;
2572   Label   patch_callsite;
2573 
2574   // Regular (verified) c2i entry point.
2575   c2i_entrypoint = __ pc();
2576 
2577   // Call patching needed?
2578   __ load_and_test_long(Z_R0_scratch, method_(code));
2579   __ z_lg(ientry, method_(interpreter_entry));  // Preload interpreter entry (also if patching).
2580   __ z_brne(patch_callsite);                    // Patch required if code isn't null (compiled target exists).
2581 
2582   __ bind(skip_fixup);  // Return point from patch_callsite.
2583 
2584   // Since all args are passed on the stack, total_args_passed*wordSize is the
2585   // space we need. We need ABI scratch area but we use the caller's since
2586   // it has already been allocated.
2587   int       total_args_passed = sig->length();
2588   const int abi_scratch = frame::z_top_ijava_frame_abi_size;
2589   int       extraspace  = align_up(total_args_passed, 2)*wordSize + abi_scratch;
2590   Register  sender_SP   = Z_R10;
2591   Register  value       = Z_R12;
2592 
2593   // Remember the senderSP so we can pop the interpreter arguments off of the stack.
2594   // In addition, template interpreter expects initial_caller_sp in Z_R10.
2595   __ z_lgr(sender_SP, Z_SP);
2596 
2597   // This should always fit in 14 bit immediate.
2598   __ resize_frame(-extraspace, Z_R0_scratch);
2599 
2600   // We use the caller's ABI scratch area (out_preserved_stack_slots) for the initial
2601   // args. This essentially moves the callers ABI scratch area from the top to the
2602   // bottom of the arg area.
2603 
2604   int st_off =  extraspace - wordSize;
2605 
2606   // Now write the args into the outgoing interpreter space.
2607   for (int i = 0; i < total_args_passed; i++) {
2608     BasicType bt = sig->at(i)._bt;
2609 
2610     VMReg r_1 = regs[i].first();
2611     VMReg r_2 = regs[i].second();
2612     if (!r_1->is_valid()) {
2613       assert(!r_2->is_valid(), "");
2614       continue;
2615     }
2616     if (r_1->is_stack()) {
2617       // The calling convention produces OptoRegs that ignore the preserve area (abi scratch).
2618       // We must account for it here.
2619       int ld_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
2620 
2621       if (!r_2->is_valid()) {
2622         __ z_mvc(Address(Z_SP, st_off), Address(sender_SP, ld_off), sizeof(void*));
2623       } else {
2624         // longs are given 2 64-bit slots in the interpreter,
2625         // but the data is passed in only 1 slot.
2626         if (bt == T_LONG || bt == T_DOUBLE) {
2627 #ifdef ASSERT
2628           __ clear_mem(Address(Z_SP, st_off), sizeof(void *));
2629 #endif
2630           st_off -= wordSize;
2631         }
2632         __ z_mvc(Address(Z_SP, st_off), Address(sender_SP, ld_off), sizeof(void*));
2633       }
2634     } else {
2635       if (r_1->is_Register()) {
2636         if (!r_2->is_valid()) {
2637           __ z_st(r_1->as_Register(), st_off, Z_SP);
2638         } else {
2639           // longs are given 2 64-bit slots in the interpreter, but the
2640           // data is passed in only 1 slot.
2641           if (bt == T_LONG || bt == T_DOUBLE) {
2642 #ifdef ASSERT
2643             __ clear_mem(Address(Z_SP, st_off), sizeof(void *));
2644 #endif
2645             st_off -= wordSize;
2646           }
2647           __ z_stg(r_1->as_Register(), st_off, Z_SP);
2648         }
2649       } else {
2650         assert(r_1->is_FloatRegister(), "");
2651         if (!r_2->is_valid()) {
2652           __ z_ste(r_1->as_FloatRegister(), st_off, Z_SP);
2653         } else {
2654           // In 64bit, doubles are given 2 64-bit slots in the interpreter, but the
2655           // data is passed in only 1 slot.
2656           // One of these should get known junk...
2657 #ifdef ASSERT
2658           __ z_lzdr(Z_F1);
2659           __ z_std(Z_F1, st_off, Z_SP);
2660 #endif
2661           st_off-=wordSize;
2662           __ z_std(r_1->as_FloatRegister(), st_off, Z_SP);
2663         }
2664       }
2665     }
2666     st_off -= wordSize;
2667   }
2668 
2669 
2670   // Jump to the interpreter just as if interpreter was doing it.
2671   __ add2reg(Z_esp, st_off, Z_SP);
2672 
2673   // Frame_manager expects initial_caller_sp (= SP without resize by c2i) in Z_R10.
2674   __ z_br(ientry);
2675 
2676 
2677   // Prevent illegal entry to out-of-line code.
2678   __ z_illtrap(0x22);
2679 
2680   // Generate out-of-line runtime call to patch caller,
2681   // then continue as interpreted.
2682 
2683   // IF you lose the race you go interpreted.
2684   // We don't see any possible endless c2i -> i2c -> c2i ...
2685   // transitions no matter how rare.
2686   __ bind(patch_callsite);
2687 
2688   RegisterSaver::save_live_registers(masm, RegisterSaver::arg_registers);
2689   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite), Z_method, Z_R14);
2690   RegisterSaver::restore_live_registers(masm, RegisterSaver::arg_registers);
2691   __ z_bru(skip_fixup);
2692 
2693   // end of out-of-line code
2694 
2695   return c2i_entrypoint;
2696 }
2697 
2698 // On entry, the following registers are set
2699 //
2700 //    Z_thread  r8  - JavaThread*
2701 //    Z_method  r9  - callee's method (method to be invoked)
2702 //    Z_esp     r7  - operand (or expression) stack pointer of caller. one slot above last arg.
2703 //    Z_SP      r15 - SP prepared by call stub such that caller's outgoing args are near top
2704 //
2705 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
2706                                     int comp_args_on_stack,
2707                                     const GrowableArray<SigEntry>* sig,
2708                                     const VMRegPair *regs) {
2709   const Register value = Z_R12;
2710   const Register ld_ptr= Z_esp;
2711   int total_args_passed = sig->length();
2712 
2713   int ld_offset = total_args_passed * wordSize;
2714 
2715   // Cut-out for having no stack args.
2716   if (comp_args_on_stack) {
2717     // Sig words on the stack are greater than VMRegImpl::stack0. Those in
2718     // registers are below. By subtracting stack0, we either get a negative
2719     // number (all values in registers) or the maximum stack slot accessed.
2720     // Convert VMRegImpl (4 byte) stack slots to words.
2721     int comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
2722     // Round up to miminum stack alignment, in wordSize
2723     comp_words_on_stack = align_up(comp_words_on_stack, 2);
2724 
2725     __ resize_frame(-comp_words_on_stack*wordSize, Z_R0_scratch);
2726   }
2727 
2728   // Now generate the shuffle code. Pick up all register args and move the
2729   // rest through register value=Z_R12.
2730   for (int i = 0; i < total_args_passed; i++) {
2731     BasicType bt = sig->at(i)._bt;
2732     if (bt == T_VOID) {
2733       assert(i > 0 && (sig->at(i - 1)._bt == T_LONG || sig->at(i - 1)._bt == T_DOUBLE), "missing half");
2734       continue;
2735     }
2736 
2737     // Pick up 0, 1 or 2 words from ld_ptr.
2738     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
2739            "scrambled load targets?");
2740     VMReg r_1 = regs[i].first();
2741     VMReg r_2 = regs[i].second();
2742     if (!r_1->is_valid()) {
2743       assert(!r_2->is_valid(), "");
2744       continue;
2745     }
2746     if (r_1->is_FloatRegister()) {
2747       if (!r_2->is_valid()) {
2748         __ z_le(r_1->as_FloatRegister(), ld_offset, ld_ptr);
2749         ld_offset-=wordSize;
2750       } else {
2751         // Skip the unused interpreter slot.
2752         __ z_ld(r_1->as_FloatRegister(), ld_offset - wordSize, ld_ptr);
2753         ld_offset -= 2 * wordSize;
2754       }
2755     } else {
2756       if (r_1->is_stack()) {
2757         // Must do a memory to memory move.
2758         int st_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
2759 
2760         if (!r_2->is_valid()) {
2761           __ z_mvc(Address(Z_SP, st_off), Address(ld_ptr, ld_offset), sizeof(void*));
2762         } else {
2763           // In 64bit, longs are given 2 64-bit slots in the interpreter, but the
2764           // data is passed in only 1 slot.
2765           if (bt == T_LONG || bt == T_DOUBLE) {
2766             ld_offset -= wordSize;
2767           }
2768           __ z_mvc(Address(Z_SP, st_off), Address(ld_ptr, ld_offset), sizeof(void*));
2769         }
2770       } else {
2771         if (!r_2->is_valid()) {
2772           // Not sure we need to do this but it shouldn't hurt.
2773           if (is_reference_type(bt) || bt == T_ADDRESS) {
2774             __ z_lg(r_1->as_Register(), ld_offset, ld_ptr);
2775           } else {
2776             __ z_l(r_1->as_Register(), ld_offset, ld_ptr);
2777           }
2778         } else {
2779           // In 64bit, longs are given 2 64-bit slots in the interpreter, but the
2780           // data is passed in only 1 slot.
2781           if (bt == T_LONG || bt == T_DOUBLE) {
2782             ld_offset -= wordSize;
2783           }
2784           __ z_lg(r_1->as_Register(), ld_offset, ld_ptr);
2785         }
2786       }
2787       ld_offset -= wordSize;
2788     }
2789   }
2790 
2791   __ push_cont_fastpath(); // Set JavaThread::_cont_fastpath to the sp of the oldest interpreted frame we know about
2792 
2793   // Jump to the compiled code just as if compiled code was doing it.
2794   // load target address from method:
2795   __ z_lg(Z_R1_scratch, Address(Z_method, Method::from_compiled_offset()));
2796 
2797   // Store method into thread->callee_target.
2798   // 6243940: We might end up in handle_wrong_method if
2799   // the callee is deoptimized as we race thru here. If that
2800   // happens we don't want to take a safepoint because the
2801   // caller frame will look interpreted and arguments are now
2802   // "compiled" so it is much better to make this transition
2803   // invisible to the stack walking code. Unfortunately, if
2804   // we try and find the callee by normal means a safepoint
2805   // is possible. So we stash the desired callee in the thread
2806   // and the vm will find it there should this case occur.
2807   __ z_stg(Z_method, thread_(callee_target));
2808 
2809   __ z_br(Z_R1_scratch);
2810 }
2811 
2812 void SharedRuntime::generate_i2c2i_adapters(MacroAssembler* masm,
2813                                             int comp_args_on_stack,
2814                                             const GrowableArray<SigEntry>* sig,
2815                                             const VMRegPair* regs,
2816                                             const GrowableArray<SigEntry>* sig_cc,
2817                                             const VMRegPair* regs_cc,
2818                                             const GrowableArray<SigEntry>* sig_cc_ro,
2819                                             const VMRegPair* regs_cc_ro,
2820                                             address entry_address[AdapterBlob::ENTRY_COUNT],
2821                                             AdapterBlob*& new_adapter,
2822                                             bool allocate_code_blob) {
2823   __ align(CodeEntryAlignment);
2824   entry_address[AdapterBlob::I2C] = __ pc();
2825   gen_i2c_adapter(masm, comp_args_on_stack, sig, regs);
2826 
2827   Label skip_fixup;
2828   {
2829     Label ic_miss;
2830 
2831     // Out-of-line call to ic_miss handler.
2832     __ call_ic_miss_handler(ic_miss, 0x11, 0, Z_R1_scratch);
2833 
2834     // Unverified Entry Point UEP
2835     __ align(CodeEntryAlignment);
2836     entry_address[AdapterBlob::C2I_Unverified] = __ pc();
2837 
2838     __ ic_check(2);
2839     __ z_lg(Z_method, Address(Z_inline_cache, CompiledICData::speculated_method_offset()));
2840     // This def MUST MATCH code in gen_c2i_adapter!
2841     const Register code = Z_R11;
2842 
2843     __ load_and_test_long(Z_R0, method_(code));
2844     __ z_brne(ic_miss);  // Cache miss: call runtime to handle this.
2845 
2846     // Fallthru to VEP. Duplicate LTG, but saved taken branch.
2847   }
2848 
2849   entry_address[AdapterBlob::C2I] = __ pc();
2850 
2851   // Class initialization barrier for static methods
2852   entry_address[AdapterBlob::C2I_No_Clinit_Check] = nullptr;
2853   assert(VM_Version::supports_fast_class_init_checks(), "sanity");
2854   Label L_skip_barrier;
2855 
2856   // Bypass the barrier for non-static methods
2857   __ testbit_ushort(Address(Z_method, Method::access_flags_offset()), JVM_ACC_STATIC_BIT);
2858   __ z_bfalse(L_skip_barrier); // non-static
2859 
2860   Register klass = Z_R11;
2861   __ load_method_holder(klass, Z_method);
2862   __ clinit_barrier(klass, Z_thread, &L_skip_barrier /*L_fast_path*/);
2863 
2864   __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub());
2865   __ z_br(klass);
2866 
2867   __ bind(L_skip_barrier);
2868   entry_address[AdapterBlob::C2I_No_Clinit_Check] = __ pc();
2869 
2870   gen_c2i_adapter(masm, comp_args_on_stack, sig, regs, skip_fixup);
2871   return;
2872 }
2873 
2874 // This function returns the adjust size (in number of words) to a c2i adapter
2875 // activation for use during deoptimization.
2876 //
2877 // Actually only compiled frames need to be adjusted, but it
2878 // doesn't harm to adjust entry and interpreter frames, too.
2879 //
2880 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2881   assert(callee_locals >= callee_parameters,
2882           "test and remove; got more parms than locals");
2883   // Handle the abi adjustment here instead of doing it in push_skeleton_frames.
2884   return (callee_locals - callee_parameters) * Interpreter::stackElementWords +
2885          frame::z_parent_ijava_frame_abi_size / BytesPerWord;
2886 }
2887 
2888 uint SharedRuntime::in_preserve_stack_slots() {
2889   return frame::jit_in_preserve_size_in_4_byte_units;
2890 }
2891 
2892 uint SharedRuntime::out_preserve_stack_slots() {
2893   return frame::z_jit_out_preserve_size/VMRegImpl::stack_slot_size;
2894 }
2895 
2896 VMReg SharedRuntime::thread_register() {
2897   return Z_thread->as_VMReg();
2898 }
2899 
2900 //
2901 // Frame generation for deopt and uncommon trap blobs.
2902 //
2903 static void push_skeleton_frame(MacroAssembler* masm,
2904                           /* Unchanged */
2905                           Register frame_sizes_reg,
2906                           Register pcs_reg,
2907                           /* Invalidate */
2908                           Register frame_size_reg,
2909                           Register pc_reg) {
2910   BLOCK_COMMENT("  push_skeleton_frame {");
2911    __ z_lg(pc_reg, 0, pcs_reg);
2912    __ z_lg(frame_size_reg, 0, frame_sizes_reg);
2913    __ z_stg(pc_reg, _z_abi(return_pc), Z_SP);
2914    Register fp = pc_reg;
2915    __ push_frame(frame_size_reg, fp);
2916 #ifdef ASSERT
2917    // The magic is required for successful walking skeletal frames.
2918    __ load_const_optimized(frame_size_reg/*tmp*/, frame::z_istate_magic_number);
2919    __ z_stg(frame_size_reg, _z_ijava_state_neg(magic), fp);
2920    // Fill other slots that are supposedly not necessary with eye catchers.
2921    __ load_const_optimized(frame_size_reg/*use as tmp*/, 0xdeadbad1);
2922    __ z_stg(frame_size_reg, _z_ijava_state_neg(top_frame_sp), fp);
2923    // The sender_sp of the bottom frame is set before pushing it.
2924    // The sender_sp of non bottom frames is their caller's top_frame_sp, which
2925    // is unknown here. Luckily it is not needed before filling the frame in
2926    // layout_activation(), we assert this by setting an eye catcher (see
2927    // comments on sender_sp in frame_s390.hpp).
2928    __ z_stg(frame_size_reg, _z_ijava_state_neg(sender_sp), Z_SP);
2929 #endif // ASSERT
2930   BLOCK_COMMENT("  } push_skeleton_frame");
2931 }
2932 
2933 // Loop through the UnrollBlock info and create new frames.
2934 static void push_skeleton_frames(MacroAssembler* masm, bool deopt,
2935                             /* read */
2936                             Register unroll_block_reg,
2937                             /* invalidate */
2938                             Register frame_sizes_reg,
2939                             Register number_of_frames_reg,
2940                             Register pcs_reg,
2941                             Register tmp1,
2942                             Register tmp2) {
2943   BLOCK_COMMENT("push_skeleton_frames {");
2944   // _number_of_frames is of type int (deoptimization.hpp).
2945   __ z_lgf(number_of_frames_reg,
2946            Address(unroll_block_reg, Deoptimization::UnrollBlock::number_of_frames_offset()));
2947   __ z_lg(pcs_reg,
2948           Address(unroll_block_reg, Deoptimization::UnrollBlock::frame_pcs_offset()));
2949   __ z_lg(frame_sizes_reg,
2950           Address(unroll_block_reg, Deoptimization::UnrollBlock::frame_sizes_offset()));
2951 
2952   // stack: (caller_of_deoptee, ...).
2953 
2954   // If caller_of_deoptee is a compiled frame, then we extend it to make
2955   // room for the callee's locals and the frame::z_parent_ijava_frame_abi.
2956   // See also Deoptimization::last_frame_adjust() above.
2957   // Note: entry and interpreted frames are adjusted, too. But this doesn't harm.
2958 
2959   __ z_lgf(Z_R1_scratch,
2960            Address(unroll_block_reg, Deoptimization::UnrollBlock::caller_adjustment_offset()));
2961   __ z_lgr(tmp1, Z_SP);  // Save the sender sp before extending the frame.
2962   __ resize_frame_sub(Z_R1_scratch, tmp2/*tmp*/);
2963   // The oldest skeletal frame requires a valid sender_sp to make it walkable
2964   // (it is required to find the original pc of caller_of_deoptee if it is marked
2965   // for deoptimization - see nmethod::orig_pc_addr()).
2966   __ z_stg(tmp1, _z_ijava_state_neg(sender_sp), Z_SP);
2967 
2968   // Now push the new interpreter frames.
2969   Label loop, loop_entry;
2970 
2971   // Make sure that there is at least one entry in the array.
2972   DEBUG_ONLY(__ z_ltgr(number_of_frames_reg, number_of_frames_reg));
2973   __ asm_assert(Assembler::bcondNotZero, "array_size must be > 0", 0x205);
2974 
2975   __ z_bru(loop_entry);
2976 
2977   __ bind(loop);
2978 
2979   __ add2reg(frame_sizes_reg, wordSize);
2980   __ add2reg(pcs_reg, wordSize);
2981 
2982   __ bind(loop_entry);
2983 
2984   // Allocate a new frame, fill in the pc.
2985   push_skeleton_frame(masm, frame_sizes_reg, pcs_reg, tmp1, tmp2);
2986 
2987   __ z_aghi(number_of_frames_reg, -1);  // Emit AGHI, because it sets the condition code
2988   __ z_brne(loop);
2989 
2990   // Set the top frame's return pc.
2991   __ add2reg(pcs_reg, wordSize);
2992   __ z_lg(Z_R0_scratch, 0, pcs_reg);
2993   __ z_stg(Z_R0_scratch, _z_abi(return_pc), Z_SP);
2994   BLOCK_COMMENT("} push_skeleton_frames");
2995 }
2996 
2997 //------------------------------generate_deopt_blob----------------------------
2998 void SharedRuntime::generate_deopt_blob() {
2999   // Allocate space for the code.
3000   ResourceMark rm;
3001   // Setup code generation tools.
3002   const char* name = SharedRuntime::stub_name(StubId::shared_deopt_id);
3003   CodeBuffer buffer(name, 2048, 1024);
3004   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
3005   Label exec_mode_initialized;
3006   OopMap* map = nullptr;
3007   OopMapSet *oop_maps = new OopMapSet();
3008 
3009   unsigned int start_off = __ offset();
3010   Label cont;
3011 
3012   // --------------------------------------------------------------------------
3013   // Normal entry (non-exception case)
3014   //
3015   // We have been called from the deopt handler of the deoptee.
3016   // Z_R14 points to the entry point of the deopt handler.
3017   // The return_pc has been stored in the frame of the deoptee and
3018   // will replace the address of the deopt_handler in the call
3019   // to Deoptimization::fetch_unroll_info below.
3020 
3021   const Register   exec_mode_reg = Z_tmp_1;
3022 
3023   // stack: (deoptee, caller of deoptee, ...)
3024 
3025   // pushes an "unpack" frame
3026   // R14 contains the return address pointing into the deoptimized
3027   // nmethod that was valid just before the nmethod was deoptimized.
3028   // save R14 into the deoptee frame.  the `fetch_unroll_info'
3029   // procedure called below will read it from there.
3030   map = RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers, Z_R14, /* save_vectors= */ SuperwordUseVX);
3031 
3032   // note the entry point.
3033   __ load_const_optimized(exec_mode_reg, Deoptimization::Unpack_deopt);
3034   __ z_bru(exec_mode_initialized);
3035 
3036 #ifndef COMPILER1
3037   int reexecute_offset = 1; // odd offset will produce odd pc, which triggers an hardware trap
3038 #else
3039   // --------------------------------------------------------------------------
3040   // Reexecute entry
3041   // - Z_R14 = Deopt Handler in nmethod
3042 
3043   int reexecute_offset = __ offset() - start_off;
3044 
3045   // No need to update map as each call to save_live_registers will produce identical oopmap
3046   (void) RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers, Z_R14, /* save_vectors= */ SuperwordUseVX);
3047 
3048   __ load_const_optimized(exec_mode_reg, Deoptimization::Unpack_reexecute);
3049   __ z_bru(exec_mode_initialized);
3050 #endif
3051 
3052 
3053   // --------------------------------------------------------------------------
3054   // Exception entry. We reached here via a branch. Registers on entry:
3055   // - Z_EXC_OOP (Z_ARG1) = exception oop
3056   // - Z_EXC_PC  (Z_ARG2) = the exception pc.
3057 
3058   int exception_offset = __ offset() - start_off;
3059 
3060   // all registers are dead at this entry point, except for Z_EXC_OOP, and
3061   // Z_EXC_PC which contain the exception oop and exception pc
3062   // respectively.  Set them in TLS and fall thru to the
3063   // unpack_with_exception_in_tls entry point.
3064 
3065   // Store exception oop and pc in thread (location known to GC).
3066   // Need this since the call to "fetch_unroll_info()" may safepoint.
3067   __ z_stg(Z_EXC_OOP, Address(Z_thread, JavaThread::exception_oop_offset()));
3068   __ z_stg(Z_EXC_PC,  Address(Z_thread, JavaThread::exception_pc_offset()));
3069 
3070   // fall through
3071 
3072   int exception_in_tls_offset = __ offset() - start_off;
3073 
3074   // new implementation because exception oop is now passed in JavaThread
3075 
3076   // Prolog for exception case
3077   // All registers must be preserved because they might be used by LinearScan
3078   // Exceptiop oop and throwing PC are passed in JavaThread
3079 
3080   // load throwing pc from JavaThread and us it as the return address of the current frame.
3081   __ z_lg(Z_R1_scratch, Address(Z_thread, JavaThread::exception_pc_offset()));
3082 
3083   // Save everything in sight.
3084   (void) RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers, Z_R1_scratch, /* save_vectors= */ SuperwordUseVX);
3085 
3086   // Now it is safe to overwrite any register
3087 
3088   // Clear the exception pc field in JavaThread
3089   __ clear_mem(Address(Z_thread, JavaThread::exception_pc_offset()), 8);
3090 
3091   // Deopt during an exception.  Save exec mode for unpack_frames.
3092   __ load_const_optimized(exec_mode_reg, Deoptimization::Unpack_exception);
3093 
3094 
3095 #ifdef ASSERT
3096   // verify that there is really an exception oop in JavaThread
3097   __ z_lg(Z_ARG1, Address(Z_thread, JavaThread::exception_oop_offset()));
3098   __ MacroAssembler::verify_oop(Z_ARG1, FILE_AND_LINE);
3099 
3100   // verify that there is no pending exception
3101   __ asm_assert_mem8_is_zero(in_bytes(Thread::pending_exception_offset()), Z_thread,
3102                              "must not have pending exception here", __LINE__);
3103 #endif
3104 
3105   // --------------------------------------------------------------------------
3106   // At this point, the live registers are saved and
3107   // the exec_mode_reg has been set up correctly.
3108   __ bind(exec_mode_initialized);
3109 
3110   // stack: ("unpack" frame, deoptee, caller_of_deoptee, ...).
3111 
3112   const Register unroll_block_reg  = Z_tmp_2;
3113 
3114   // we need to set `last_Java_frame' because `fetch_unroll_info' will
3115   // call `last_Java_frame()'.  however we can't block and no gc will
3116   // occur so we don't need an oopmap. the value of the pc in the
3117   // frame is not particularly important.  it just needs to identify the blob.
3118 
3119   // Don't set last_Java_pc anymore here (is implicitly null then).
3120   // the correct PC is retrieved in pd_last_frame() in that case.
3121   __ set_last_Java_frame(/*sp*/Z_SP, noreg);
3122   // With EscapeAnalysis turned on, this call may safepoint
3123   // despite it's marked as "leaf call"!
3124   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info), Z_thread, exec_mode_reg);
3125   // Set an oopmap for the call site this describes all our saved volatile registers
3126   int oop_map_offs = __ offset();
3127   oop_maps->add_gc_map(oop_map_offs, map);
3128 
3129   __ reset_last_Java_frame();
3130   // save the return value.
3131   __ z_lgr(unroll_block_reg, Z_RET);
3132   // restore the return registers that have been saved
3133   // (among other registers) by save_live_registers(...).
3134   RegisterSaver::restore_result_registers(masm, /* save_vectors= */ SuperwordUseVX);
3135 
3136   // reload the exec mode from the UnrollBlock (it might have changed)
3137   __ z_llgf(exec_mode_reg, Address(unroll_block_reg, Deoptimization::UnrollBlock::unpack_kind_offset()));
3138 
3139   // In excp_deopt_mode, restore and clear exception oop which we
3140   // stored in the thread during exception entry above. The exception
3141   // oop will be the return value of this stub.
3142   NearLabel skip_restore_excp;
3143   __ compare64_and_branch(exec_mode_reg, Deoptimization::Unpack_exception, Assembler::bcondNotEqual, skip_restore_excp);
3144   __ z_lg(Z_RET, thread_(exception_oop));
3145   __ clear_mem(thread_(exception_oop), 8);
3146   __ bind(skip_restore_excp);
3147 
3148   // remove the "unpack" frame
3149   __ pop_frame();
3150 
3151   // stack: (deoptee, caller of deoptee, ...).
3152 
3153   // pop the deoptee's frame
3154   __ pop_frame();
3155 
3156   // stack: (caller_of_deoptee, ...).
3157 
3158   // Freezing continuation frames requires that the caller is trimmed to unextended sp if compiled.
3159   // If not compiled the loaded value is equal to the current SP (see frame::initial_deoptimization_info())
3160   // and the frame is effectively not resized.
3161   Register caller_sp = Z_R1_scratch;
3162   __ z_lg(caller_sp, Address(unroll_block_reg, Deoptimization::UnrollBlock::initial_info_offset()));
3163   __ resize_frame_absolute(caller_sp, Z_R0, true);
3164 
3165   // loop through the `UnrollBlock' info and create interpreter frames.
3166   push_skeleton_frames(masm, true/*deopt*/,
3167                   unroll_block_reg,
3168                   Z_tmp_3,
3169                   Z_tmp_4,
3170                   Z_ARG5,
3171                   Z_ARG4,
3172                   Z_ARG3);
3173 
3174   // stack: (skeletal interpreter frame, ..., optional skeletal
3175   // interpreter frame, caller of deoptee, ...).
3176 
3177   // push an "unpack" frame taking care of float / int return values.
3178   __ push_frame(RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers));
3179 
3180   // stack: (unpack frame, skeletal interpreter frame, ..., optional
3181   // skeletal interpreter frame, caller of deoptee, ...).
3182 
3183   // spill live volatile registers since we'll do a call.
3184   __ z_stg(Z_RET, offset_of(frame::z_abi_160_spill, spill[0]), Z_SP);
3185   __ z_std(Z_FRET, offset_of(frame::z_abi_160_spill, spill[1]), Z_SP);
3186 
3187   // let the unpacker layout information in the skeletal frames just allocated.
3188   __ get_PC(Z_RET, oop_map_offs - __ offset());
3189   __ set_last_Java_frame(/*sp*/Z_SP, /*pc*/Z_RET);
3190   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames),
3191                   Z_thread/*thread*/, exec_mode_reg/*exec_mode*/);
3192 
3193   __ reset_last_Java_frame();
3194 
3195   // restore the volatiles saved above.
3196   __ z_lg(Z_RET, offset_of(frame::z_abi_160_spill, spill[0]), Z_SP);
3197   __ z_ld(Z_FRET, offset_of(frame::z_abi_160_spill, spill[1]), Z_SP);
3198 
3199   // pop the "unpack" frame.
3200   __ pop_frame();
3201   __ restore_return_pc();
3202 
3203   // stack: (top interpreter frame, ..., optional interpreter frame,
3204   // caller of deoptee, ...).
3205 
3206   __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // restore frame pointer
3207   __ restore_bcp();
3208   __ restore_locals();
3209   __ restore_esp();
3210 
3211   // return to the interpreter entry point.
3212   __ z_br(Z_R14);
3213 
3214   // Make sure all code is generated
3215   masm->flush();
3216 
3217   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers, SuperwordUseVX)/wordSize);
3218   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
3219 }
3220 
3221 
3222 #ifdef COMPILER2
3223 //------------------------------generate_uncommon_trap_blob--------------------
3224 UncommonTrapBlob* OptoRuntime::generate_uncommon_trap_blob() {
3225   // Allocate space for the code
3226   ResourceMark rm;
3227   // Setup code generation tools
3228   const char* name = OptoRuntime::stub_name(StubId::c2_uncommon_trap_id);
3229   CodeBuffer buffer(name, 2048, 1024);
3230   if (buffer.blob() == nullptr) {
3231     return nullptr;
3232   }
3233   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
3234 
3235   Register unroll_block_reg = Z_tmp_1;
3236   Register klass_index_reg  = Z_ARG2;
3237   Register unc_trap_reg     = Z_ARG2;
3238 
3239   // stack: (deoptee, caller_of_deoptee, ...).
3240 
3241   // push a dummy "unpack" frame and call
3242   // `Deoptimization::uncommon_trap' to pack the compiled frame into a
3243   // vframe array and return the `UnrollBlock' information.
3244 
3245   // save R14 to compiled frame.
3246   __ save_return_pc();
3247   // push the "unpack_frame".
3248   __ push_frame_abi160(0);
3249 
3250   // stack: (unpack frame, deoptee, caller_of_deoptee, ...).
3251 
3252   // set the "unpack" frame as last_Java_frame.
3253   // `Deoptimization::uncommon_trap' expects it and considers its
3254   // sender frame as the deoptee frame.
3255   __ get_PC(Z_R1_scratch);
3256   __ set_last_Java_frame(/*sp*/Z_SP, /*pc*/Z_R1_scratch);
3257 
3258   __ z_lgr(klass_index_reg, Z_ARG1);  // passed implicitly as ARG2
3259   __ z_lghi(Z_ARG3, Deoptimization::Unpack_uncommon_trap);  // passed implicitly as ARG3
3260   BLOCK_COMMENT("call Deoptimization::uncommon_trap()");
3261   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap), Z_thread);
3262 
3263   __ reset_last_Java_frame();
3264 
3265   // pop the "unpack" frame
3266   __ pop_frame();
3267 
3268   // stack: (deoptee, caller_of_deoptee, ...).
3269 
3270   // save the return value.
3271   __ z_lgr(unroll_block_reg, Z_RET);
3272 
3273   // pop the deoptee frame.
3274   __ pop_frame();
3275 
3276   // stack: (caller_of_deoptee, ...).
3277 
3278 #ifdef ASSERT
3279   assert(Immediate::is_uimm8(Deoptimization::Unpack_LIMIT), "Code not fit for larger immediates");
3280   assert(Immediate::is_uimm8(Deoptimization::Unpack_uncommon_trap), "Code not fit for larger immediates");
3281   const int unpack_kind_byte_offset = in_bytes(Deoptimization::UnrollBlock::unpack_kind_offset())
3282 #ifndef VM_LITTLE_ENDIAN
3283   + 3
3284 #endif
3285   ;
3286   if (Displacement::is_shortDisp(unpack_kind_byte_offset)) {
3287     __ z_cli(unpack_kind_byte_offset, unroll_block_reg, Deoptimization::Unpack_uncommon_trap);
3288   } else {
3289     __ z_cliy(unpack_kind_byte_offset, unroll_block_reg, Deoptimization::Unpack_uncommon_trap);
3290   }
3291   __ asm_assert(Assembler::bcondEqual, "OptoRuntime::generate_deopt_blob: expected Unpack_uncommon_trap", 0);
3292 #endif
3293 
3294   __ zap_from_to(Z_SP, Z_SP, Z_R0_scratch, Z_R1, 500, -1);
3295 
3296   // Freezing continuation frames requires that the caller is trimmed to unextended sp if compiled.
3297   // If not compiled the loaded value is equal to the current SP (see frame::initial_deoptimization_info())
3298   // and the frame is effectively not resized.
3299   Register caller_sp = Z_R1_scratch;
3300   __ z_lg(caller_sp, Address(unroll_block_reg, Deoptimization::UnrollBlock::initial_info_offset()));
3301   __ resize_frame_absolute(caller_sp, Z_R0, true);
3302 
3303   // allocate new interpreter frame(s) and possibly resize the caller's frame
3304   // (no more adapters !)
3305   push_skeleton_frames(masm, false/*deopt*/,
3306                   unroll_block_reg,
3307                   Z_tmp_2,
3308                   Z_tmp_3,
3309                   Z_tmp_4,
3310                   Z_ARG5,
3311                   Z_ARG4);
3312 
3313   // stack: (skeletal interpreter frame, ..., optional skeletal
3314   // interpreter frame, (resized) caller of deoptee, ...).
3315 
3316   // push a dummy "unpack" frame taking care of float return values.
3317   // call `Deoptimization::unpack_frames' to layout information in the
3318   // interpreter frames just created
3319 
3320   // push the "unpack" frame
3321    const unsigned int framesize_in_bytes = __ push_frame_abi160(0);
3322 
3323   // stack: (unpack frame, skeletal interpreter frame, ..., optional
3324   // skeletal interpreter frame, (resized) caller of deoptee, ...).
3325 
3326   // set the "unpack" frame as last_Java_frame
3327   __ get_PC(Z_R1_scratch);
3328   __ set_last_Java_frame(/*sp*/Z_SP, /*pc*/Z_R1_scratch);
3329 
3330   // indicate it is the uncommon trap case
3331   BLOCK_COMMENT("call Deoptimization::Unpack_uncommon_trap()");
3332   __ load_const_optimized(unc_trap_reg, Deoptimization::Unpack_uncommon_trap);
3333   // let the unpacker layout information in the skeletal frames just allocated.
3334   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames), Z_thread);
3335 
3336   __ reset_last_Java_frame();
3337   // pop the "unpack" frame
3338   __ pop_frame();
3339   // restore LR from top interpreter frame
3340   __ restore_return_pc();
3341 
3342   // stack: (top interpreter frame, ..., optional interpreter frame,
3343   // (resized) caller of deoptee, ...).
3344 
3345   __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // restore frame pointer
3346   __ restore_bcp();
3347   __ restore_locals();
3348   __ restore_esp();
3349 
3350   // return to the interpreter entry point
3351   __ z_br(Z_R14);
3352 
3353   masm->flush();
3354   return UncommonTrapBlob::create(&buffer, nullptr, framesize_in_bytes/wordSize);
3355 }
3356 #endif // COMPILER2
3357 
3358 
3359 //------------------------------generate_handler_blob------
3360 //
3361 // Generate a special Compile2Runtime blob that saves all registers,
3362 // and setup oopmap.
3363 SafepointBlob* SharedRuntime::generate_handler_blob(StubId id, address call_ptr) {
3364   assert(StubRoutines::forward_exception_entry() != nullptr,
3365          "must be generated before");
3366   assert(is_polling_page_id(id), "expected a polling page stub id");
3367 
3368   ResourceMark rm;
3369   OopMapSet *oop_maps = new OopMapSet();
3370   OopMap* map;
3371 
3372   // Allocate space for the code. Setup code generation tools.
3373   const char* name = SharedRuntime::stub_name(id);
3374   CodeBuffer buffer(name, 2048, 1024);
3375   MacroAssembler* masm = new MacroAssembler(&buffer);
3376 
3377   unsigned int start_off = __ offset();
3378   address call_pc = nullptr;
3379   int frame_size_in_bytes;
3380 
3381   bool cause_return = (id == StubId::shared_polling_page_return_handler_id);
3382   // Make room for return address (or push it again)
3383   if (!cause_return) {
3384     __ z_lg(Z_R14, Address(Z_thread, JavaThread::saved_exception_pc_offset()));
3385   }
3386 
3387   bool save_vectors = (id == StubId::shared_polling_page_vectors_safepoint_handler_id);
3388   // Save registers, fpu state, and flags
3389   map = RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers, Z_R14, save_vectors);
3390 
3391   if (!cause_return) {
3392     // Keep a copy of the return pc to detect if it gets modified.
3393     __ z_lgr(Z_R6, Z_R14);
3394   }
3395 
3396   // The following is basically a call_VM. However, we need the precise
3397   // address of the call in order to generate an oopmap. Hence, we do all the
3398   // work ourselves.
3399   __ set_last_Java_frame(Z_SP, noreg);
3400 
3401   // call into the runtime to handle the safepoint poll
3402   __ call_VM_leaf(call_ptr, Z_thread);
3403 
3404 
3405   // Set an oopmap for the call site. This oopmap will map all
3406   // oop-registers and debug-info registers as callee-saved. This
3407   // will allow deoptimization at this safepoint to find all possible
3408   // debug-info recordings, as well as let GC find all oops.
3409 
3410   oop_maps->add_gc_map((int)(__ offset()-start_off), map);
3411 
3412   Label noException;
3413 
3414   __ reset_last_Java_frame();
3415 
3416   __ load_and_test_long(Z_R1, thread_(pending_exception));
3417   __ z_bre(noException);
3418 
3419   // Pending exception case, used (sporadically) by
3420   // api/java_lang/Thread.State/index#ThreadState et al.
3421   RegisterSaver::restore_live_registers(masm, RegisterSaver::all_registers, save_vectors);
3422 
3423   // Jump to forward_exception_entry, with the issuing PC in Z_R14
3424   // so it looks like the original nmethod called forward_exception_entry.
3425   __ load_const_optimized(Z_R1_scratch, StubRoutines::forward_exception_entry());
3426   __ z_br(Z_R1_scratch);
3427 
3428   // No exception case
3429   __ bind(noException);
3430 
3431   if (!cause_return) {
3432     Label no_adjust;
3433      // If our stashed return pc was modified by the runtime we avoid touching it
3434     const int offset_of_return_pc = _z_common_abi(return_pc) + RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers, save_vectors);
3435     __ z_cg(Z_R6, offset_of_return_pc, Z_SP);
3436     __ z_brne(no_adjust);
3437 
3438     // Adjust return pc forward to step over the safepoint poll instruction
3439     __ instr_size(Z_R1_scratch, Z_R6);
3440     __ z_agr(Z_R6, Z_R1_scratch);
3441     __ z_stg(Z_R6, offset_of_return_pc, Z_SP);
3442 
3443     __ bind(no_adjust);
3444   }
3445 
3446   // Normal exit, restore registers and exit.
3447   RegisterSaver::restore_live_registers(masm, RegisterSaver::all_registers, save_vectors);
3448 
3449   __ z_br(Z_R14);
3450 
3451   // Make sure all code is generated
3452   masm->flush();
3453 
3454   // Fill-out other meta info
3455   return SafepointBlob::create(&buffer, oop_maps, RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers, save_vectors)/wordSize);
3456 }
3457 
3458 
3459 //
3460 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3461 //
3462 // Generate a stub that calls into vm to find out the proper destination
3463 // of a Java call. All the argument registers are live at this point
3464 // but since this is generic code we don't know what they are and the caller
3465 // must do any gc of the args.
3466 //
3467 RuntimeStub* SharedRuntime::generate_resolve_blob(StubId id, address destination) {
3468   assert (StubRoutines::forward_exception_entry() != nullptr, "must be generated before");
3469   assert(is_resolve_id(id), "expected a resolve stub id");
3470 
3471   // allocate space for the code
3472   ResourceMark rm;
3473 
3474   const char* name = SharedRuntime::stub_name(id);
3475   CodeBuffer buffer(name, 1000, 512);
3476   MacroAssembler* masm                = new MacroAssembler(&buffer);
3477 
3478   OopMapSet *oop_maps = new OopMapSet();
3479   OopMap* map = nullptr;
3480 
3481   unsigned int start_off = __ offset();
3482 
3483   map = RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers);
3484 
3485   // We must save a PC from within the stub as return PC
3486   // C code doesn't store the LR where we expect the PC,
3487   // so we would run into trouble upon stack walking.
3488   __ get_PC(Z_R1_scratch);
3489 
3490   unsigned int frame_complete = __ offset();
3491 
3492   __ set_last_Java_frame(/*sp*/Z_SP, Z_R1_scratch);
3493 
3494   __ call_VM_leaf(destination, Z_thread, Z_method);
3495 
3496 
3497   // Set an oopmap for the call site.
3498   // We need this not only for callee-saved registers, but also for volatile
3499   // registers that the compiler might be keeping live across a safepoint.
3500 
3501   oop_maps->add_gc_map((int)(frame_complete-start_off), map);
3502 
3503   // clear last_Java_sp
3504   __ reset_last_Java_frame();
3505 
3506   // check for pending exceptions
3507   Label pending;
3508   __ load_and_test_long(Z_R0, Address(Z_thread, Thread::pending_exception_offset()));
3509   __ z_brne(pending);
3510 
3511   __ z_lgr(Z_R1_scratch, Z_R2); // r1 is neither saved nor restored, r2 contains the continuation.
3512   RegisterSaver::restore_live_registers(masm, RegisterSaver::all_registers);
3513 
3514   // get the returned method
3515   __ get_vm_result_metadata(Z_method);
3516 
3517   // We are back to the original state on entry and ready to go.
3518   __ z_br(Z_R1_scratch);
3519 
3520   // Pending exception after the safepoint
3521 
3522   __ bind(pending);
3523 
3524   RegisterSaver::restore_live_registers(masm, RegisterSaver::all_registers);
3525 
3526   // exception pending => remove activation and forward to exception handler
3527 
3528   __ z_lgr(Z_R2, Z_R0); // pending_exception
3529   __ clear_mem(Address(Z_thread, JavaThread::vm_result_oop_offset()), sizeof(jlong));
3530   __ load_const_optimized(Z_R1_scratch, StubRoutines::forward_exception_entry());
3531   __ z_br(Z_R1_scratch);
3532 
3533   // -------------
3534   // make sure all code is generated
3535   masm->flush();
3536 
3537   // return the blob
3538   // frame_size_words or bytes??
3539   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers)/wordSize,
3540                                        oop_maps, true);
3541 
3542 }
3543 
3544 // Continuation point for throwing of implicit exceptions that are
3545 // not handled in the current activation. Fabricates an exception
3546 // oop and initiates normal exception dispatching in this
3547 // frame. Only callee-saved registers are preserved (through the
3548 // normal RegisterMap handling). If the compiler
3549 // needs all registers to be preserved between the fault point and
3550 // the exception handler then it must assume responsibility for that
3551 // in AbstractCompiler::continuation_for_implicit_null_exception or
3552 // continuation_for_implicit_division_by_zero_exception. All other
3553 // implicit exceptions (e.g., NullPointerException or
3554 // AbstractMethodError on entry) are either at call sites or
3555 // otherwise assume that stack unwinding will be initiated, so
3556 // caller saved registers were assumed volatile in the compiler.
3557 
3558 // Note that we generate only this stub into a RuntimeStub, because
3559 // it needs to be properly traversed and ignored during GC, so we
3560 // change the meaning of the "__" macro within this method.
3561 
3562 // Note: the routine set_pc_not_at_call_for_caller in
3563 // SharedRuntime.cpp requires that this code be generated into a
3564 // RuntimeStub.
3565 
3566 RuntimeStub* SharedRuntime::generate_throw_exception(StubId id, address runtime_entry) {
3567   assert(is_throw_id(id), "expected a throw stub id");
3568 
3569   const char* name = SharedRuntime::stub_name(id);
3570 
3571   int insts_size = 256;
3572   int locs_size  = 0;
3573 
3574   ResourceMark rm;
3575   const char* timer_msg = "SharedRuntime generate_throw_exception";
3576   TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime));
3577 
3578   CodeBuffer      code(name, insts_size, locs_size);
3579   MacroAssembler* masm = new MacroAssembler(&code);
3580   int framesize_in_bytes;
3581   address start = __ pc();
3582 
3583   __ save_return_pc();
3584   framesize_in_bytes = __ push_frame_abi160(0);
3585 
3586   address frame_complete_pc = __ pc();
3587 
3588   // Note that we always have a runtime stub frame on the top of stack at this point.
3589   __ get_PC(Z_R1);
3590   __ set_last_Java_frame(/*sp*/Z_SP, /*pc*/Z_R1);
3591 
3592   // Do the call.
3593   BLOCK_COMMENT("call runtime_entry");
3594   __ call_VM_leaf(runtime_entry, Z_thread);
3595 
3596   __ reset_last_Java_frame();
3597 
3598 #ifdef ASSERT
3599   // Make sure that this code is only executed if there is a pending exception.
3600   { Label L;
3601     __ z_lg(Z_R0,
3602             in_bytes(Thread::pending_exception_offset()),
3603             Z_thread);
3604     __ z_ltgr(Z_R0, Z_R0);
3605     __ z_brne(L);
3606     __ stop("SharedRuntime::throw_exception: no pending exception");
3607     __ bind(L);
3608   }
3609 #endif
3610 
3611   __ pop_frame();
3612   __ restore_return_pc();
3613 
3614   __ load_const_optimized(Z_R1, StubRoutines::forward_exception_entry());
3615   __ z_br(Z_R1);
3616 
3617   RuntimeStub* stub =
3618     RuntimeStub::new_runtime_stub(name, &code,
3619                                   frame_complete_pc - start,
3620                                   framesize_in_bytes/wordSize,
3621                                   nullptr /*oop_maps*/, false);
3622 
3623   return stub;
3624 }
3625 
3626 //------------------------------Montgomery multiplication------------------------
3627 //
3628 
3629 // Subtract 0:b from carry:a. Return carry.
3630 static unsigned long
3631 sub(unsigned long a[], unsigned long b[], unsigned long carry, long len) {
3632   unsigned long i, c = 8 * (unsigned long)(len - 1);
3633   __asm__ __volatile__ (
3634     "SLGR   %[i], %[i]         \n" // initialize to 0 and pre-set carry
3635     "LGHI   0, 8               \n" // index increment (for BRXLG)
3636     "LGR    1, %[c]            \n" // index limit (for BRXLG)
3637     "0:                        \n"
3638     "LG     %[c], 0(%[i],%[a]) \n"
3639     "SLBG   %[c], 0(%[i],%[b]) \n" // subtract with borrow
3640     "STG    %[c], 0(%[i],%[a]) \n"
3641     "BRXLG  %[i], 0, 0b        \n" // while ((i+=8)<limit);
3642     "SLBGR  %[c], %[c]         \n" // save carry - 1
3643     : [i]"=&a"(i), [c]"+r"(c)
3644     : [a]"a"(a), [b]"a"(b)
3645     : "cc", "memory", "r0", "r1"
3646  );
3647   return carry + c;
3648 }
3649 
3650 // Multiply (unsigned) Long A by Long B, accumulating the double-
3651 // length result into the accumulator formed of T0, T1, and T2.
3652 inline void MACC(unsigned long A[], long A_ind,
3653                  unsigned long B[], long B_ind,
3654                  unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3655   long A_si = 8 * A_ind,
3656        B_si = 8 * B_ind;
3657   __asm__ __volatile__ (
3658     "LG     1, 0(%[A_si],%[A]) \n"
3659     "MLG    0, 0(%[B_si],%[B]) \n" // r0r1 = A * B
3660     "ALGR   %[T0], 1           \n"
3661     "LGHI   1, 0               \n" // r1 = 0
3662     "ALCGR  %[T1], 0           \n"
3663     "ALCGR  %[T2], 1           \n"
3664     : [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3665     : [A]"r"(A), [A_si]"r"(A_si), [B]"r"(B), [B_si]"r"(B_si)
3666     : "cc", "r0", "r1"
3667  );
3668 }
3669 
3670 // As above, but add twice the double-length result into the
3671 // accumulator.
3672 inline void MACC2(unsigned long A[], long A_ind,
3673                   unsigned long B[], long B_ind,
3674                   unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3675   const unsigned long zero = 0;
3676   long A_si = 8 * A_ind,
3677        B_si = 8 * B_ind;
3678   __asm__ __volatile__ (
3679     "LG     1, 0(%[A_si],%[A]) \n"
3680     "MLG    0, 0(%[B_si],%[B]) \n" // r0r1 = A * B
3681     "ALGR   %[T0], 1           \n"
3682     "ALCGR  %[T1], 0           \n"
3683     "ALCGR  %[T2], %[zero]     \n"
3684     "ALGR   %[T0], 1           \n"
3685     "ALCGR  %[T1], 0           \n"
3686     "ALCGR  %[T2], %[zero]     \n"
3687     : [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3688     : [A]"r"(A), [A_si]"r"(A_si), [B]"r"(B), [B_si]"r"(B_si), [zero]"r"(zero)
3689     : "cc", "r0", "r1"
3690  );
3691 }
3692 
3693 // Fast Montgomery multiplication. The derivation of the algorithm is
3694 // in "A Cryptographic Library for the Motorola DSP56000,
3695 // Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237".
3696 static void
3697 montgomery_multiply(unsigned long a[], unsigned long b[], unsigned long n[],
3698                     unsigned long m[], unsigned long inv, int len) {
3699   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3700   int i;
3701 
3702   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3703 
3704   for (i = 0; i < len; i++) {
3705     int j;
3706     for (j = 0; j < i; j++) {
3707       MACC(a, j, b, i-j, t0, t1, t2);
3708       MACC(m, j, n, i-j, t0, t1, t2);
3709     }
3710     MACC(a, i, b, 0, t0, t1, t2);
3711     m[i] = t0 * inv;
3712     MACC(m, i, n, 0, t0, t1, t2);
3713 
3714     assert(t0 == 0, "broken Montgomery multiply");
3715 
3716     t0 = t1; t1 = t2; t2 = 0;
3717   }
3718 
3719   for (i = len; i < 2 * len; i++) {
3720     int j;
3721     for (j = i - len + 1; j < len; j++) {
3722       MACC(a, j, b, i-j, t0, t1, t2);
3723       MACC(m, j, n, i-j, t0, t1, t2);
3724     }
3725     m[i-len] = t0;
3726     t0 = t1; t1 = t2; t2 = 0;
3727   }
3728 
3729   while (t0) {
3730     t0 = sub(m, n, t0, len);
3731   }
3732 }
3733 
3734 // Fast Montgomery squaring. This uses asymptotically 25% fewer
3735 // multiplies so it should be up to 25% faster than Montgomery
3736 // multiplication. However, its loop control is more complex and it
3737 // may actually run slower on some machines.
3738 static void
3739 montgomery_square(unsigned long a[], unsigned long n[],
3740                   unsigned long m[], unsigned long inv, int len) {
3741   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3742   int i;
3743 
3744   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3745 
3746   for (i = 0; i < len; i++) {
3747     int j;
3748     int end = (i+1)/2;
3749     for (j = 0; j < end; j++) {
3750       MACC2(a, j, a, i-j, t0, t1, t2);
3751       MACC(m, j, n, i-j, t0, t1, t2);
3752     }
3753     if ((i & 1) == 0) {
3754       MACC(a, j, a, j, t0, t1, t2);
3755     }
3756     for (; j < i; j++) {
3757       MACC(m, j, n, i-j, t0, t1, t2);
3758     }
3759     m[i] = t0 * inv;
3760     MACC(m, i, n, 0, t0, t1, t2);
3761 
3762     assert(t0 == 0, "broken Montgomery square");
3763 
3764     t0 = t1; t1 = t2; t2 = 0;
3765   }
3766 
3767   for (i = len; i < 2*len; i++) {
3768     int start = i-len+1;
3769     int end = start + (len - start)/2;
3770     int j;
3771     for (j = start; j < end; j++) {
3772       MACC2(a, j, a, i-j, t0, t1, t2);
3773       MACC(m, j, n, i-j, t0, t1, t2);
3774     }
3775     if ((i & 1) == 0) {
3776       MACC(a, j, a, j, t0, t1, t2);
3777     }
3778     for (; j < len; j++) {
3779       MACC(m, j, n, i-j, t0, t1, t2);
3780     }
3781     m[i-len] = t0;
3782     t0 = t1; t1 = t2; t2 = 0;
3783   }
3784 
3785   while (t0) {
3786     t0 = sub(m, n, t0, len);
3787   }
3788 }
3789 
3790 // The threshold at which squaring is advantageous was determined
3791 // experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
3792 // Value seems to be ok for other platforms, too.
3793 #define MONTGOMERY_SQUARING_THRESHOLD 64
3794 
3795 // Copy len longwords from s to d, word-swapping as we go. The
3796 // destination array is reversed.
3797 static void reverse_words(unsigned long *s, unsigned long *d, int len) {
3798   d += len;
3799   while(len-- > 0) {
3800     d--;
3801     unsigned long s_val = *s;
3802     // Swap words in a longword on little endian machines.
3803 #ifdef VM_LITTLE_ENDIAN
3804      Unimplemented();
3805 #endif
3806     *d = s_val;
3807     s++;
3808   }
3809 }
3810 
3811 void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
3812                                         jint len, jlong inv,
3813                                         jint *m_ints) {
3814   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3815   assert(len % 2 == 0, "array length in montgomery_multiply must be even");
3816   int longwords = len/2;
3817 
3818   // Make very sure we don't use so much space that the stack might
3819   // overflow. 512 jints corresponds to an 16384-bit integer and
3820   // will use here a total of 8k bytes of stack space.
3821   int divisor = sizeof(unsigned long) * 4;
3822   guarantee(longwords <= 8192 / divisor, "must be");
3823   int total_allocation = longwords * sizeof (unsigned long) * 4;
3824   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3825 
3826   // Local scratch arrays
3827   unsigned long
3828     *a = scratch + 0 * longwords,
3829     *b = scratch + 1 * longwords,
3830     *n = scratch + 2 * longwords,
3831     *m = scratch + 3 * longwords;
3832 
3833   reverse_words((unsigned long *)a_ints, a, longwords);
3834   reverse_words((unsigned long *)b_ints, b, longwords);
3835   reverse_words((unsigned long *)n_ints, n, longwords);
3836 
3837   ::montgomery_multiply(a, b, n, m, (unsigned long)inv, longwords);
3838 
3839   reverse_words(m, (unsigned long *)m_ints, longwords);
3840 }
3841 
3842 void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
3843                                       jint len, jlong inv,
3844                                       jint *m_ints) {
3845   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3846   assert(len % 2 == 0, "array length in montgomery_square must be even");
3847   int longwords = len/2;
3848 
3849   // Make very sure we don't use so much space that the stack might
3850   // overflow. 512 jints corresponds to an 16384-bit integer and
3851   // will use here a total of 6k bytes of stack space.
3852   int divisor = sizeof(unsigned long) * 3;
3853   guarantee(longwords <= (8192 / divisor), "must be");
3854   int total_allocation = longwords * sizeof (unsigned long) * 3;
3855   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3856 
3857   // Local scratch arrays
3858   unsigned long
3859     *a = scratch + 0 * longwords,
3860     *n = scratch + 1 * longwords,
3861     *m = scratch + 2 * longwords;
3862 
3863   reverse_words((unsigned long *)a_ints, a, longwords);
3864   reverse_words((unsigned long *)n_ints, n, longwords);
3865 
3866   if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
3867     ::montgomery_square(a, n, m, (unsigned long)inv, longwords);
3868   } else {
3869     ::montgomery_multiply(a, a, n, m, (unsigned long)inv, longwords);
3870   }
3871 
3872   reverse_words(m, (unsigned long *)m_ints, longwords);
3873 }
3874 
3875 extern "C"
3876 int SpinPause() {
3877   return 0;
3878 }
3879 
3880 #if INCLUDE_JFR
3881 
3882 // For c2: c_rarg0 is junk, call to runtime to write a checkpoint.
3883 // It returns a jobject handle to the event writer.
3884 // The handle is dereferenced and the return value is the event writer oop.
3885 RuntimeStub* SharedRuntime::generate_jfr_write_checkpoint() {
3886   const char* name = SharedRuntime::stub_name(StubId::shared_jfr_write_checkpoint_id);
3887   CodeBuffer code(name, 512, 64);
3888   MacroAssembler* masm = new MacroAssembler(&code);
3889 
3890   int framesize = frame::z_abi_160_size / VMRegImpl::stack_slot_size;
3891   address start = __ pc();
3892   __ save_return_pc(); // save return_pc (Z_R14)
3893   __ push_frame_abi160(0);
3894   int frame_complete = __ pc() - start;
3895   __ set_last_Java_frame(Z_SP, noreg);
3896 
3897   __ call_VM_leaf(CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::write_checkpoint), Z_thread);
3898   address calls_return_pc = __ last_calls_return_pc();
3899   __ reset_last_Java_frame();
3900 
3901   // The handle is dereferenced through a load barrier.
3902   __ resolve_global_jobject(Z_ARG1, Z_tmp_1, Z_tmp_2);
3903   __ pop_frame();
3904   __ restore_return_pc();
3905   __ z_br(Z_R14);
3906 
3907   OopMapSet* oop_maps = new OopMapSet();
3908   OopMap* map = new OopMap(framesize, 0);
3909   oop_maps->add_gc_map(calls_return_pc - start, map);
3910 
3911   RuntimeStub* stub = // codeBlob framesize is in words (not VMRegImpl::slot_size)
3912     RuntimeStub::new_runtime_stub(name, &code, frame_complete,
3913                                   (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3914                                   oop_maps, false);
3915 
3916   return stub;
3917 }
3918 
3919 // For c2: call to return a leased buffer.
3920 RuntimeStub* SharedRuntime::generate_jfr_return_lease() {
3921   const char* name = SharedRuntime::stub_name(StubId::shared_jfr_return_lease_id);
3922   CodeBuffer code(name, 512, 64);
3923   MacroAssembler* masm = new MacroAssembler(&code);
3924 
3925   int framesize = frame::z_abi_160_size / VMRegImpl::stack_slot_size;
3926   address start = __ pc();
3927   __ save_return_pc(); // save return_pc (Z_R14)
3928   __ push_frame_abi160(0);
3929   int frame_complete = __ pc() - start;
3930   __ set_last_Java_frame(Z_SP, noreg);
3931 
3932   __ call_VM_leaf(CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::return_lease), Z_thread);
3933   address calls_return_pc = __ last_calls_return_pc();
3934 
3935   __ reset_last_Java_frame();
3936 
3937   __ pop_frame();
3938   __ restore_return_pc();
3939   __ z_br(Z_R14);
3940 
3941   OopMapSet* oop_maps = new OopMapSet();
3942   OopMap* map = new OopMap(framesize, 0);
3943   oop_maps->add_gc_map(calls_return_pc - start, map);
3944 
3945   RuntimeStub* stub = // codeBlob framesize is in words (not VMRegImpl::slot_size)
3946     RuntimeStub::new_runtime_stub(name, &code, frame_complete,
3947                                   (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3948                                   oop_maps, false);
3949 
3950   return stub;
3951 }
3952 
3953 #endif // INCLUDE_JFR
3954 
3955 const uint SharedRuntime::java_return_convention_max_int = Argument::n_int_register_parameters_j;
3956 const uint SharedRuntime::java_return_convention_max_float = Argument::n_float_register_parameters_j;
3957 
3958 int SharedRuntime::java_return_convention(const BasicType *sig_bt, VMRegPair *regs, int total_args_passed) {
3959   Unimplemented();
3960   return 0;
3961 }
3962 
3963 BufferedInlineTypeBlob* SharedRuntime::generate_buffered_inline_type_adapter(const InlineKlass* vk) {
3964   Unimplemented();
3965   return nullptr;
3966 }
3967 
3968 // Call here from the interpreter or compiled code to store returned
3969 // values to a newly allocated inline type instance.
3970 RuntimeStub* SharedRuntime::generate_return_value_stub(address destination) {
3971   Unimplemented();
3972   return nullptr;
3973 }