quick_trampoline_entrypoints.cc revision e7732be2390f00b1f98b8c0066a37892ee1126f6
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "art_method-inl.h"
18#include "base/callee_save_type.h"
19#include "base/enums.h"
20#include "callee_save_frame.h"
21#include "common_throws.h"
22#include "debugger.h"
23#include "dex_file-inl.h"
24#include "dex_file_types.h"
25#include "dex_instruction-inl.h"
26#include "entrypoints/entrypoint_utils-inl.h"
27#include "entrypoints/runtime_asm_entrypoints.h"
28#include "gc/accounting/card_table-inl.h"
29#include "imt_conflict_table.h"
30#include "imtable-inl.h"
31#include "instrumentation.h"
32#include "interpreter/interpreter.h"
33#include "linear_alloc.h"
34#include "method_bss_mapping.h"
35#include "method_handles.h"
36#include "method_reference.h"
37#include "mirror/class-inl.h"
38#include "mirror/dex_cache-inl.h"
39#include "mirror/method.h"
40#include "mirror/method_handle_impl.h"
41#include "mirror/object-inl.h"
42#include "mirror/object_array-inl.h"
43#include "oat_file.h"
44#include "oat_quick_method_header.h"
45#include "quick_exception_handler.h"
46#include "runtime.h"
47#include "scoped_thread_state_change-inl.h"
48#include "stack.h"
49#include "thread-inl.h"
50#include "well_known_classes.h"
51
52namespace art {
53
54// Visits the arguments as saved to the stack by a CalleeSaveType::kRefAndArgs callee save frame.
55class QuickArgumentVisitor {
56  // Number of bytes for each out register in the caller method's frame.
57  static constexpr size_t kBytesStackArgLocation = 4;
58  // Frame size in bytes of a callee-save frame for RefsAndArgs.
59  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_FrameSize =
60      GetCalleeSaveFrameSize(kRuntimeISA, CalleeSaveType::kSaveRefsAndArgs);
61#if defined(__arm__)
62  // The callee save frame is pointed to by SP.
63  // | argN       |  |
64  // | ...        |  |
65  // | arg4       |  |
66  // | arg3 spill |  |  Caller's frame
67  // | arg2 spill |  |
68  // | arg1 spill |  |
69  // | Method*    | ---
70  // | LR         |
71  // | ...        |    4x6 bytes callee saves
72  // | R3         |
73  // | R2         |
74  // | R1         |
75  // | S15        |
76  // | :          |
77  // | S0         |
78  // |            |    4x2 bytes padding
79  // | Method*    |  <- sp
80  static constexpr bool kSplitPairAcrossRegisterAndStack = false;
81  static constexpr bool kAlignPairRegister = true;
82  static constexpr bool kQuickSoftFloatAbi = false;
83  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = true;
84  static constexpr bool kQuickSkipOddFpRegisters = false;
85  static constexpr size_t kNumQuickGprArgs = 3;
86  static constexpr size_t kNumQuickFprArgs = 16;
87  static constexpr bool kGprFprLockstep = false;
88  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset =
89      arm::ArmCalleeSaveFpr1Offset(CalleeSaveType::kSaveRefsAndArgs);  // Offset of first FPR arg.
90  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset =
91      arm::ArmCalleeSaveGpr1Offset(CalleeSaveType::kSaveRefsAndArgs);  // Offset of first GPR arg.
92  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset =
93      arm::ArmCalleeSaveLrOffset(CalleeSaveType::kSaveRefsAndArgs);  // Offset of return address.
94  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
95    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
96  }
97#elif defined(__aarch64__)
98  // The callee save frame is pointed to by SP.
99  // | argN       |  |
100  // | ...        |  |
101  // | arg4       |  |
102  // | arg3 spill |  |  Caller's frame
103  // | arg2 spill |  |
104  // | arg1 spill |  |
105  // | Method*    | ---
106  // | LR         |
107  // | X29        |
108  // |  :         |
109  // | X20        |
110  // | X7         |
111  // | :          |
112  // | X1         |
113  // | D7         |
114  // |  :         |
115  // | D0         |
116  // |            |    padding
117  // | Method*    |  <- sp
118  static constexpr bool kSplitPairAcrossRegisterAndStack = false;
119  static constexpr bool kAlignPairRegister = false;
120  static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
121  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
122  static constexpr bool kQuickSkipOddFpRegisters = false;
123  static constexpr size_t kNumQuickGprArgs = 7;  // 7 arguments passed in GPRs.
124  static constexpr size_t kNumQuickFprArgs = 8;  // 8 arguments passed in FPRs.
125  static constexpr bool kGprFprLockstep = false;
126  // Offset of first FPR arg.
127  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset =
128      arm64::Arm64CalleeSaveFpr1Offset(CalleeSaveType::kSaveRefsAndArgs);
129  // Offset of first GPR arg.
130  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset =
131      arm64::Arm64CalleeSaveGpr1Offset(CalleeSaveType::kSaveRefsAndArgs);
132  // Offset of return address.
133  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset =
134      arm64::Arm64CalleeSaveLrOffset(CalleeSaveType::kSaveRefsAndArgs);
135  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
136    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
137  }
138#elif defined(__mips__) && !defined(__LP64__)
139  // The callee save frame is pointed to by SP.
140  // | argN       |  |
141  // | ...        |  |
142  // | arg4       |  |
143  // | arg3 spill |  |  Caller's frame
144  // | arg2 spill |  |
145  // | arg1 spill |  |
146  // | Method*    | ---
147  // | RA         |
148  // | ...        |    callee saves
149  // | T1         |    arg5
150  // | T0         |    arg4
151  // | A3         |    arg3
152  // | A2         |    arg2
153  // | A1         |    arg1
154  // | F19        |
155  // | F18        |    f_arg5
156  // | F17        |
157  // | F16        |    f_arg4
158  // | F15        |
159  // | F14        |    f_arg3
160  // | F13        |
161  // | F12        |    f_arg2
162  // | F11        |
163  // | F10        |    f_arg1
164  // | F9         |
165  // | F8         |    f_arg0
166  // |            |    padding
167  // | A0/Method* |  <- sp
168  static constexpr bool kSplitPairAcrossRegisterAndStack = false;
169  static constexpr bool kAlignPairRegister = true;
170  static constexpr bool kQuickSoftFloatAbi = false;
171  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
172  static constexpr bool kQuickSkipOddFpRegisters = true;
173  static constexpr size_t kNumQuickGprArgs = 5;   // 5 arguments passed in GPRs.
174  static constexpr size_t kNumQuickFprArgs = 12;  // 6 arguments passed in FPRs. Floats can be
175                                                  // passed only in even numbered registers and each
176                                                  // double occupies two registers.
177  static constexpr bool kGprFprLockstep = false;
178  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 8;  // Offset of first FPR arg.
179  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 56;  // Offset of first GPR arg.
180  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 108;  // Offset of return address.
181  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
182    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
183  }
184#elif defined(__mips__) && defined(__LP64__)
185  // The callee save frame is pointed to by SP.
186  // | argN       |  |
187  // | ...        |  |
188  // | arg4       |  |
189  // | arg3 spill |  |  Caller's frame
190  // | arg2 spill |  |
191  // | arg1 spill |  |
192  // | Method*    | ---
193  // | RA         |
194  // | ...        |    callee saves
195  // | A7         |    arg7
196  // | A6         |    arg6
197  // | A5         |    arg5
198  // | A4         |    arg4
199  // | A3         |    arg3
200  // | A2         |    arg2
201  // | A1         |    arg1
202  // | F19        |    f_arg7
203  // | F18        |    f_arg6
204  // | F17        |    f_arg5
205  // | F16        |    f_arg4
206  // | F15        |    f_arg3
207  // | F14        |    f_arg2
208  // | F13        |    f_arg1
209  // | F12        |    f_arg0
210  // |            |    padding
211  // | A0/Method* |  <- sp
212  // NOTE: for Mip64, when A0 is skipped, F12 is also skipped.
213  static constexpr bool kSplitPairAcrossRegisterAndStack = false;
214  static constexpr bool kAlignPairRegister = false;
215  static constexpr bool kQuickSoftFloatAbi = false;
216  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
217  static constexpr bool kQuickSkipOddFpRegisters = false;
218  static constexpr size_t kNumQuickGprArgs = 7;  // 7 arguments passed in GPRs.
219  static constexpr size_t kNumQuickFprArgs = 7;  // 7 arguments passed in FPRs.
220  static constexpr bool kGprFprLockstep = true;
221
222  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 24;  // Offset of first FPR arg (F13).
223  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 80;  // Offset of first GPR arg (A1).
224  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 200;  // Offset of return address.
225  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
226    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
227  }
228#elif defined(__i386__)
229  // The callee save frame is pointed to by SP.
230  // | argN        |  |
231  // | ...         |  |
232  // | arg4        |  |
233  // | arg3 spill  |  |  Caller's frame
234  // | arg2 spill  |  |
235  // | arg1 spill  |  |
236  // | Method*     | ---
237  // | Return      |
238  // | EBP,ESI,EDI |    callee saves
239  // | EBX         |    arg3
240  // | EDX         |    arg2
241  // | ECX         |    arg1
242  // | XMM3        |    float arg 4
243  // | XMM2        |    float arg 3
244  // | XMM1        |    float arg 2
245  // | XMM0        |    float arg 1
246  // | EAX/Method* |  <- sp
247  static constexpr bool kSplitPairAcrossRegisterAndStack = false;
248  static constexpr bool kAlignPairRegister = false;
249  static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
250  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
251  static constexpr bool kQuickSkipOddFpRegisters = false;
252  static constexpr size_t kNumQuickGprArgs = 3;  // 3 arguments passed in GPRs.
253  static constexpr size_t kNumQuickFprArgs = 4;  // 4 arguments passed in FPRs.
254  static constexpr bool kGprFprLockstep = false;
255  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 4;  // Offset of first FPR arg.
256  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 4 + 4*8;  // Offset of first GPR arg.
257  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 28 + 4*8;  // Offset of return address.
258  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
259    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
260  }
261#elif defined(__x86_64__)
262  // The callee save frame is pointed to by SP.
263  // | argN            |  |
264  // | ...             |  |
265  // | reg. arg spills |  |  Caller's frame
266  // | Method*         | ---
267  // | Return          |
268  // | R15             |    callee save
269  // | R14             |    callee save
270  // | R13             |    callee save
271  // | R12             |    callee save
272  // | R9              |    arg5
273  // | R8              |    arg4
274  // | RSI/R6          |    arg1
275  // | RBP/R5          |    callee save
276  // | RBX/R3          |    callee save
277  // | RDX/R2          |    arg2
278  // | RCX/R1          |    arg3
279  // | XMM7            |    float arg 8
280  // | XMM6            |    float arg 7
281  // | XMM5            |    float arg 6
282  // | XMM4            |    float arg 5
283  // | XMM3            |    float arg 4
284  // | XMM2            |    float arg 3
285  // | XMM1            |    float arg 2
286  // | XMM0            |    float arg 1
287  // | Padding         |
288  // | RDI/Method*     |  <- sp
289  static constexpr bool kSplitPairAcrossRegisterAndStack = false;
290  static constexpr bool kAlignPairRegister = false;
291  static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
292  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
293  static constexpr bool kQuickSkipOddFpRegisters = false;
294  static constexpr size_t kNumQuickGprArgs = 5;  // 5 arguments passed in GPRs.
295  static constexpr size_t kNumQuickFprArgs = 8;  // 8 arguments passed in FPRs.
296  static constexpr bool kGprFprLockstep = false;
297  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 16;  // Offset of first FPR arg.
298  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 80 + 4*8;  // Offset of first GPR arg.
299  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 168 + 4*8;  // Offset of return address.
300  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
301    switch (gpr_index) {
302      case 0: return (4 * GetBytesPerGprSpillLocation(kRuntimeISA));
303      case 1: return (1 * GetBytesPerGprSpillLocation(kRuntimeISA));
304      case 2: return (0 * GetBytesPerGprSpillLocation(kRuntimeISA));
305      case 3: return (5 * GetBytesPerGprSpillLocation(kRuntimeISA));
306      case 4: return (6 * GetBytesPerGprSpillLocation(kRuntimeISA));
307      default:
308      LOG(FATAL) << "Unexpected GPR index: " << gpr_index;
309      return 0;
310    }
311  }
312#else
313#error "Unsupported architecture"
314#endif
315
316 public:
317  // Special handling for proxy methods. Proxy methods are instance methods so the
318  // 'this' object is the 1st argument. They also have the same frame layout as the
319  // kRefAndArgs runtime method. Since 'this' is a reference, it is located in the
320  // 1st GPR.
321  static mirror::Object* GetProxyThisObject(ArtMethod** sp)
322      REQUIRES_SHARED(Locks::mutator_lock_) {
323    CHECK((*sp)->IsProxyMethod());
324    CHECK_GT(kNumQuickGprArgs, 0u);
325    constexpr uint32_t kThisGprIndex = 0u;  // 'this' is in the 1st GPR.
326    size_t this_arg_offset = kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset +
327        GprIndexToGprOffset(kThisGprIndex);
328    uint8_t* this_arg_address = reinterpret_cast<uint8_t*>(sp) + this_arg_offset;
329    return reinterpret_cast<StackReference<mirror::Object>*>(this_arg_address)->AsMirrorPtr();
330  }
331
332  static ArtMethod* GetCallingMethod(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
333    DCHECK((*sp)->IsCalleeSaveMethod());
334    return GetCalleeSaveMethodCaller(sp, CalleeSaveType::kSaveRefsAndArgs);
335  }
336
337  static ArtMethod* GetOuterMethod(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
338    DCHECK((*sp)->IsCalleeSaveMethod());
339    uint8_t* previous_sp =
340        reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_FrameSize;
341    return *reinterpret_cast<ArtMethod**>(previous_sp);
342  }
343
344  static uint32_t GetCallingDexPc(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
345    DCHECK((*sp)->IsCalleeSaveMethod());
346    const size_t callee_frame_size = GetCalleeSaveFrameSize(kRuntimeISA,
347                                                            CalleeSaveType::kSaveRefsAndArgs);
348    ArtMethod** caller_sp = reinterpret_cast<ArtMethod**>(
349        reinterpret_cast<uintptr_t>(sp) + callee_frame_size);
350    uintptr_t outer_pc = QuickArgumentVisitor::GetCallingPc(sp);
351    const OatQuickMethodHeader* current_code = (*caller_sp)->GetOatQuickMethodHeader(outer_pc);
352    uintptr_t outer_pc_offset = current_code->NativeQuickPcOffset(outer_pc);
353
354    if (current_code->IsOptimized()) {
355      CodeInfo code_info = current_code->GetOptimizedCodeInfo();
356      CodeInfoEncoding encoding = code_info.ExtractEncoding();
357      StackMap stack_map = code_info.GetStackMapForNativePcOffset(outer_pc_offset, encoding);
358      DCHECK(stack_map.IsValid());
359      if (stack_map.HasInlineInfo(encoding.stack_map.encoding)) {
360        InlineInfo inline_info = code_info.GetInlineInfoOf(stack_map, encoding);
361        return inline_info.GetDexPcAtDepth(encoding.inline_info.encoding,
362                                           inline_info.GetDepth(encoding.inline_info.encoding)-1);
363      } else {
364        return stack_map.GetDexPc(encoding.stack_map.encoding);
365      }
366    } else {
367      return current_code->ToDexPc(*caller_sp, outer_pc);
368    }
369  }
370
371  static bool GetInvokeType(ArtMethod** sp, InvokeType* invoke_type, uint32_t* dex_method_index)
372      REQUIRES_SHARED(Locks::mutator_lock_) {
373    DCHECK((*sp)->IsCalleeSaveMethod());
374    const size_t callee_frame_size = GetCalleeSaveFrameSize(kRuntimeISA,
375                                                            CalleeSaveType::kSaveRefsAndArgs);
376    ArtMethod** caller_sp = reinterpret_cast<ArtMethod**>(
377        reinterpret_cast<uintptr_t>(sp) + callee_frame_size);
378    uintptr_t outer_pc = QuickArgumentVisitor::GetCallingPc(sp);
379    const OatQuickMethodHeader* current_code = (*caller_sp)->GetOatQuickMethodHeader(outer_pc);
380    if (!current_code->IsOptimized()) {
381      return false;
382    }
383    uintptr_t outer_pc_offset = current_code->NativeQuickPcOffset(outer_pc);
384    CodeInfo code_info = current_code->GetOptimizedCodeInfo();
385    CodeInfoEncoding encoding = code_info.ExtractEncoding();
386    MethodInfo method_info = current_code->GetOptimizedMethodInfo();
387    InvokeInfo invoke(code_info.GetInvokeInfoForNativePcOffset(outer_pc_offset, encoding));
388    if (invoke.IsValid()) {
389      *invoke_type = static_cast<InvokeType>(invoke.GetInvokeType(encoding.invoke_info.encoding));
390      *dex_method_index = invoke.GetMethodIndex(encoding.invoke_info.encoding, method_info);
391      return true;
392    }
393    return false;
394  }
395
396  // For the given quick ref and args quick frame, return the caller's PC.
397  static uintptr_t GetCallingPc(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
398    DCHECK((*sp)->IsCalleeSaveMethod());
399    uint8_t* lr = reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_LrOffset;
400    return *reinterpret_cast<uintptr_t*>(lr);
401  }
402
403  QuickArgumentVisitor(ArtMethod** sp, bool is_static, const char* shorty,
404                       uint32_t shorty_len) REQUIRES_SHARED(Locks::mutator_lock_) :
405          is_static_(is_static), shorty_(shorty), shorty_len_(shorty_len),
406          gpr_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset),
407          fpr_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset),
408          stack_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_FrameSize
409              + sizeof(ArtMethod*)),  // Skip ArtMethod*.
410          gpr_index_(0), fpr_index_(0), fpr_double_index_(0), stack_index_(0),
411          cur_type_(Primitive::kPrimVoid), is_split_long_or_double_(false) {
412    static_assert(kQuickSoftFloatAbi == (kNumQuickFprArgs == 0),
413                  "Number of Quick FPR arguments unexpected");
414    static_assert(!(kQuickSoftFloatAbi && kQuickDoubleRegAlignedFloatBackFilled),
415                  "Double alignment unexpected");
416    // For register alignment, we want to assume that counters(fpr_double_index_) are even if the
417    // next register is even.
418    static_assert(!kQuickDoubleRegAlignedFloatBackFilled || kNumQuickFprArgs % 2 == 0,
419                  "Number of Quick FPR arguments not even");
420    DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
421  }
422
423  virtual ~QuickArgumentVisitor() {}
424
425  virtual void Visit() = 0;
426
427  Primitive::Type GetParamPrimitiveType() const {
428    return cur_type_;
429  }
430
431  uint8_t* GetParamAddress() const {
432    if (!kQuickSoftFloatAbi) {
433      Primitive::Type type = GetParamPrimitiveType();
434      if (UNLIKELY((type == Primitive::kPrimDouble) || (type == Primitive::kPrimFloat))) {
435        if (type == Primitive::kPrimDouble && kQuickDoubleRegAlignedFloatBackFilled) {
436          if (fpr_double_index_ + 2 < kNumQuickFprArgs + 1) {
437            return fpr_args_ + (fpr_double_index_ * GetBytesPerFprSpillLocation(kRuntimeISA));
438          }
439        } else if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
440          return fpr_args_ + (fpr_index_ * GetBytesPerFprSpillLocation(kRuntimeISA));
441        }
442        return stack_args_ + (stack_index_ * kBytesStackArgLocation);
443      }
444    }
445    if (gpr_index_ < kNumQuickGprArgs) {
446      return gpr_args_ + GprIndexToGprOffset(gpr_index_);
447    }
448    return stack_args_ + (stack_index_ * kBytesStackArgLocation);
449  }
450
451  bool IsSplitLongOrDouble() const {
452    if ((GetBytesPerGprSpillLocation(kRuntimeISA) == 4) ||
453        (GetBytesPerFprSpillLocation(kRuntimeISA) == 4)) {
454      return is_split_long_or_double_;
455    } else {
456      return false;  // An optimization for when GPR and FPRs are 64bit.
457    }
458  }
459
460  bool IsParamAReference() const {
461    return GetParamPrimitiveType() == Primitive::kPrimNot;
462  }
463
464  bool IsParamALongOrDouble() const {
465    Primitive::Type type = GetParamPrimitiveType();
466    return type == Primitive::kPrimLong || type == Primitive::kPrimDouble;
467  }
468
469  uint64_t ReadSplitLongParam() const {
470    // The splitted long is always available through the stack.
471    return *reinterpret_cast<uint64_t*>(stack_args_
472        + stack_index_ * kBytesStackArgLocation);
473  }
474
475  void IncGprIndex() {
476    gpr_index_++;
477    if (kGprFprLockstep) {
478      fpr_index_++;
479    }
480  }
481
482  void IncFprIndex() {
483    fpr_index_++;
484    if (kGprFprLockstep) {
485      gpr_index_++;
486    }
487  }
488
489  void VisitArguments() REQUIRES_SHARED(Locks::mutator_lock_) {
490    // (a) 'stack_args_' should point to the first method's argument
491    // (b) whatever the argument type it is, the 'stack_index_' should
492    //     be moved forward along with every visiting.
493    gpr_index_ = 0;
494    fpr_index_ = 0;
495    if (kQuickDoubleRegAlignedFloatBackFilled) {
496      fpr_double_index_ = 0;
497    }
498    stack_index_ = 0;
499    if (!is_static_) {  // Handle this.
500      cur_type_ = Primitive::kPrimNot;
501      is_split_long_or_double_ = false;
502      Visit();
503      stack_index_++;
504      if (kNumQuickGprArgs > 0) {
505        IncGprIndex();
506      }
507    }
508    for (uint32_t shorty_index = 1; shorty_index < shorty_len_; ++shorty_index) {
509      cur_type_ = Primitive::GetType(shorty_[shorty_index]);
510      switch (cur_type_) {
511        case Primitive::kPrimNot:
512        case Primitive::kPrimBoolean:
513        case Primitive::kPrimByte:
514        case Primitive::kPrimChar:
515        case Primitive::kPrimShort:
516        case Primitive::kPrimInt:
517          is_split_long_or_double_ = false;
518          Visit();
519          stack_index_++;
520          if (gpr_index_ < kNumQuickGprArgs) {
521            IncGprIndex();
522          }
523          break;
524        case Primitive::kPrimFloat:
525          is_split_long_or_double_ = false;
526          Visit();
527          stack_index_++;
528          if (kQuickSoftFloatAbi) {
529            if (gpr_index_ < kNumQuickGprArgs) {
530              IncGprIndex();
531            }
532          } else {
533            if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
534              IncFprIndex();
535              if (kQuickDoubleRegAlignedFloatBackFilled) {
536                // Double should not overlap with float.
537                // For example, if fpr_index_ = 3, fpr_double_index_ should be at least 4.
538                fpr_double_index_ = std::max(fpr_double_index_, RoundUp(fpr_index_, 2));
539                // Float should not overlap with double.
540                if (fpr_index_ % 2 == 0) {
541                  fpr_index_ = std::max(fpr_double_index_, fpr_index_);
542                }
543              } else if (kQuickSkipOddFpRegisters) {
544                IncFprIndex();
545              }
546            }
547          }
548          break;
549        case Primitive::kPrimDouble:
550        case Primitive::kPrimLong:
551          if (kQuickSoftFloatAbi || (cur_type_ == Primitive::kPrimLong)) {
552            if (cur_type_ == Primitive::kPrimLong &&
553#if defined(__mips__) && !defined(__LP64__)
554                (gpr_index_ == 0 || gpr_index_ == 2) &&
555#else
556                gpr_index_ == 0 &&
557#endif
558                kAlignPairRegister) {
559              // Currently, this is only for ARM and MIPS, where we align long parameters with
560              // even-numbered registers by skipping R1 (on ARM) or A1(A3) (on MIPS) and using
561              // R2 (on ARM) or A2(T0) (on MIPS) instead.
562              IncGprIndex();
563            }
564            is_split_long_or_double_ = (GetBytesPerGprSpillLocation(kRuntimeISA) == 4) &&
565                ((gpr_index_ + 1) == kNumQuickGprArgs);
566            if (!kSplitPairAcrossRegisterAndStack && is_split_long_or_double_) {
567              // We don't want to split this. Pass over this register.
568              gpr_index_++;
569              is_split_long_or_double_ = false;
570            }
571            Visit();
572            if (kBytesStackArgLocation == 4) {
573              stack_index_+= 2;
574            } else {
575              CHECK_EQ(kBytesStackArgLocation, 8U);
576              stack_index_++;
577            }
578            if (gpr_index_ < kNumQuickGprArgs) {
579              IncGprIndex();
580              if (GetBytesPerGprSpillLocation(kRuntimeISA) == 4) {
581                if (gpr_index_ < kNumQuickGprArgs) {
582                  IncGprIndex();
583                }
584              }
585            }
586          } else {
587            is_split_long_or_double_ = (GetBytesPerFprSpillLocation(kRuntimeISA) == 4) &&
588                ((fpr_index_ + 1) == kNumQuickFprArgs) && !kQuickDoubleRegAlignedFloatBackFilled;
589            Visit();
590            if (kBytesStackArgLocation == 4) {
591              stack_index_+= 2;
592            } else {
593              CHECK_EQ(kBytesStackArgLocation, 8U);
594              stack_index_++;
595            }
596            if (kQuickDoubleRegAlignedFloatBackFilled) {
597              if (fpr_double_index_ + 2 < kNumQuickFprArgs + 1) {
598                fpr_double_index_ += 2;
599                // Float should not overlap with double.
600                if (fpr_index_ % 2 == 0) {
601                  fpr_index_ = std::max(fpr_double_index_, fpr_index_);
602                }
603              }
604            } else if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
605              IncFprIndex();
606              if (GetBytesPerFprSpillLocation(kRuntimeISA) == 4) {
607                if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
608                  IncFprIndex();
609                }
610              }
611            }
612          }
613          break;
614        default:
615          LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty_;
616      }
617    }
618  }
619
620 protected:
621  const bool is_static_;
622  const char* const shorty_;
623  const uint32_t shorty_len_;
624
625 private:
626  uint8_t* const gpr_args_;  // Address of GPR arguments in callee save frame.
627  uint8_t* const fpr_args_;  // Address of FPR arguments in callee save frame.
628  uint8_t* const stack_args_;  // Address of stack arguments in caller's frame.
629  uint32_t gpr_index_;  // Index into spilled GPRs.
630  // Index into spilled FPRs.
631  // In case kQuickDoubleRegAlignedFloatBackFilled, it may index a hole while fpr_double_index_
632  // holds a higher register number.
633  uint32_t fpr_index_;
634  // Index into spilled FPRs for aligned double.
635  // Only used when kQuickDoubleRegAlignedFloatBackFilled. Next available double register indexed in
636  // terms of singles, may be behind fpr_index.
637  uint32_t fpr_double_index_;
638  uint32_t stack_index_;  // Index into arguments on the stack.
639  // The current type of argument during VisitArguments.
640  Primitive::Type cur_type_;
641  // Does a 64bit parameter straddle the register and stack arguments?
642  bool is_split_long_or_double_;
643};
644
645// Returns the 'this' object of a proxy method. This function is only used by StackVisitor. It
646// allows to use the QuickArgumentVisitor constants without moving all the code in its own module.
647extern "C" mirror::Object* artQuickGetProxyThisObject(ArtMethod** sp)
648    REQUIRES_SHARED(Locks::mutator_lock_) {
649  return QuickArgumentVisitor::GetProxyThisObject(sp);
650}
651
652// Visits arguments on the stack placing them into the shadow frame.
653class BuildQuickShadowFrameVisitor FINAL : public QuickArgumentVisitor {
654 public:
655  BuildQuickShadowFrameVisitor(ArtMethod** sp, bool is_static, const char* shorty,
656                               uint32_t shorty_len, ShadowFrame* sf, size_t first_arg_reg) :
657      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), sf_(sf), cur_reg_(first_arg_reg) {}
658
659  void Visit() REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE;
660
661 private:
662  ShadowFrame* const sf_;
663  uint32_t cur_reg_;
664
665  DISALLOW_COPY_AND_ASSIGN(BuildQuickShadowFrameVisitor);
666};
667
668void BuildQuickShadowFrameVisitor::Visit() {
669  Primitive::Type type = GetParamPrimitiveType();
670  switch (type) {
671    case Primitive::kPrimLong:  // Fall-through.
672    case Primitive::kPrimDouble:
673      if (IsSplitLongOrDouble()) {
674        sf_->SetVRegLong(cur_reg_, ReadSplitLongParam());
675      } else {
676        sf_->SetVRegLong(cur_reg_, *reinterpret_cast<jlong*>(GetParamAddress()));
677      }
678      ++cur_reg_;
679      break;
680    case Primitive::kPrimNot: {
681        StackReference<mirror::Object>* stack_ref =
682            reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
683        sf_->SetVRegReference(cur_reg_, stack_ref->AsMirrorPtr());
684      }
685      break;
686    case Primitive::kPrimBoolean:  // Fall-through.
687    case Primitive::kPrimByte:     // Fall-through.
688    case Primitive::kPrimChar:     // Fall-through.
689    case Primitive::kPrimShort:    // Fall-through.
690    case Primitive::kPrimInt:      // Fall-through.
691    case Primitive::kPrimFloat:
692      sf_->SetVReg(cur_reg_, *reinterpret_cast<jint*>(GetParamAddress()));
693      break;
694    case Primitive::kPrimVoid:
695      LOG(FATAL) << "UNREACHABLE";
696      UNREACHABLE();
697  }
698  ++cur_reg_;
699}
700
701// Don't inline. See b/65159206.
702NO_INLINE
703static void HandleDeoptimization(JValue* result,
704                                 ArtMethod* method,
705                                 ShadowFrame* deopt_frame,
706                                 ManagedStack* fragment)
707    REQUIRES_SHARED(Locks::mutator_lock_) {
708  // Coming from partial-fragment deopt.
709  Thread* self = Thread::Current();
710  if (kIsDebugBuild) {
711    // Sanity-check: are the methods as expected? We check that the last shadow frame (the bottom
712    // of the call-stack) corresponds to the called method.
713    ShadowFrame* linked = deopt_frame;
714    while (linked->GetLink() != nullptr) {
715      linked = linked->GetLink();
716    }
717    CHECK_EQ(method, linked->GetMethod()) << method->PrettyMethod() << " "
718        << ArtMethod::PrettyMethod(linked->GetMethod());
719  }
720
721  if (VLOG_IS_ON(deopt)) {
722    // Print out the stack to verify that it was a partial-fragment deopt.
723    LOG(INFO) << "Continue-ing from deopt. Stack is:";
724    QuickExceptionHandler::DumpFramesWithType(self, true);
725  }
726
727  ObjPtr<mirror::Throwable> pending_exception;
728  bool from_code = false;
729  DeoptimizationMethodType method_type;
730  self->PopDeoptimizationContext(/* out */ result,
731                                 /* out */ &pending_exception,
732                                 /* out */ &from_code,
733                                 /* out */ &method_type);
734
735  // Push a transition back into managed code onto the linked list in thread.
736  self->PushManagedStackFragment(fragment);
737
738  // Ensure that the stack is still in order.
739  if (kIsDebugBuild) {
740    class DummyStackVisitor : public StackVisitor {
741     public:
742      explicit DummyStackVisitor(Thread* self_in) REQUIRES_SHARED(Locks::mutator_lock_)
743          : StackVisitor(self_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames) {}
744
745      bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
746        // Nothing to do here. In a debug build, SanityCheckFrame will do the work in the walking
747        // logic. Just always say we want to continue.
748        return true;
749      }
750    };
751    DummyStackVisitor dsv(self);
752    dsv.WalkStack();
753  }
754
755  // Restore the exception that was pending before deoptimization then interpret the
756  // deoptimized frames.
757  if (pending_exception != nullptr) {
758    self->SetException(pending_exception);
759  }
760  interpreter::EnterInterpreterFromDeoptimize(self,
761                                              deopt_frame,
762                                              result,
763                                              from_code,
764                                              DeoptimizationMethodType::kDefault);
765}
766
767extern "C" uint64_t artQuickToInterpreterBridge(ArtMethod* method, Thread* self, ArtMethod** sp)
768    REQUIRES_SHARED(Locks::mutator_lock_) {
769  // Ensure we don't get thread suspension until the object arguments are safely in the shadow
770  // frame.
771  ScopedQuickEntrypointChecks sqec(self);
772
773  if (UNLIKELY(!method->IsInvokable())) {
774    method->ThrowInvocationTimeError();
775    return 0;
776  }
777
778  JValue tmp_value;
779  ShadowFrame* deopt_frame = self->PopStackedShadowFrame(
780      StackedShadowFrameType::kDeoptimizationShadowFrame, false);
781  ManagedStack fragment;
782
783  DCHECK(!method->IsNative()) << method->PrettyMethod();
784  uint32_t shorty_len = 0;
785  ArtMethod* non_proxy_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
786  const DexFile::CodeItem* code_item = non_proxy_method->GetCodeItem();
787  DCHECK(code_item != nullptr) << method->PrettyMethod();
788  const char* shorty = non_proxy_method->GetShorty(&shorty_len);
789
790  JValue result;
791
792  if (UNLIKELY(deopt_frame != nullptr)) {
793    HandleDeoptimization(&result, method, deopt_frame, &fragment);
794  } else {
795    const char* old_cause = self->StartAssertNoThreadSuspension(
796        "Building interpreter shadow frame");
797    uint16_t num_regs = code_item->registers_size_;
798    // No last shadow coming from quick.
799    ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
800        CREATE_SHADOW_FRAME(num_regs, /* link */ nullptr, method, /* dex pc */ 0);
801    ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
802    size_t first_arg_reg = code_item->registers_size_ - code_item->ins_size_;
803    BuildQuickShadowFrameVisitor shadow_frame_builder(sp, method->IsStatic(), shorty, shorty_len,
804                                                      shadow_frame, first_arg_reg);
805    shadow_frame_builder.VisitArguments();
806    const bool needs_initialization =
807        method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
808    // Push a transition back into managed code onto the linked list in thread.
809    self->PushManagedStackFragment(&fragment);
810    self->PushShadowFrame(shadow_frame);
811    self->EndAssertNoThreadSuspension(old_cause);
812
813    if (needs_initialization) {
814      // Ensure static method's class is initialized.
815      StackHandleScope<1> hs(self);
816      Handle<mirror::Class> h_class(hs.NewHandle(shadow_frame->GetMethod()->GetDeclaringClass()));
817      if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
818        DCHECK(Thread::Current()->IsExceptionPending())
819            << shadow_frame->GetMethod()->PrettyMethod();
820        self->PopManagedStackFragment(fragment);
821        return 0;
822      }
823    }
824
825    result = interpreter::EnterInterpreterFromEntryPoint(self, code_item, shadow_frame);
826  }
827
828  // Pop transition.
829  self->PopManagedStackFragment(fragment);
830
831  // Request a stack deoptimization if needed
832  ArtMethod* caller = QuickArgumentVisitor::GetCallingMethod(sp);
833  uintptr_t caller_pc = QuickArgumentVisitor::GetCallingPc(sp);
834  // If caller_pc is the instrumentation exit stub, the stub will check to see if deoptimization
835  // should be done and it knows the real return pc.
836  if (UNLIKELY(caller_pc != reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()) &&
837               Dbg::IsForcedInterpreterNeededForUpcall(self, caller))) {
838    if (!Runtime::Current()->IsAsyncDeoptimizeable(caller_pc)) {
839      LOG(WARNING) << "Got a deoptimization request on un-deoptimizable method "
840                   << caller->PrettyMethod();
841    } else {
842      // Push the context of the deoptimization stack so we can restore the return value and the
843      // exception before executing the deoptimized frames.
844      self->PushDeoptimizationContext(
845          result,
846          shorty[0] == 'L' || shorty[0] == '[',  /* class or array */
847          self->GetException(),
848          false /* from_code */,
849          DeoptimizationMethodType::kDefault);
850
851      // Set special exception to cause deoptimization.
852      self->SetException(Thread::GetDeoptimizationException());
853    }
854  }
855
856  // No need to restore the args since the method has already been run by the interpreter.
857  return result.GetJ();
858}
859
860// Visits arguments on the stack placing them into the args vector, Object* arguments are converted
861// to jobjects.
862class BuildQuickArgumentVisitor FINAL : public QuickArgumentVisitor {
863 public:
864  BuildQuickArgumentVisitor(ArtMethod** sp, bool is_static, const char* shorty, uint32_t shorty_len,
865                            ScopedObjectAccessUnchecked* soa, std::vector<jvalue>* args) :
866      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa), args_(args) {}
867
868  void Visit() REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE;
869
870  void FixupReferences() REQUIRES_SHARED(Locks::mutator_lock_);
871
872 private:
873  ScopedObjectAccessUnchecked* const soa_;
874  std::vector<jvalue>* const args_;
875  // References which we must update when exiting in case the GC moved the objects.
876  std::vector<std::pair<jobject, StackReference<mirror::Object>*>> references_;
877
878  DISALLOW_COPY_AND_ASSIGN(BuildQuickArgumentVisitor);
879};
880
881void BuildQuickArgumentVisitor::Visit() {
882  jvalue val;
883  Primitive::Type type = GetParamPrimitiveType();
884  switch (type) {
885    case Primitive::kPrimNot: {
886      StackReference<mirror::Object>* stack_ref =
887          reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
888      val.l = soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
889      references_.push_back(std::make_pair(val.l, stack_ref));
890      break;
891    }
892    case Primitive::kPrimLong:  // Fall-through.
893    case Primitive::kPrimDouble:
894      if (IsSplitLongOrDouble()) {
895        val.j = ReadSplitLongParam();
896      } else {
897        val.j = *reinterpret_cast<jlong*>(GetParamAddress());
898      }
899      break;
900    case Primitive::kPrimBoolean:  // Fall-through.
901    case Primitive::kPrimByte:     // Fall-through.
902    case Primitive::kPrimChar:     // Fall-through.
903    case Primitive::kPrimShort:    // Fall-through.
904    case Primitive::kPrimInt:      // Fall-through.
905    case Primitive::kPrimFloat:
906      val.i = *reinterpret_cast<jint*>(GetParamAddress());
907      break;
908    case Primitive::kPrimVoid:
909      LOG(FATAL) << "UNREACHABLE";
910      UNREACHABLE();
911  }
912  args_->push_back(val);
913}
914
915void BuildQuickArgumentVisitor::FixupReferences() {
916  // Fixup any references which may have changed.
917  for (const auto& pair : references_) {
918    pair.second->Assign(soa_->Decode<mirror::Object>(pair.first));
919    soa_->Env()->DeleteLocalRef(pair.first);
920  }
921}
922// Handler for invocation on proxy methods. On entry a frame will exist for the proxy object method
923// which is responsible for recording callee save registers. We explicitly place into jobjects the
924// incoming reference arguments (so they survive GC). We invoke the invocation handler, which is a
925// field within the proxy object, which will box the primitive arguments and deal with error cases.
926extern "C" uint64_t artQuickProxyInvokeHandler(
927    ArtMethod* proxy_method, mirror::Object* receiver, Thread* self, ArtMethod** sp)
928    REQUIRES_SHARED(Locks::mutator_lock_) {
929  DCHECK(proxy_method->IsProxyMethod()) << proxy_method->PrettyMethod();
930  DCHECK(receiver->GetClass()->IsProxyClass()) << proxy_method->PrettyMethod();
931  // Ensure we don't get thread suspension until the object arguments are safely in jobjects.
932  const char* old_cause =
933      self->StartAssertNoThreadSuspension("Adding to IRT proxy object arguments");
934  // Register the top of the managed stack, making stack crawlable.
935  DCHECK_EQ((*sp), proxy_method) << proxy_method->PrettyMethod();
936  self->VerifyStack();
937  // Start new JNI local reference state.
938  JNIEnvExt* env = self->GetJniEnv();
939  ScopedObjectAccessUnchecked soa(env);
940  ScopedJniEnvLocalRefState env_state(env);
941  // Create local ref. copies of proxy method and the receiver.
942  jobject rcvr_jobj = soa.AddLocalReference<jobject>(receiver);
943
944  // Placing arguments into args vector and remove the receiver.
945  ArtMethod* non_proxy_method = proxy_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
946  CHECK(!non_proxy_method->IsStatic()) << proxy_method->PrettyMethod() << " "
947                                       << non_proxy_method->PrettyMethod();
948  std::vector<jvalue> args;
949  uint32_t shorty_len = 0;
950  const char* shorty = non_proxy_method->GetShorty(&shorty_len);
951  BuildQuickArgumentVisitor local_ref_visitor(sp, false, shorty, shorty_len, &soa, &args);
952
953  local_ref_visitor.VisitArguments();
954  DCHECK_GT(args.size(), 0U) << proxy_method->PrettyMethod();
955  args.erase(args.begin());
956
957  // Convert proxy method into expected interface method.
958  ArtMethod* interface_method = proxy_method->FindOverriddenMethod(kRuntimePointerSize);
959  DCHECK(interface_method != nullptr) << proxy_method->PrettyMethod();
960  DCHECK(!interface_method->IsProxyMethod()) << interface_method->PrettyMethod();
961  self->EndAssertNoThreadSuspension(old_cause);
962  DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
963  DCHECK(!Runtime::Current()->IsActiveTransaction());
964  jobject interface_method_jobj = soa.AddLocalReference<jobject>(
965      mirror::Method::CreateFromArtMethod<kRuntimePointerSize, false>(soa.Self(),
966                                                                      interface_method));
967
968  // All naked Object*s should now be in jobjects, so its safe to go into the main invoke code
969  // that performs allocations.
970  JValue result = InvokeProxyInvocationHandler(soa, shorty, rcvr_jobj, interface_method_jobj, args);
971  // Restore references which might have moved.
972  local_ref_visitor.FixupReferences();
973  return result.GetJ();
974}
975
976// Read object references held in arguments from quick frames and place in a JNI local references,
977// so they don't get garbage collected.
978class RememberForGcArgumentVisitor FINAL : public QuickArgumentVisitor {
979 public:
980  RememberForGcArgumentVisitor(ArtMethod** sp, bool is_static, const char* shorty,
981                               uint32_t shorty_len, ScopedObjectAccessUnchecked* soa) :
982      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa) {}
983
984  void Visit() REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE;
985
986  void FixupReferences() REQUIRES_SHARED(Locks::mutator_lock_);
987
988 private:
989  ScopedObjectAccessUnchecked* const soa_;
990  // References which we must update when exiting in case the GC moved the objects.
991  std::vector<std::pair<jobject, StackReference<mirror::Object>*> > references_;
992
993  DISALLOW_COPY_AND_ASSIGN(RememberForGcArgumentVisitor);
994};
995
996void RememberForGcArgumentVisitor::Visit() {
997  if (IsParamAReference()) {
998    StackReference<mirror::Object>* stack_ref =
999        reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
1000    jobject reference =
1001        soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
1002    references_.push_back(std::make_pair(reference, stack_ref));
1003  }
1004}
1005
1006void RememberForGcArgumentVisitor::FixupReferences() {
1007  // Fixup any references which may have changed.
1008  for (const auto& pair : references_) {
1009    pair.second->Assign(soa_->Decode<mirror::Object>(pair.first));
1010    soa_->Env()->DeleteLocalRef(pair.first);
1011  }
1012}
1013
1014extern "C" const void* artInstrumentationMethodEntryFromCode(ArtMethod* method,
1015                                                             mirror::Object* this_object,
1016                                                             Thread* self,
1017                                                             ArtMethod** sp)
1018    REQUIRES_SHARED(Locks::mutator_lock_) {
1019  const void* result;
1020  // Instrumentation changes the stack. Thus, when exiting, the stack cannot be verified, so skip
1021  // that part.
1022  ScopedQuickEntrypointChecks sqec(self, kIsDebugBuild, false);
1023  instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1024  if (instrumentation->IsDeoptimized(method)) {
1025    result = GetQuickToInterpreterBridge();
1026  } else {
1027    result = instrumentation->GetQuickCodeFor(method, kRuntimePointerSize);
1028    DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(result));
1029  }
1030
1031  bool interpreter_entry = (result == GetQuickToInterpreterBridge());
1032  bool is_static = method->IsStatic();
1033  uint32_t shorty_len;
1034  const char* shorty =
1035      method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(&shorty_len);
1036
1037  ScopedObjectAccessUnchecked soa(self);
1038  RememberForGcArgumentVisitor visitor(sp, is_static, shorty, shorty_len, &soa);
1039  visitor.VisitArguments();
1040
1041  instrumentation->PushInstrumentationStackFrame(self,
1042                                                 is_static ? nullptr : this_object,
1043                                                 method,
1044                                                 QuickArgumentVisitor::GetCallingPc(sp),
1045                                                 interpreter_entry);
1046
1047  visitor.FixupReferences();
1048  if (UNLIKELY(self->IsExceptionPending())) {
1049    return nullptr;
1050  }
1051  CHECK(result != nullptr) << method->PrettyMethod();
1052  return result;
1053}
1054
1055extern "C" TwoWordReturn artInstrumentationMethodExitFromCode(Thread* self,
1056                                                              ArtMethod** sp,
1057                                                              uint64_t* gpr_result,
1058                                                              uint64_t* fpr_result)
1059    REQUIRES_SHARED(Locks::mutator_lock_) {
1060  DCHECK_EQ(reinterpret_cast<uintptr_t>(self), reinterpret_cast<uintptr_t>(Thread::Current()));
1061  CHECK(gpr_result != nullptr);
1062  CHECK(fpr_result != nullptr);
1063  // Instrumentation exit stub must not be entered with a pending exception.
1064  CHECK(!self->IsExceptionPending()) << "Enter instrumentation exit stub with pending exception "
1065                                     << self->GetException()->Dump();
1066  // Compute address of return PC and sanity check that it currently holds 0.
1067  size_t return_pc_offset = GetCalleeSaveReturnPcOffset(kRuntimeISA,
1068                                                        CalleeSaveType::kSaveEverything);
1069  uintptr_t* return_pc = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(sp) +
1070                                                      return_pc_offset);
1071  CHECK_EQ(*return_pc, 0U);
1072
1073  // Pop the frame filling in the return pc. The low half of the return value is 0 when
1074  // deoptimization shouldn't be performed with the high-half having the return address. When
1075  // deoptimization should be performed the low half is zero and the high-half the address of the
1076  // deoptimization entry point.
1077  instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1078  TwoWordReturn return_or_deoptimize_pc = instrumentation->PopInstrumentationStackFrame(
1079      self, return_pc, gpr_result, fpr_result);
1080  if (self->IsExceptionPending()) {
1081    return GetTwoWordFailureValue();
1082  }
1083  return return_or_deoptimize_pc;
1084}
1085
1086// Lazily resolve a method for quick. Called by stub code.
1087extern "C" const void* artQuickResolutionTrampoline(
1088    ArtMethod* called, mirror::Object* receiver, Thread* self, ArtMethod** sp)
1089    REQUIRES_SHARED(Locks::mutator_lock_) {
1090  // The resolution trampoline stashes the resolved method into the callee-save frame to transport
1091  // it. Thus, when exiting, the stack cannot be verified (as the resolved method most likely
1092  // does not have the same stack layout as the callee-save method).
1093  ScopedQuickEntrypointChecks sqec(self, kIsDebugBuild, false);
1094  // Start new JNI local reference state
1095  JNIEnvExt* env = self->GetJniEnv();
1096  ScopedObjectAccessUnchecked soa(env);
1097  ScopedJniEnvLocalRefState env_state(env);
1098  const char* old_cause = self->StartAssertNoThreadSuspension("Quick method resolution set up");
1099
1100  // Compute details about the called method (avoid GCs)
1101  ClassLinker* linker = Runtime::Current()->GetClassLinker();
1102  InvokeType invoke_type;
1103  MethodReference called_method(nullptr, 0);
1104  const bool called_method_known_on_entry = !called->IsRuntimeMethod();
1105  ArtMethod* caller = nullptr;
1106  if (!called_method_known_on_entry) {
1107    caller = QuickArgumentVisitor::GetCallingMethod(sp);
1108    called_method.dex_file = caller->GetDexFile();
1109
1110    InvokeType stack_map_invoke_type;
1111    uint32_t stack_map_dex_method_idx;
1112    const bool found_stack_map = QuickArgumentVisitor::GetInvokeType(sp,
1113                                                                     &stack_map_invoke_type,
1114                                                                     &stack_map_dex_method_idx);
1115    // For debug builds, we make sure both of the paths are consistent by also looking at the dex
1116    // code.
1117    if (!found_stack_map || kIsDebugBuild) {
1118      uint32_t dex_pc = QuickArgumentVisitor::GetCallingDexPc(sp);
1119      const DexFile::CodeItem* code;
1120      code = caller->GetCodeItem();
1121      CHECK_LT(dex_pc, code->insns_size_in_code_units_);
1122      const Instruction& instr = code->InstructionAt(dex_pc);
1123      Instruction::Code instr_code = instr.Opcode();
1124      bool is_range;
1125      switch (instr_code) {
1126        case Instruction::INVOKE_DIRECT:
1127          invoke_type = kDirect;
1128          is_range = false;
1129          break;
1130        case Instruction::INVOKE_DIRECT_RANGE:
1131          invoke_type = kDirect;
1132          is_range = true;
1133          break;
1134        case Instruction::INVOKE_STATIC:
1135          invoke_type = kStatic;
1136          is_range = false;
1137          break;
1138        case Instruction::INVOKE_STATIC_RANGE:
1139          invoke_type = kStatic;
1140          is_range = true;
1141          break;
1142        case Instruction::INVOKE_SUPER:
1143          invoke_type = kSuper;
1144          is_range = false;
1145          break;
1146        case Instruction::INVOKE_SUPER_RANGE:
1147          invoke_type = kSuper;
1148          is_range = true;
1149          break;
1150        case Instruction::INVOKE_VIRTUAL:
1151          invoke_type = kVirtual;
1152          is_range = false;
1153          break;
1154        case Instruction::INVOKE_VIRTUAL_RANGE:
1155          invoke_type = kVirtual;
1156          is_range = true;
1157          break;
1158        case Instruction::INVOKE_INTERFACE:
1159          invoke_type = kInterface;
1160          is_range = false;
1161          break;
1162        case Instruction::INVOKE_INTERFACE_RANGE:
1163          invoke_type = kInterface;
1164          is_range = true;
1165          break;
1166        default:
1167          LOG(FATAL) << "Unexpected call into trampoline: " << instr.DumpString(nullptr);
1168          UNREACHABLE();
1169      }
1170      called_method.index = (is_range) ? instr.VRegB_3rc() : instr.VRegB_35c();
1171      // Check that the invoke matches what we expected, note that this path only happens for debug
1172      // builds.
1173      if (found_stack_map) {
1174        DCHECK_EQ(stack_map_invoke_type, invoke_type);
1175        if (invoke_type != kSuper) {
1176          // Super may be sharpened.
1177          DCHECK_EQ(stack_map_dex_method_idx, called_method.index)
1178              << called_method.dex_file->PrettyMethod(stack_map_dex_method_idx) << " "
1179              << called_method.PrettyMethod();
1180        }
1181      } else {
1182        VLOG(dex) << "Accessed dex file for invoke " << invoke_type << " "
1183                  << called_method.index;
1184      }
1185    } else {
1186      invoke_type = stack_map_invoke_type;
1187      called_method.index = stack_map_dex_method_idx;
1188    }
1189  } else {
1190    invoke_type = kStatic;
1191    called_method.dex_file = called->GetDexFile();
1192    called_method.index = called->GetDexMethodIndex();
1193  }
1194  uint32_t shorty_len;
1195  const char* shorty =
1196      called_method.dex_file->GetMethodShorty(called_method.GetMethodId(), &shorty_len);
1197  RememberForGcArgumentVisitor visitor(sp, invoke_type == kStatic, shorty, shorty_len, &soa);
1198  visitor.VisitArguments();
1199  self->EndAssertNoThreadSuspension(old_cause);
1200  const bool virtual_or_interface = invoke_type == kVirtual || invoke_type == kInterface;
1201  // Resolve method filling in dex cache.
1202  if (!called_method_known_on_entry) {
1203    StackHandleScope<1> hs(self);
1204    mirror::Object* dummy = nullptr;
1205    HandleWrapper<mirror::Object> h_receiver(
1206        hs.NewHandleWrapper(virtual_or_interface ? &receiver : &dummy));
1207    DCHECK_EQ(caller->GetDexFile(), called_method.dex_file);
1208    called = linker->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
1209        self, called_method.index, caller, invoke_type);
1210
1211    // Update .bss entry in oat file if any.
1212    if (called != nullptr && called_method.dex_file->GetOatDexFile() != nullptr) {
1213      const MethodBssMapping* mapping =
1214          called_method.dex_file->GetOatDexFile()->GetMethodBssMapping();
1215      if (mapping != nullptr) {
1216        auto pp = std::partition_point(
1217            mapping->begin(),
1218            mapping->end(),
1219            [called_method](const MethodBssMappingEntry& entry) {
1220              return entry.method_index < called_method.index;
1221            });
1222        if (pp != mapping->end() && pp->CoversIndex(called_method.index)) {
1223          size_t bss_offset = pp->GetBssOffset(called_method.index,
1224                                               static_cast<size_t>(kRuntimePointerSize));
1225          DCHECK_ALIGNED(bss_offset, static_cast<size_t>(kRuntimePointerSize));
1226          const OatFile* oat_file = called_method.dex_file->GetOatDexFile()->GetOatFile();
1227          ArtMethod** method_entry = reinterpret_cast<ArtMethod**>(const_cast<uint8_t*>(
1228              oat_file->BssBegin() + bss_offset));
1229          DCHECK_GE(method_entry, oat_file->GetBssMethods().data());
1230          DCHECK_LT(method_entry,
1231                    oat_file->GetBssMethods().data() + oat_file->GetBssMethods().size());
1232          *method_entry = called;
1233        }
1234      }
1235    }
1236  }
1237  const void* code = nullptr;
1238  if (LIKELY(!self->IsExceptionPending())) {
1239    // Incompatible class change should have been handled in resolve method.
1240    CHECK(!called->CheckIncompatibleClassChange(invoke_type))
1241        << called->PrettyMethod() << " " << invoke_type;
1242    if (virtual_or_interface || invoke_type == kSuper) {
1243      // Refine called method based on receiver for kVirtual/kInterface, and
1244      // caller for kSuper.
1245      ArtMethod* orig_called = called;
1246      if (invoke_type == kVirtual) {
1247        CHECK(receiver != nullptr) << invoke_type;
1248        called = receiver->GetClass()->FindVirtualMethodForVirtual(called, kRuntimePointerSize);
1249      } else if (invoke_type == kInterface) {
1250        CHECK(receiver != nullptr) << invoke_type;
1251        called = receiver->GetClass()->FindVirtualMethodForInterface(called, kRuntimePointerSize);
1252      } else {
1253        DCHECK_EQ(invoke_type, kSuper);
1254        CHECK(caller != nullptr) << invoke_type;
1255        StackHandleScope<2> hs(self);
1256        Handle<mirror::DexCache> dex_cache(
1257            hs.NewHandle(caller->GetDeclaringClass()->GetDexCache()));
1258        Handle<mirror::ClassLoader> class_loader(
1259            hs.NewHandle(caller->GetDeclaringClass()->GetClassLoader()));
1260        // TODO Maybe put this into a mirror::Class function.
1261        ObjPtr<mirror::Class> ref_class = linker->LookupResolvedType(
1262            *dex_cache->GetDexFile(),
1263            dex_cache->GetDexFile()->GetMethodId(called_method.index).class_idx_,
1264            dex_cache.Get(),
1265            class_loader.Get());
1266        if (ref_class->IsInterface()) {
1267          called = ref_class->FindVirtualMethodForInterfaceSuper(called, kRuntimePointerSize);
1268        } else {
1269          called = caller->GetDeclaringClass()->GetSuperClass()->GetVTableEntry(
1270              called->GetMethodIndex(), kRuntimePointerSize);
1271        }
1272      }
1273
1274      CHECK(called != nullptr) << orig_called->PrettyMethod() << " "
1275                               << mirror::Object::PrettyTypeOf(receiver) << " "
1276                               << invoke_type << " " << orig_called->GetVtableIndex();
1277    }
1278
1279    // Ensure that the called method's class is initialized.
1280    StackHandleScope<1> hs(soa.Self());
1281    Handle<mirror::Class> called_class(hs.NewHandle(called->GetDeclaringClass()));
1282    linker->EnsureInitialized(soa.Self(), called_class, true, true);
1283    if (LIKELY(called_class->IsInitialized())) {
1284      if (UNLIKELY(Dbg::IsForcedInterpreterNeededForResolution(self, called))) {
1285        // If we are single-stepping or the called method is deoptimized (by a
1286        // breakpoint, for example), then we have to execute the called method
1287        // with the interpreter.
1288        code = GetQuickToInterpreterBridge();
1289      } else if (UNLIKELY(Dbg::IsForcedInstrumentationNeededForResolution(self, caller))) {
1290        // If the caller is deoptimized (by a breakpoint, for example), we have to
1291        // continue its execution with interpreter when returning from the called
1292        // method. Because we do not want to execute the called method with the
1293        // interpreter, we wrap its execution into the instrumentation stubs.
1294        // When the called method returns, it will execute the instrumentation
1295        // exit hook that will determine the need of the interpreter with a call
1296        // to Dbg::IsForcedInterpreterNeededForUpcall and deoptimize the stack if
1297        // it is needed.
1298        code = GetQuickInstrumentationEntryPoint();
1299      } else {
1300        code = called->GetEntryPointFromQuickCompiledCode();
1301      }
1302    } else if (called_class->IsInitializing()) {
1303      if (UNLIKELY(Dbg::IsForcedInterpreterNeededForResolution(self, called))) {
1304        // If we are single-stepping or the called method is deoptimized (by a
1305        // breakpoint, for example), then we have to execute the called method
1306        // with the interpreter.
1307        code = GetQuickToInterpreterBridge();
1308      } else if (invoke_type == kStatic) {
1309        // Class is still initializing, go to oat and grab code (trampoline must be left in place
1310        // until class is initialized to stop races between threads).
1311        code = linker->GetQuickOatCodeFor(called);
1312      } else {
1313        // No trampoline for non-static methods.
1314        code = called->GetEntryPointFromQuickCompiledCode();
1315      }
1316    } else {
1317      DCHECK(called_class->IsErroneous());
1318    }
1319  }
1320  CHECK_EQ(code == nullptr, self->IsExceptionPending());
1321  // Fixup any locally saved objects may have moved during a GC.
1322  visitor.FixupReferences();
1323  // Place called method in callee-save frame to be placed as first argument to quick method.
1324  *sp = called;
1325
1326  return code;
1327}
1328
1329/*
1330 * This class uses a couple of observations to unite the different calling conventions through
1331 * a few constants.
1332 *
1333 * 1) Number of registers used for passing is normally even, so counting down has no penalty for
1334 *    possible alignment.
1335 * 2) Known 64b architectures store 8B units on the stack, both for integral and floating point
1336 *    types, so using uintptr_t is OK. Also means that we can use kRegistersNeededX to denote
1337 *    when we have to split things
1338 * 3) The only soft-float, Arm, is 32b, so no widening needs to be taken into account for floats
1339 *    and we can use Int handling directly.
1340 * 4) Only 64b architectures widen, and their stack is aligned 8B anyways, so no padding code
1341 *    necessary when widening. Also, widening of Ints will take place implicitly, and the
1342 *    extension should be compatible with Aarch64, which mandates copying the available bits
1343 *    into LSB and leaving the rest unspecified.
1344 * 5) Aligning longs and doubles is necessary on arm only, and it's the same in registers and on
1345 *    the stack.
1346 * 6) There is only little endian.
1347 *
1348 *
1349 * Actual work is supposed to be done in a delegate of the template type. The interface is as
1350 * follows:
1351 *
1352 * void PushGpr(uintptr_t):   Add a value for the next GPR
1353 *
1354 * void PushFpr4(float):      Add a value for the next FPR of size 32b. Is only called if we need
1355 *                            padding, that is, think the architecture is 32b and aligns 64b.
1356 *
1357 * void PushFpr8(uint64_t):   Push a double. We _will_ call this on 32b, it's the callee's job to
1358 *                            split this if necessary. The current state will have aligned, if
1359 *                            necessary.
1360 *
1361 * void PushStack(uintptr_t): Push a value to the stack.
1362 *
1363 * uintptr_t PushHandleScope(mirror::Object* ref): Add a reference to the HandleScope. This _will_ have nullptr,
1364 *                                          as this might be important for null initialization.
1365 *                                          Must return the jobject, that is, the reference to the
1366 *                                          entry in the HandleScope (nullptr if necessary).
1367 *
1368 */
1369template<class T> class BuildNativeCallFrameStateMachine {
1370 public:
1371#if defined(__arm__)
1372  // TODO: These are all dummy values!
1373  static constexpr bool kNativeSoftFloatAbi = true;
1374  static constexpr size_t kNumNativeGprArgs = 4;  // 4 arguments passed in GPRs, r0-r3
1375  static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
1376
1377  static constexpr size_t kRegistersNeededForLong = 2;
1378  static constexpr size_t kRegistersNeededForDouble = 2;
1379  static constexpr bool kMultiRegistersAligned = true;
1380  static constexpr bool kMultiFPRegistersWidened = false;
1381  static constexpr bool kMultiGPRegistersWidened = false;
1382  static constexpr bool kAlignLongOnStack = true;
1383  static constexpr bool kAlignDoubleOnStack = true;
1384#elif defined(__aarch64__)
1385  static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
1386  static constexpr size_t kNumNativeGprArgs = 8;  // 6 arguments passed in GPRs.
1387  static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
1388
1389  static constexpr size_t kRegistersNeededForLong = 1;
1390  static constexpr size_t kRegistersNeededForDouble = 1;
1391  static constexpr bool kMultiRegistersAligned = false;
1392  static constexpr bool kMultiFPRegistersWidened = false;
1393  static constexpr bool kMultiGPRegistersWidened = false;
1394  static constexpr bool kAlignLongOnStack = false;
1395  static constexpr bool kAlignDoubleOnStack = false;
1396#elif defined(__mips__) && !defined(__LP64__)
1397  static constexpr bool kNativeSoftFloatAbi = true;  // This is a hard float ABI.
1398  static constexpr size_t kNumNativeGprArgs = 4;  // 4 arguments passed in GPRs.
1399  static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
1400
1401  static constexpr size_t kRegistersNeededForLong = 2;
1402  static constexpr size_t kRegistersNeededForDouble = 2;
1403  static constexpr bool kMultiRegistersAligned = true;
1404  static constexpr bool kMultiFPRegistersWidened = true;
1405  static constexpr bool kMultiGPRegistersWidened = false;
1406  static constexpr bool kAlignLongOnStack = true;
1407  static constexpr bool kAlignDoubleOnStack = true;
1408#elif defined(__mips__) && defined(__LP64__)
1409  // Let the code prepare GPRs only and we will load the FPRs with same data.
1410  static constexpr bool kNativeSoftFloatAbi = true;
1411  static constexpr size_t kNumNativeGprArgs = 8;
1412  static constexpr size_t kNumNativeFprArgs = 0;
1413
1414  static constexpr size_t kRegistersNeededForLong = 1;
1415  static constexpr size_t kRegistersNeededForDouble = 1;
1416  static constexpr bool kMultiRegistersAligned = false;
1417  static constexpr bool kMultiFPRegistersWidened = false;
1418  static constexpr bool kMultiGPRegistersWidened = true;
1419  static constexpr bool kAlignLongOnStack = false;
1420  static constexpr bool kAlignDoubleOnStack = false;
1421#elif defined(__i386__)
1422  // TODO: Check these!
1423  static constexpr bool kNativeSoftFloatAbi = false;  // Not using int registers for fp
1424  static constexpr size_t kNumNativeGprArgs = 0;  // 6 arguments passed in GPRs.
1425  static constexpr size_t kNumNativeFprArgs = 0;  // 8 arguments passed in FPRs.
1426
1427  static constexpr size_t kRegistersNeededForLong = 2;
1428  static constexpr size_t kRegistersNeededForDouble = 2;
1429  static constexpr bool kMultiRegistersAligned = false;  // x86 not using regs, anyways
1430  static constexpr bool kMultiFPRegistersWidened = false;
1431  static constexpr bool kMultiGPRegistersWidened = false;
1432  static constexpr bool kAlignLongOnStack = false;
1433  static constexpr bool kAlignDoubleOnStack = false;
1434#elif defined(__x86_64__)
1435  static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
1436  static constexpr size_t kNumNativeGprArgs = 6;  // 6 arguments passed in GPRs.
1437  static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
1438
1439  static constexpr size_t kRegistersNeededForLong = 1;
1440  static constexpr size_t kRegistersNeededForDouble = 1;
1441  static constexpr bool kMultiRegistersAligned = false;
1442  static constexpr bool kMultiFPRegistersWidened = false;
1443  static constexpr bool kMultiGPRegistersWidened = false;
1444  static constexpr bool kAlignLongOnStack = false;
1445  static constexpr bool kAlignDoubleOnStack = false;
1446#else
1447#error "Unsupported architecture"
1448#endif
1449
1450 public:
1451  explicit BuildNativeCallFrameStateMachine(T* delegate)
1452      : gpr_index_(kNumNativeGprArgs),
1453        fpr_index_(kNumNativeFprArgs),
1454        stack_entries_(0),
1455        delegate_(delegate) {
1456    // For register alignment, we want to assume that counters (gpr_index_, fpr_index_) are even iff
1457    // the next register is even; counting down is just to make the compiler happy...
1458    static_assert(kNumNativeGprArgs % 2 == 0U, "Number of native GPR arguments not even");
1459    static_assert(kNumNativeFprArgs % 2 == 0U, "Number of native FPR arguments not even");
1460  }
1461
1462  virtual ~BuildNativeCallFrameStateMachine() {}
1463
1464  bool HavePointerGpr() const {
1465    return gpr_index_ > 0;
1466  }
1467
1468  void AdvancePointer(const void* val) {
1469    if (HavePointerGpr()) {
1470      gpr_index_--;
1471      PushGpr(reinterpret_cast<uintptr_t>(val));
1472    } else {
1473      stack_entries_++;  // TODO: have a field for pointer length as multiple of 32b
1474      PushStack(reinterpret_cast<uintptr_t>(val));
1475      gpr_index_ = 0;
1476    }
1477  }
1478
1479  bool HaveHandleScopeGpr() const {
1480    return gpr_index_ > 0;
1481  }
1482
1483  void AdvanceHandleScope(mirror::Object* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
1484    uintptr_t handle = PushHandle(ptr);
1485    if (HaveHandleScopeGpr()) {
1486      gpr_index_--;
1487      PushGpr(handle);
1488    } else {
1489      stack_entries_++;
1490      PushStack(handle);
1491      gpr_index_ = 0;
1492    }
1493  }
1494
1495  bool HaveIntGpr() const {
1496    return gpr_index_ > 0;
1497  }
1498
1499  void AdvanceInt(uint32_t val) {
1500    if (HaveIntGpr()) {
1501      gpr_index_--;
1502      if (kMultiGPRegistersWidened) {
1503        DCHECK_EQ(sizeof(uintptr_t), sizeof(int64_t));
1504        PushGpr(static_cast<int64_t>(bit_cast<int32_t, uint32_t>(val)));
1505      } else {
1506        PushGpr(val);
1507      }
1508    } else {
1509      stack_entries_++;
1510      if (kMultiGPRegistersWidened) {
1511        DCHECK_EQ(sizeof(uintptr_t), sizeof(int64_t));
1512        PushStack(static_cast<int64_t>(bit_cast<int32_t, uint32_t>(val)));
1513      } else {
1514        PushStack(val);
1515      }
1516      gpr_index_ = 0;
1517    }
1518  }
1519
1520  bool HaveLongGpr() const {
1521    return gpr_index_ >= kRegistersNeededForLong + (LongGprNeedsPadding() ? 1 : 0);
1522  }
1523
1524  bool LongGprNeedsPadding() const {
1525    return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1526        kAlignLongOnStack &&                  // and when it needs alignment
1527        (gpr_index_ & 1) == 1;                // counter is odd, see constructor
1528  }
1529
1530  bool LongStackNeedsPadding() const {
1531    return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1532        kAlignLongOnStack &&                  // and when it needs 8B alignment
1533        (stack_entries_ & 1) == 1;            // counter is odd
1534  }
1535
1536  void AdvanceLong(uint64_t val) {
1537    if (HaveLongGpr()) {
1538      if (LongGprNeedsPadding()) {
1539        PushGpr(0);
1540        gpr_index_--;
1541      }
1542      if (kRegistersNeededForLong == 1) {
1543        PushGpr(static_cast<uintptr_t>(val));
1544      } else {
1545        PushGpr(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1546        PushGpr(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1547      }
1548      gpr_index_ -= kRegistersNeededForLong;
1549    } else {
1550      if (LongStackNeedsPadding()) {
1551        PushStack(0);
1552        stack_entries_++;
1553      }
1554      if (kRegistersNeededForLong == 1) {
1555        PushStack(static_cast<uintptr_t>(val));
1556        stack_entries_++;
1557      } else {
1558        PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1559        PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1560        stack_entries_ += 2;
1561      }
1562      gpr_index_ = 0;
1563    }
1564  }
1565
1566  bool HaveFloatFpr() const {
1567    return fpr_index_ > 0;
1568  }
1569
1570  void AdvanceFloat(float val) {
1571    if (kNativeSoftFloatAbi) {
1572      AdvanceInt(bit_cast<uint32_t, float>(val));
1573    } else {
1574      if (HaveFloatFpr()) {
1575        fpr_index_--;
1576        if (kRegistersNeededForDouble == 1) {
1577          if (kMultiFPRegistersWidened) {
1578            PushFpr8(bit_cast<uint64_t, double>(val));
1579          } else {
1580            // No widening, just use the bits.
1581            PushFpr8(static_cast<uint64_t>(bit_cast<uint32_t, float>(val)));
1582          }
1583        } else {
1584          PushFpr4(val);
1585        }
1586      } else {
1587        stack_entries_++;
1588        if (kRegistersNeededForDouble == 1 && kMultiFPRegistersWidened) {
1589          // Need to widen before storing: Note the "double" in the template instantiation.
1590          // Note: We need to jump through those hoops to make the compiler happy.
1591          DCHECK_EQ(sizeof(uintptr_t), sizeof(uint64_t));
1592          PushStack(static_cast<uintptr_t>(bit_cast<uint64_t, double>(val)));
1593        } else {
1594          PushStack(static_cast<uintptr_t>(bit_cast<uint32_t, float>(val)));
1595        }
1596        fpr_index_ = 0;
1597      }
1598    }
1599  }
1600
1601  bool HaveDoubleFpr() const {
1602    return fpr_index_ >= kRegistersNeededForDouble + (DoubleFprNeedsPadding() ? 1 : 0);
1603  }
1604
1605  bool DoubleFprNeedsPadding() const {
1606    return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1607        kAlignDoubleOnStack &&                  // and when it needs alignment
1608        (fpr_index_ & 1) == 1;                  // counter is odd, see constructor
1609  }
1610
1611  bool DoubleStackNeedsPadding() const {
1612    return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1613        kAlignDoubleOnStack &&                  // and when it needs 8B alignment
1614        (stack_entries_ & 1) == 1;              // counter is odd
1615  }
1616
1617  void AdvanceDouble(uint64_t val) {
1618    if (kNativeSoftFloatAbi) {
1619      AdvanceLong(val);
1620    } else {
1621      if (HaveDoubleFpr()) {
1622        if (DoubleFprNeedsPadding()) {
1623          PushFpr4(0);
1624          fpr_index_--;
1625        }
1626        PushFpr8(val);
1627        fpr_index_ -= kRegistersNeededForDouble;
1628      } else {
1629        if (DoubleStackNeedsPadding()) {
1630          PushStack(0);
1631          stack_entries_++;
1632        }
1633        if (kRegistersNeededForDouble == 1) {
1634          PushStack(static_cast<uintptr_t>(val));
1635          stack_entries_++;
1636        } else {
1637          PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1638          PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1639          stack_entries_ += 2;
1640        }
1641        fpr_index_ = 0;
1642      }
1643    }
1644  }
1645
1646  uint32_t GetStackEntries() const {
1647    return stack_entries_;
1648  }
1649
1650  uint32_t GetNumberOfUsedGprs() const {
1651    return kNumNativeGprArgs - gpr_index_;
1652  }
1653
1654  uint32_t GetNumberOfUsedFprs() const {
1655    return kNumNativeFprArgs - fpr_index_;
1656  }
1657
1658 private:
1659  void PushGpr(uintptr_t val) {
1660    delegate_->PushGpr(val);
1661  }
1662  void PushFpr4(float val) {
1663    delegate_->PushFpr4(val);
1664  }
1665  void PushFpr8(uint64_t val) {
1666    delegate_->PushFpr8(val);
1667  }
1668  void PushStack(uintptr_t val) {
1669    delegate_->PushStack(val);
1670  }
1671  uintptr_t PushHandle(mirror::Object* ref) REQUIRES_SHARED(Locks::mutator_lock_) {
1672    return delegate_->PushHandle(ref);
1673  }
1674
1675  uint32_t gpr_index_;      // Number of free GPRs
1676  uint32_t fpr_index_;      // Number of free FPRs
1677  uint32_t stack_entries_;  // Stack entries are in multiples of 32b, as floats are usually not
1678                            // extended
1679  T* const delegate_;             // What Push implementation gets called
1680};
1681
1682// Computes the sizes of register stacks and call stack area. Handling of references can be extended
1683// in subclasses.
1684//
1685// To handle native pointers, use "L" in the shorty for an object reference, which simulates
1686// them with handles.
1687class ComputeNativeCallFrameSize {
1688 public:
1689  ComputeNativeCallFrameSize() : num_stack_entries_(0) {}
1690
1691  virtual ~ComputeNativeCallFrameSize() {}
1692
1693  uint32_t GetStackSize() const {
1694    return num_stack_entries_ * sizeof(uintptr_t);
1695  }
1696
1697  uint8_t* LayoutCallStack(uint8_t* sp8) const {
1698    sp8 -= GetStackSize();
1699    // Align by kStackAlignment.
1700    sp8 = reinterpret_cast<uint8_t*>(RoundDown(reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1701    return sp8;
1702  }
1703
1704  uint8_t* LayoutCallRegisterStacks(uint8_t* sp8, uintptr_t** start_gpr, uint32_t** start_fpr)
1705      const {
1706    // Assumption is OK right now, as we have soft-float arm
1707    size_t fregs = BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeFprArgs;
1708    sp8 -= fregs * sizeof(uintptr_t);
1709    *start_fpr = reinterpret_cast<uint32_t*>(sp8);
1710    size_t iregs = BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeGprArgs;
1711    sp8 -= iregs * sizeof(uintptr_t);
1712    *start_gpr = reinterpret_cast<uintptr_t*>(sp8);
1713    return sp8;
1714  }
1715
1716  uint8_t* LayoutNativeCall(uint8_t* sp8, uintptr_t** start_stack, uintptr_t** start_gpr,
1717                            uint32_t** start_fpr) const {
1718    // Native call stack.
1719    sp8 = LayoutCallStack(sp8);
1720    *start_stack = reinterpret_cast<uintptr_t*>(sp8);
1721
1722    // Put fprs and gprs below.
1723    sp8 = LayoutCallRegisterStacks(sp8, start_gpr, start_fpr);
1724
1725    // Return the new bottom.
1726    return sp8;
1727  }
1728
1729  virtual void WalkHeader(
1730      BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm ATTRIBUTE_UNUSED)
1731      REQUIRES_SHARED(Locks::mutator_lock_) {
1732  }
1733
1734  void Walk(const char* shorty, uint32_t shorty_len) REQUIRES_SHARED(Locks::mutator_lock_) {
1735    BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize> sm(this);
1736
1737    WalkHeader(&sm);
1738
1739    for (uint32_t i = 1; i < shorty_len; ++i) {
1740      Primitive::Type cur_type_ = Primitive::GetType(shorty[i]);
1741      switch (cur_type_) {
1742        case Primitive::kPrimNot:
1743          // TODO: fix abuse of mirror types.
1744          sm.AdvanceHandleScope(
1745              reinterpret_cast<mirror::Object*>(0x12345678));
1746          break;
1747
1748        case Primitive::kPrimBoolean:
1749        case Primitive::kPrimByte:
1750        case Primitive::kPrimChar:
1751        case Primitive::kPrimShort:
1752        case Primitive::kPrimInt:
1753          sm.AdvanceInt(0);
1754          break;
1755        case Primitive::kPrimFloat:
1756          sm.AdvanceFloat(0);
1757          break;
1758        case Primitive::kPrimDouble:
1759          sm.AdvanceDouble(0);
1760          break;
1761        case Primitive::kPrimLong:
1762          sm.AdvanceLong(0);
1763          break;
1764        default:
1765          LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty;
1766          UNREACHABLE();
1767      }
1768    }
1769
1770    num_stack_entries_ = sm.GetStackEntries();
1771  }
1772
1773  void PushGpr(uintptr_t /* val */) {
1774    // not optimizing registers, yet
1775  }
1776
1777  void PushFpr4(float /* val */) {
1778    // not optimizing registers, yet
1779  }
1780
1781  void PushFpr8(uint64_t /* val */) {
1782    // not optimizing registers, yet
1783  }
1784
1785  void PushStack(uintptr_t /* val */) {
1786    // counting is already done in the superclass
1787  }
1788
1789  virtual uintptr_t PushHandle(mirror::Object* /* ptr */) {
1790    return reinterpret_cast<uintptr_t>(nullptr);
1791  }
1792
1793 protected:
1794  uint32_t num_stack_entries_;
1795};
1796
1797class ComputeGenericJniFrameSize FINAL : public ComputeNativeCallFrameSize {
1798 public:
1799  explicit ComputeGenericJniFrameSize(bool critical_native)
1800    : num_handle_scope_references_(0), critical_native_(critical_native) {}
1801
1802  // Lays out the callee-save frame. Assumes that the incorrect frame corresponding to RefsAndArgs
1803  // is at *m = sp. Will update to point to the bottom of the save frame.
1804  //
1805  // Note: assumes ComputeAll() has been run before.
1806  void LayoutCalleeSaveFrame(Thread* self, ArtMethod*** m, void* sp, HandleScope** handle_scope)
1807      REQUIRES_SHARED(Locks::mutator_lock_) {
1808    ArtMethod* method = **m;
1809
1810    DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
1811
1812    uint8_t* sp8 = reinterpret_cast<uint8_t*>(sp);
1813
1814    // First, fix up the layout of the callee-save frame.
1815    // We have to squeeze in the HandleScope, and relocate the method pointer.
1816
1817    // "Free" the slot for the method.
1818    sp8 += sizeof(void*);  // In the callee-save frame we use a full pointer.
1819
1820    // Under the callee saves put handle scope and new method stack reference.
1821    size_t handle_scope_size = HandleScope::SizeOf(num_handle_scope_references_);
1822    size_t scope_and_method = handle_scope_size + sizeof(ArtMethod*);
1823
1824    sp8 -= scope_and_method;
1825    // Align by kStackAlignment.
1826    sp8 = reinterpret_cast<uint8_t*>(RoundDown(reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1827
1828    uint8_t* sp8_table = sp8 + sizeof(ArtMethod*);
1829    *handle_scope = HandleScope::Create(sp8_table, self->GetTopHandleScope(),
1830                                        num_handle_scope_references_);
1831
1832    // Add a slot for the method pointer, and fill it. Fix the pointer-pointer given to us.
1833    uint8_t* method_pointer = sp8;
1834    auto** new_method_ref = reinterpret_cast<ArtMethod**>(method_pointer);
1835    *new_method_ref = method;
1836    *m = new_method_ref;
1837  }
1838
1839  // Adds space for the cookie. Note: may leave stack unaligned.
1840  void LayoutCookie(uint8_t** sp) const {
1841    // Reference cookie and padding
1842    *sp -= 8;
1843  }
1844
1845  // Re-layout the callee-save frame (insert a handle-scope). Then add space for the cookie.
1846  // Returns the new bottom. Note: this may be unaligned.
1847  uint8_t* LayoutJNISaveFrame(Thread* self, ArtMethod*** m, void* sp, HandleScope** handle_scope)
1848      REQUIRES_SHARED(Locks::mutator_lock_) {
1849    // First, fix up the layout of the callee-save frame.
1850    // We have to squeeze in the HandleScope, and relocate the method pointer.
1851    LayoutCalleeSaveFrame(self, m, sp, handle_scope);
1852
1853    // The bottom of the callee-save frame is now where the method is, *m.
1854    uint8_t* sp8 = reinterpret_cast<uint8_t*>(*m);
1855
1856    // Add space for cookie.
1857    LayoutCookie(&sp8);
1858
1859    return sp8;
1860  }
1861
1862  // WARNING: After this, *sp won't be pointing to the method anymore!
1863  uint8_t* ComputeLayout(Thread* self, ArtMethod*** m, const char* shorty, uint32_t shorty_len,
1864                         HandleScope** handle_scope, uintptr_t** start_stack, uintptr_t** start_gpr,
1865                         uint32_t** start_fpr)
1866      REQUIRES_SHARED(Locks::mutator_lock_) {
1867    Walk(shorty, shorty_len);
1868
1869    // JNI part.
1870    uint8_t* sp8 = LayoutJNISaveFrame(self, m, reinterpret_cast<void*>(*m), handle_scope);
1871
1872    sp8 = LayoutNativeCall(sp8, start_stack, start_gpr, start_fpr);
1873
1874    // Return the new bottom.
1875    return sp8;
1876  }
1877
1878  uintptr_t PushHandle(mirror::Object* /* ptr */) OVERRIDE;
1879
1880  // Add JNIEnv* and jobj/jclass before the shorty-derived elements.
1881  void WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) OVERRIDE
1882      REQUIRES_SHARED(Locks::mutator_lock_);
1883
1884 private:
1885  uint32_t num_handle_scope_references_;
1886  const bool critical_native_;
1887};
1888
1889uintptr_t ComputeGenericJniFrameSize::PushHandle(mirror::Object* /* ptr */) {
1890  num_handle_scope_references_++;
1891  return reinterpret_cast<uintptr_t>(nullptr);
1892}
1893
1894void ComputeGenericJniFrameSize::WalkHeader(
1895    BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) {
1896  // First 2 parameters are always excluded for @CriticalNative.
1897  if (UNLIKELY(critical_native_)) {
1898    return;
1899  }
1900
1901  // JNIEnv
1902  sm->AdvancePointer(nullptr);
1903
1904  // Class object or this as first argument
1905  sm->AdvanceHandleScope(reinterpret_cast<mirror::Object*>(0x12345678));
1906}
1907
1908// Class to push values to three separate regions. Used to fill the native call part. Adheres to
1909// the template requirements of BuildGenericJniFrameStateMachine.
1910class FillNativeCall {
1911 public:
1912  FillNativeCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) :
1913      cur_gpr_reg_(gpr_regs), cur_fpr_reg_(fpr_regs), cur_stack_arg_(stack_args) {}
1914
1915  virtual ~FillNativeCall() {}
1916
1917  void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) {
1918    cur_gpr_reg_ = gpr_regs;
1919    cur_fpr_reg_ = fpr_regs;
1920    cur_stack_arg_ = stack_args;
1921  }
1922
1923  void PushGpr(uintptr_t val) {
1924    *cur_gpr_reg_ = val;
1925    cur_gpr_reg_++;
1926  }
1927
1928  void PushFpr4(float val) {
1929    *cur_fpr_reg_ = val;
1930    cur_fpr_reg_++;
1931  }
1932
1933  void PushFpr8(uint64_t val) {
1934    uint64_t* tmp = reinterpret_cast<uint64_t*>(cur_fpr_reg_);
1935    *tmp = val;
1936    cur_fpr_reg_ += 2;
1937  }
1938
1939  void PushStack(uintptr_t val) {
1940    *cur_stack_arg_ = val;
1941    cur_stack_arg_++;
1942  }
1943
1944  virtual uintptr_t PushHandle(mirror::Object*) REQUIRES_SHARED(Locks::mutator_lock_) {
1945    LOG(FATAL) << "(Non-JNI) Native call does not use handles.";
1946    UNREACHABLE();
1947  }
1948
1949 private:
1950  uintptr_t* cur_gpr_reg_;
1951  uint32_t* cur_fpr_reg_;
1952  uintptr_t* cur_stack_arg_;
1953};
1954
1955// Visits arguments on the stack placing them into a region lower down the stack for the benefit
1956// of transitioning into native code.
1957class BuildGenericJniFrameVisitor FINAL : public QuickArgumentVisitor {
1958 public:
1959  BuildGenericJniFrameVisitor(Thread* self,
1960                              bool is_static,
1961                              bool critical_native,
1962                              const char* shorty,
1963                              uint32_t shorty_len,
1964                              ArtMethod*** sp)
1965     : QuickArgumentVisitor(*sp, is_static, shorty, shorty_len),
1966       jni_call_(nullptr, nullptr, nullptr, nullptr, critical_native),
1967       sm_(&jni_call_) {
1968    ComputeGenericJniFrameSize fsc(critical_native);
1969    uintptr_t* start_gpr_reg;
1970    uint32_t* start_fpr_reg;
1971    uintptr_t* start_stack_arg;
1972    bottom_of_used_area_ = fsc.ComputeLayout(self, sp, shorty, shorty_len,
1973                                             &handle_scope_,
1974                                             &start_stack_arg,
1975                                             &start_gpr_reg, &start_fpr_reg);
1976
1977    jni_call_.Reset(start_gpr_reg, start_fpr_reg, start_stack_arg, handle_scope_);
1978
1979    // First 2 parameters are always excluded for CriticalNative methods.
1980    if (LIKELY(!critical_native)) {
1981      // jni environment is always first argument
1982      sm_.AdvancePointer(self->GetJniEnv());
1983
1984      if (is_static) {
1985        sm_.AdvanceHandleScope((**sp)->GetDeclaringClass());
1986      }  // else "this" reference is already handled by QuickArgumentVisitor.
1987    }
1988  }
1989
1990  void Visit() REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE;
1991
1992  void FinalizeHandleScope(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1993
1994  StackReference<mirror::Object>* GetFirstHandleScopeEntry() {
1995    return handle_scope_->GetHandle(0).GetReference();
1996  }
1997
1998  jobject GetFirstHandleScopeJObject() const REQUIRES_SHARED(Locks::mutator_lock_) {
1999    return handle_scope_->GetHandle(0).ToJObject();
2000  }
2001
2002  void* GetBottomOfUsedArea() const {
2003    return bottom_of_used_area_;
2004  }
2005
2006 private:
2007  // A class to fill a JNI call. Adds reference/handle-scope management to FillNativeCall.
2008  class FillJniCall FINAL : public FillNativeCall {
2009   public:
2010    FillJniCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args,
2011                HandleScope* handle_scope, bool critical_native)
2012      : FillNativeCall(gpr_regs, fpr_regs, stack_args),
2013                       handle_scope_(handle_scope),
2014        cur_entry_(0),
2015        critical_native_(critical_native) {}
2016
2017    uintptr_t PushHandle(mirror::Object* ref) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_);
2018
2019    void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args, HandleScope* scope) {
2020      FillNativeCall::Reset(gpr_regs, fpr_regs, stack_args);
2021      handle_scope_ = scope;
2022      cur_entry_ = 0U;
2023    }
2024
2025    void ResetRemainingScopeSlots() REQUIRES_SHARED(Locks::mutator_lock_) {
2026      // Initialize padding entries.
2027      size_t expected_slots = handle_scope_->NumberOfReferences();
2028      while (cur_entry_ < expected_slots) {
2029        handle_scope_->GetMutableHandle(cur_entry_++).Assign(nullptr);
2030      }
2031
2032      if (!critical_native_) {
2033        // Non-critical natives have at least the self class (jclass) or this (jobject).
2034        DCHECK_NE(cur_entry_, 0U);
2035      }
2036    }
2037
2038    bool CriticalNative() const {
2039      return critical_native_;
2040    }
2041
2042   private:
2043    HandleScope* handle_scope_;
2044    size_t cur_entry_;
2045    const bool critical_native_;
2046  };
2047
2048  HandleScope* handle_scope_;
2049  FillJniCall jni_call_;
2050  void* bottom_of_used_area_;
2051
2052  BuildNativeCallFrameStateMachine<FillJniCall> sm_;
2053
2054  DISALLOW_COPY_AND_ASSIGN(BuildGenericJniFrameVisitor);
2055};
2056
2057uintptr_t BuildGenericJniFrameVisitor::FillJniCall::PushHandle(mirror::Object* ref) {
2058  uintptr_t tmp;
2059  MutableHandle<mirror::Object> h = handle_scope_->GetMutableHandle(cur_entry_);
2060  h.Assign(ref);
2061  tmp = reinterpret_cast<uintptr_t>(h.ToJObject());
2062  cur_entry_++;
2063  return tmp;
2064}
2065
2066void BuildGenericJniFrameVisitor::Visit() {
2067  Primitive::Type type = GetParamPrimitiveType();
2068  switch (type) {
2069    case Primitive::kPrimLong: {
2070      jlong long_arg;
2071      if (IsSplitLongOrDouble()) {
2072        long_arg = ReadSplitLongParam();
2073      } else {
2074        long_arg = *reinterpret_cast<jlong*>(GetParamAddress());
2075      }
2076      sm_.AdvanceLong(long_arg);
2077      break;
2078    }
2079    case Primitive::kPrimDouble: {
2080      uint64_t double_arg;
2081      if (IsSplitLongOrDouble()) {
2082        // Read into union so that we don't case to a double.
2083        double_arg = ReadSplitLongParam();
2084      } else {
2085        double_arg = *reinterpret_cast<uint64_t*>(GetParamAddress());
2086      }
2087      sm_.AdvanceDouble(double_arg);
2088      break;
2089    }
2090    case Primitive::kPrimNot: {
2091      StackReference<mirror::Object>* stack_ref =
2092          reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
2093      sm_.AdvanceHandleScope(stack_ref->AsMirrorPtr());
2094      break;
2095    }
2096    case Primitive::kPrimFloat:
2097      sm_.AdvanceFloat(*reinterpret_cast<float*>(GetParamAddress()));
2098      break;
2099    case Primitive::kPrimBoolean:  // Fall-through.
2100    case Primitive::kPrimByte:     // Fall-through.
2101    case Primitive::kPrimChar:     // Fall-through.
2102    case Primitive::kPrimShort:    // Fall-through.
2103    case Primitive::kPrimInt:      // Fall-through.
2104      sm_.AdvanceInt(*reinterpret_cast<jint*>(GetParamAddress()));
2105      break;
2106    case Primitive::kPrimVoid:
2107      LOG(FATAL) << "UNREACHABLE";
2108      UNREACHABLE();
2109  }
2110}
2111
2112void BuildGenericJniFrameVisitor::FinalizeHandleScope(Thread* self) {
2113  // Clear out rest of the scope.
2114  jni_call_.ResetRemainingScopeSlots();
2115  if (!jni_call_.CriticalNative()) {
2116    // Install HandleScope.
2117    self->PushHandleScope(handle_scope_);
2118  }
2119}
2120
2121#if defined(__arm__) || defined(__aarch64__)
2122extern "C" const void* artFindNativeMethod();
2123#else
2124extern "C" const void* artFindNativeMethod(Thread* self);
2125#endif
2126
2127static uint64_t artQuickGenericJniEndJNIRef(Thread* self,
2128                                            uint32_t cookie,
2129                                            bool fast_native ATTRIBUTE_UNUSED,
2130                                            jobject l,
2131                                            jobject lock) {
2132  // TODO: add entrypoints for @FastNative returning objects.
2133  if (lock != nullptr) {
2134    return reinterpret_cast<uint64_t>(JniMethodEndWithReferenceSynchronized(l, cookie, lock, self));
2135  } else {
2136    return reinterpret_cast<uint64_t>(JniMethodEndWithReference(l, cookie, self));
2137  }
2138}
2139
2140static void artQuickGenericJniEndJNINonRef(Thread* self,
2141                                           uint32_t cookie,
2142                                           bool fast_native,
2143                                           jobject lock) {
2144  if (lock != nullptr) {
2145    JniMethodEndSynchronized(cookie, lock, self);
2146    // Ignore "fast_native" here because synchronized functions aren't very fast.
2147  } else {
2148    if (UNLIKELY(fast_native)) {
2149      JniMethodFastEnd(cookie, self);
2150    } else {
2151      JniMethodEnd(cookie, self);
2152    }
2153  }
2154}
2155
2156/*
2157 * Initializes an alloca region assumed to be directly below sp for a native call:
2158 * Create a HandleScope and call stack and fill a mini stack with values to be pushed to registers.
2159 * The final element on the stack is a pointer to the native code.
2160 *
2161 * On entry, the stack has a standard callee-save frame above sp, and an alloca below it.
2162 * We need to fix this, as the handle scope needs to go into the callee-save frame.
2163 *
2164 * The return of this function denotes:
2165 * 1) How many bytes of the alloca can be released, if the value is non-negative.
2166 * 2) An error, if the value is negative.
2167 */
2168extern "C" TwoWordReturn artQuickGenericJniTrampoline(Thread* self, ArtMethod** sp)
2169    REQUIRES_SHARED(Locks::mutator_lock_) {
2170  ArtMethod* called = *sp;
2171  DCHECK(called->IsNative()) << called->PrettyMethod(true);
2172  // Fix up a callee-save frame at the bottom of the stack (at `*sp`,
2173  // above the alloca region) while we check for optimization
2174  // annotations, thus allowing stack walking until the completion of
2175  // the JNI frame creation.
2176  //
2177  // Note however that the Generic JNI trampoline does not expect
2178  // exception being thrown at that stage.
2179  *sp = Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
2180  self->SetTopOfStack(sp);
2181  uint32_t shorty_len = 0;
2182  const char* shorty = called->GetShorty(&shorty_len);
2183  // Optimization annotations lookup does not try to resolve classes,
2184  // as this may throw an exception, which is not supported by the
2185  // Generic JNI trampoline at this stage; instead, method's
2186  // annotations' classes are looked up in the bootstrap class
2187  // loader's resolved types (which won't trigger an exception).
2188  CHECK(!self->IsExceptionPending());
2189  bool critical_native = called->IsAnnotatedWithCriticalNative();
2190  CHECK(!self->IsExceptionPending());
2191  bool fast_native = called->IsAnnotatedWithFastNative();
2192  CHECK(!self->IsExceptionPending());
2193  bool normal_native = !critical_native && !fast_native;
2194  // Restore the initial ArtMethod pointer at `*sp`.
2195  *sp = called;
2196
2197  // Run the visitor and update sp.
2198  BuildGenericJniFrameVisitor visitor(self,
2199                                      called->IsStatic(),
2200                                      critical_native,
2201                                      shorty,
2202                                      shorty_len,
2203                                      &sp);
2204  {
2205    ScopedAssertNoThreadSuspension sants(__FUNCTION__);
2206    visitor.VisitArguments();
2207    // FinalizeHandleScope pushes the handle scope on the thread.
2208    visitor.FinalizeHandleScope(self);
2209  }
2210
2211  // Fix up managed-stack things in Thread.
2212  self->SetTopOfStack(sp);
2213
2214  self->VerifyStack();
2215
2216  uint32_t cookie;
2217  uint32_t* sp32;
2218  // Skip calling JniMethodStart for @CriticalNative.
2219  if (LIKELY(!critical_native)) {
2220    // Start JNI, save the cookie.
2221    if (called->IsSynchronized()) {
2222      DCHECK(normal_native) << " @FastNative and synchronize is not supported";
2223      cookie = JniMethodStartSynchronized(visitor.GetFirstHandleScopeJObject(), self);
2224      if (self->IsExceptionPending()) {
2225        self->PopHandleScope();
2226        // A negative value denotes an error.
2227        return GetTwoWordFailureValue();
2228      }
2229    } else {
2230      if (fast_native) {
2231        cookie = JniMethodFastStart(self);
2232      } else {
2233        DCHECK(normal_native);
2234        cookie = JniMethodStart(self);
2235      }
2236    }
2237    sp32 = reinterpret_cast<uint32_t*>(sp);
2238    *(sp32 - 1) = cookie;
2239  }
2240
2241  // Retrieve the stored native code.
2242  void const* nativeCode = called->GetEntryPointFromJni();
2243
2244  // There are two cases for the content of nativeCode:
2245  // 1) Pointer to the native function.
2246  // 2) Pointer to the trampoline for native code binding.
2247  // In the second case, we need to execute the binding and continue with the actual native function
2248  // pointer.
2249  DCHECK(nativeCode != nullptr);
2250  if (nativeCode == GetJniDlsymLookupStub()) {
2251#if defined(__arm__) || defined(__aarch64__)
2252    nativeCode = artFindNativeMethod();
2253#else
2254    nativeCode = artFindNativeMethod(self);
2255#endif
2256
2257    if (nativeCode == nullptr) {
2258      DCHECK(self->IsExceptionPending());    // There should be an exception pending now.
2259
2260      // @CriticalNative calls do not need to call back into JniMethodEnd.
2261      if (LIKELY(!critical_native)) {
2262        // End JNI, as the assembly will move to deliver the exception.
2263        jobject lock = called->IsSynchronized() ? visitor.GetFirstHandleScopeJObject() : nullptr;
2264        if (shorty[0] == 'L') {
2265          artQuickGenericJniEndJNIRef(self, cookie, fast_native, nullptr, lock);
2266        } else {
2267          artQuickGenericJniEndJNINonRef(self, cookie, fast_native, lock);
2268        }
2269      }
2270
2271      return GetTwoWordFailureValue();
2272    }
2273    // Note that the native code pointer will be automatically set by artFindNativeMethod().
2274  }
2275
2276#if defined(__mips__) && !defined(__LP64__)
2277  // On MIPS32 if the first two arguments are floating-point, we need to know their types
2278  // so that art_quick_generic_jni_trampoline can correctly extract them from the stack
2279  // and load into floating-point registers.
2280  // Possible arrangements of first two floating-point arguments on the stack (32-bit FPU
2281  // view):
2282  // (1)
2283  //  |     DOUBLE    |     DOUBLE    | other args, if any
2284  //  |  F12  |  F13  |  F14  |  F15  |
2285  //  |  SP+0 |  SP+4 |  SP+8 | SP+12 | SP+16
2286  // (2)
2287  //  |     DOUBLE    | FLOAT | (PAD) | other args, if any
2288  //  |  F12  |  F13  |  F14  |       |
2289  //  |  SP+0 |  SP+4 |  SP+8 | SP+12 | SP+16
2290  // (3)
2291  //  | FLOAT | (PAD) |     DOUBLE    | other args, if any
2292  //  |  F12  |       |  F14  |  F15  |
2293  //  |  SP+0 |  SP+4 |  SP+8 | SP+12 | SP+16
2294  // (4)
2295  //  | FLOAT | FLOAT | other args, if any
2296  //  |  F12  |  F14  |
2297  //  |  SP+0 |  SP+4 | SP+8
2298  // As you can see, only the last case (4) is special. In all others we can just
2299  // load F12/F13 and F14/F15 in the same manner.
2300  // Set bit 0 of the native code address to 1 in this case (valid code addresses
2301  // are always a multiple of 4 on MIPS32, so we have 2 spare bits available).
2302  if (nativeCode != nullptr &&
2303      shorty != nullptr &&
2304      shorty_len >= 3 &&
2305      shorty[1] == 'F' &&
2306      shorty[2] == 'F') {
2307    nativeCode = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(nativeCode) | 1);
2308  }
2309#endif
2310
2311  // Return native code addr(lo) and bottom of alloca address(hi).
2312  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(visitor.GetBottomOfUsedArea()),
2313                                reinterpret_cast<uintptr_t>(nativeCode));
2314}
2315
2316// Defined in quick_jni_entrypoints.cc.
2317extern uint64_t GenericJniMethodEnd(Thread* self, uint32_t saved_local_ref_cookie,
2318                                    jvalue result, uint64_t result_f, ArtMethod* called,
2319                                    HandleScope* handle_scope);
2320/*
2321 * Is called after the native JNI code. Responsible for cleanup (handle scope, saved state) and
2322 * unlocking.
2323 */
2324extern "C" uint64_t artQuickGenericJniEndTrampoline(Thread* self,
2325                                                    jvalue result,
2326                                                    uint64_t result_f) {
2327  // We're here just back from a native call. We don't have the shared mutator lock at this point
2328  // yet until we call GoToRunnable() later in GenericJniMethodEnd(). Accessing objects or doing
2329  // anything that requires a mutator lock before that would cause problems as GC may have the
2330  // exclusive mutator lock and may be moving objects, etc.
2331  ArtMethod** sp = self->GetManagedStack()->GetTopQuickFrame();
2332  uint32_t* sp32 = reinterpret_cast<uint32_t*>(sp);
2333  ArtMethod* called = *sp;
2334  uint32_t cookie = *(sp32 - 1);
2335  HandleScope* table = reinterpret_cast<HandleScope*>(reinterpret_cast<uint8_t*>(sp) + sizeof(*sp));
2336  return GenericJniMethodEnd(self, cookie, result, result_f, called, table);
2337}
2338
2339// We use TwoWordReturn to optimize scalar returns. We use the hi value for code, and the lo value
2340// for the method pointer.
2341//
2342// It is valid to use this, as at the usage points here (returns from C functions) we are assuming
2343// to hold the mutator lock (see REQUIRES_SHARED(Locks::mutator_lock_) annotations).
2344
2345template <InvokeType type, bool access_check>
2346static TwoWordReturn artInvokeCommon(uint32_t method_idx,
2347                                     ObjPtr<mirror::Object> this_object,
2348                                     Thread* self,
2349                                     ArtMethod** sp) {
2350  ScopedQuickEntrypointChecks sqec(self);
2351  DCHECK_EQ(*sp, Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
2352  ArtMethod* caller_method = QuickArgumentVisitor::GetCallingMethod(sp);
2353  ArtMethod* method = FindMethodFast<type, access_check>(method_idx, this_object, caller_method);
2354  if (UNLIKELY(method == nullptr)) {
2355    const DexFile* dex_file = caller_method->GetDeclaringClass()->GetDexCache()->GetDexFile();
2356    uint32_t shorty_len;
2357    const char* shorty = dex_file->GetMethodShorty(dex_file->GetMethodId(method_idx), &shorty_len);
2358    {
2359      // Remember the args in case a GC happens in FindMethodFromCode.
2360      ScopedObjectAccessUnchecked soa(self->GetJniEnv());
2361      RememberForGcArgumentVisitor visitor(sp, type == kStatic, shorty, shorty_len, &soa);
2362      visitor.VisitArguments();
2363      method = FindMethodFromCode<type, access_check>(method_idx,
2364                                                      &this_object,
2365                                                      caller_method,
2366                                                      self);
2367      visitor.FixupReferences();
2368    }
2369
2370    if (UNLIKELY(method == nullptr)) {
2371      CHECK(self->IsExceptionPending());
2372      return GetTwoWordFailureValue();  // Failure.
2373    }
2374  }
2375  DCHECK(!self->IsExceptionPending());
2376  const void* code = method->GetEntryPointFromQuickCompiledCode();
2377
2378  // When we return, the caller will branch to this address, so it had better not be 0!
2379  DCHECK(code != nullptr) << "Code was null in method: " << method->PrettyMethod()
2380                          << " location: "
2381                          << method->GetDexFile()->GetLocation();
2382
2383  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(code),
2384                                reinterpret_cast<uintptr_t>(method));
2385}
2386
2387// Explicit artInvokeCommon template function declarations to please analysis tool.
2388#define EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(type, access_check)                                \
2389  template REQUIRES_SHARED(Locks::mutator_lock_)                                          \
2390  TwoWordReturn artInvokeCommon<type, access_check>(                                            \
2391      uint32_t method_idx, ObjPtr<mirror::Object> his_object, Thread* self, ArtMethod** sp)
2392
2393EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kVirtual, false);
2394EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kVirtual, true);
2395EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kInterface, false);
2396EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kInterface, true);
2397EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kDirect, false);
2398EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kDirect, true);
2399EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kStatic, false);
2400EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kStatic, true);
2401EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kSuper, false);
2402EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kSuper, true);
2403#undef EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL
2404
2405// See comments in runtime_support_asm.S
2406extern "C" TwoWordReturn artInvokeInterfaceTrampolineWithAccessCheck(
2407    uint32_t method_idx, mirror::Object* this_object, Thread* self, ArtMethod** sp)
2408    REQUIRES_SHARED(Locks::mutator_lock_) {
2409  return artInvokeCommon<kInterface, true>(method_idx, this_object, self, sp);
2410}
2411
2412extern "C" TwoWordReturn artInvokeDirectTrampolineWithAccessCheck(
2413    uint32_t method_idx, mirror::Object* this_object, Thread* self, ArtMethod** sp)
2414    REQUIRES_SHARED(Locks::mutator_lock_) {
2415  return artInvokeCommon<kDirect, true>(method_idx, this_object, self, sp);
2416}
2417
2418extern "C" TwoWordReturn artInvokeStaticTrampolineWithAccessCheck(
2419    uint32_t method_idx,
2420    mirror::Object* this_object ATTRIBUTE_UNUSED,
2421    Thread* self,
2422    ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
2423  // For static, this_object is not required and may be random garbage. Don't pass it down so that
2424  // it doesn't cause ObjPtr alignment failure check.
2425  return artInvokeCommon<kStatic, true>(method_idx, nullptr, self, sp);
2426}
2427
2428extern "C" TwoWordReturn artInvokeSuperTrampolineWithAccessCheck(
2429    uint32_t method_idx, mirror::Object* this_object, Thread* self, ArtMethod** sp)
2430    REQUIRES_SHARED(Locks::mutator_lock_) {
2431  return artInvokeCommon<kSuper, true>(method_idx, this_object, self, sp);
2432}
2433
2434extern "C" TwoWordReturn artInvokeVirtualTrampolineWithAccessCheck(
2435    uint32_t method_idx, mirror::Object* this_object, Thread* self, ArtMethod** sp)
2436    REQUIRES_SHARED(Locks::mutator_lock_) {
2437  return artInvokeCommon<kVirtual, true>(method_idx, this_object, self, sp);
2438}
2439
2440// Helper function for art_quick_imt_conflict_trampoline to look up the interface method.
2441extern "C" ArtMethod* artLookupResolvedMethod(uint32_t method_index, ArtMethod* referrer)
2442    REQUIRES_SHARED(Locks::mutator_lock_) {
2443  ScopedAssertNoThreadSuspension ants(__FUNCTION__);
2444  DCHECK(!referrer->IsProxyMethod());
2445  ArtMethod* result = Runtime::Current()->GetClassLinker()->LookupResolvedMethod(
2446      method_index, referrer->GetDexCache(), referrer->GetClassLoader());
2447  DCHECK(result == nullptr ||
2448         result->GetDeclaringClass()->IsInterface() ||
2449         result->GetDeclaringClass() ==
2450             WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object))
2451      << result->PrettyMethod();
2452  return result;
2453}
2454
2455// Determine target of interface dispatch. The interface method and this object are known non-null.
2456// The interface method is the method returned by the dex cache in the conflict trampoline.
2457extern "C" TwoWordReturn artInvokeInterfaceTrampoline(ArtMethod* interface_method,
2458                                                      mirror::Object* raw_this_object,
2459                                                      Thread* self,
2460                                                      ArtMethod** sp)
2461    REQUIRES_SHARED(Locks::mutator_lock_) {
2462  ScopedQuickEntrypointChecks sqec(self);
2463  StackHandleScope<2> hs(self);
2464  Handle<mirror::Object> this_object = hs.NewHandle(raw_this_object);
2465  Handle<mirror::Class> cls = hs.NewHandle(this_object->GetClass());
2466
2467  ArtMethod* caller_method = QuickArgumentVisitor::GetCallingMethod(sp);
2468  ArtMethod* method = nullptr;
2469  ImTable* imt = cls->GetImt(kRuntimePointerSize);
2470
2471  if (UNLIKELY(interface_method == nullptr)) {
2472    // The interface method is unresolved, so resolve it in the dex file of the caller.
2473    // Fetch the dex_method_idx of the target interface method from the caller.
2474    uint32_t dex_method_idx;
2475    uint32_t dex_pc = QuickArgumentVisitor::GetCallingDexPc(sp);
2476    const DexFile::CodeItem* code_item = caller_method->GetCodeItem();
2477    DCHECK_LT(dex_pc, code_item->insns_size_in_code_units_);
2478    const Instruction& instr = code_item->InstructionAt(dex_pc);
2479    Instruction::Code instr_code = instr.Opcode();
2480    DCHECK(instr_code == Instruction::INVOKE_INTERFACE ||
2481           instr_code == Instruction::INVOKE_INTERFACE_RANGE)
2482        << "Unexpected call into interface trampoline: " << instr.DumpString(nullptr);
2483    if (instr_code == Instruction::INVOKE_INTERFACE) {
2484      dex_method_idx = instr.VRegB_35c();
2485    } else {
2486      DCHECK_EQ(instr_code, Instruction::INVOKE_INTERFACE_RANGE);
2487      dex_method_idx = instr.VRegB_3rc();
2488    }
2489
2490    const DexFile& dex_file = caller_method->GetDeclaringClass()->GetDexFile();
2491    uint32_t shorty_len;
2492    const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(dex_method_idx),
2493                                                  &shorty_len);
2494    {
2495      // Remember the args in case a GC happens in ClassLinker::ResolveMethod().
2496      ScopedObjectAccessUnchecked soa(self->GetJniEnv());
2497      RememberForGcArgumentVisitor visitor(sp, false, shorty, shorty_len, &soa);
2498      visitor.VisitArguments();
2499      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2500      interface_method = class_linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
2501          self, dex_method_idx, caller_method, kInterface);
2502      visitor.FixupReferences();
2503    }
2504
2505    if (UNLIKELY(interface_method == nullptr)) {
2506      CHECK(self->IsExceptionPending());
2507      return GetTwoWordFailureValue();  // Failure.
2508    }
2509  }
2510
2511  DCHECK(!interface_method->IsRuntimeMethod());
2512  // Look whether we have a match in the ImtConflictTable.
2513  uint32_t imt_index = ImTable::GetImtIndex(interface_method);
2514  ArtMethod* conflict_method = imt->Get(imt_index, kRuntimePointerSize);
2515  if (LIKELY(conflict_method->IsRuntimeMethod())) {
2516    ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
2517    DCHECK(current_table != nullptr);
2518    method = current_table->Lookup(interface_method, kRuntimePointerSize);
2519  } else {
2520    // It seems we aren't really a conflict method!
2521    if (kIsDebugBuild) {
2522      ArtMethod* m = cls->FindVirtualMethodForInterface(interface_method, kRuntimePointerSize);
2523      CHECK_EQ(conflict_method, m)
2524          << interface_method->PrettyMethod() << " / " << conflict_method->PrettyMethod() << " / "
2525          << " / " << ArtMethod::PrettyMethod(m) << " / " << cls->PrettyClass();
2526    }
2527    method = conflict_method;
2528  }
2529  if (method != nullptr) {
2530    return GetTwoWordSuccessValue(
2531        reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCode()),
2532        reinterpret_cast<uintptr_t>(method));
2533  }
2534
2535  // No match, use the IfTable.
2536  method = cls->FindVirtualMethodForInterface(interface_method, kRuntimePointerSize);
2537  if (UNLIKELY(method == nullptr)) {
2538    ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(
2539        interface_method, this_object.Get(), caller_method);
2540    return GetTwoWordFailureValue();  // Failure.
2541  }
2542
2543  // We arrive here if we have found an implementation, and it is not in the ImtConflictTable.
2544  // We create a new table with the new pair { interface_method, method }.
2545  DCHECK(conflict_method->IsRuntimeMethod());
2546  ArtMethod* new_conflict_method = Runtime::Current()->GetClassLinker()->AddMethodToConflictTable(
2547      cls.Get(),
2548      conflict_method,
2549      interface_method,
2550      method,
2551      /*force_new_conflict_method*/false);
2552  if (new_conflict_method != conflict_method) {
2553    // Update the IMT if we create a new conflict method. No fence needed here, as the
2554    // data is consistent.
2555    imt->Set(imt_index,
2556             new_conflict_method,
2557             kRuntimePointerSize);
2558  }
2559
2560  const void* code = method->GetEntryPointFromQuickCompiledCode();
2561
2562  // When we return, the caller will branch to this address, so it had better not be 0!
2563  DCHECK(code != nullptr) << "Code was null in method: " << method->PrettyMethod()
2564                          << " location: " << method->GetDexFile()->GetLocation();
2565
2566  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(code),
2567                                reinterpret_cast<uintptr_t>(method));
2568}
2569
2570// Returns shorty type so the caller can determine how to put |result|
2571// into expected registers. The shorty type is static so the compiler
2572// could call different flavors of this code path depending on the
2573// shorty type though this would require different entry points for
2574// each type.
2575extern "C" uintptr_t artInvokePolymorphic(
2576    JValue* result,
2577    mirror::Object* raw_method_handle,
2578    Thread* self,
2579    ArtMethod** sp)
2580    REQUIRES_SHARED(Locks::mutator_lock_) {
2581  ScopedQuickEntrypointChecks sqec(self);
2582  DCHECK_EQ(*sp, Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
2583
2584  // Start new JNI local reference state
2585  JNIEnvExt* env = self->GetJniEnv();
2586  ScopedObjectAccessUnchecked soa(env);
2587  ScopedJniEnvLocalRefState env_state(env);
2588  const char* old_cause = self->StartAssertNoThreadSuspension("Making stack arguments safe.");
2589
2590  // From the instruction, get the |callsite_shorty| and expose arguments on the stack to the GC.
2591  ArtMethod* caller_method = QuickArgumentVisitor::GetCallingMethod(sp);
2592  uint32_t dex_pc = QuickArgumentVisitor::GetCallingDexPc(sp);
2593  const DexFile::CodeItem* code = caller_method->GetCodeItem();
2594  const Instruction& inst = code->InstructionAt(dex_pc);
2595  DCHECK(inst.Opcode() == Instruction::INVOKE_POLYMORPHIC ||
2596         inst.Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE);
2597  const DexFile* dex_file = caller_method->GetDexFile();
2598  const uint32_t proto_idx = inst.VRegH();
2599  const char* shorty = dex_file->GetShorty(proto_idx);
2600  const size_t shorty_length = strlen(shorty);
2601  static const bool kMethodIsStatic = false;  // invoke() and invokeExact() are not static.
2602  RememberForGcArgumentVisitor gc_visitor(sp, kMethodIsStatic, shorty, shorty_length, &soa);
2603  gc_visitor.VisitArguments();
2604
2605  // Wrap raw_method_handle in a Handle for safety.
2606  StackHandleScope<2> hs(self);
2607  Handle<mirror::MethodHandle> method_handle(
2608      hs.NewHandle(ObjPtr<mirror::MethodHandle>::DownCast(MakeObjPtr(raw_method_handle))));
2609  raw_method_handle = nullptr;
2610  self->EndAssertNoThreadSuspension(old_cause);
2611
2612  // Resolve method - it's either MethodHandle.invoke() or MethodHandle.invokeExact().
2613  ClassLinker* linker = Runtime::Current()->GetClassLinker();
2614  ArtMethod* resolved_method = linker->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
2615      self, inst.VRegB(), caller_method, kVirtual);
2616  DCHECK((resolved_method ==
2617          jni::DecodeArtMethod(WellKnownClasses::java_lang_invoke_MethodHandle_invokeExact)) ||
2618         (resolved_method ==
2619          jni::DecodeArtMethod(WellKnownClasses::java_lang_invoke_MethodHandle_invoke)));
2620  if (UNLIKELY(method_handle.IsNull())) {
2621    ThrowNullPointerExceptionForMethodAccess(resolved_method, InvokeType::kVirtual);
2622    return static_cast<uintptr_t>('V');
2623  }
2624
2625  Handle<mirror::MethodType> method_type(
2626      hs.NewHandle(linker->ResolveMethodType(self, proto_idx, caller_method)));
2627
2628  // This implies we couldn't resolve one or more types in this method handle.
2629  if (UNLIKELY(method_type.IsNull())) {
2630    CHECK(self->IsExceptionPending());
2631    return static_cast<uintptr_t>('V');
2632  }
2633
2634  DCHECK_EQ(ArtMethod::NumArgRegisters(shorty) + 1u, (uint32_t)inst.VRegA());
2635  DCHECK_EQ(resolved_method->IsStatic(), kMethodIsStatic);
2636
2637  // Fix references before constructing the shadow frame.
2638  gc_visitor.FixupReferences();
2639
2640  // Construct shadow frame placing arguments consecutively from |first_arg|.
2641  const bool is_range = (inst.Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE);
2642  const size_t num_vregs = is_range ? inst.VRegA_4rcc() : inst.VRegA_45cc();
2643  const size_t first_arg = 0;
2644  ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
2645      CREATE_SHADOW_FRAME(num_vregs, /* link */ nullptr, resolved_method, dex_pc);
2646  ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
2647  ScopedStackedShadowFramePusher
2648      frame_pusher(self, shadow_frame, StackedShadowFrameType::kShadowFrameUnderConstruction);
2649  BuildQuickShadowFrameVisitor shadow_frame_builder(sp,
2650                                                    kMethodIsStatic,
2651                                                    shorty,
2652                                                    strlen(shorty),
2653                                                    shadow_frame,
2654                                                    first_arg);
2655  shadow_frame_builder.VisitArguments();
2656
2657  // Push a transition back into managed code onto the linked list in thread.
2658  ManagedStack fragment;
2659  self->PushManagedStackFragment(&fragment);
2660
2661  // Call DoInvokePolymorphic with |is_range| = true, as shadow frame has argument registers in
2662  // consecutive order.
2663  uint32_t unused_args[Instruction::kMaxVarArgRegs] = {};
2664  uint32_t first_callee_arg = first_arg + 1;
2665  if (!DoInvokePolymorphic<true /* is_range */>(self,
2666                                                resolved_method,
2667                                                *shadow_frame,
2668                                                method_handle,
2669                                                method_type,
2670                                                unused_args,
2671                                                first_callee_arg,
2672                                                result)) {
2673    DCHECK(self->IsExceptionPending());
2674  }
2675
2676  // Pop transition record.
2677  self->PopManagedStackFragment(fragment);
2678
2679  return static_cast<uintptr_t>(shorty[0]);
2680}
2681
2682}  // namespace art
2683