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