1 /*
   2  * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2012, 2016 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 "frame_ppc.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "interpreter/interp_masm.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "oops/compiledICHolder.hpp"
  36 #include "prims/jvmtiRedefineClassesTrace.hpp"
  37 #include "runtime/sharedRuntime.hpp"
  38 #include "runtime/vframeArray.hpp"
  39 #include "vmreg_ppc.inline.hpp"
  40 #ifdef COMPILER1
  41 #include "c1/c1_Runtime1.hpp"
  42 #endif
  43 #ifdef COMPILER2
  44 #include "adfiles/ad_ppc_64.hpp"
  45 #include "opto/runtime.hpp"
  46 #endif
  47 
  48 #include <alloca.h>
  49 
  50 #define __ masm->
  51 
  52 #ifdef PRODUCT
  53 #define BLOCK_COMMENT(str) // nothing
  54 #else
  55 #define BLOCK_COMMENT(str) __ block_comment(str)
  56 #endif
  57 
  58 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  59 
  60 
  61 class RegisterSaver {
  62  // Used for saving volatile registers.
  63  public:
  64 
  65   // Support different return pc locations.
  66   enum ReturnPCLocation {
  67     return_pc_is_lr,
  68     return_pc_is_pre_saved,
  69     return_pc_is_thread_saved_exception_pc
  70   };
  71 
  72   static OopMap* push_frame_reg_args_and_save_live_registers(MacroAssembler* masm,
  73                          int* out_frame_size_in_bytes,
  74                          bool generate_oop_map,
  75                          int return_pc_adjustment,
  76                          ReturnPCLocation return_pc_location);
  77   static void    restore_live_registers_and_pop_frame(MacroAssembler* masm,
  78                          int frame_size_in_bytes,
  79                          bool restore_ctr);
  80 
  81   static void push_frame_and_save_argument_registers(MacroAssembler* masm,
  82                          Register r_temp,
  83                          int frame_size,
  84                          int total_args,
  85                          const VMRegPair *regs, const VMRegPair *regs2 = NULL);
  86   static void restore_argument_registers_and_pop_frame(MacroAssembler*masm,
  87                          int frame_size,
  88                          int total_args,
  89                          const VMRegPair *regs, const VMRegPair *regs2 = NULL);
  90 
  91   // During deoptimization only the result registers need to be restored
  92   // all the other values have already been extracted.
  93   static void restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes);
  94 
  95   // Constants and data structures:
  96 
  97   typedef enum {
  98     int_reg           = 0,
  99     float_reg         = 1,
 100     special_reg       = 2
 101   } RegisterType;
 102 
 103   typedef enum {
 104     reg_size          = 8,
 105     half_reg_size     = reg_size / 2,
 106   } RegisterConstants;
 107 
 108   typedef struct {
 109     RegisterType        reg_type;
 110     int                 reg_num;
 111     VMReg               vmreg;
 112   } LiveRegType;
 113 };
 114 
 115 
 116 #define RegisterSaver_LiveSpecialReg(regname) \
 117   { RegisterSaver::special_reg, regname->encoding(), regname->as_VMReg() }
 118 
 119 #define RegisterSaver_LiveIntReg(regname) \
 120   { RegisterSaver::int_reg,     regname->encoding(), regname->as_VMReg() }
 121 
 122 #define RegisterSaver_LiveFloatReg(regname) \
 123   { RegisterSaver::float_reg,   regname->encoding(), regname->as_VMReg() }
 124 
 125 static const RegisterSaver::LiveRegType RegisterSaver_LiveRegs[] = {
 126   // Live registers which get spilled to the stack. Register
 127   // positions in this array correspond directly to the stack layout.
 128 
 129   //
 130   // live special registers:
 131   //
 132   RegisterSaver_LiveSpecialReg(SR_CTR),
 133   //
 134   // live float registers:
 135   //
 136   RegisterSaver_LiveFloatReg( F0  ),
 137   RegisterSaver_LiveFloatReg( F1  ),
 138   RegisterSaver_LiveFloatReg( F2  ),
 139   RegisterSaver_LiveFloatReg( F3  ),
 140   RegisterSaver_LiveFloatReg( F4  ),
 141   RegisterSaver_LiveFloatReg( F5  ),
 142   RegisterSaver_LiveFloatReg( F6  ),
 143   RegisterSaver_LiveFloatReg( F7  ),
 144   RegisterSaver_LiveFloatReg( F8  ),
 145   RegisterSaver_LiveFloatReg( F9  ),
 146   RegisterSaver_LiveFloatReg( F10 ),
 147   RegisterSaver_LiveFloatReg( F11 ),
 148   RegisterSaver_LiveFloatReg( F12 ),
 149   RegisterSaver_LiveFloatReg( F13 ),
 150   RegisterSaver_LiveFloatReg( F14 ),
 151   RegisterSaver_LiveFloatReg( F15 ),
 152   RegisterSaver_LiveFloatReg( F16 ),
 153   RegisterSaver_LiveFloatReg( F17 ),
 154   RegisterSaver_LiveFloatReg( F18 ),
 155   RegisterSaver_LiveFloatReg( F19 ),
 156   RegisterSaver_LiveFloatReg( F20 ),
 157   RegisterSaver_LiveFloatReg( F21 ),
 158   RegisterSaver_LiveFloatReg( F22 ),
 159   RegisterSaver_LiveFloatReg( F23 ),
 160   RegisterSaver_LiveFloatReg( F24 ),
 161   RegisterSaver_LiveFloatReg( F25 ),
 162   RegisterSaver_LiveFloatReg( F26 ),
 163   RegisterSaver_LiveFloatReg( F27 ),
 164   RegisterSaver_LiveFloatReg( F28 ),
 165   RegisterSaver_LiveFloatReg( F29 ),
 166   RegisterSaver_LiveFloatReg( F30 ),
 167   RegisterSaver_LiveFloatReg( F31 ),
 168   //
 169   // live integer registers:
 170   //
 171   RegisterSaver_LiveIntReg(   R0  ),
 172   //RegisterSaver_LiveIntReg( R1  ), // stack pointer
 173   RegisterSaver_LiveIntReg(   R2  ),
 174   RegisterSaver_LiveIntReg(   R3  ),
 175   RegisterSaver_LiveIntReg(   R4  ),
 176   RegisterSaver_LiveIntReg(   R5  ),
 177   RegisterSaver_LiveIntReg(   R6  ),
 178   RegisterSaver_LiveIntReg(   R7  ),
 179   RegisterSaver_LiveIntReg(   R8  ),
 180   RegisterSaver_LiveIntReg(   R9  ),
 181   RegisterSaver_LiveIntReg(   R10 ),
 182   RegisterSaver_LiveIntReg(   R11 ),
 183   RegisterSaver_LiveIntReg(   R12 ),
 184   //RegisterSaver_LiveIntReg( R13 ), // system thread id
 185   RegisterSaver_LiveIntReg(   R14 ),
 186   RegisterSaver_LiveIntReg(   R15 ),
 187   RegisterSaver_LiveIntReg(   R16 ),
 188   RegisterSaver_LiveIntReg(   R17 ),
 189   RegisterSaver_LiveIntReg(   R18 ),
 190   RegisterSaver_LiveIntReg(   R19 ),
 191   RegisterSaver_LiveIntReg(   R20 ),
 192   RegisterSaver_LiveIntReg(   R21 ),
 193   RegisterSaver_LiveIntReg(   R22 ),
 194   RegisterSaver_LiveIntReg(   R23 ),
 195   RegisterSaver_LiveIntReg(   R24 ),
 196   RegisterSaver_LiveIntReg(   R25 ),
 197   RegisterSaver_LiveIntReg(   R26 ),
 198   RegisterSaver_LiveIntReg(   R27 ),
 199   RegisterSaver_LiveIntReg(   R28 ),
 200   RegisterSaver_LiveIntReg(   R29 ),
 201   RegisterSaver_LiveIntReg(   R30 ),
 202   RegisterSaver_LiveIntReg(   R31 ), // must be the last register (see save/restore functions below)
 203 };
 204 
 205 OopMap* RegisterSaver::push_frame_reg_args_and_save_live_registers(MacroAssembler* masm,
 206                          int* out_frame_size_in_bytes,
 207                          bool generate_oop_map,
 208                          int return_pc_adjustment,
 209                          ReturnPCLocation return_pc_location) {
 210   // Push an abi_reg_args-frame and store all registers which may be live.
 211   // If requested, create an OopMap: Record volatile registers as
 212   // callee-save values in an OopMap so their save locations will be
 213   // propagated to the RegisterMap of the caller frame during
 214   // StackFrameStream construction (needed for deoptimization; see
 215   // compiledVFrame::create_stack_value).
 216   // If return_pc_adjustment != 0 adjust the return pc by return_pc_adjustment.
 217 
 218   int i;
 219   int offset;
 220 
 221   // calcualte frame size
 222   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 223                                    sizeof(RegisterSaver::LiveRegType);
 224   const int register_save_size   = regstosave_num * reg_size;
 225   const int frame_size_in_bytes  = round_to(register_save_size, frame::alignment_in_bytes)
 226                                    + frame::abi_reg_args_size;
 227   *out_frame_size_in_bytes       = frame_size_in_bytes;
 228   const int frame_size_in_slots  = frame_size_in_bytes / sizeof(jint);
 229   const int register_save_offset = frame_size_in_bytes - register_save_size;
 230 
 231   // OopMap frame size is in c2 stack slots (sizeof(jint)) not bytes or words.
 232   OopMap* map = generate_oop_map ? new OopMap(frame_size_in_slots, 0) : NULL;
 233 
 234   BLOCK_COMMENT("push_frame_reg_args_and_save_live_registers {");
 235 
 236   // Save r31 in the last slot of the not yet pushed frame so that we
 237   // can use it as scratch reg.
 238   __ std(R31, -reg_size, R1_SP);
 239   assert(-reg_size == register_save_offset - frame_size_in_bytes + ((regstosave_num-1)*reg_size),
 240          "consistency check");
 241 
 242   // save the flags
 243   // Do the save_LR_CR by hand and adjust the return pc if requested.
 244   __ mfcr(R31);
 245   __ std(R31, _abi(cr), R1_SP);
 246   switch (return_pc_location) {
 247     case return_pc_is_lr: __ mflr(R31); break;
 248     case return_pc_is_pre_saved: assert(return_pc_adjustment == 0, "unsupported"); break;
 249     case return_pc_is_thread_saved_exception_pc: __ ld(R31, thread_(saved_exception_pc)); break;
 250     default: ShouldNotReachHere();
 251   }
 252   if (return_pc_location != return_pc_is_pre_saved) {
 253     if (return_pc_adjustment != 0) {
 254       __ addi(R31, R31, return_pc_adjustment);
 255     }
 256     __ std(R31, _abi(lr), R1_SP);
 257   }
 258 
 259   // push a new frame
 260   __ push_frame(frame_size_in_bytes, R31);
 261 
 262   // save all registers (ints and floats)
 263   offset = register_save_offset;
 264   for (int i = 0; i < regstosave_num; i++) {
 265     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 266     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 267 
 268     switch (reg_type) {
 269       case RegisterSaver::int_reg: {
 270         if (reg_num != 31) { // We spilled R31 right at the beginning.
 271           __ std(as_Register(reg_num), offset, R1_SP);
 272         }
 273         break;
 274       }
 275       case RegisterSaver::float_reg: {
 276         __ stfd(as_FloatRegister(reg_num), offset, R1_SP);
 277         break;
 278       }
 279       case RegisterSaver::special_reg: {
 280         if (reg_num == SR_CTR_SpecialRegisterEnumValue) {
 281           __ mfctr(R31);
 282           __ std(R31, offset, R1_SP);
 283         } else {
 284           Unimplemented();
 285         }
 286         break;
 287       }
 288       default:
 289         ShouldNotReachHere();
 290     }
 291 
 292     if (generate_oop_map) {
 293       map->set_callee_saved(VMRegImpl::stack2reg(offset>>2),
 294                             RegisterSaver_LiveRegs[i].vmreg);
 295       map->set_callee_saved(VMRegImpl::stack2reg((offset + half_reg_size)>>2),
 296                             RegisterSaver_LiveRegs[i].vmreg->next());
 297     }
 298     offset += reg_size;
 299   }
 300 
 301   BLOCK_COMMENT("} push_frame_reg_args_and_save_live_registers");
 302 
 303   // And we're done.
 304   return map;
 305 }
 306 
 307 
 308 // Pop the current frame and restore all the registers that we
 309 // saved.
 310 void RegisterSaver::restore_live_registers_and_pop_frame(MacroAssembler* masm,
 311                                                          int frame_size_in_bytes,
 312                                                          bool restore_ctr) {
 313   int i;
 314   int offset;
 315   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 316                                    sizeof(RegisterSaver::LiveRegType);
 317   const int register_save_size   = regstosave_num * reg_size;
 318   const int register_save_offset = frame_size_in_bytes - register_save_size;
 319 
 320   BLOCK_COMMENT("restore_live_registers_and_pop_frame {");
 321 
 322   // restore all registers (ints and floats)
 323   offset = register_save_offset;
 324   for (int i = 0; i < regstosave_num; i++) {
 325     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 326     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 327 
 328     switch (reg_type) {
 329       case RegisterSaver::int_reg: {
 330         if (reg_num != 31) // R31 restored at the end, it's the tmp reg!
 331           __ ld(as_Register(reg_num), offset, R1_SP);
 332         break;
 333       }
 334       case RegisterSaver::float_reg: {
 335         __ lfd(as_FloatRegister(reg_num), offset, R1_SP);
 336         break;
 337       }
 338       case RegisterSaver::special_reg: {
 339         if (reg_num == SR_CTR_SpecialRegisterEnumValue) {
 340           if (restore_ctr) { // Nothing to do here if ctr already contains the next address.
 341             __ ld(R31, offset, R1_SP);
 342             __ mtctr(R31);
 343           }
 344         } else {
 345           Unimplemented();
 346         }
 347         break;
 348       }
 349       default:
 350         ShouldNotReachHere();
 351     }
 352     offset += reg_size;
 353   }
 354 
 355   // pop the frame
 356   __ pop_frame();
 357 
 358   // restore the flags
 359   __ restore_LR_CR(R31);
 360 
 361   // restore scratch register's value
 362   __ ld(R31, -reg_size, R1_SP);
 363 
 364   BLOCK_COMMENT("} restore_live_registers_and_pop_frame");
 365 }
 366 
 367 void RegisterSaver::push_frame_and_save_argument_registers(MacroAssembler* masm, Register r_temp,
 368                                                            int frame_size,int total_args, const VMRegPair *regs,
 369                                                            const VMRegPair *regs2) {
 370   __ push_frame(frame_size, r_temp);
 371   int st_off = frame_size - wordSize;
 372   for (int i = 0; i < total_args; i++) {
 373     VMReg r_1 = regs[i].first();
 374     VMReg r_2 = regs[i].second();
 375     if (!r_1->is_valid()) {
 376       assert(!r_2->is_valid(), "");
 377       continue;
 378     }
 379     if (r_1->is_Register()) {
 380       Register r = r_1->as_Register();
 381       __ std(r, st_off, R1_SP);
 382       st_off -= wordSize;
 383     } else if (r_1->is_FloatRegister()) {
 384       FloatRegister f = r_1->as_FloatRegister();
 385       __ stfd(f, st_off, R1_SP);
 386       st_off -= wordSize;
 387     }
 388   }
 389   if (regs2 != NULL) {
 390     for (int i = 0; i < total_args; i++) {
 391       VMReg r_1 = regs2[i].first();
 392       VMReg r_2 = regs2[i].second();
 393       if (!r_1->is_valid()) {
 394         assert(!r_2->is_valid(), "");
 395         continue;
 396       }
 397       if (r_1->is_Register()) {
 398         Register r = r_1->as_Register();
 399         __ std(r, st_off, R1_SP);
 400         st_off -= wordSize;
 401       } else if (r_1->is_FloatRegister()) {
 402         FloatRegister f = r_1->as_FloatRegister();
 403         __ stfd(f, st_off, R1_SP);
 404         st_off -= wordSize;
 405       }
 406     }
 407   }
 408 }
 409 
 410 void RegisterSaver::restore_argument_registers_and_pop_frame(MacroAssembler*masm, int frame_size,
 411                                                              int total_args, const VMRegPair *regs,
 412                                                              const VMRegPair *regs2) {
 413   int st_off = frame_size - wordSize;
 414   for (int i = 0; i < total_args; i++) {
 415     VMReg r_1 = regs[i].first();
 416     VMReg r_2 = regs[i].second();
 417     if (r_1->is_Register()) {
 418       Register r = r_1->as_Register();
 419       __ ld(r, st_off, R1_SP);
 420       st_off -= wordSize;
 421     } else if (r_1->is_FloatRegister()) {
 422       FloatRegister f = r_1->as_FloatRegister();
 423       __ lfd(f, st_off, R1_SP);
 424       st_off -= wordSize;
 425     }
 426   }
 427   if (regs2 != NULL)
 428     for (int i = 0; i < total_args; i++) {
 429       VMReg r_1 = regs2[i].first();
 430       VMReg r_2 = regs2[i].second();
 431       if (r_1->is_Register()) {
 432         Register r = r_1->as_Register();
 433         __ ld(r, st_off, R1_SP);
 434         st_off -= wordSize;
 435       } else if (r_1->is_FloatRegister()) {
 436         FloatRegister f = r_1->as_FloatRegister();
 437         __ lfd(f, st_off, R1_SP);
 438         st_off -= wordSize;
 439       }
 440     }
 441   __ pop_frame();
 442 }
 443 
 444 // Restore the registers that might be holding a result.
 445 void RegisterSaver::restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes) {
 446   int i;
 447   int offset;
 448   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 449                                    sizeof(RegisterSaver::LiveRegType);
 450   const int register_save_size   = regstosave_num * reg_size;
 451   const int register_save_offset = frame_size_in_bytes - register_save_size;
 452 
 453   // restore all result registers (ints and floats)
 454   offset = register_save_offset;
 455   for (int i = 0; i < regstosave_num; i++) {
 456     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 457     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 458     switch (reg_type) {
 459       case RegisterSaver::int_reg: {
 460         if (as_Register(reg_num)==R3_RET) // int result_reg
 461           __ ld(as_Register(reg_num), offset, R1_SP);
 462         break;
 463       }
 464       case RegisterSaver::float_reg: {
 465         if (as_FloatRegister(reg_num)==F1_RET) // float result_reg
 466           __ lfd(as_FloatRegister(reg_num), offset, R1_SP);
 467         break;
 468       }
 469       case RegisterSaver::special_reg: {
 470         // Special registers don't hold a result.
 471         break;
 472       }
 473       default:
 474         ShouldNotReachHere();
 475     }
 476     offset += reg_size;
 477   }
 478 }
 479 
 480 // Is vector's size (in bytes) bigger than a size saved by default?
 481 bool SharedRuntime::is_wide_vector(int size) {
 482   // Note, MaxVectorSize == 8 on PPC64.
 483   assert(size <= 8, "%d bytes vectors are not supported", size);
 484   return size > 8;
 485 }
 486 #ifdef COMPILER2
 487 static int reg2slot(VMReg r) {
 488   return r->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 489 }
 490 
 491 static int reg2offset(VMReg r) {
 492   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 493 }
 494 #endif
 495 
 496 // ---------------------------------------------------------------------------
 497 // Read the array of BasicTypes from a signature, and compute where the
 498 // arguments should go. Values in the VMRegPair regs array refer to 4-byte
 499 // quantities. Values less than VMRegImpl::stack0 are registers, those above
 500 // refer to 4-byte stack slots. All stack slots are based off of the stack pointer
 501 // as framesizes are fixed.
 502 // VMRegImpl::stack0 refers to the first slot 0(sp).
 503 // and VMRegImpl::stack0+1 refers to the memory word 4-bytes higher. Register
 504 // up to RegisterImpl::number_of_registers) are the 64-bit
 505 // integer registers.
 506 
 507 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 508 // either 32-bit or 64-bit depending on the build. The OUTPUTS are in 32-bit
 509 // units regardless of build. Of course for i486 there is no 64 bit build
 510 
 511 // The Java calling convention is a "shifted" version of the C ABI.
 512 // By skipping the first C ABI register we can call non-static jni methods
 513 // with small numbers of arguments without having to shuffle the arguments
 514 // at all. Since we control the java ABI we ought to at least get some
 515 // advantage out of it.
 516 
 517 const VMReg java_iarg_reg[8] = {
 518   R3->as_VMReg(),
 519   R4->as_VMReg(),
 520   R5->as_VMReg(),
 521   R6->as_VMReg(),
 522   R7->as_VMReg(),
 523   R8->as_VMReg(),
 524   R9->as_VMReg(),
 525   R10->as_VMReg()
 526 };
 527 
 528 const VMReg java_farg_reg[13] = {
 529   F1->as_VMReg(),
 530   F2->as_VMReg(),
 531   F3->as_VMReg(),
 532   F4->as_VMReg(),
 533   F5->as_VMReg(),
 534   F6->as_VMReg(),
 535   F7->as_VMReg(),
 536   F8->as_VMReg(),
 537   F9->as_VMReg(),
 538   F10->as_VMReg(),
 539   F11->as_VMReg(),
 540   F12->as_VMReg(),
 541   F13->as_VMReg()
 542 };
 543 
 544 const int num_java_iarg_registers = sizeof(java_iarg_reg) / sizeof(java_iarg_reg[0]);
 545 const int num_java_farg_registers = sizeof(java_farg_reg) / sizeof(java_farg_reg[0]);
 546 
 547 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 548                                            VMRegPair *regs,
 549                                            int total_args_passed,
 550                                            int is_outgoing) {
 551   // C2c calling conventions for compiled-compiled calls.
 552   // Put 8 ints/longs into registers _AND_ 13 float/doubles into
 553   // registers _AND_ put the rest on the stack.
 554 
 555   const int inc_stk_for_intfloat   = 1; // 1 slots for ints and floats
 556   const int inc_stk_for_longdouble = 2; // 2 slots for longs and doubles
 557 
 558   int i;
 559   VMReg reg;
 560   int stk = 0;
 561   int ireg = 0;
 562   int freg = 0;
 563 
 564   // We put the first 8 arguments into registers and the rest on the
 565   // stack, float arguments are already in their argument registers
 566   // due to c2c calling conventions (see calling_convention).
 567   for (int i = 0; i < total_args_passed; ++i) {
 568     switch(sig_bt[i]) {
 569     case T_BOOLEAN:
 570     case T_CHAR:
 571     case T_BYTE:
 572     case T_SHORT:
 573     case T_INT:
 574       if (ireg < num_java_iarg_registers) {
 575         // Put int/ptr in register
 576         reg = java_iarg_reg[ireg];
 577         ++ireg;
 578       } else {
 579         // Put int/ptr on stack.
 580         reg = VMRegImpl::stack2reg(stk);
 581         stk += inc_stk_for_intfloat;
 582       }
 583       regs[i].set1(reg);
 584       break;
 585     case T_LONG:
 586       assert(sig_bt[i+1] == T_VOID, "expecting half");
 587       if (ireg < num_java_iarg_registers) {
 588         // Put long in register.
 589         reg = java_iarg_reg[ireg];
 590         ++ireg;
 591       } else {
 592         // Put long on stack. They must be aligned to 2 slots.
 593         if (stk & 0x1) ++stk;
 594         reg = VMRegImpl::stack2reg(stk);
 595         stk += inc_stk_for_longdouble;
 596       }
 597       regs[i].set2(reg);
 598       break;
 599     case T_OBJECT:
 600     case T_ARRAY:
 601     case T_ADDRESS:
 602       if (ireg < num_java_iarg_registers) {
 603         // Put ptr in register.
 604         reg = java_iarg_reg[ireg];
 605         ++ireg;
 606       } else {
 607         // Put ptr on stack. Objects must be aligned to 2 slots too,
 608         // because "64-bit pointers record oop-ishness on 2 aligned
 609         // adjacent registers." (see OopFlow::build_oop_map).
 610         if (stk & 0x1) ++stk;
 611         reg = VMRegImpl::stack2reg(stk);
 612         stk += inc_stk_for_longdouble;
 613       }
 614       regs[i].set2(reg);
 615       break;
 616     case T_FLOAT:
 617       if (freg < num_java_farg_registers) {
 618         // Put float in register.
 619         reg = java_farg_reg[freg];
 620         ++freg;
 621       } else {
 622         // Put float on stack.
 623         reg = VMRegImpl::stack2reg(stk);
 624         stk += inc_stk_for_intfloat;
 625       }
 626       regs[i].set1(reg);
 627       break;
 628     case T_DOUBLE:
 629       assert(sig_bt[i+1] == T_VOID, "expecting half");
 630       if (freg < num_java_farg_registers) {
 631         // Put double in register.
 632         reg = java_farg_reg[freg];
 633         ++freg;
 634       } else {
 635         // Put double on stack. They must be aligned to 2 slots.
 636         if (stk & 0x1) ++stk;
 637         reg = VMRegImpl::stack2reg(stk);
 638         stk += inc_stk_for_longdouble;
 639       }
 640       regs[i].set2(reg);
 641       break;
 642     case T_VOID:
 643       // Do not count halves.
 644       regs[i].set_bad();
 645       break;
 646     default:
 647       ShouldNotReachHere();
 648     }
 649   }
 650   return round_to(stk, 2);
 651 }
 652 
 653 #if defined(COMPILER1) || defined(COMPILER2)
 654 // Calling convention for calling C code.
 655 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 656                                         VMRegPair *regs,
 657                                         VMRegPair *regs2,
 658                                         int total_args_passed) {
 659   // Calling conventions for C runtime calls and calls to JNI native methods.
 660   //
 661   // PPC64 convention: Hoist the first 8 int/ptr/long's in the first 8
 662   // int regs, leaving int regs undefined if the arg is flt/dbl. Hoist
 663   // the first 13 flt/dbl's in the first 13 fp regs but additionally
 664   // copy flt/dbl to the stack if they are beyond the 8th argument.
 665 
 666   const VMReg iarg_reg[8] = {
 667     R3->as_VMReg(),
 668     R4->as_VMReg(),
 669     R5->as_VMReg(),
 670     R6->as_VMReg(),
 671     R7->as_VMReg(),
 672     R8->as_VMReg(),
 673     R9->as_VMReg(),
 674     R10->as_VMReg()
 675   };
 676 
 677   const VMReg farg_reg[13] = {
 678     F1->as_VMReg(),
 679     F2->as_VMReg(),
 680     F3->as_VMReg(),
 681     F4->as_VMReg(),
 682     F5->as_VMReg(),
 683     F6->as_VMReg(),
 684     F7->as_VMReg(),
 685     F8->as_VMReg(),
 686     F9->as_VMReg(),
 687     F10->as_VMReg(),
 688     F11->as_VMReg(),
 689     F12->as_VMReg(),
 690     F13->as_VMReg()
 691   };
 692 
 693   // Check calling conventions consistency.
 694   assert(sizeof(iarg_reg) / sizeof(iarg_reg[0]) == Argument::n_int_register_parameters_c &&
 695          sizeof(farg_reg) / sizeof(farg_reg[0]) == Argument::n_float_register_parameters_c,
 696          "consistency");
 697 
 698   // `Stk' counts stack slots. Due to alignment, 32 bit values occupy
 699   // 2 such slots, like 64 bit values do.
 700   const int inc_stk_for_intfloat   = 2; // 2 slots for ints and floats
 701   const int inc_stk_for_longdouble = 2; // 2 slots for longs and doubles
 702 
 703   int i;
 704   VMReg reg;
 705   // Leave room for C-compatible ABI_REG_ARGS.
 706   int stk = (frame::abi_reg_args_size - frame::jit_out_preserve_size) / VMRegImpl::stack_slot_size;
 707   int arg = 0;
 708   int freg = 0;
 709 
 710   // Avoid passing C arguments in the wrong stack slots.
 711 #if defined(ABI_ELFv2)
 712   assert((SharedRuntime::out_preserve_stack_slots() + stk) * VMRegImpl::stack_slot_size == 96,
 713          "passing C arguments in wrong stack slots");
 714 #else
 715   assert((SharedRuntime::out_preserve_stack_slots() + stk) * VMRegImpl::stack_slot_size == 112,
 716          "passing C arguments in wrong stack slots");
 717 #endif
 718   // We fill-out regs AND regs2 if an argument must be passed in a
 719   // register AND in a stack slot. If regs2 is NULL in such a
 720   // situation, we bail-out with a fatal error.
 721   for (int i = 0; i < total_args_passed; ++i, ++arg) {
 722     // Initialize regs2 to BAD.
 723     if (regs2 != NULL) regs2[i].set_bad();
 724 
 725     switch(sig_bt[i]) {
 726 
 727     //
 728     // If arguments 0-7 are integers, they are passed in integer registers.
 729     // Argument i is placed in iarg_reg[i].
 730     //
 731     case T_BOOLEAN:
 732     case T_CHAR:
 733     case T_BYTE:
 734     case T_SHORT:
 735     case T_INT:
 736       // We must cast ints to longs and use full 64 bit stack slots
 737       // here.  Thus fall through, handle as long.
 738     case T_LONG:
 739     case T_OBJECT:
 740     case T_ARRAY:
 741     case T_ADDRESS:
 742     case T_METADATA:
 743       // Oops are already boxed if required (JNI).
 744       if (arg < Argument::n_int_register_parameters_c) {
 745         reg = iarg_reg[arg];
 746       } else {
 747         reg = VMRegImpl::stack2reg(stk);
 748         stk += inc_stk_for_longdouble;
 749       }
 750       regs[i].set2(reg);
 751       break;
 752 
 753     //
 754     // Floats are treated differently from int regs:  The first 13 float arguments
 755     // are passed in registers (not the float args among the first 13 args).
 756     // Thus argument i is NOT passed in farg_reg[i] if it is float.  It is passed
 757     // in farg_reg[j] if argument i is the j-th float argument of this call.
 758     //
 759     case T_FLOAT:
 760 #if defined(LINUX)
 761       // Linux uses ELF ABI. Both original ELF and ELFv2 ABIs have float
 762       // in the least significant word of an argument slot.
 763 #if defined(VM_LITTLE_ENDIAN)
 764 #define FLOAT_WORD_OFFSET_IN_SLOT 0
 765 #else
 766 #define FLOAT_WORD_OFFSET_IN_SLOT 1
 767 #endif
 768 #elif defined(AIX)
 769       // Although AIX runs on big endian CPU, float is in the most
 770       // significant word of an argument slot.
 771 #define FLOAT_WORD_OFFSET_IN_SLOT 0
 772 #else
 773 #error "unknown OS"
 774 #endif
 775       if (freg < Argument::n_float_register_parameters_c) {
 776         // Put float in register ...
 777         reg = farg_reg[freg];
 778         ++freg;
 779 
 780         // Argument i for i > 8 is placed on the stack even if it's
 781         // placed in a register (if it's a float arg). Aix disassembly
 782         // shows that xlC places these float args on the stack AND in
 783         // a register. This is not documented, but we follow this
 784         // convention, too.
 785         if (arg >= Argument::n_regs_not_on_stack_c) {
 786           // ... and on the stack.
 787           guarantee(regs2 != NULL, "must pass float in register and stack slot");
 788           VMReg reg2 = VMRegImpl::stack2reg(stk + FLOAT_WORD_OFFSET_IN_SLOT);
 789           regs2[i].set1(reg2);
 790           stk += inc_stk_for_intfloat;
 791         }
 792 
 793       } else {
 794         // Put float on stack.
 795         reg = VMRegImpl::stack2reg(stk + FLOAT_WORD_OFFSET_IN_SLOT);
 796         stk += inc_stk_for_intfloat;
 797       }
 798       regs[i].set1(reg);
 799       break;
 800     case T_DOUBLE:
 801       assert(sig_bt[i+1] == T_VOID, "expecting half");
 802       if (freg < Argument::n_float_register_parameters_c) {
 803         // Put double in register ...
 804         reg = farg_reg[freg];
 805         ++freg;
 806 
 807         // Argument i for i > 8 is placed on the stack even if it's
 808         // placed in a register (if it's a double arg). Aix disassembly
 809         // shows that xlC places these float args on the stack AND in
 810         // a register. This is not documented, but we follow this
 811         // convention, too.
 812         if (arg >= Argument::n_regs_not_on_stack_c) {
 813           // ... and on the stack.
 814           guarantee(regs2 != NULL, "must pass float in register and stack slot");
 815           VMReg reg2 = VMRegImpl::stack2reg(stk);
 816           regs2[i].set2(reg2);
 817           stk += inc_stk_for_longdouble;
 818         }
 819       } else {
 820         // Put double on stack.
 821         reg = VMRegImpl::stack2reg(stk);
 822         stk += inc_stk_for_longdouble;
 823       }
 824       regs[i].set2(reg);
 825       break;
 826 
 827     case T_VOID:
 828       // Do not count halves.
 829       regs[i].set_bad();
 830       --arg;
 831       break;
 832     default:
 833       ShouldNotReachHere();
 834     }
 835   }
 836 
 837   return round_to(stk, 2);
 838 }
 839 #endif // COMPILER2
 840 
 841 static address gen_c2i_adapter(MacroAssembler *masm,
 842                             int total_args_passed,
 843                             int comp_args_on_stack,
 844                             const BasicType *sig_bt,
 845                             const VMRegPair *regs,
 846                             Label& call_interpreter,
 847                             const Register& ientry) {
 848 
 849   address c2i_entrypoint;
 850 
 851   const Register sender_SP = R21_sender_SP; // == R21_tmp1
 852   const Register code      = R22_tmp2;
 853   //const Register ientry  = R23_tmp3;
 854   const Register value_regs[] = { R24_tmp4, R25_tmp5, R26_tmp6 };
 855   const int num_value_regs = sizeof(value_regs) / sizeof(Register);
 856   int value_regs_index = 0;
 857 
 858   const Register return_pc = R27_tmp7;
 859   const Register tmp       = R28_tmp8;
 860 
 861   assert_different_registers(sender_SP, code, ientry, return_pc, tmp);
 862 
 863   // Adapter needs TOP_IJAVA_FRAME_ABI.
 864   const int adapter_size = frame::top_ijava_frame_abi_size +
 865                            round_to(total_args_passed * wordSize, frame::alignment_in_bytes);
 866 
 867   // regular (verified) c2i entry point
 868   c2i_entrypoint = __ pc();
 869 
 870   // Does compiled code exists? If yes, patch the caller's callsite.
 871   __ ld(code, method_(code));
 872   __ cmpdi(CCR0, code, 0);
 873   __ ld(ientry, method_(interpreter_entry)); // preloaded
 874   __ beq(CCR0, call_interpreter);
 875 
 876 
 877   // Patch caller's callsite, method_(code) was not NULL which means that
 878   // compiled code exists.
 879   __ mflr(return_pc);
 880   __ std(return_pc, _abi(lr), R1_SP);
 881   RegisterSaver::push_frame_and_save_argument_registers(masm, tmp, adapter_size, total_args_passed, regs);
 882 
 883   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite), R19_method, return_pc);
 884 
 885   RegisterSaver::restore_argument_registers_and_pop_frame(masm, adapter_size, total_args_passed, regs);
 886   __ ld(return_pc, _abi(lr), R1_SP);
 887   __ ld(ientry, method_(interpreter_entry)); // preloaded
 888   __ mtlr(return_pc);
 889 
 890 
 891   // Call the interpreter.
 892   __ BIND(call_interpreter);
 893   __ mtctr(ientry);
 894 
 895   // Get a copy of the current SP for loading caller's arguments.
 896   __ mr(sender_SP, R1_SP);
 897 
 898   // Add space for the adapter.
 899   __ resize_frame(-adapter_size, R12_scratch2);
 900 
 901   int st_off = adapter_size - wordSize;
 902 
 903   // Write the args into the outgoing interpreter space.
 904   for (int i = 0; i < total_args_passed; i++) {
 905     VMReg r_1 = regs[i].first();
 906     VMReg r_2 = regs[i].second();
 907     if (!r_1->is_valid()) {
 908       assert(!r_2->is_valid(), "");
 909       continue;
 910     }
 911     if (r_1->is_stack()) {
 912       Register tmp_reg = value_regs[value_regs_index];
 913       value_regs_index = (value_regs_index + 1) % num_value_regs;
 914       // The calling convention produces OptoRegs that ignore the out
 915       // preserve area (JIT's ABI). We must account for it here.
 916       int ld_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 917       if (!r_2->is_valid()) {
 918         __ lwz(tmp_reg, ld_off, sender_SP);
 919       } else {
 920         __ ld(tmp_reg, ld_off, sender_SP);
 921       }
 922       // Pretend stack targets were loaded into tmp_reg.
 923       r_1 = tmp_reg->as_VMReg();
 924     }
 925 
 926     if (r_1->is_Register()) {
 927       Register r = r_1->as_Register();
 928       if (!r_2->is_valid()) {
 929         __ stw(r, st_off, R1_SP);
 930         st_off-=wordSize;
 931       } else {
 932         // Longs are given 2 64-bit slots in the interpreter, but the
 933         // data is passed in only 1 slot.
 934         if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 935           DEBUG_ONLY( __ li(tmp, 0); __ std(tmp, st_off, R1_SP); )
 936           st_off-=wordSize;
 937         }
 938         __ std(r, st_off, R1_SP);
 939         st_off-=wordSize;
 940       }
 941     } else {
 942       assert(r_1->is_FloatRegister(), "");
 943       FloatRegister f = r_1->as_FloatRegister();
 944       if (!r_2->is_valid()) {
 945         __ stfs(f, st_off, R1_SP);
 946         st_off-=wordSize;
 947       } else {
 948         // In 64bit, doubles are given 2 64-bit slots in the interpreter, but the
 949         // data is passed in only 1 slot.
 950         // One of these should get known junk...
 951         DEBUG_ONLY( __ li(tmp, 0); __ std(tmp, st_off, R1_SP); )
 952         st_off-=wordSize;
 953         __ stfd(f, st_off, R1_SP);
 954         st_off-=wordSize;
 955       }
 956     }
 957   }
 958 
 959   // Jump to the interpreter just as if interpreter was doing it.
 960 
 961   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
 962 
 963   // load TOS
 964   __ addi(R15_esp, R1_SP, st_off);
 965 
 966   // Frame_manager expects initial_caller_sp (= SP without resize by c2i) in R21_tmp1.
 967   assert(sender_SP == R21_sender_SP, "passing initial caller's SP in wrong register");
 968   __ bctr();
 969 
 970   return c2i_entrypoint;
 971 }
 972 
 973 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 974                                     int total_args_passed,
 975                                     int comp_args_on_stack,
 976                                     const BasicType *sig_bt,
 977                                     const VMRegPair *regs) {
 978 
 979   // Load method's entry-point from method.
 980   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
 981   __ mtctr(R12_scratch2);
 982 
 983   // We will only enter here from an interpreted frame and never from after
 984   // passing thru a c2i. Azul allowed this but we do not. If we lose the
 985   // race and use a c2i we will remain interpreted for the race loser(s).
 986   // This removes all sorts of headaches on the x86 side and also eliminates
 987   // the possibility of having c2i -> i2c -> c2i -> ... endless transitions.
 988 
 989   // Note: r13 contains the senderSP on entry. We must preserve it since
 990   // we may do a i2c -> c2i transition if we lose a race where compiled
 991   // code goes non-entrant while we get args ready.
 992   // In addition we use r13 to locate all the interpreter args as
 993   // we must align the stack to 16 bytes on an i2c entry else we
 994   // lose alignment we expect in all compiled code and register
 995   // save code can segv when fxsave instructions find improperly
 996   // aligned stack pointer.
 997 
 998   const Register ld_ptr = R15_esp;
 999   const Register value_regs[] = { R22_tmp2, R23_tmp3, R24_tmp4, R25_tmp5, R26_tmp6 };
1000   const int num_value_regs = sizeof(value_regs) / sizeof(Register);
1001   int value_regs_index = 0;
1002 
1003   int ld_offset = total_args_passed*wordSize;
1004 
1005   // Cut-out for having no stack args. Since up to 2 int/oop args are passed
1006   // in registers, we will occasionally have no stack args.
1007   int comp_words_on_stack = 0;
1008   if (comp_args_on_stack) {
1009     // Sig words on the stack are greater-than VMRegImpl::stack0. Those in
1010     // registers are below. By subtracting stack0, we either get a negative
1011     // number (all values in registers) or the maximum stack slot accessed.
1012 
1013     // Convert 4-byte c2 stack slots to words.
1014     comp_words_on_stack = round_to(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
1015     // Round up to miminum stack alignment, in wordSize.
1016     comp_words_on_stack = round_to(comp_words_on_stack, 2);
1017     __ resize_frame(-comp_words_on_stack * wordSize, R11_scratch1);
1018   }
1019 
1020   // Now generate the shuffle code.  Pick up all register args and move the
1021   // rest through register value=Z_R12.
1022   BLOCK_COMMENT("Shuffle arguments");
1023   for (int i = 0; i < total_args_passed; i++) {
1024     if (sig_bt[i] == T_VOID) {
1025       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
1026       continue;
1027     }
1028 
1029     // Pick up 0, 1 or 2 words from ld_ptr.
1030     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
1031             "scrambled load targets?");
1032     VMReg r_1 = regs[i].first();
1033     VMReg r_2 = regs[i].second();
1034     if (!r_1->is_valid()) {
1035       assert(!r_2->is_valid(), "");
1036       continue;
1037     }
1038     if (r_1->is_FloatRegister()) {
1039       if (!r_2->is_valid()) {
1040         __ lfs(r_1->as_FloatRegister(), ld_offset, ld_ptr);
1041         ld_offset-=wordSize;
1042       } else {
1043         // Skip the unused interpreter slot.
1044         __ lfd(r_1->as_FloatRegister(), ld_offset-wordSize, ld_ptr);
1045         ld_offset-=2*wordSize;
1046       }
1047     } else {
1048       Register r;
1049       if (r_1->is_stack()) {
1050         // Must do a memory to memory move thru "value".
1051         r = value_regs[value_regs_index];
1052         value_regs_index = (value_regs_index + 1) % num_value_regs;
1053       } else {
1054         r = r_1->as_Register();
1055       }
1056       if (!r_2->is_valid()) {
1057         // Not sure we need to do this but it shouldn't hurt.
1058         if (sig_bt[i] == T_OBJECT || sig_bt[i] == T_ADDRESS || sig_bt[i] == T_ARRAY) {
1059           __ ld(r, ld_offset, ld_ptr);
1060           ld_offset-=wordSize;
1061         } else {
1062           __ lwz(r, ld_offset, ld_ptr);
1063           ld_offset-=wordSize;
1064         }
1065       } else {
1066         // In 64bit, longs are given 2 64-bit slots in the interpreter, but the
1067         // data is passed in only 1 slot.
1068         if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
1069           ld_offset-=wordSize;
1070         }
1071         __ ld(r, ld_offset, ld_ptr);
1072         ld_offset-=wordSize;
1073       }
1074 
1075       if (r_1->is_stack()) {
1076         // Now store value where the compiler expects it
1077         int st_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots())*VMRegImpl::stack_slot_size;
1078 
1079         if (sig_bt[i] == T_INT   || sig_bt[i] == T_FLOAT ||sig_bt[i] == T_BOOLEAN ||
1080             sig_bt[i] == T_SHORT || sig_bt[i] == T_CHAR  || sig_bt[i] == T_BYTE) {
1081           __ stw(r, st_off, R1_SP);
1082         } else {
1083           __ std(r, st_off, R1_SP);
1084         }
1085       }
1086     }
1087   }
1088 
1089   BLOCK_COMMENT("Store method");
1090   // Store method into thread->callee_target.
1091   // We might end up in handle_wrong_method if the callee is
1092   // deoptimized as we race thru here. If that happens we don't want
1093   // to take a safepoint because the caller frame will look
1094   // interpreted and arguments are now "compiled" so it is much better
1095   // to make this transition invisible to the stack walking
1096   // code. Unfortunately if we try and find the callee by normal means
1097   // a safepoint is possible. So we stash the desired callee in the
1098   // thread and the vm will find there should this case occur.
1099   __ std(R19_method, thread_(callee_target));
1100 
1101   // Jump to the compiled code just as if compiled code was doing it.
1102   __ bctr();
1103 }
1104 
1105 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
1106                                                             int total_args_passed,
1107                                                             int comp_args_on_stack,
1108                                                             const BasicType *sig_bt,
1109                                                             const VMRegPair *regs,
1110                                                             AdapterFingerPrint* fingerprint) {
1111   address i2c_entry;
1112   address c2i_unverified_entry;
1113   address c2i_entry;
1114 
1115 
1116   // entry: i2c
1117 
1118   __ align(CodeEntryAlignment);
1119   i2c_entry = __ pc();
1120   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
1121 
1122 
1123   // entry: c2i unverified
1124 
1125   __ align(CodeEntryAlignment);
1126   BLOCK_COMMENT("c2i unverified entry");
1127   c2i_unverified_entry = __ pc();
1128 
1129   // inline_cache contains a compiledICHolder
1130   const Register ic             = R19_method;
1131   const Register ic_klass       = R11_scratch1;
1132   const Register receiver_klass = R12_scratch2;
1133   const Register code           = R21_tmp1;
1134   const Register ientry         = R23_tmp3;
1135 
1136   assert_different_registers(ic, ic_klass, receiver_klass, R3_ARG1, code, ientry);
1137   assert(R11_scratch1 == R11, "need prologue scratch register");
1138 
1139   Label call_interpreter;
1140 
1141   assert(!MacroAssembler::needs_explicit_null_check(oopDesc::klass_offset_in_bytes()),
1142          "klass offset should reach into any page");
1143   // Check for NULL argument if we don't have implicit null checks.
1144   if (!ImplicitNullChecks || !os::zero_page_read_protected()) {
1145     if (TrapBasedNullChecks) {
1146       __ trap_null_check(R3_ARG1);
1147     } else {
1148       Label valid;
1149       __ cmpdi(CCR0, R3_ARG1, 0);
1150       __ bne_predict_taken(CCR0, valid);
1151       // We have a null argument, branch to ic_miss_stub.
1152       __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
1153                        relocInfo::runtime_call_type);
1154       __ BIND(valid);
1155     }
1156   }
1157   // Assume argument is not NULL, load klass from receiver.
1158   __ load_klass(receiver_klass, R3_ARG1);
1159 
1160   __ ld(ic_klass, CompiledICHolder::holder_klass_offset(), ic);
1161 
1162   if (TrapBasedICMissChecks) {
1163     __ trap_ic_miss_check(receiver_klass, ic_klass);
1164   } else {
1165     Label valid;
1166     __ cmpd(CCR0, receiver_klass, ic_klass);
1167     __ beq_predict_taken(CCR0, valid);
1168     // We have an unexpected klass, branch to ic_miss_stub.
1169     __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
1170                      relocInfo::runtime_call_type);
1171     __ BIND(valid);
1172   }
1173 
1174   // Argument is valid and klass is as expected, continue.
1175 
1176   // Extract method from inline cache, verified entry point needs it.
1177   __ ld(R19_method, CompiledICHolder::holder_method_offset(), ic);
1178   assert(R19_method == ic, "the inline cache register is dead here");
1179 
1180   __ ld(code, method_(code));
1181   __ cmpdi(CCR0, code, 0);
1182   __ ld(ientry, method_(interpreter_entry)); // preloaded
1183   __ beq_predict_taken(CCR0, call_interpreter);
1184 
1185   // Branch to ic_miss_stub.
1186   __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(), relocInfo::runtime_call_type);
1187 
1188   // entry: c2i
1189 
1190   c2i_entry = gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, call_interpreter, ientry);
1191 
1192   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
1193 }
1194 
1195 #ifdef COMPILER2
1196 // An oop arg. Must pass a handle not the oop itself.
1197 static void object_move(MacroAssembler* masm,
1198                         int frame_size_in_slots,
1199                         OopMap* oop_map, int oop_handle_offset,
1200                         bool is_receiver, int* receiver_offset,
1201                         VMRegPair src, VMRegPair dst,
1202                         Register r_caller_sp, Register r_temp_1, Register r_temp_2) {
1203   assert(!is_receiver || (is_receiver && (*receiver_offset == -1)),
1204          "receiver has already been moved");
1205 
1206   // We must pass a handle. First figure out the location we use as a handle.
1207 
1208   if (src.first()->is_stack()) {
1209     // stack to stack or reg
1210 
1211     const Register r_handle = dst.first()->is_stack() ? r_temp_1 : dst.first()->as_Register();
1212     Label skip;
1213     const int oop_slot_in_callers_frame = reg2slot(src.first());
1214 
1215     guarantee(!is_receiver, "expecting receiver in register");
1216     oop_map->set_oop(VMRegImpl::stack2reg(oop_slot_in_callers_frame + frame_size_in_slots));
1217 
1218     __ addi(r_handle, r_caller_sp, reg2offset(src.first()));
1219     __ ld(  r_temp_2, reg2offset(src.first()), r_caller_sp);
1220     __ cmpdi(CCR0, r_temp_2, 0);
1221     __ bne(CCR0, skip);
1222     // Use a NULL handle if oop is NULL.
1223     __ li(r_handle, 0);
1224     __ bind(skip);
1225 
1226     if (dst.first()->is_stack()) {
1227       // stack to stack
1228       __ std(r_handle, reg2offset(dst.first()), R1_SP);
1229     } else {
1230       // stack to reg
1231       // Nothing to do, r_handle is already the dst register.
1232     }
1233   } else {
1234     // reg to stack or reg
1235     const Register r_oop      = src.first()->as_Register();
1236     const Register r_handle   = dst.first()->is_stack() ? r_temp_1 : dst.first()->as_Register();
1237     const int oop_slot        = (r_oop->encoding()-R3_ARG1->encoding()) * VMRegImpl::slots_per_word
1238                                 + oop_handle_offset; // in slots
1239     const int oop_offset = oop_slot * VMRegImpl::stack_slot_size;
1240     Label skip;
1241 
1242     if (is_receiver) {
1243       *receiver_offset = oop_offset;
1244     }
1245     oop_map->set_oop(VMRegImpl::stack2reg(oop_slot));
1246 
1247     __ std( r_oop,    oop_offset, R1_SP);
1248     __ addi(r_handle, R1_SP, oop_offset);
1249 
1250     __ cmpdi(CCR0, r_oop, 0);
1251     __ bne(CCR0, skip);
1252     // Use a NULL handle if oop is NULL.
1253     __ li(r_handle, 0);
1254     __ bind(skip);
1255 
1256     if (dst.first()->is_stack()) {
1257       // reg to stack
1258       __ std(r_handle, reg2offset(dst.first()), R1_SP);
1259     } else {
1260       // reg to reg
1261       // Nothing to do, r_handle is already the dst register.
1262     }
1263   }
1264 }
1265 
1266 static void int_move(MacroAssembler*masm,
1267                      VMRegPair src, VMRegPair dst,
1268                      Register r_caller_sp, Register r_temp) {
1269   assert(src.first()->is_valid(), "incoming must be int");
1270   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be long");
1271 
1272   if (src.first()->is_stack()) {
1273     if (dst.first()->is_stack()) {
1274       // stack to stack
1275       __ lwa(r_temp, reg2offset(src.first()), r_caller_sp);
1276       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1277     } else {
1278       // stack to reg
1279       __ lwa(dst.first()->as_Register(), reg2offset(src.first()), r_caller_sp);
1280     }
1281   } else if (dst.first()->is_stack()) {
1282     // reg to stack
1283     __ extsw(r_temp, src.first()->as_Register());
1284     __ std(r_temp, reg2offset(dst.first()), R1_SP);
1285   } else {
1286     // reg to reg
1287     __ extsw(dst.first()->as_Register(), src.first()->as_Register());
1288   }
1289 }
1290 
1291 static void long_move(MacroAssembler*masm,
1292                       VMRegPair src, VMRegPair dst,
1293                       Register r_caller_sp, Register r_temp) {
1294   assert(src.first()->is_valid() && src.second() == src.first()->next(), "incoming must be long");
1295   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be long");
1296 
1297   if (src.first()->is_stack()) {
1298     if (dst.first()->is_stack()) {
1299       // stack to stack
1300       __ ld( r_temp, reg2offset(src.first()), r_caller_sp);
1301       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1302     } else {
1303       // stack to reg
1304       __ ld(dst.first()->as_Register(), reg2offset(src.first()), r_caller_sp);
1305     }
1306   } else if (dst.first()->is_stack()) {
1307     // reg to stack
1308     __ std(src.first()->as_Register(), reg2offset(dst.first()), R1_SP);
1309   } else {
1310     // reg to reg
1311     if (dst.first()->as_Register() != src.first()->as_Register())
1312       __ mr(dst.first()->as_Register(), src.first()->as_Register());
1313   }
1314 }
1315 
1316 static void float_move(MacroAssembler*masm,
1317                        VMRegPair src, VMRegPair dst,
1318                        Register r_caller_sp, Register r_temp) {
1319   assert(src.first()->is_valid() && !src.second()->is_valid(), "incoming must be float");
1320   assert(dst.first()->is_valid() && !dst.second()->is_valid(), "outgoing must be float");
1321 
1322   if (src.first()->is_stack()) {
1323     if (dst.first()->is_stack()) {
1324       // stack to stack
1325       __ lwz(r_temp, reg2offset(src.first()), r_caller_sp);
1326       __ stw(r_temp, reg2offset(dst.first()), R1_SP);
1327     } else {
1328       // stack to reg
1329       __ lfs(dst.first()->as_FloatRegister(), reg2offset(src.first()), r_caller_sp);
1330     }
1331   } else if (dst.first()->is_stack()) {
1332     // reg to stack
1333     __ stfs(src.first()->as_FloatRegister(), reg2offset(dst.first()), R1_SP);
1334   } else {
1335     // reg to reg
1336     if (dst.first()->as_FloatRegister() != src.first()->as_FloatRegister())
1337       __ fmr(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1338   }
1339 }
1340 
1341 static void double_move(MacroAssembler*masm,
1342                         VMRegPair src, VMRegPair dst,
1343                         Register r_caller_sp, Register r_temp) {
1344   assert(src.first()->is_valid() && src.second() == src.first()->next(), "incoming must be double");
1345   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be double");
1346 
1347   if (src.first()->is_stack()) {
1348     if (dst.first()->is_stack()) {
1349       // stack to stack
1350       __ ld( r_temp, reg2offset(src.first()), r_caller_sp);
1351       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1352     } else {
1353       // stack to reg
1354       __ lfd(dst.first()->as_FloatRegister(), reg2offset(src.first()), r_caller_sp);
1355     }
1356   } else if (dst.first()->is_stack()) {
1357     // reg to stack
1358     __ stfd(src.first()->as_FloatRegister(), reg2offset(dst.first()), R1_SP);
1359   } else {
1360     // reg to reg
1361     if (dst.first()->as_FloatRegister() != src.first()->as_FloatRegister())
1362       __ fmr(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1363   }
1364 }
1365 
1366 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1367   switch (ret_type) {
1368     case T_BOOLEAN:
1369     case T_CHAR:
1370     case T_BYTE:
1371     case T_SHORT:
1372     case T_INT:
1373       __ stw (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1374       break;
1375     case T_ARRAY:
1376     case T_OBJECT:
1377     case T_LONG:
1378       __ std (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1379       break;
1380     case T_FLOAT:
1381       __ stfs(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1382       break;
1383     case T_DOUBLE:
1384       __ stfd(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1385       break;
1386     case T_VOID:
1387       break;
1388     default:
1389       ShouldNotReachHere();
1390       break;
1391   }
1392 }
1393 
1394 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1395   switch (ret_type) {
1396     case T_BOOLEAN:
1397     case T_CHAR:
1398     case T_BYTE:
1399     case T_SHORT:
1400     case T_INT:
1401       __ lwz(R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1402       break;
1403     case T_ARRAY:
1404     case T_OBJECT:
1405     case T_LONG:
1406       __ ld (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1407       break;
1408     case T_FLOAT:
1409       __ lfs(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1410       break;
1411     case T_DOUBLE:
1412       __ lfd(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1413       break;
1414     case T_VOID:
1415       break;
1416     default:
1417       ShouldNotReachHere();
1418       break;
1419   }
1420 }
1421 
1422 static void save_or_restore_arguments(MacroAssembler* masm,
1423                                       const int stack_slots,
1424                                       const int total_in_args,
1425                                       const int arg_save_area,
1426                                       OopMap* map,
1427                                       VMRegPair* in_regs,
1428                                       BasicType* in_sig_bt) {
1429   // If map is non-NULL then the code should store the values,
1430   // otherwise it should load them.
1431   int slot = arg_save_area;
1432   // Save down double word first.
1433   for (int i = 0; i < total_in_args; i++) {
1434     if (in_regs[i].first()->is_FloatRegister() && in_sig_bt[i] == T_DOUBLE) {
1435       int offset = slot * VMRegImpl::stack_slot_size;
1436       slot += VMRegImpl::slots_per_word;
1437       assert(slot <= stack_slots, "overflow (after DOUBLE stack slot)");
1438       if (map != NULL) {
1439         __ stfd(in_regs[i].first()->as_FloatRegister(), offset, R1_SP);
1440       } else {
1441         __ lfd(in_regs[i].first()->as_FloatRegister(), offset, R1_SP);
1442       }
1443     } else if (in_regs[i].first()->is_Register() &&
1444         (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_ARRAY)) {
1445       int offset = slot * VMRegImpl::stack_slot_size;
1446       if (map != NULL) {
1447         __ std(in_regs[i].first()->as_Register(), offset, R1_SP);
1448         if (in_sig_bt[i] == T_ARRAY) {
1449           map->set_oop(VMRegImpl::stack2reg(slot));
1450         }
1451       } else {
1452         __ ld(in_regs[i].first()->as_Register(), offset, R1_SP);
1453       }
1454       slot += VMRegImpl::slots_per_word;
1455       assert(slot <= stack_slots, "overflow (after LONG/ARRAY stack slot)");
1456     }
1457   }
1458   // Save or restore single word registers.
1459   for (int i = 0; i < total_in_args; i++) {
1460     // PPC64: pass ints as longs: must only deal with floats here.
1461     if (in_regs[i].first()->is_FloatRegister()) {
1462       if (in_sig_bt[i] == T_FLOAT) {
1463         int offset = slot * VMRegImpl::stack_slot_size;
1464         slot++;
1465         assert(slot <= stack_slots, "overflow (after FLOAT stack slot)");
1466         if (map != NULL) {
1467           __ stfs(in_regs[i].first()->as_FloatRegister(), offset, R1_SP);
1468         } else {
1469           __ lfs(in_regs[i].first()->as_FloatRegister(), offset, R1_SP);
1470         }
1471       }
1472     } else if (in_regs[i].first()->is_stack()) {
1473       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1474         int offset_in_older_frame = in_regs[i].first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1475         map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + stack_slots));
1476       }
1477     }
1478   }
1479 }
1480 
1481 // Check GCLocker::needs_gc and enter the runtime if it's true. This
1482 // keeps a new JNI critical region from starting until a GC has been
1483 // forced. Save down any oops in registers and describe them in an
1484 // OopMap.
1485 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1486                                                const int stack_slots,
1487                                                const int total_in_args,
1488                                                const int arg_save_area,
1489                                                OopMapSet* oop_maps,
1490                                                VMRegPair* in_regs,
1491                                                BasicType* in_sig_bt,
1492                                                Register tmp_reg ) {
1493   __ block_comment("check GCLocker::needs_gc");
1494   Label cont;
1495   __ lbz(tmp_reg, (RegisterOrConstant)(intptr_t)GCLocker::needs_gc_address());
1496   __ cmplwi(CCR0, tmp_reg, 0);
1497   __ beq(CCR0, cont);
1498 
1499   // Save down any values that are live in registers and call into the
1500   // runtime to halt for a GC.
1501   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1502   save_or_restore_arguments(masm, stack_slots, total_in_args,
1503                             arg_save_area, map, in_regs, in_sig_bt);
1504 
1505   __ mr(R3_ARG1, R16_thread);
1506   __ set_last_Java_frame(R1_SP, noreg);
1507 
1508   __ block_comment("block_for_jni_critical");
1509   address entry_point = CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical);
1510 #if defined(ABI_ELFv2)
1511   __ call_c(entry_point, relocInfo::runtime_call_type);
1512 #else
1513   __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, entry_point), relocInfo::runtime_call_type);
1514 #endif
1515   address start           = __ pc() - __ offset(),
1516           calls_return_pc = __ last_calls_return_pc();
1517   oop_maps->add_gc_map(calls_return_pc - start, map);
1518 
1519   __ reset_last_Java_frame();
1520 
1521   // Reload all the register arguments.
1522   save_or_restore_arguments(masm, stack_slots, total_in_args,
1523                             arg_save_area, NULL, in_regs, in_sig_bt);
1524 
1525   __ BIND(cont);
1526 
1527 #ifdef ASSERT
1528   if (StressCriticalJNINatives) {
1529     // Stress register saving.
1530     OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1531     save_or_restore_arguments(masm, stack_slots, total_in_args,
1532                               arg_save_area, map, in_regs, in_sig_bt);
1533     // Destroy argument registers.
1534     for (int i = 0; i < total_in_args; i++) {
1535       if (in_regs[i].first()->is_Register()) {
1536         const Register reg = in_regs[i].first()->as_Register();
1537         __ neg(reg, reg);
1538       } else if (in_regs[i].first()->is_FloatRegister()) {
1539         __ fneg(in_regs[i].first()->as_FloatRegister(), in_regs[i].first()->as_FloatRegister());
1540       }
1541     }
1542 
1543     save_or_restore_arguments(masm, stack_slots, total_in_args,
1544                               arg_save_area, NULL, in_regs, in_sig_bt);
1545   }
1546 #endif
1547 }
1548 
1549 static void move_ptr(MacroAssembler* masm, VMRegPair src, VMRegPair dst, Register r_caller_sp, Register r_temp) {
1550   if (src.first()->is_stack()) {
1551     if (dst.first()->is_stack()) {
1552       // stack to stack
1553       __ ld(r_temp, reg2offset(src.first()), r_caller_sp);
1554       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1555     } else {
1556       // stack to reg
1557       __ ld(dst.first()->as_Register(), reg2offset(src.first()), r_caller_sp);
1558     }
1559   } else if (dst.first()->is_stack()) {
1560     // reg to stack
1561     __ std(src.first()->as_Register(), reg2offset(dst.first()), R1_SP);
1562   } else {
1563     if (dst.first() != src.first()) {
1564       __ mr(dst.first()->as_Register(), src.first()->as_Register());
1565     }
1566   }
1567 }
1568 
1569 // Unpack an array argument into a pointer to the body and the length
1570 // if the array is non-null, otherwise pass 0 for both.
1571 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type,
1572                                   VMRegPair body_arg, VMRegPair length_arg, Register r_caller_sp,
1573                                   Register tmp_reg, Register tmp2_reg) {
1574   assert(!body_arg.first()->is_Register() || body_arg.first()->as_Register() != tmp_reg,
1575          "possible collision");
1576   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
1577          "possible collision");
1578 
1579   // Pass the length, ptr pair.
1580   Label set_out_args;
1581   VMRegPair tmp, tmp2;
1582   tmp.set_ptr(tmp_reg->as_VMReg());
1583   tmp2.set_ptr(tmp2_reg->as_VMReg());
1584   if (reg.first()->is_stack()) {
1585     // Load the arg up from the stack.
1586     move_ptr(masm, reg, tmp, r_caller_sp, /*unused*/ R0);
1587     reg = tmp;
1588   }
1589   __ li(tmp2_reg, 0); // Pass zeros if Array=null.
1590   if (tmp_reg != reg.first()->as_Register()) __ li(tmp_reg, 0);
1591   __ cmpdi(CCR0, reg.first()->as_Register(), 0);
1592   __ beq(CCR0, set_out_args);
1593   __ lwa(tmp2_reg, arrayOopDesc::length_offset_in_bytes(), reg.first()->as_Register());
1594   __ addi(tmp_reg, reg.first()->as_Register(), arrayOopDesc::base_offset_in_bytes(in_elem_type));
1595   __ bind(set_out_args);
1596   move_ptr(masm, tmp, body_arg, r_caller_sp, /*unused*/ R0);
1597   move_ptr(masm, tmp2, length_arg, r_caller_sp, /*unused*/ R0); // Same as move32_64 on PPC64.
1598 }
1599 
1600 static void verify_oop_args(MacroAssembler* masm,
1601                             methodHandle method,
1602                             const BasicType* sig_bt,
1603                             const VMRegPair* regs) {
1604   Register temp_reg = R19_method;  // not part of any compiled calling seq
1605   if (VerifyOops) {
1606     for (int i = 0; i < method->size_of_parameters(); i++) {
1607       if (sig_bt[i] == T_OBJECT ||
1608           sig_bt[i] == T_ARRAY) {
1609         VMReg r = regs[i].first();
1610         assert(r->is_valid(), "bad oop arg");
1611         if (r->is_stack()) {
1612           __ ld(temp_reg, reg2offset(r), R1_SP);
1613           __ verify_oop(temp_reg);
1614         } else {
1615           __ verify_oop(r->as_Register());
1616         }
1617       }
1618     }
1619   }
1620 }
1621 
1622 static void gen_special_dispatch(MacroAssembler* masm,
1623                                  methodHandle method,
1624                                  const BasicType* sig_bt,
1625                                  const VMRegPair* regs) {
1626   verify_oop_args(masm, method, sig_bt, regs);
1627   vmIntrinsics::ID iid = method->intrinsic_id();
1628 
1629   // Now write the args into the outgoing interpreter space
1630   bool     has_receiver   = false;
1631   Register receiver_reg   = noreg;
1632   int      member_arg_pos = -1;
1633   Register member_reg     = noreg;
1634   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1635   if (ref_kind != 0) {
1636     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1637     member_reg = R19_method;  // known to be free at this point
1638     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1639   } else if (iid == vmIntrinsics::_invokeBasic) {
1640     has_receiver = true;
1641   } else {
1642     fatal("unexpected intrinsic id %d", iid);
1643   }
1644 
1645   if (member_reg != noreg) {
1646     // Load the member_arg into register, if necessary.
1647     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1648     VMReg r = regs[member_arg_pos].first();
1649     if (r->is_stack()) {
1650       __ ld(member_reg, reg2offset(r), R1_SP);
1651     } else {
1652       // no data motion is needed
1653       member_reg = r->as_Register();
1654     }
1655   }
1656 
1657   if (has_receiver) {
1658     // Make sure the receiver is loaded into a register.
1659     assert(method->size_of_parameters() > 0, "oob");
1660     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1661     VMReg r = regs[0].first();
1662     assert(r->is_valid(), "bad receiver arg");
1663     if (r->is_stack()) {
1664       // Porting note:  This assumes that compiled calling conventions always
1665       // pass the receiver oop in a register.  If this is not true on some
1666       // platform, pick a temp and load the receiver from stack.
1667       fatal("receiver always in a register");
1668       receiver_reg = R11_scratch1;  // TODO (hs24): is R11_scratch1 really free at this point?
1669       __ ld(receiver_reg, reg2offset(r), R1_SP);
1670     } else {
1671       // no data motion is needed
1672       receiver_reg = r->as_Register();
1673     }
1674   }
1675 
1676   // Figure out which address we are really jumping to:
1677   MethodHandles::generate_method_handle_dispatch(masm, iid,
1678                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1679 }
1680 
1681 #endif // COMPILER2
1682 
1683 // ---------------------------------------------------------------------------
1684 // Generate a native wrapper for a given method. The method takes arguments
1685 // in the Java compiled code convention, marshals them to the native
1686 // convention (handlizes oops, etc), transitions to native, makes the call,
1687 // returns to java state (possibly blocking), unhandlizes any result and
1688 // returns.
1689 //
1690 // Critical native functions are a shorthand for the use of
1691 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1692 // functions.  The wrapper is expected to unpack the arguments before
1693 // passing them to the callee and perform checks before and after the
1694 // native call to ensure that they GCLocker
1695 // lock_critical/unlock_critical semantics are followed.  Some other
1696 // parts of JNI setup are skipped like the tear down of the JNI handle
1697 // block and the check for pending exceptions it's impossible for them
1698 // to be thrown.
1699 //
1700 // They are roughly structured like this:
1701 //   if (GCLocker::needs_gc())
1702 //     SharedRuntime::block_for_jni_critical();
1703 //   tranistion to thread_in_native
1704 //   unpack arrray arguments and call native entry point
1705 //   check for safepoint in progress
1706 //   check if any thread suspend flags are set
1707 //     call into JVM and possible unlock the JNI critical
1708 //     if a GC was suppressed while in the critical native.
1709 //   transition back to thread_in_Java
1710 //   return to caller
1711 //
1712 nmethod *SharedRuntime::generate_native_wrapper(MacroAssembler *masm,
1713                                                 const methodHandle& method,
1714                                                 int compile_id,
1715                                                 BasicType *in_sig_bt,
1716                                                 VMRegPair *in_regs,
1717                                                 BasicType ret_type) {
1718 #ifdef COMPILER2
1719   if (method->is_method_handle_intrinsic()) {
1720     vmIntrinsics::ID iid = method->intrinsic_id();
1721     intptr_t start = (intptr_t)__ pc();
1722     int vep_offset = ((intptr_t)__ pc()) - start;
1723     gen_special_dispatch(masm,
1724                          method,
1725                          in_sig_bt,
1726                          in_regs);
1727     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1728     __ flush();
1729     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1730     return nmethod::new_native_nmethod(method,
1731                                        compile_id,
1732                                        masm->code(),
1733                                        vep_offset,
1734                                        frame_complete,
1735                                        stack_slots / VMRegImpl::slots_per_word,
1736                                        in_ByteSize(-1),
1737                                        in_ByteSize(-1),
1738                                        (OopMapSet*)NULL);
1739   }
1740 
1741   bool is_critical_native = true;
1742   address native_func = method->critical_native_function();
1743   if (native_func == NULL) {
1744     native_func = method->native_function();
1745     is_critical_native = false;
1746   }
1747   assert(native_func != NULL, "must have function");
1748 
1749   // First, create signature for outgoing C call
1750   // --------------------------------------------------------------------------
1751 
1752   int total_in_args = method->size_of_parameters();
1753   // We have received a description of where all the java args are located
1754   // on entry to the wrapper. We need to convert these args to where
1755   // the jni function will expect them. To figure out where they go
1756   // we convert the java signature to a C signature by inserting
1757   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1758 
1759   // Calculate the total number of C arguments and create arrays for the
1760   // signature and the outgoing registers.
1761   // On ppc64, we have two arrays for the outgoing registers, because
1762   // some floating-point arguments must be passed in registers _and_
1763   // in stack locations.
1764   bool method_is_static = method->is_static();
1765   int  total_c_args     = total_in_args;
1766 
1767   if (!is_critical_native) {
1768     int n_hidden_args = method_is_static ? 2 : 1;
1769     total_c_args += n_hidden_args;
1770   } else {
1771     // No JNIEnv*, no this*, but unpacked arrays (base+length).
1772     for (int i = 0; i < total_in_args; i++) {
1773       if (in_sig_bt[i] == T_ARRAY) {
1774         total_c_args++;
1775       }
1776     }
1777   }
1778 
1779   BasicType *out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1780   VMRegPair *out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1781   VMRegPair *out_regs2  = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1782   BasicType* in_elem_bt = NULL;
1783 
1784   // Create the signature for the C call:
1785   //   1) add the JNIEnv*
1786   //   2) add the class if the method is static
1787   //   3) copy the rest of the incoming signature (shifted by the number of
1788   //      hidden arguments).
1789 
1790   int argc = 0;
1791   if (!is_critical_native) {
1792     out_sig_bt[argc++] = T_ADDRESS;
1793     if (method->is_static()) {
1794       out_sig_bt[argc++] = T_OBJECT;
1795     }
1796 
1797     for (int i = 0; i < total_in_args ; i++ ) {
1798       out_sig_bt[argc++] = in_sig_bt[i];
1799     }
1800   } else {
1801     Thread* THREAD = Thread::current();
1802     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1803     SignatureStream ss(method->signature());
1804     int o = 0;
1805     for (int i = 0; i < total_in_args ; i++, o++) {
1806       if (in_sig_bt[i] == T_ARRAY) {
1807         // Arrays are passed as int, elem* pair
1808         Symbol* atype = ss.as_symbol(CHECK_NULL);
1809         const char* at = atype->as_C_string();
1810         if (strlen(at) == 2) {
1811           assert(at[0] == '[', "must be");
1812           switch (at[1]) {
1813             case 'B': in_elem_bt[o] = T_BYTE; break;
1814             case 'C': in_elem_bt[o] = T_CHAR; break;
1815             case 'D': in_elem_bt[o] = T_DOUBLE; break;
1816             case 'F': in_elem_bt[o] = T_FLOAT; break;
1817             case 'I': in_elem_bt[o] = T_INT; break;
1818             case 'J': in_elem_bt[o] = T_LONG; break;
1819             case 'S': in_elem_bt[o] = T_SHORT; break;
1820             case 'Z': in_elem_bt[o] = T_BOOLEAN; break;
1821             default: ShouldNotReachHere();
1822           }
1823         }
1824       } else {
1825         in_elem_bt[o] = T_VOID;
1826       }
1827       if (in_sig_bt[i] != T_VOID) {
1828         assert(in_sig_bt[i] == ss.type(), "must match");
1829         ss.next();
1830       }
1831     }
1832 
1833     for (int i = 0; i < total_in_args ; i++ ) {
1834       if (in_sig_bt[i] == T_ARRAY) {
1835         // Arrays are passed as int, elem* pair.
1836         out_sig_bt[argc++] = T_INT;
1837         out_sig_bt[argc++] = T_ADDRESS;
1838       } else {
1839         out_sig_bt[argc++] = in_sig_bt[i];
1840       }
1841     }
1842   }
1843 
1844 
1845   // Compute the wrapper's frame size.
1846   // --------------------------------------------------------------------------
1847 
1848   // Now figure out where the args must be stored and how much stack space
1849   // they require.
1850   //
1851   // Compute framesize for the wrapper. We need to handlize all oops in
1852   // incoming registers.
1853   //
1854   // Calculate the total number of stack slots we will need:
1855   //   1) abi requirements
1856   //   2) outgoing arguments
1857   //   3) space for inbound oop handle area
1858   //   4) space for handlizing a klass if static method
1859   //   5) space for a lock if synchronized method
1860   //   6) workspace for saving return values, int <-> float reg moves, etc.
1861   //   7) alignment
1862   //
1863   // Layout of the native wrapper frame:
1864   // (stack grows upwards, memory grows downwards)
1865   //
1866   // NW     [ABI_REG_ARGS]             <-- 1) R1_SP
1867   //        [outgoing arguments]       <-- 2) R1_SP + out_arg_slot_offset
1868   //        [oopHandle area]           <-- 3) R1_SP + oop_handle_offset (save area for critical natives)
1869   //        klass                      <-- 4) R1_SP + klass_offset
1870   //        lock                       <-- 5) R1_SP + lock_offset
1871   //        [workspace]                <-- 6) R1_SP + workspace_offset
1872   //        [alignment] (optional)     <-- 7)
1873   // caller [JIT_TOP_ABI_48]           <-- r_callers_sp
1874   //
1875   // - *_slot_offset Indicates offset from SP in number of stack slots.
1876   // - *_offset      Indicates offset from SP in bytes.
1877 
1878   int stack_slots = c_calling_convention(out_sig_bt, out_regs, out_regs2, total_c_args) // 1+2)
1879                   + SharedRuntime::out_preserve_stack_slots(); // See c_calling_convention.
1880 
1881   // Now the space for the inbound oop handle area.
1882   int total_save_slots = num_java_iarg_registers * VMRegImpl::slots_per_word;
1883   if (is_critical_native) {
1884     // Critical natives may have to call out so they need a save area
1885     // for register arguments.
1886     int double_slots = 0;
1887     int single_slots = 0;
1888     for (int i = 0; i < total_in_args; i++) {
1889       if (in_regs[i].first()->is_Register()) {
1890         const Register reg = in_regs[i].first()->as_Register();
1891         switch (in_sig_bt[i]) {
1892           case T_BOOLEAN:
1893           case T_BYTE:
1894           case T_SHORT:
1895           case T_CHAR:
1896           case T_INT:
1897           // Fall through.
1898           case T_ARRAY:
1899           case T_LONG: double_slots++; break;
1900           default:  ShouldNotReachHere();
1901         }
1902       } else if (in_regs[i].first()->is_FloatRegister()) {
1903         switch (in_sig_bt[i]) {
1904           case T_FLOAT:  single_slots++; break;
1905           case T_DOUBLE: double_slots++; break;
1906           default:  ShouldNotReachHere();
1907         }
1908       }
1909     }
1910     total_save_slots = double_slots * 2 + round_to(single_slots, 2); // round to even
1911   }
1912 
1913   int oop_handle_slot_offset = stack_slots;
1914   stack_slots += total_save_slots;                                                // 3)
1915 
1916   int klass_slot_offset = 0;
1917   int klass_offset      = -1;
1918   if (method_is_static && !is_critical_native) {                                  // 4)
1919     klass_slot_offset  = stack_slots;
1920     klass_offset       = klass_slot_offset * VMRegImpl::stack_slot_size;
1921     stack_slots       += VMRegImpl::slots_per_word;
1922   }
1923 
1924   int lock_slot_offset = 0;
1925   int lock_offset      = -1;
1926   if (method->is_synchronized()) {                                                // 5)
1927     lock_slot_offset   = stack_slots;
1928     lock_offset        = lock_slot_offset * VMRegImpl::stack_slot_size;
1929     stack_slots       += VMRegImpl::slots_per_word;
1930   }
1931 
1932   int workspace_slot_offset = stack_slots;                                        // 6)
1933   stack_slots         += 2;
1934 
1935   // Now compute actual number of stack words we need.
1936   // Rounding to make stack properly aligned.
1937   stack_slots = round_to(stack_slots,                                             // 7)
1938                          frame::alignment_in_bytes / VMRegImpl::stack_slot_size);
1939   int frame_size_in_bytes = stack_slots * VMRegImpl::stack_slot_size;
1940 
1941 
1942   // Now we can start generating code.
1943   // --------------------------------------------------------------------------
1944 
1945   intptr_t start_pc = (intptr_t)__ pc();
1946   intptr_t vep_start_pc;
1947   intptr_t frame_done_pc;
1948   intptr_t oopmap_pc;
1949 
1950   Label    ic_miss;
1951   Label    handle_pending_exception;
1952 
1953   Register r_callers_sp = R21;
1954   Register r_temp_1     = R22;
1955   Register r_temp_2     = R23;
1956   Register r_temp_3     = R24;
1957   Register r_temp_4     = R25;
1958   Register r_temp_5     = R26;
1959   Register r_temp_6     = R27;
1960   Register r_return_pc  = R28;
1961 
1962   Register r_carg1_jnienv        = noreg;
1963   Register r_carg2_classorobject = noreg;
1964   if (!is_critical_native) {
1965     r_carg1_jnienv        = out_regs[0].first()->as_Register();
1966     r_carg2_classorobject = out_regs[1].first()->as_Register();
1967   }
1968 
1969 
1970   // Generate the Unverified Entry Point (UEP).
1971   // --------------------------------------------------------------------------
1972   assert(start_pc == (intptr_t)__ pc(), "uep must be at start");
1973 
1974   // Check ic: object class == cached class?
1975   if (!method_is_static) {
1976   Register ic = as_Register(Matcher::inline_cache_reg_encode());
1977   Register receiver_klass = r_temp_1;
1978 
1979   __ cmpdi(CCR0, R3_ARG1, 0);
1980   __ beq(CCR0, ic_miss);
1981   __ verify_oop(R3_ARG1);
1982   __ load_klass(receiver_klass, R3_ARG1);
1983 
1984   __ cmpd(CCR0, receiver_klass, ic);
1985   __ bne(CCR0, ic_miss);
1986   }
1987 
1988 
1989   // Generate the Verified Entry Point (VEP).
1990   // --------------------------------------------------------------------------
1991   vep_start_pc = (intptr_t)__ pc();
1992 
1993   __ save_LR_CR(r_temp_1);
1994   __ generate_stack_overflow_check(frame_size_in_bytes); // Check before creating frame.
1995   __ mr(r_callers_sp, R1_SP);                            // Remember frame pointer.
1996   __ push_frame(frame_size_in_bytes, r_temp_1);          // Push the c2n adapter's frame.
1997   frame_done_pc = (intptr_t)__ pc();
1998 
1999   __ verify_thread();
2000 
2001   // Native nmethod wrappers never take possesion of the oop arguments.
2002   // So the caller will gc the arguments.
2003   // The only thing we need an oopMap for is if the call is static.
2004   //
2005   // An OopMap for lock (and class if static), and one for the VM call itself.
2006   OopMapSet *oop_maps = new OopMapSet();
2007   OopMap    *oop_map  = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
2008 
2009   if (is_critical_native) {
2010     check_needs_gc_for_critical_native(masm, stack_slots, total_in_args, oop_handle_slot_offset, oop_maps, in_regs, in_sig_bt, r_temp_1);
2011   }
2012 
2013   // Move arguments from register/stack to register/stack.
2014   // --------------------------------------------------------------------------
2015   //
2016   // We immediately shuffle the arguments so that for any vm call we have
2017   // to make from here on out (sync slow path, jvmti, etc.) we will have
2018   // captured the oops from our caller and have a valid oopMap for them.
2019   //
2020   // Natives require 1 or 2 extra arguments over the normal ones: the JNIEnv*
2021   // (derived from JavaThread* which is in R16_thread) and, if static,
2022   // the class mirror instead of a receiver. This pretty much guarantees that
2023   // register layout will not match. We ignore these extra arguments during
2024   // the shuffle. The shuffle is described by the two calling convention
2025   // vectors we have in our possession. We simply walk the java vector to
2026   // get the source locations and the c vector to get the destinations.
2027 
2028   // Record sp-based slot for receiver on stack for non-static methods.
2029   int receiver_offset = -1;
2030 
2031   // We move the arguments backward because the floating point registers
2032   // destination will always be to a register with a greater or equal
2033   // register number or the stack.
2034   //   in  is the index of the incoming Java arguments
2035   //   out is the index of the outgoing C arguments
2036 
2037 #ifdef ASSERT
2038   bool reg_destroyed[RegisterImpl::number_of_registers];
2039   bool freg_destroyed[FloatRegisterImpl::number_of_registers];
2040   for (int r = 0 ; r < RegisterImpl::number_of_registers ; r++) {
2041     reg_destroyed[r] = false;
2042   }
2043   for (int f = 0 ; f < FloatRegisterImpl::number_of_registers ; f++) {
2044     freg_destroyed[f] = false;
2045   }
2046 #endif // ASSERT
2047 
2048   for (int in = total_in_args - 1, out = total_c_args - 1; in >= 0 ; in--, out--) {
2049 
2050 #ifdef ASSERT
2051     if (in_regs[in].first()->is_Register()) {
2052       assert(!reg_destroyed[in_regs[in].first()->as_Register()->encoding()], "ack!");
2053     } else if (in_regs[in].first()->is_FloatRegister()) {
2054       assert(!freg_destroyed[in_regs[in].first()->as_FloatRegister()->encoding()], "ack!");
2055     }
2056     if (out_regs[out].first()->is_Register()) {
2057       reg_destroyed[out_regs[out].first()->as_Register()->encoding()] = true;
2058     } else if (out_regs[out].first()->is_FloatRegister()) {
2059       freg_destroyed[out_regs[out].first()->as_FloatRegister()->encoding()] = true;
2060     }
2061     if (out_regs2[out].first()->is_Register()) {
2062       reg_destroyed[out_regs2[out].first()->as_Register()->encoding()] = true;
2063     } else if (out_regs2[out].first()->is_FloatRegister()) {
2064       freg_destroyed[out_regs2[out].first()->as_FloatRegister()->encoding()] = true;
2065     }
2066 #endif // ASSERT
2067 
2068     switch (in_sig_bt[in]) {
2069       case T_BOOLEAN:
2070       case T_CHAR:
2071       case T_BYTE:
2072       case T_SHORT:
2073       case T_INT:
2074         // Move int and do sign extension.
2075         int_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
2076         break;
2077       case T_LONG:
2078         long_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
2079         break;
2080       case T_ARRAY:
2081         if (is_critical_native) {
2082           int body_arg = out;
2083           out -= 1; // Point to length arg.
2084           unpack_array_argument(masm, in_regs[in], in_elem_bt[in], out_regs[body_arg], out_regs[out],
2085                                 r_callers_sp, r_temp_1, r_temp_2);
2086           break;
2087         }
2088       case T_OBJECT:
2089         assert(!is_critical_native, "no oop arguments");
2090         object_move(masm, stack_slots,
2091                     oop_map, oop_handle_slot_offset,
2092                     ((in == 0) && (!method_is_static)), &receiver_offset,
2093                     in_regs[in], out_regs[out],
2094                     r_callers_sp, r_temp_1, r_temp_2);
2095         break;
2096       case T_VOID:
2097         break;
2098       case T_FLOAT:
2099         float_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
2100         if (out_regs2[out].first()->is_valid()) {
2101           float_move(masm, in_regs[in], out_regs2[out], r_callers_sp, r_temp_1);
2102         }
2103         break;
2104       case T_DOUBLE:
2105         double_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
2106         if (out_regs2[out].first()->is_valid()) {
2107           double_move(masm, in_regs[in], out_regs2[out], r_callers_sp, r_temp_1);
2108         }
2109         break;
2110       case T_ADDRESS:
2111         fatal("found type (T_ADDRESS) in java args");
2112         break;
2113       default:
2114         ShouldNotReachHere();
2115         break;
2116     }
2117   }
2118 
2119   // Pre-load a static method's oop into ARG2.
2120   // Used both by locking code and the normal JNI call code.
2121   if (method_is_static && !is_critical_native) {
2122     __ set_oop_constant(JNIHandles::make_local(method->method_holder()->java_mirror()),
2123                         r_carg2_classorobject);
2124 
2125     // Now handlize the static class mirror in carg2. It's known not-null.
2126     __ std(r_carg2_classorobject, klass_offset, R1_SP);
2127     oop_map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
2128     __ addi(r_carg2_classorobject, R1_SP, klass_offset);
2129   }
2130 
2131   // Get JNIEnv* which is first argument to native.
2132   if (!is_critical_native) {
2133     __ addi(r_carg1_jnienv, R16_thread, in_bytes(JavaThread::jni_environment_offset()));
2134   }
2135 
2136   // NOTE:
2137   //
2138   // We have all of the arguments setup at this point.
2139   // We MUST NOT touch any outgoing regs from this point on.
2140   // So if we must call out we must push a new frame.
2141 
2142   // Get current pc for oopmap, and load it patchable relative to global toc.
2143   oopmap_pc = (intptr_t) __ pc();
2144   __ calculate_address_from_global_toc(r_return_pc, (address)oopmap_pc, true, true, true, true);
2145 
2146   // We use the same pc/oopMap repeatedly when we call out.
2147   oop_maps->add_gc_map(oopmap_pc - start_pc, oop_map);
2148 
2149   // r_return_pc now has the pc loaded that we will use when we finally call
2150   // to native.
2151 
2152   // Make sure that thread is non-volatile; it crosses a bunch of VM calls below.
2153   assert(R16_thread->is_nonvolatile(), "thread must be in non-volatile register");
2154 
2155 # if 0
2156   // DTrace method entry
2157 # endif
2158 
2159   // Lock a synchronized method.
2160   // --------------------------------------------------------------------------
2161 
2162   if (method->is_synchronized()) {
2163     assert(!is_critical_native, "unhandled");
2164     ConditionRegister r_flag = CCR1;
2165     Register          r_oop  = r_temp_4;
2166     const Register    r_box  = r_temp_5;
2167     Label             done, locked;
2168 
2169     // Load the oop for the object or class. r_carg2_classorobject contains
2170     // either the handlized oop from the incoming arguments or the handlized
2171     // class mirror (if the method is static).
2172     __ ld(r_oop, 0, r_carg2_classorobject);
2173 
2174     // Get the lock box slot's address.
2175     __ addi(r_box, R1_SP, lock_offset);
2176 
2177 #   ifdef ASSERT
2178     if (UseBiasedLocking) {
2179       // Making the box point to itself will make it clear it went unused
2180       // but also be obviously invalid.
2181       __ std(r_box, 0, r_box);
2182     }
2183 #   endif // ASSERT
2184 
2185     // Try fastpath for locking.
2186     // fast_lock kills r_temp_1, r_temp_2, r_temp_3.
2187     __ compiler_fast_lock_object(r_flag, r_oop, r_box, r_temp_1, r_temp_2, r_temp_3);
2188     __ beq(r_flag, locked);
2189 
2190     // None of the above fast optimizations worked so we have to get into the
2191     // slow case of monitor enter. Inline a special case of call_VM that
2192     // disallows any pending_exception.
2193 
2194     // Save argument registers and leave room for C-compatible ABI_REG_ARGS.
2195     int frame_size = frame::abi_reg_args_size +
2196                      round_to(total_c_args * wordSize, frame::alignment_in_bytes);
2197     __ mr(R11_scratch1, R1_SP);
2198     RegisterSaver::push_frame_and_save_argument_registers(masm, R12_scratch2, frame_size, total_c_args, out_regs, out_regs2);
2199 
2200     // Do the call.
2201     __ set_last_Java_frame(R11_scratch1, r_return_pc);
2202     assert(r_return_pc->is_nonvolatile(), "expecting return pc to be in non-volatile register");
2203     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), r_oop, r_box, R16_thread);
2204     __ reset_last_Java_frame();
2205 
2206     RegisterSaver::restore_argument_registers_and_pop_frame(masm, frame_size, total_c_args, out_regs, out_regs2);
2207 
2208     __ asm_assert_mem8_is_zero(thread_(pending_exception),
2209        "no pending exception allowed on exit from SharedRuntime::complete_monitor_locking_C", 0);
2210 
2211     __ bind(locked);
2212   }
2213 
2214 
2215   // Publish thread state
2216   // --------------------------------------------------------------------------
2217 
2218   // Use that pc we placed in r_return_pc a while back as the current frame anchor.
2219   __ set_last_Java_frame(R1_SP, r_return_pc);
2220 
2221   // Transition from _thread_in_Java to _thread_in_native.
2222   __ li(R0, _thread_in_native);
2223   __ release();
2224   // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2225   __ stw(R0, thread_(thread_state));
2226   if (UseMembar) {
2227     __ fence();
2228   }
2229 
2230 
2231   // The JNI call
2232   // --------------------------------------------------------------------------
2233 #if defined(ABI_ELFv2)
2234   __ call_c(native_func, relocInfo::runtime_call_type);
2235 #else
2236   FunctionDescriptor* fd_native_method = (FunctionDescriptor*) native_func;
2237   __ call_c(fd_native_method, relocInfo::runtime_call_type);
2238 #endif
2239 
2240 
2241   // Now, we are back from the native code.
2242 
2243 
2244   // Unpack the native result.
2245   // --------------------------------------------------------------------------
2246 
2247   // For int-types, we do any needed sign-extension required.
2248   // Care must be taken that the return values (R3_RET and F1_RET)
2249   // will survive any VM calls for blocking or unlocking.
2250   // An OOP result (handle) is done specially in the slow-path code.
2251 
2252   switch (ret_type) {
2253     case T_VOID:    break;        // Nothing to do!
2254     case T_FLOAT:   break;        // Got it where we want it (unless slow-path).
2255     case T_DOUBLE:  break;        // Got it where we want it (unless slow-path).
2256     case T_LONG:    break;        // Got it where we want it (unless slow-path).
2257     case T_OBJECT:  break;        // Really a handle.
2258                                   // Cannot de-handlize until after reclaiming jvm_lock.
2259     case T_ARRAY:   break;
2260 
2261     case T_BOOLEAN: {             // 0 -> false(0); !0 -> true(1)
2262       Label skip_modify;
2263       __ cmpwi(CCR0, R3_RET, 0);
2264       __ beq(CCR0, skip_modify);
2265       __ li(R3_RET, 1);
2266       __ bind(skip_modify);
2267       break;
2268       }
2269     case T_BYTE: {                // sign extension
2270       __ extsb(R3_RET, R3_RET);
2271       break;
2272       }
2273     case T_CHAR: {                // unsigned result
2274       __ andi(R3_RET, R3_RET, 0xffff);
2275       break;
2276       }
2277     case T_SHORT: {               // sign extension
2278       __ extsh(R3_RET, R3_RET);
2279       break;
2280       }
2281     case T_INT:                   // nothing to do
2282       break;
2283     default:
2284       ShouldNotReachHere();
2285       break;
2286   }
2287 
2288 
2289   // Publish thread state
2290   // --------------------------------------------------------------------------
2291 
2292   // Switch thread to "native transition" state before reading the
2293   // synchronization state. This additional state is necessary because reading
2294   // and testing the synchronization state is not atomic w.r.t. GC, as this
2295   // scenario demonstrates:
2296   //   - Java thread A, in _thread_in_native state, loads _not_synchronized
2297   //     and is preempted.
2298   //   - VM thread changes sync state to synchronizing and suspends threads
2299   //     for GC.
2300   //   - Thread A is resumed to finish this native method, but doesn't block
2301   //     here since it didn't see any synchronization in progress, and escapes.
2302 
2303   // Transition from _thread_in_native to _thread_in_native_trans.
2304   __ li(R0, _thread_in_native_trans);
2305   __ release();
2306   // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2307   __ stw(R0, thread_(thread_state));
2308 
2309 
2310   // Must we block?
2311   // --------------------------------------------------------------------------
2312 
2313   // Block, if necessary, before resuming in _thread_in_Java state.
2314   // In order for GC to work, don't clear the last_Java_sp until after blocking.
2315   Label after_transition;
2316   {
2317     Label no_block, sync;
2318 
2319     if (os::is_MP()) {
2320       if (UseMembar) {
2321         // Force this write out before the read below.
2322         __ fence();
2323       } else {
2324         // Write serialization page so VM thread can do a pseudo remote membar.
2325         // We use the current thread pointer to calculate a thread specific
2326         // offset to write to within the page. This minimizes bus traffic
2327         // due to cache line collision.
2328         __ serialize_memory(R16_thread, r_temp_4, r_temp_5);
2329       }
2330     }
2331 
2332     Register sync_state_addr = r_temp_4;
2333     Register sync_state      = r_temp_5;
2334     Register suspend_flags   = r_temp_6;
2335 
2336     __ load_const(sync_state_addr, SafepointSynchronize::address_of_state(), /*temp*/ sync_state);
2337 
2338     // TODO: PPC port assert(4 == SafepointSynchronize::sz_state(), "unexpected field size");
2339     __ lwz(sync_state, 0, sync_state_addr);
2340 
2341     // TODO: PPC port assert(4 == Thread::sz_suspend_flags(), "unexpected field size");
2342     __ lwz(suspend_flags, thread_(suspend_flags));
2343 
2344     __ acquire();
2345 
2346     Label do_safepoint;
2347     // No synchronization in progress nor yet synchronized.
2348     __ cmpwi(CCR0, sync_state, SafepointSynchronize::_not_synchronized);
2349     // Not suspended.
2350     __ cmpwi(CCR1, suspend_flags, 0);
2351 
2352     __ bne(CCR0, sync);
2353     __ beq(CCR1, no_block);
2354 
2355     // Block. Save any potential method result value before the operation and
2356     // use a leaf call to leave the last_Java_frame setup undisturbed. Doing this
2357     // lets us share the oopMap we used when we went native rather than create
2358     // a distinct one for this pc.
2359     __ bind(sync);
2360 
2361     address entry_point = is_critical_native
2362       ? CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans_and_transition)
2363       : CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans);
2364     save_native_result(masm, ret_type, workspace_slot_offset);
2365     __ call_VM_leaf(entry_point, R16_thread);
2366     restore_native_result(masm, ret_type, workspace_slot_offset);
2367 
2368     if (is_critical_native) {
2369       __ b(after_transition); // No thread state transition here.
2370     }
2371     __ bind(no_block);
2372   }
2373 
2374   // Publish thread state.
2375   // --------------------------------------------------------------------------
2376 
2377   // Thread state is thread_in_native_trans. Any safepoint blocking has
2378   // already happened so we can now change state to _thread_in_Java.
2379 
2380   // Transition from _thread_in_native_trans to _thread_in_Java.
2381   __ li(R0, _thread_in_Java);
2382   __ release();
2383   // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2384   __ stw(R0, thread_(thread_state));
2385   if (UseMembar) {
2386     __ fence();
2387   }
2388   __ bind(after_transition);
2389 
2390   // Reguard any pages if necessary.
2391   // --------------------------------------------------------------------------
2392 
2393   Label no_reguard;
2394   __ lwz(r_temp_1, thread_(stack_guard_state));
2395   __ cmpwi(CCR0, r_temp_1, JavaThread::stack_guard_yellow_reserved_disabled);
2396   __ bne(CCR0, no_reguard);
2397 
2398   save_native_result(masm, ret_type, workspace_slot_offset);
2399   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
2400   restore_native_result(masm, ret_type, workspace_slot_offset);
2401 
2402   __ bind(no_reguard);
2403 
2404 
2405   // Unlock
2406   // --------------------------------------------------------------------------
2407 
2408   if (method->is_synchronized()) {
2409 
2410     ConditionRegister r_flag   = CCR1;
2411     const Register r_oop       = r_temp_4;
2412     const Register r_box       = r_temp_5;
2413     const Register r_exception = r_temp_6;
2414     Label done;
2415 
2416     // Get oop and address of lock object box.
2417     if (method_is_static) {
2418       assert(klass_offset != -1, "");
2419       __ ld(r_oop, klass_offset, R1_SP);
2420     } else {
2421       assert(receiver_offset != -1, "");
2422       __ ld(r_oop, receiver_offset, R1_SP);
2423     }
2424     __ addi(r_box, R1_SP, lock_offset);
2425 
2426     // Try fastpath for unlocking.
2427     __ compiler_fast_unlock_object(r_flag, r_oop, r_box, r_temp_1, r_temp_2, r_temp_3);
2428     __ beq(r_flag, done);
2429 
2430     // Save and restore any potential method result value around the unlocking operation.
2431     save_native_result(masm, ret_type, workspace_slot_offset);
2432 
2433     // Must save pending exception around the slow-path VM call. Since it's a
2434     // leaf call, the pending exception (if any) can be kept in a register.
2435     __ ld(r_exception, thread_(pending_exception));
2436     assert(r_exception->is_nonvolatile(), "exception register must be non-volatile");
2437     __ li(R0, 0);
2438     __ std(R0, thread_(pending_exception));
2439 
2440     // Slow case of monitor enter.
2441     // Inline a special case of call_VM that disallows any pending_exception.
2442     // Arguments are (oop obj, BasicLock* lock, JavaThread* thread).
2443     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C), r_oop, r_box, R16_thread);
2444 
2445     __ asm_assert_mem8_is_zero(thread_(pending_exception),
2446        "no pending exception allowed on exit from SharedRuntime::complete_monitor_unlocking_C", 0);
2447 
2448     restore_native_result(masm, ret_type, workspace_slot_offset);
2449 
2450     // Check_forward_pending_exception jump to forward_exception if any pending
2451     // exception is set. The forward_exception routine expects to see the
2452     // exception in pending_exception and not in a register. Kind of clumsy,
2453     // since all folks who branch to forward_exception must have tested
2454     // pending_exception first and hence have it in a register already.
2455     __ std(r_exception, thread_(pending_exception));
2456 
2457     __ bind(done);
2458   }
2459 
2460 # if 0
2461   // DTrace method exit
2462 # endif
2463 
2464   // Clear "last Java frame" SP and PC.
2465   // --------------------------------------------------------------------------
2466 
2467   __ reset_last_Java_frame();
2468 
2469   // Unpack oop result.
2470   // --------------------------------------------------------------------------
2471 
2472   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2473     Label skip_unboxing;
2474     __ cmpdi(CCR0, R3_RET, 0);
2475     __ beq(CCR0, skip_unboxing);
2476     __ ld(R3_RET, 0, R3_RET);
2477     __ bind(skip_unboxing);
2478     __ verify_oop(R3_RET);
2479   }
2480 
2481 
2482   // Reset handle block.
2483   // --------------------------------------------------------------------------
2484   if (!is_critical_native) {
2485   __ ld(r_temp_1, thread_(active_handles));
2486   // TODO: PPC port assert(4 == JNIHandleBlock::top_size_in_bytes(), "unexpected field size");
2487   __ li(r_temp_2, 0);
2488   __ stw(r_temp_2, JNIHandleBlock::top_offset_in_bytes(), r_temp_1);
2489 
2490 
2491   // Check for pending exceptions.
2492   // --------------------------------------------------------------------------
2493   __ ld(r_temp_2, thread_(pending_exception));
2494   __ cmpdi(CCR0, r_temp_2, 0);
2495   __ bne(CCR0, handle_pending_exception);
2496   }
2497 
2498   // Return
2499   // --------------------------------------------------------------------------
2500 
2501   __ pop_frame();
2502   __ restore_LR_CR(R11);
2503   __ blr();
2504 
2505 
2506   // Handler for pending exceptions (out-of-line).
2507   // --------------------------------------------------------------------------
2508 
2509   // Since this is a native call, we know the proper exception handler
2510   // is the empty function. We just pop this frame and then jump to
2511   // forward_exception_entry.
2512   if (!is_critical_native) {
2513   __ align(InteriorEntryAlignment);
2514   __ bind(handle_pending_exception);
2515 
2516   __ pop_frame();
2517   __ restore_LR_CR(R11);
2518   __ b64_patchable((address)StubRoutines::forward_exception_entry(),
2519                        relocInfo::runtime_call_type);
2520   }
2521 
2522   // Handler for a cache miss (out-of-line).
2523   // --------------------------------------------------------------------------
2524 
2525   if (!method_is_static) {
2526   __ align(InteriorEntryAlignment);
2527   __ bind(ic_miss);
2528 
2529   __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
2530                        relocInfo::runtime_call_type);
2531   }
2532 
2533   // Done.
2534   // --------------------------------------------------------------------------
2535 
2536   __ flush();
2537 
2538   nmethod *nm = nmethod::new_native_nmethod(method,
2539                                             compile_id,
2540                                             masm->code(),
2541                                             vep_start_pc-start_pc,
2542                                             frame_done_pc-start_pc,
2543                                             stack_slots / VMRegImpl::slots_per_word,
2544                                             (method_is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2545                                             in_ByteSize(lock_offset),
2546                                             oop_maps);
2547 
2548   if (is_critical_native) {
2549     nm->set_lazy_critical_native(true);
2550   }
2551 
2552   return nm;
2553 #else
2554   ShouldNotReachHere();
2555   return NULL;
2556 #endif // COMPILER2
2557 }
2558 
2559 // This function returns the adjust size (in number of words) to a c2i adapter
2560 // activation for use during deoptimization.
2561 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2562   return round_to((callee_locals - callee_parameters) * Interpreter::stackElementWords, frame::alignment_in_bytes);
2563 }
2564 
2565 uint SharedRuntime::out_preserve_stack_slots() {
2566 #if defined(COMPILER1) || defined(COMPILER2)
2567   return frame::jit_out_preserve_size / VMRegImpl::stack_slot_size;
2568 #else
2569   return 0;
2570 #endif
2571 }
2572 
2573 #if defined(COMPILER1) || defined(COMPILER2)
2574 // Frame generation for deopt and uncommon trap blobs.
2575 static void push_skeleton_frame(MacroAssembler* masm, bool deopt,
2576                                 /* Read */
2577                                 Register unroll_block_reg,
2578                                 /* Update */
2579                                 Register frame_sizes_reg,
2580                                 Register number_of_frames_reg,
2581                                 Register pcs_reg,
2582                                 /* Invalidate */
2583                                 Register frame_size_reg,
2584                                 Register pc_reg) {
2585 
2586   __ ld(pc_reg, 0, pcs_reg);
2587   __ ld(frame_size_reg, 0, frame_sizes_reg);
2588   __ std(pc_reg, _abi(lr), R1_SP);
2589   __ push_frame(frame_size_reg, R0/*tmp*/);
2590 #ifdef ASSERT
2591   __ load_const_optimized(pc_reg, 0x5afe);
2592   __ std(pc_reg, _ijava_state_neg(ijava_reserved), R1_SP);
2593 #endif
2594   __ std(R1_SP, _ijava_state_neg(sender_sp), R1_SP);
2595   __ addi(number_of_frames_reg, number_of_frames_reg, -1);
2596   __ addi(frame_sizes_reg, frame_sizes_reg, wordSize);
2597   __ addi(pcs_reg, pcs_reg, wordSize);
2598 }
2599 
2600 // Loop through the UnrollBlock info and create new frames.
2601 static void push_skeleton_frames(MacroAssembler* masm, bool deopt,
2602                                  /* read */
2603                                  Register unroll_block_reg,
2604                                  /* invalidate */
2605                                  Register frame_sizes_reg,
2606                                  Register number_of_frames_reg,
2607                                  Register pcs_reg,
2608                                  Register frame_size_reg,
2609                                  Register pc_reg) {
2610   Label loop;
2611 
2612  // _number_of_frames is of type int (deoptimization.hpp)
2613   __ lwa(number_of_frames_reg,
2614              Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes(),
2615              unroll_block_reg);
2616   __ ld(pcs_reg,
2617             Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes(),
2618             unroll_block_reg);
2619   __ ld(frame_sizes_reg,
2620             Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes(),
2621             unroll_block_reg);
2622 
2623   // stack: (caller_of_deoptee, ...).
2624 
2625   // At this point we either have an interpreter frame or a compiled
2626   // frame on top of stack. If it is a compiled frame we push a new c2i
2627   // adapter here
2628 
2629   // Memorize top-frame stack-pointer.
2630   __ mr(frame_size_reg/*old_sp*/, R1_SP);
2631 
2632   // Resize interpreter top frame OR C2I adapter.
2633 
2634   // At this moment, the top frame (which is the caller of the deoptee) is
2635   // an interpreter frame or a newly pushed C2I adapter or an entry frame.
2636   // The top frame has a TOP_IJAVA_FRAME_ABI and the frame contains the
2637   // outgoing arguments.
2638   //
2639   // In order to push the interpreter frame for the deoptee, we need to
2640   // resize the top frame such that we are able to place the deoptee's
2641   // locals in the frame.
2642   // Additionally, we have to turn the top frame's TOP_IJAVA_FRAME_ABI
2643   // into a valid PARENT_IJAVA_FRAME_ABI.
2644 
2645   __ lwa(R11_scratch1,
2646              Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes(),
2647              unroll_block_reg);
2648   __ neg(R11_scratch1, R11_scratch1);
2649 
2650   // R11_scratch1 contains size of locals for frame resizing.
2651   // R12_scratch2 contains top frame's lr.
2652 
2653   // Resize frame by complete frame size prevents TOC from being
2654   // overwritten by locals. A more stack space saving way would be
2655   // to copy the TOC to its location in the new abi.
2656   __ addi(R11_scratch1, R11_scratch1, - frame::parent_ijava_frame_abi_size);
2657 
2658   // now, resize the frame
2659   __ resize_frame(R11_scratch1, pc_reg/*tmp*/);
2660 
2661   // In the case where we have resized a c2i frame above, the optional
2662   // alignment below the locals has size 32 (why?).
2663   __ std(R12_scratch2, _abi(lr), R1_SP);
2664 
2665   // Initialize initial_caller_sp.
2666 #ifdef ASSERT
2667  __ load_const_optimized(pc_reg, 0x5afe);
2668  __ std(pc_reg, _ijava_state_neg(ijava_reserved), R1_SP);
2669 #endif
2670  __ std(frame_size_reg, _ijava_state_neg(sender_sp), R1_SP);
2671 
2672 #ifdef ASSERT
2673   // Make sure that there is at least one entry in the array.
2674   __ cmpdi(CCR0, number_of_frames_reg, 0);
2675   __ asm_assert_ne("array_size must be > 0", 0x205);
2676 #endif
2677 
2678   // Now push the new interpreter frames.
2679   //
2680   __ bind(loop);
2681   // Allocate a new frame, fill in the pc.
2682   push_skeleton_frame(masm, deopt,
2683                       unroll_block_reg,
2684                       frame_sizes_reg,
2685                       number_of_frames_reg,
2686                       pcs_reg,
2687                       frame_size_reg,
2688                       pc_reg);
2689   __ cmpdi(CCR0, number_of_frames_reg, 0);
2690   __ bne(CCR0, loop);
2691 
2692   // Get the return address pointing into the frame manager.
2693   __ ld(R0, 0, pcs_reg);
2694   // Store it in the top interpreter frame.
2695   __ std(R0, _abi(lr), R1_SP);
2696   // Initialize frame_manager_lr of interpreter top frame.
2697 }
2698 #endif
2699 
2700 void SharedRuntime::generate_deopt_blob() {
2701   // Allocate space for the code
2702   ResourceMark rm;
2703   // Setup code generation tools
2704   CodeBuffer buffer("deopt_blob", 2048, 1024);
2705   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
2706   Label exec_mode_initialized;
2707   int frame_size_in_words;
2708   OopMap* map = NULL;
2709   OopMapSet *oop_maps = new OopMapSet();
2710 
2711   // size of ABI112 plus spill slots for R3_RET and F1_RET.
2712   const int frame_size_in_bytes = frame::abi_reg_args_spill_size;
2713   const int frame_size_in_slots = frame_size_in_bytes / sizeof(jint);
2714   int first_frame_size_in_bytes = 0; // frame size of "unpack frame" for call to fetch_unroll_info.
2715 
2716   const Register exec_mode_reg = R21_tmp1;
2717 
2718   const address start = __ pc();
2719 
2720 #if defined(COMPILER1) || defined(COMPILER2)
2721   // --------------------------------------------------------------------------
2722   // Prolog for non exception case!
2723 
2724   // We have been called from the deopt handler of the deoptee.
2725   //
2726   // deoptee:
2727   //                      ...
2728   //                      call X
2729   //                      ...
2730   //  deopt_handler:      call_deopt_stub
2731   //  cur. return pc  --> ...
2732   //
2733   // So currently SR_LR points behind the call in the deopt handler.
2734   // We adjust it such that it points to the start of the deopt handler.
2735   // The return_pc has been stored in the frame of the deoptee and
2736   // will replace the address of the deopt_handler in the call
2737   // to Deoptimization::fetch_unroll_info below.
2738   // We can't grab a free register here, because all registers may
2739   // contain live values, so let the RegisterSaver do the adjustment
2740   // of the return pc.
2741   const int return_pc_adjustment_no_exception = -HandlerImpl::size_deopt_handler();
2742 
2743   // Push the "unpack frame"
2744   // Save everything in sight.
2745   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2746                                                                    &first_frame_size_in_bytes,
2747                                                                    /*generate_oop_map=*/ true,
2748                                                                    return_pc_adjustment_no_exception,
2749                                                                    RegisterSaver::return_pc_is_lr);
2750   assert(map != NULL, "OopMap must have been created");
2751 
2752   __ li(exec_mode_reg, Deoptimization::Unpack_deopt);
2753   // Save exec mode for unpack_frames.
2754   __ b(exec_mode_initialized);
2755 
2756   // --------------------------------------------------------------------------
2757   // Prolog for exception case
2758 
2759   // An exception is pending.
2760   // We have been called with a return (interpreter) or a jump (exception blob).
2761   //
2762   // - R3_ARG1: exception oop
2763   // - R4_ARG2: exception pc
2764 
2765   int exception_offset = __ pc() - start;
2766 
2767   BLOCK_COMMENT("Prolog for exception case");
2768 
2769   // Store exception oop and pc in thread (location known to GC).
2770   // This is needed since the call to "fetch_unroll_info()" may safepoint.
2771   __ std(R3_ARG1, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2772   __ std(R4_ARG2, in_bytes(JavaThread::exception_pc_offset()),  R16_thread);
2773   __ std(R4_ARG2, _abi(lr), R1_SP);
2774 
2775   // Vanilla deoptimization with an exception pending in exception_oop.
2776   int exception_in_tls_offset = __ pc() - start;
2777 
2778   // Push the "unpack frame".
2779   // Save everything in sight.
2780   RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2781                                                              &first_frame_size_in_bytes,
2782                                                              /*generate_oop_map=*/ false,
2783                                                              /*return_pc_adjustment_exception=*/ 0,
2784                                                              RegisterSaver::return_pc_is_pre_saved);
2785 
2786   // Deopt during an exception. Save exec mode for unpack_frames.
2787   __ li(exec_mode_reg, Deoptimization::Unpack_exception);
2788 
2789   // fall through
2790 
2791   int reexecute_offset = 0;
2792 #ifdef COMPILER1
2793   __ b(exec_mode_initialized);
2794 
2795   // Reexecute entry, similar to c2 uncommon trap
2796   reexecute_offset = __ pc() - start;
2797 
2798   RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2799                                                              &first_frame_size_in_bytes,
2800                                                              /*generate_oop_map=*/ false,
2801                                                              /*return_pc_adjustment_reexecute=*/ 0,
2802                                                              RegisterSaver::return_pc_is_pre_saved);
2803   __ li(exec_mode_reg, Deoptimization::Unpack_reexecute);
2804 #endif
2805 
2806   // --------------------------------------------------------------------------
2807   __ BIND(exec_mode_initialized);
2808 
2809   {
2810   const Register unroll_block_reg = R22_tmp2;
2811 
2812   // We need to set `last_Java_frame' because `fetch_unroll_info' will
2813   // call `last_Java_frame()'. The value of the pc in the frame is not
2814   // particularly important. It just needs to identify this blob.
2815   __ set_last_Java_frame(R1_SP, noreg);
2816 
2817   // With EscapeAnalysis turned on, this call may safepoint!
2818   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info), R16_thread, exec_mode_reg);
2819   address calls_return_pc = __ last_calls_return_pc();
2820   // Set an oopmap for the call site that describes all our saved registers.
2821   oop_maps->add_gc_map(calls_return_pc - start, map);
2822 
2823   __ reset_last_Java_frame();
2824   // Save the return value.
2825   __ mr(unroll_block_reg, R3_RET);
2826 
2827   // Restore only the result registers that have been saved
2828   // by save_volatile_registers(...).
2829   RegisterSaver::restore_result_registers(masm, first_frame_size_in_bytes);
2830 
2831   // reload the exec mode from the UnrollBlock (it might have changed)
2832   __ lwz(exec_mode_reg, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes(), unroll_block_reg);
2833   // In excp_deopt_mode, restore and clear exception oop which we
2834   // stored in the thread during exception entry above. The exception
2835   // oop will be the return value of this stub.
2836   Label skip_restore_excp;
2837   __ cmpdi(CCR0, exec_mode_reg, Deoptimization::Unpack_exception);
2838   __ bne(CCR0, skip_restore_excp);
2839   __ ld(R3_RET, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2840   __ ld(R4_ARG2, in_bytes(JavaThread::exception_pc_offset()), R16_thread);
2841   __ li(R0, 0);
2842   __ std(R0, in_bytes(JavaThread::exception_pc_offset()),  R16_thread);
2843   __ std(R0, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2844   __ BIND(skip_restore_excp);
2845 
2846   __ pop_frame();
2847 
2848   // stack: (deoptee, optional i2c, caller of deoptee, ...).
2849 
2850   // pop the deoptee's frame
2851   __ pop_frame();
2852 
2853   // stack: (caller_of_deoptee, ...).
2854 
2855   // Loop through the `UnrollBlock' info and create interpreter frames.
2856   push_skeleton_frames(masm, true/*deopt*/,
2857                        unroll_block_reg,
2858                        R23_tmp3,
2859                        R24_tmp4,
2860                        R25_tmp5,
2861                        R26_tmp6,
2862                        R27_tmp7);
2863 
2864   // stack: (skeletal interpreter frame, ..., optional skeletal
2865   // interpreter frame, optional c2i, caller of deoptee, ...).
2866   }
2867 
2868   // push an `unpack_frame' taking care of float / int return values.
2869   __ push_frame(frame_size_in_bytes, R0/*tmp*/);
2870 
2871   // stack: (unpack frame, skeletal interpreter frame, ..., optional
2872   // skeletal interpreter frame, optional c2i, caller of deoptee,
2873   // ...).
2874 
2875   // Spill live volatile registers since we'll do a call.
2876   __ std( R3_RET, _abi_reg_args_spill(spill_ret),  R1_SP);
2877   __ stfd(F1_RET, _abi_reg_args_spill(spill_fret), R1_SP);
2878 
2879   // Let the unpacker layout information in the skeletal frames just
2880   // allocated.
2881   __ get_PC_trash_LR(R3_RET);
2882   __ set_last_Java_frame(/*sp*/R1_SP, /*pc*/R3_RET);
2883   // This is a call to a LEAF method, so no oop map is required.
2884   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames),
2885                   R16_thread/*thread*/, exec_mode_reg/*exec_mode*/);
2886   __ reset_last_Java_frame();
2887 
2888   // Restore the volatiles saved above.
2889   __ ld( R3_RET, _abi_reg_args_spill(spill_ret),  R1_SP);
2890   __ lfd(F1_RET, _abi_reg_args_spill(spill_fret), R1_SP);
2891 
2892   // Pop the unpack frame.
2893   __ pop_frame();
2894   __ restore_LR_CR(R0);
2895 
2896   // stack: (top interpreter frame, ..., optional interpreter frame,
2897   // optional c2i, caller of deoptee, ...).
2898 
2899   // Initialize R14_state.
2900   __ restore_interpreter_state(R11_scratch1);
2901   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
2902 
2903   // Return to the interpreter entry point.
2904   __ blr();
2905   __ flush();
2906 #else // COMPILER2
2907   __ unimplemented("deopt blob needed only with compiler");
2908   int exception_offset = __ pc() - start;
2909 #endif // COMPILER2
2910 
2911   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset,
2912                                            reexecute_offset, first_frame_size_in_bytes / wordSize);
2913   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2914 }
2915 
2916 #ifdef COMPILER2
2917 void SharedRuntime::generate_uncommon_trap_blob() {
2918   // Allocate space for the code.
2919   ResourceMark rm;
2920   // Setup code generation tools.
2921   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2922   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
2923   address start = __ pc();
2924 
2925   Register unroll_block_reg = R21_tmp1;
2926   Register klass_index_reg  = R22_tmp2;
2927   Register unc_trap_reg     = R23_tmp3;
2928 
2929   OopMapSet* oop_maps = new OopMapSet();
2930   int frame_size_in_bytes = frame::abi_reg_args_size;
2931   OopMap* map = new OopMap(frame_size_in_bytes / sizeof(jint), 0);
2932 
2933   // stack: (deoptee, optional i2c, caller_of_deoptee, ...).
2934 
2935   // Push a dummy `unpack_frame' and call
2936   // `Deoptimization::uncommon_trap' to pack the compiled frame into a
2937   // vframe array and return the `UnrollBlock' information.
2938 
2939   // Save LR to compiled frame.
2940   __ save_LR_CR(R11_scratch1);
2941 
2942   // Push an "uncommon_trap" frame.
2943   __ push_frame_reg_args(0, R11_scratch1);
2944 
2945   // stack: (unpack frame, deoptee, optional i2c, caller_of_deoptee, ...).
2946 
2947   // Set the `unpack_frame' as last_Java_frame.
2948   // `Deoptimization::uncommon_trap' expects it and considers its
2949   // sender frame as the deoptee frame.
2950   // Remember the offset of the instruction whose address will be
2951   // moved to R11_scratch1.
2952   address gc_map_pc = __ get_PC_trash_LR(R11_scratch1);
2953 
2954   __ set_last_Java_frame(/*sp*/R1_SP, /*pc*/R11_scratch1);
2955 
2956   __ mr(klass_index_reg, R3);
2957   __ li(R5_ARG3, Deoptimization::Unpack_uncommon_trap);
2958   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap),
2959                   R16_thread, klass_index_reg, R5_ARG3);
2960 
2961   // Set an oopmap for the call site.
2962   oop_maps->add_gc_map(gc_map_pc - start, map);
2963 
2964   __ reset_last_Java_frame();
2965 
2966   // Pop the `unpack frame'.
2967   __ pop_frame();
2968 
2969   // stack: (deoptee, optional i2c, caller_of_deoptee, ...).
2970 
2971   // Save the return value.
2972   __ mr(unroll_block_reg, R3_RET);
2973 
2974   // Pop the uncommon_trap frame.
2975   __ pop_frame();
2976 
2977   // stack: (caller_of_deoptee, ...).
2978 
2979 #ifdef ASSERT
2980   __ lwz(R22_tmp2, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes(), unroll_block_reg);
2981   __ cmpdi(CCR0, R22_tmp2, (unsigned)Deoptimization::Unpack_uncommon_trap);
2982   __ asm_assert_eq("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap", 0);
2983 #endif
2984 
2985   // Allocate new interpreter frame(s) and possibly a c2i adapter
2986   // frame.
2987   push_skeleton_frames(masm, false/*deopt*/,
2988                        unroll_block_reg,
2989                        R22_tmp2,
2990                        R23_tmp3,
2991                        R24_tmp4,
2992                        R25_tmp5,
2993                        R26_tmp6);
2994 
2995   // stack: (skeletal interpreter frame, ..., optional skeletal
2996   // interpreter frame, optional c2i, caller of deoptee, ...).
2997 
2998   // Push a dummy `unpack_frame' taking care of float return values.
2999   // Call `Deoptimization::unpack_frames' to layout information in the
3000   // interpreter frames just created.
3001 
3002   // Push a simple "unpack frame" here.
3003   __ push_frame_reg_args(0, R11_scratch1);
3004 
3005   // stack: (unpack frame, skeletal interpreter frame, ..., optional
3006   // skeletal interpreter frame, optional c2i, caller of deoptee,
3007   // ...).
3008 
3009   // Set the "unpack_frame" as last_Java_frame.
3010   __ get_PC_trash_LR(R11_scratch1);
3011   __ set_last_Java_frame(/*sp*/R1_SP, /*pc*/R11_scratch1);
3012 
3013   // Indicate it is the uncommon trap case.
3014   __ li(unc_trap_reg, Deoptimization::Unpack_uncommon_trap);
3015   // Let the unpacker layout information in the skeletal frames just
3016   // allocated.
3017   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames),
3018                   R16_thread, unc_trap_reg);
3019 
3020   __ reset_last_Java_frame();
3021   // Pop the `unpack frame'.
3022   __ pop_frame();
3023   // Restore LR from top interpreter frame.
3024   __ restore_LR_CR(R11_scratch1);
3025 
3026   // stack: (top interpreter frame, ..., optional interpreter frame,
3027   // optional c2i, caller of deoptee, ...).
3028 
3029   __ restore_interpreter_state(R11_scratch1);
3030   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
3031 
3032   // Return to the interpreter entry point.
3033   __ blr();
3034 
3035   masm->flush();
3036 
3037   _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, oop_maps, frame_size_in_bytes/wordSize);
3038 }
3039 #endif // COMPILER2
3040 
3041 // Generate a special Compile2Runtime blob that saves all registers, and setup oopmap.
3042 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
3043   assert(StubRoutines::forward_exception_entry() != NULL,
3044          "must be generated before");
3045 
3046   ResourceMark rm;
3047   OopMapSet *oop_maps = new OopMapSet();
3048   OopMap* map;
3049 
3050   // Allocate space for the code. Setup code generation tools.
3051   CodeBuffer buffer("handler_blob", 2048, 1024);
3052   MacroAssembler* masm = new MacroAssembler(&buffer);
3053 
3054   address start = __ pc();
3055   int frame_size_in_bytes = 0;
3056 
3057   RegisterSaver::ReturnPCLocation return_pc_location;
3058   bool cause_return = (poll_type == POLL_AT_RETURN);
3059   if (cause_return) {
3060     // Nothing to do here. The frame has already been popped in MachEpilogNode.
3061     // Register LR already contains the return pc.
3062     return_pc_location = RegisterSaver::return_pc_is_lr;
3063   } else {
3064     // Use thread()->saved_exception_pc() as return pc.
3065     return_pc_location = RegisterSaver::return_pc_is_thread_saved_exception_pc;
3066   }
3067 
3068   // Save registers, fpu state, and flags.
3069   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
3070                                                                    &frame_size_in_bytes,
3071                                                                    /*generate_oop_map=*/ true,
3072                                                                    /*return_pc_adjustment=*/0,
3073                                                                    return_pc_location);
3074 
3075   // The following is basically a call_VM. However, we need the precise
3076   // address of the call in order to generate an oopmap. Hence, we do all the
3077   // work outselves.
3078   __ set_last_Java_frame(/*sp=*/R1_SP, /*pc=*/noreg);
3079 
3080   // The return address must always be correct so that the frame constructor
3081   // never sees an invalid pc.
3082 
3083   // Do the call
3084   __ call_VM_leaf(call_ptr, R16_thread);
3085   address calls_return_pc = __ last_calls_return_pc();
3086 
3087   // Set an oopmap for the call site. This oopmap will map all
3088   // oop-registers and debug-info registers as callee-saved. This
3089   // will allow deoptimization at this safepoint to find all possible
3090   // debug-info recordings, as well as let GC find all oops.
3091   oop_maps->add_gc_map(calls_return_pc - start, map);
3092 
3093   Label noException;
3094 
3095   // Clear the last Java frame.
3096   __ reset_last_Java_frame();
3097 
3098   BLOCK_COMMENT("  Check pending exception.");
3099   const Register pending_exception = R0;
3100   __ ld(pending_exception, thread_(pending_exception));
3101   __ cmpdi(CCR0, pending_exception, 0);
3102   __ beq(CCR0, noException);
3103 
3104   // Exception pending
3105   RegisterSaver::restore_live_registers_and_pop_frame(masm,
3106                                                       frame_size_in_bytes,
3107                                                       /*restore_ctr=*/true);
3108 
3109   BLOCK_COMMENT("  Jump to forward_exception_entry.");
3110   // Jump to forward_exception_entry, with the issuing PC in LR
3111   // so it looks like the original nmethod called forward_exception_entry.
3112   __ b64_patchable(StubRoutines::forward_exception_entry(), relocInfo::runtime_call_type);
3113 
3114   // No exception case.
3115   __ BIND(noException);
3116 
3117 
3118   // Normal exit, restore registers and exit.
3119   RegisterSaver::restore_live_registers_and_pop_frame(masm,
3120                                                       frame_size_in_bytes,
3121                                                       /*restore_ctr=*/true);
3122 
3123   __ blr();
3124 
3125   // Make sure all code is generated
3126   masm->flush();
3127 
3128   // Fill-out other meta info
3129   // CodeBlob frame size is in words.
3130   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_bytes / wordSize);
3131 }
3132 
3133 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss)
3134 //
3135 // Generate a stub that calls into the vm to find out the proper destination
3136 // of a java call. All the argument registers are live at this point
3137 // but since this is generic code we don't know what they are and the caller
3138 // must do any gc of the args.
3139 //
3140 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3141 
3142   // allocate space for the code
3143   ResourceMark rm;
3144 
3145   CodeBuffer buffer(name, 1000, 512);
3146   MacroAssembler* masm = new MacroAssembler(&buffer);
3147 
3148   int frame_size_in_bytes;
3149 
3150   OopMapSet *oop_maps = new OopMapSet();
3151   OopMap* map = NULL;
3152 
3153   address start = __ pc();
3154 
3155   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
3156                                                                    &frame_size_in_bytes,
3157                                                                    /*generate_oop_map*/ true,
3158                                                                    /*return_pc_adjustment*/ 0,
3159                                                                    RegisterSaver::return_pc_is_lr);
3160 
3161   // Use noreg as last_Java_pc, the return pc will be reconstructed
3162   // from the physical frame.
3163   __ set_last_Java_frame(/*sp*/R1_SP, noreg);
3164 
3165   int frame_complete = __ offset();
3166 
3167   // Pass R19_method as 2nd (optional) argument, used by
3168   // counter_overflow_stub.
3169   __ call_VM_leaf(destination, R16_thread, R19_method);
3170   address calls_return_pc = __ last_calls_return_pc();
3171   // Set an oopmap for the call site.
3172   // We need this not only for callee-saved registers, but also for volatile
3173   // registers that the compiler might be keeping live across a safepoint.
3174   // Create the oopmap for the call's return pc.
3175   oop_maps->add_gc_map(calls_return_pc - start, map);
3176 
3177   // R3_RET contains the address we are going to jump to assuming no exception got installed.
3178 
3179   // clear last_Java_sp
3180   __ reset_last_Java_frame();
3181 
3182   // Check for pending exceptions.
3183   BLOCK_COMMENT("Check for pending exceptions.");
3184   Label pending;
3185   __ ld(R11_scratch1, thread_(pending_exception));
3186   __ cmpdi(CCR0, R11_scratch1, 0);
3187   __ bne(CCR0, pending);
3188 
3189   __ mtctr(R3_RET); // Ctr will not be touched by restore_live_registers_and_pop_frame.
3190 
3191   RegisterSaver::restore_live_registers_and_pop_frame(masm, frame_size_in_bytes, /*restore_ctr*/ false);
3192 
3193   // Get the returned method.
3194   __ get_vm_result_2(R19_method);
3195 
3196   __ bctr();
3197 
3198 
3199   // Pending exception after the safepoint.
3200   __ BIND(pending);
3201 
3202   RegisterSaver::restore_live_registers_and_pop_frame(masm, frame_size_in_bytes, /*restore_ctr*/ true);
3203 
3204   // exception pending => remove activation and forward to exception handler
3205 
3206   __ li(R11_scratch1, 0);
3207   __ ld(R3_ARG1, thread_(pending_exception));
3208   __ std(R11_scratch1, in_bytes(JavaThread::vm_result_offset()), R16_thread);
3209   __ b64_patchable(StubRoutines::forward_exception_entry(), relocInfo::runtime_call_type);
3210 
3211   // -------------
3212   // Make sure all code is generated.
3213   masm->flush();
3214 
3215   // return the blob
3216   // frame_size_words or bytes??
3217   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_bytes/wordSize,
3218                                        oop_maps, true);
3219 }
3220 
3221 
3222 //------------------------------Montgomery multiplication------------------------
3223 //
3224 
3225 // Subtract 0:b from carry:a. Return carry.
3226 static unsigned long
3227 sub(unsigned long a[], unsigned long b[], unsigned long carry, long len) {
3228   long i = 0;
3229   unsigned long tmp, tmp2;
3230   __asm__ __volatile__ (
3231     "subfc  %[tmp], %[tmp], %[tmp]   \n" // pre-set CA
3232     "mtctr  %[len]                   \n"
3233     "0:                              \n"
3234     "ldx    %[tmp], %[i], %[a]       \n"
3235     "ldx    %[tmp2], %[i], %[b]      \n"
3236     "subfe  %[tmp], %[tmp2], %[tmp]  \n" // subtract extended
3237     "stdx   %[tmp], %[i], %[a]       \n"
3238     "addi   %[i], %[i], 8            \n"
3239     "bdnz   0b                       \n"
3240     "addme  %[tmp], %[carry]         \n" // carry + CA - 1
3241     : [i]"+b"(i), [tmp]"=&r"(tmp), [tmp2]"=&r"(tmp2)
3242     : [a]"r"(a), [b]"r"(b), [carry]"r"(carry), [len]"r"(len)
3243     : "ctr", "xer", "memory"
3244   );
3245   return tmp;
3246 }
3247 
3248 // Multiply (unsigned) Long A by Long B, accumulating the double-
3249 // length result into the accumulator formed of T0, T1, and T2.
3250 inline void MACC(unsigned long A, unsigned long B, unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3251   unsigned long hi, lo;
3252   __asm__ __volatile__ (
3253     "mulld  %[lo], %[A], %[B]    \n"
3254     "mulhdu %[hi], %[A], %[B]    \n"
3255     "addc   %[T0], %[T0], %[lo]  \n"
3256     "adde   %[T1], %[T1], %[hi]  \n"
3257     "addze  %[T2], %[T2]         \n"
3258     : [hi]"=&r"(hi), [lo]"=&r"(lo), [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3259     : [A]"r"(A), [B]"r"(B)
3260     : "xer"
3261   );
3262 }
3263 
3264 // As above, but add twice the double-length result into the
3265 // accumulator.
3266 inline void MACC2(unsigned long A, unsigned long B, unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3267   unsigned long hi, lo;
3268   __asm__ __volatile__ (
3269     "mulld  %[lo], %[A], %[B]    \n"
3270     "mulhdu %[hi], %[A], %[B]    \n"
3271     "addc   %[T0], %[T0], %[lo]  \n"
3272     "adde   %[T1], %[T1], %[hi]  \n"
3273     "addze  %[T2], %[T2]         \n"
3274     "addc   %[T0], %[T0], %[lo]  \n"
3275     "adde   %[T1], %[T1], %[hi]  \n"
3276     "addze  %[T2], %[T2]         \n"
3277     : [hi]"=&r"(hi), [lo]"=&r"(lo), [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3278     : [A]"r"(A), [B]"r"(B)
3279     : "xer"
3280   );
3281 }
3282 
3283 // Fast Montgomery multiplication. The derivation of the algorithm is
3284 // in "A Cryptographic Library for the Motorola DSP56000,
3285 // Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237".
3286 static void
3287 montgomery_multiply(unsigned long a[], unsigned long b[], unsigned long n[],
3288                     unsigned long m[], unsigned long inv, int len) {
3289   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3290   int i;
3291 
3292   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3293 
3294   for (i = 0; i < len; i++) {
3295     int j;
3296     for (j = 0; j < i; j++) {
3297       MACC(a[j], b[i-j], t0, t1, t2);
3298       MACC(m[j], n[i-j], t0, t1, t2);
3299     }
3300     MACC(a[i], b[0], t0, t1, t2);
3301     m[i] = t0 * inv;
3302     MACC(m[i], n[0], t0, t1, t2);
3303 
3304     assert(t0 == 0, "broken Montgomery multiply");
3305 
3306     t0 = t1; t1 = t2; t2 = 0;
3307   }
3308 
3309   for (i = len; i < 2*len; i++) {
3310     int j;
3311     for (j = i-len+1; j < len; j++) {
3312       MACC(a[j], b[i-j], t0, t1, t2);
3313       MACC(m[j], n[i-j], t0, t1, t2);
3314     }
3315     m[i-len] = t0;
3316     t0 = t1; t1 = t2; t2 = 0;
3317   }
3318 
3319   while (t0) {
3320     t0 = sub(m, n, t0, len);
3321   }
3322 }
3323 
3324 // Fast Montgomery squaring. This uses asymptotically 25% fewer
3325 // multiplies so it should be up to 25% faster than Montgomery
3326 // multiplication. However, its loop control is more complex and it
3327 // may actually run slower on some machines.
3328 static void
3329 montgomery_square(unsigned long a[], unsigned long n[],
3330                   unsigned long m[], unsigned long inv, int len) {
3331   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3332   int i;
3333 
3334   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3335 
3336   for (i = 0; i < len; i++) {
3337     int j;
3338     int end = (i+1)/2;
3339     for (j = 0; j < end; j++) {
3340       MACC2(a[j], a[i-j], t0, t1, t2);
3341       MACC(m[j], n[i-j], t0, t1, t2);
3342     }
3343     if ((i & 1) == 0) {
3344       MACC(a[j], a[j], t0, t1, t2);
3345     }
3346     for (; j < i; j++) {
3347       MACC(m[j], n[i-j], t0, t1, t2);
3348     }
3349     m[i] = t0 * inv;
3350     MACC(m[i], n[0], t0, t1, t2);
3351 
3352     assert(t0 == 0, "broken Montgomery square");
3353 
3354     t0 = t1; t1 = t2; t2 = 0;
3355   }
3356 
3357   for (i = len; i < 2*len; i++) {
3358     int start = i-len+1;
3359     int end = start + (len - start)/2;
3360     int j;
3361     for (j = start; j < end; j++) {
3362       MACC2(a[j], a[i-j], t0, t1, t2);
3363       MACC(m[j], n[i-j], t0, t1, t2);
3364     }
3365     if ((i & 1) == 0) {
3366       MACC(a[j], a[j], t0, t1, t2);
3367     }
3368     for (; j < len; j++) {
3369       MACC(m[j], n[i-j], t0, t1, t2);
3370     }
3371     m[i-len] = t0;
3372     t0 = t1; t1 = t2; t2 = 0;
3373   }
3374 
3375   while (t0) {
3376     t0 = sub(m, n, t0, len);
3377   }
3378 }
3379 
3380 // The threshold at which squaring is advantageous was determined
3381 // experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
3382 // Doesn't seem to be relevant for Power8 so we use the same value.
3383 #define MONTGOMERY_SQUARING_THRESHOLD 64
3384 
3385 // Copy len longwords from s to d, word-swapping as we go. The
3386 // destination array is reversed.
3387 static void reverse_words(unsigned long *s, unsigned long *d, int len) {
3388   d += len;
3389   while(len-- > 0) {
3390     d--;
3391     unsigned long s_val = *s;
3392     // Swap words in a longword on little endian machines.
3393 #ifdef VM_LITTLE_ENDIAN
3394      s_val = (s_val << 32) | (s_val >> 32);
3395 #endif
3396     *d = s_val;
3397     s++;
3398   }
3399 }
3400 
3401 void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
3402                                         jint len, jlong inv,
3403                                         jint *m_ints) {
3404   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3405   assert(len % 2 == 0, "array length in montgomery_multiply must be even");
3406   int longwords = len/2;
3407 
3408   // Make very sure we don't use so much space that the stack might
3409   // overflow. 512 jints corresponds to an 16384-bit integer and
3410   // will use here a total of 8k bytes of stack space.
3411   int total_allocation = longwords * sizeof (unsigned long) * 4;
3412   guarantee(total_allocation <= 8192, "must be");
3413   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3414 
3415   // Local scratch arrays
3416   unsigned long
3417     *a = scratch + 0 * longwords,
3418     *b = scratch + 1 * longwords,
3419     *n = scratch + 2 * longwords,
3420     *m = scratch + 3 * longwords;
3421 
3422   reverse_words((unsigned long *)a_ints, a, longwords);
3423   reverse_words((unsigned long *)b_ints, b, longwords);
3424   reverse_words((unsigned long *)n_ints, n, longwords);
3425 
3426   ::montgomery_multiply(a, b, n, m, (unsigned long)inv, longwords);
3427 
3428   reverse_words(m, (unsigned long *)m_ints, longwords);
3429 }
3430 
3431 void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
3432                                       jint len, jlong inv,
3433                                       jint *m_ints) {
3434   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3435   assert(len % 2 == 0, "array length in montgomery_square must be even");
3436   int longwords = len/2;
3437 
3438   // Make very sure we don't use so much space that the stack might
3439   // overflow. 512 jints corresponds to an 16384-bit integer and
3440   // will use here a total of 6k bytes of stack space.
3441   int total_allocation = longwords * sizeof (unsigned long) * 3;
3442   guarantee(total_allocation <= 8192, "must be");
3443   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3444 
3445   // Local scratch arrays
3446   unsigned long
3447     *a = scratch + 0 * longwords,
3448     *n = scratch + 1 * longwords,
3449     *m = scratch + 2 * longwords;
3450 
3451   reverse_words((unsigned long *)a_ints, a, longwords);
3452   reverse_words((unsigned long *)n_ints, n, longwords);
3453 
3454   if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
3455     ::montgomery_square(a, n, m, (unsigned long)inv, longwords);
3456   } else {
3457     ::montgomery_multiply(a, a, n, m, (unsigned long)inv, longwords);
3458   }
3459 
3460   reverse_words(m, (unsigned long *)m_ints, longwords);
3461 }