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