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