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