quick_trampoline_entrypoints.cc revision e2abbc604ce003c776c00ecf1293796bb4c4ac5a
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 = kArm32QuickCodeUseSoftFloat;
81  static constexpr bool kAlignPairRegister = !kArm32QuickCodeUseSoftFloat;
82  static constexpr bool kQuickSoftFloatAbi = kArm32QuickCodeUseSoftFloat;
83  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = !kArm32QuickCodeUseSoftFloat;
84  static constexpr bool kQuickSkipOddFpRegisters = false;
85  static constexpr size_t kNumQuickGprArgs = 3;
86  static constexpr size_t kNumQuickFprArgs = kArm32QuickCodeUseSoftFloat ? 0 : 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
701extern "C" uint64_t artQuickToInterpreterBridge(ArtMethod* method, Thread* self, ArtMethod** sp)
702    REQUIRES_SHARED(Locks::mutator_lock_) {
703  // Ensure we don't get thread suspension until the object arguments are safely in the shadow
704  // frame.
705  ScopedQuickEntrypointChecks sqec(self);
706
707  if (UNLIKELY(!method->IsInvokable())) {
708    method->ThrowInvocationTimeError();
709    return 0;
710  }
711
712  JValue tmp_value;
713  ShadowFrame* deopt_frame = self->PopStackedShadowFrame(
714      StackedShadowFrameType::kDeoptimizationShadowFrame, false);
715  ManagedStack fragment;
716
717  DCHECK(!method->IsNative()) << method->PrettyMethod();
718  uint32_t shorty_len = 0;
719  ArtMethod* non_proxy_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
720  const DexFile::CodeItem* code_item = non_proxy_method->GetCodeItem();
721  DCHECK(code_item != nullptr) << method->PrettyMethod();
722  const char* shorty = non_proxy_method->GetShorty(&shorty_len);
723
724  JValue result;
725
726  if (deopt_frame != nullptr) {
727    // Coming from partial-fragment deopt.
728
729    if (kIsDebugBuild) {
730      // Sanity-check: are the methods as expected? We check that the last shadow frame (the bottom
731      // of the call-stack) corresponds to the called method.
732      ShadowFrame* linked = deopt_frame;
733      while (linked->GetLink() != nullptr) {
734        linked = linked->GetLink();
735      }
736      CHECK_EQ(method, linked->GetMethod()) << method->PrettyMethod() << " "
737          << ArtMethod::PrettyMethod(linked->GetMethod());
738    }
739
740    if (VLOG_IS_ON(deopt)) {
741      // Print out the stack to verify that it was a partial-fragment deopt.
742      LOG(INFO) << "Continue-ing from deopt. Stack is:";
743      QuickExceptionHandler::DumpFramesWithType(self, true);
744    }
745
746    ObjPtr<mirror::Throwable> pending_exception;
747    bool from_code = false;
748    DeoptimizationMethodType method_type;
749    self->PopDeoptimizationContext(/* out */ &result,
750                                   /* out */ &pending_exception,
751                                   /* out */ &from_code,
752                                   /* out */ &method_type);
753
754    // Push a transition back into managed code onto the linked list in thread.
755    self->PushManagedStackFragment(&fragment);
756
757    // Ensure that the stack is still in order.
758    if (kIsDebugBuild) {
759      class DummyStackVisitor : public StackVisitor {
760       public:
761        explicit DummyStackVisitor(Thread* self_in) REQUIRES_SHARED(Locks::mutator_lock_)
762            : StackVisitor(self_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames) {}
763
764        bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
765          // Nothing to do here. In a debug build, SanityCheckFrame will do the work in the walking
766          // logic. Just always say we want to continue.
767          return true;
768        }
769      };
770      DummyStackVisitor dsv(self);
771      dsv.WalkStack();
772    }
773
774    // Restore the exception that was pending before deoptimization then interpret the
775    // deoptimized frames.
776    if (pending_exception != nullptr) {
777      self->SetException(pending_exception);
778    }
779    interpreter::EnterInterpreterFromDeoptimize(self,
780                                                deopt_frame,
781                                                &result,
782                                                from_code,
783                                                DeoptimizationMethodType::kDefault);
784  } else {
785    const char* old_cause = self->StartAssertNoThreadSuspension(
786        "Building interpreter shadow frame");
787    uint16_t num_regs = code_item->registers_size_;
788    // No last shadow coming from quick.
789    ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
790        CREATE_SHADOW_FRAME(num_regs, /* link */ nullptr, method, /* dex pc */ 0);
791    ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
792    size_t first_arg_reg = code_item->registers_size_ - code_item->ins_size_;
793    BuildQuickShadowFrameVisitor shadow_frame_builder(sp, method->IsStatic(), shorty, shorty_len,
794                                                      shadow_frame, first_arg_reg);
795    shadow_frame_builder.VisitArguments();
796    const bool needs_initialization =
797        method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
798    // Push a transition back into managed code onto the linked list in thread.
799    self->PushManagedStackFragment(&fragment);
800    self->PushShadowFrame(shadow_frame);
801    self->EndAssertNoThreadSuspension(old_cause);
802
803    if (needs_initialization) {
804      // Ensure static method's class is initialized.
805      StackHandleScope<1> hs(self);
806      Handle<mirror::Class> h_class(hs.NewHandle(shadow_frame->GetMethod()->GetDeclaringClass()));
807      if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
808        DCHECK(Thread::Current()->IsExceptionPending())
809            << shadow_frame->GetMethod()->PrettyMethod();
810        self->PopManagedStackFragment(fragment);
811        return 0;
812      }
813    }
814
815    result = interpreter::EnterInterpreterFromEntryPoint(self, code_item, shadow_frame);
816  }
817
818  // Pop transition.
819  self->PopManagedStackFragment(fragment);
820
821  // Request a stack deoptimization if needed
822  ArtMethod* caller = QuickArgumentVisitor::GetCallingMethod(sp);
823  uintptr_t caller_pc = QuickArgumentVisitor::GetCallingPc(sp);
824  // If caller_pc is the instrumentation exit stub, the stub will check to see if deoptimization
825  // should be done and it knows the real return pc.
826  if (UNLIKELY(caller_pc != reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()) &&
827               Dbg::IsForcedInterpreterNeededForUpcall(self, caller))) {
828    if (!Runtime::Current()->IsAsyncDeoptimizeable(caller_pc)) {
829      LOG(WARNING) << "Got a deoptimization request on un-deoptimizable method "
830                   << caller->PrettyMethod();
831    } else {
832      // Push the context of the deoptimization stack so we can restore the return value and the
833      // exception before executing the deoptimized frames.
834      self->PushDeoptimizationContext(
835          result,
836          shorty[0] == 'L' || shorty[0] == '[',  /* class or array */
837          self->GetException(),
838          false /* from_code */,
839          DeoptimizationMethodType::kDefault);
840
841      // Set special exception to cause deoptimization.
842      self->SetException(Thread::GetDeoptimizationException());
843    }
844  }
845
846  // No need to restore the args since the method has already been run by the interpreter.
847  return result.GetJ();
848}
849
850// Visits arguments on the stack placing them into the args vector, Object* arguments are converted
851// to jobjects.
852class BuildQuickArgumentVisitor FINAL : public QuickArgumentVisitor {
853 public:
854  BuildQuickArgumentVisitor(ArtMethod** sp, bool is_static, const char* shorty, uint32_t shorty_len,
855                            ScopedObjectAccessUnchecked* soa, std::vector<jvalue>* args) :
856      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa), args_(args) {}
857
858  void Visit() REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE;
859
860  void FixupReferences() REQUIRES_SHARED(Locks::mutator_lock_);
861
862 private:
863  ScopedObjectAccessUnchecked* const soa_;
864  std::vector<jvalue>* const args_;
865  // References which we must update when exiting in case the GC moved the objects.
866  std::vector<std::pair<jobject, StackReference<mirror::Object>*>> references_;
867
868  DISALLOW_COPY_AND_ASSIGN(BuildQuickArgumentVisitor);
869};
870
871void BuildQuickArgumentVisitor::Visit() {
872  jvalue val;
873  Primitive::Type type = GetParamPrimitiveType();
874  switch (type) {
875    case Primitive::kPrimNot: {
876      StackReference<mirror::Object>* stack_ref =
877          reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
878      val.l = soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
879      references_.push_back(std::make_pair(val.l, stack_ref));
880      break;
881    }
882    case Primitive::kPrimLong:  // Fall-through.
883    case Primitive::kPrimDouble:
884      if (IsSplitLongOrDouble()) {
885        val.j = ReadSplitLongParam();
886      } else {
887        val.j = *reinterpret_cast<jlong*>(GetParamAddress());
888      }
889      break;
890    case Primitive::kPrimBoolean:  // Fall-through.
891    case Primitive::kPrimByte:     // Fall-through.
892    case Primitive::kPrimChar:     // Fall-through.
893    case Primitive::kPrimShort:    // Fall-through.
894    case Primitive::kPrimInt:      // Fall-through.
895    case Primitive::kPrimFloat:
896      val.i = *reinterpret_cast<jint*>(GetParamAddress());
897      break;
898    case Primitive::kPrimVoid:
899      LOG(FATAL) << "UNREACHABLE";
900      UNREACHABLE();
901  }
902  args_->push_back(val);
903}
904
905void BuildQuickArgumentVisitor::FixupReferences() {
906  // Fixup any references which may have changed.
907  for (const auto& pair : references_) {
908    pair.second->Assign(soa_->Decode<mirror::Object>(pair.first));
909    soa_->Env()->DeleteLocalRef(pair.first);
910  }
911}
912// Handler for invocation on proxy methods. On entry a frame will exist for the proxy object method
913// which is responsible for recording callee save registers. We explicitly place into jobjects the
914// incoming reference arguments (so they survive GC). We invoke the invocation handler, which is a
915// field within the proxy object, which will box the primitive arguments and deal with error cases.
916extern "C" uint64_t artQuickProxyInvokeHandler(
917    ArtMethod* proxy_method, mirror::Object* receiver, Thread* self, ArtMethod** sp)
918    REQUIRES_SHARED(Locks::mutator_lock_) {
919  DCHECK(proxy_method->IsProxyMethod()) << proxy_method->PrettyMethod();
920  DCHECK(receiver->GetClass()->IsProxyClass()) << proxy_method->PrettyMethod();
921  // Ensure we don't get thread suspension until the object arguments are safely in jobjects.
922  const char* old_cause =
923      self->StartAssertNoThreadSuspension("Adding to IRT proxy object arguments");
924  // Register the top of the managed stack, making stack crawlable.
925  DCHECK_EQ((*sp), proxy_method) << proxy_method->PrettyMethod();
926  self->VerifyStack();
927  // Start new JNI local reference state.
928  JNIEnvExt* env = self->GetJniEnv();
929  ScopedObjectAccessUnchecked soa(env);
930  ScopedJniEnvLocalRefState env_state(env);
931  // Create local ref. copies of proxy method and the receiver.
932  jobject rcvr_jobj = soa.AddLocalReference<jobject>(receiver);
933
934  // Placing arguments into args vector and remove the receiver.
935  ArtMethod* non_proxy_method = proxy_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
936  CHECK(!non_proxy_method->IsStatic()) << proxy_method->PrettyMethod() << " "
937                                       << non_proxy_method->PrettyMethod();
938  std::vector<jvalue> args;
939  uint32_t shorty_len = 0;
940  const char* shorty = non_proxy_method->GetShorty(&shorty_len);
941  BuildQuickArgumentVisitor local_ref_visitor(sp, false, shorty, shorty_len, &soa, &args);
942
943  local_ref_visitor.VisitArguments();
944  DCHECK_GT(args.size(), 0U) << proxy_method->PrettyMethod();
945  args.erase(args.begin());
946
947  // Convert proxy method into expected interface method.
948  ArtMethod* interface_method = proxy_method->FindOverriddenMethod(kRuntimePointerSize);
949  DCHECK(interface_method != nullptr) << proxy_method->PrettyMethod();
950  DCHECK(!interface_method->IsProxyMethod()) << interface_method->PrettyMethod();
951  self->EndAssertNoThreadSuspension(old_cause);
952  DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
953  DCHECK(!Runtime::Current()->IsActiveTransaction());
954  jobject interface_method_jobj = soa.AddLocalReference<jobject>(
955      mirror::Method::CreateFromArtMethod<kRuntimePointerSize, false>(soa.Self(),
956                                                                      interface_method));
957
958  // All naked Object*s should now be in jobjects, so its safe to go into the main invoke code
959  // that performs allocations.
960  JValue result = InvokeProxyInvocationHandler(soa, shorty, rcvr_jobj, interface_method_jobj, args);
961  // Restore references which might have moved.
962  local_ref_visitor.FixupReferences();
963  return result.GetJ();
964}
965
966// Read object references held in arguments from quick frames and place in a JNI local references,
967// so they don't get garbage collected.
968class RememberForGcArgumentVisitor FINAL : public QuickArgumentVisitor {
969 public:
970  RememberForGcArgumentVisitor(ArtMethod** sp, bool is_static, const char* shorty,
971                               uint32_t shorty_len, ScopedObjectAccessUnchecked* soa) :
972      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa) {}
973
974  void Visit() REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE;
975
976  void FixupReferences() REQUIRES_SHARED(Locks::mutator_lock_);
977
978 private:
979  ScopedObjectAccessUnchecked* const soa_;
980  // References which we must update when exiting in case the GC moved the objects.
981  std::vector<std::pair<jobject, StackReference<mirror::Object>*> > references_;
982
983  DISALLOW_COPY_AND_ASSIGN(RememberForGcArgumentVisitor);
984};
985
986void RememberForGcArgumentVisitor::Visit() {
987  if (IsParamAReference()) {
988    StackReference<mirror::Object>* stack_ref =
989        reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
990    jobject reference =
991        soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
992    references_.push_back(std::make_pair(reference, stack_ref));
993  }
994}
995
996void RememberForGcArgumentVisitor::FixupReferences() {
997  // Fixup any references which may have changed.
998  for (const auto& pair : references_) {
999    pair.second->Assign(soa_->Decode<mirror::Object>(pair.first));
1000    soa_->Env()->DeleteLocalRef(pair.first);
1001  }
1002}
1003
1004extern "C" const void* artInstrumentationMethodEntryFromCode(ArtMethod* method,
1005                                                             mirror::Object* this_object,
1006                                                             Thread* self,
1007                                                             ArtMethod** sp)
1008    REQUIRES_SHARED(Locks::mutator_lock_) {
1009  const void* result;
1010  // Instrumentation changes the stack. Thus, when exiting, the stack cannot be verified, so skip
1011  // that part.
1012  ScopedQuickEntrypointChecks sqec(self, kIsDebugBuild, false);
1013  instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1014  if (instrumentation->IsDeoptimized(method)) {
1015    result = GetQuickToInterpreterBridge();
1016  } else {
1017    result = instrumentation->GetQuickCodeFor(method, kRuntimePointerSize);
1018    DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(result));
1019  }
1020
1021  bool interpreter_entry = (result == GetQuickToInterpreterBridge());
1022  bool is_static = method->IsStatic();
1023  uint32_t shorty_len;
1024  const char* shorty =
1025      method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(&shorty_len);
1026
1027  ScopedObjectAccessUnchecked soa(self);
1028  RememberForGcArgumentVisitor visitor(sp, is_static, shorty, shorty_len, &soa);
1029  visitor.VisitArguments();
1030
1031  instrumentation->PushInstrumentationStackFrame(self,
1032                                                 is_static ? nullptr : this_object,
1033                                                 method,
1034                                                 QuickArgumentVisitor::GetCallingPc(sp),
1035                                                 interpreter_entry);
1036
1037  visitor.FixupReferences();
1038  if (UNLIKELY(self->IsExceptionPending())) {
1039    return nullptr;
1040  }
1041  CHECK(result != nullptr) << method->PrettyMethod();
1042  return result;
1043}
1044
1045extern "C" TwoWordReturn artInstrumentationMethodExitFromCode(Thread* self,
1046                                                              ArtMethod** sp,
1047                                                              uint64_t* gpr_result,
1048                                                              uint64_t* fpr_result)
1049    REQUIRES_SHARED(Locks::mutator_lock_) {
1050  DCHECK_EQ(reinterpret_cast<uintptr_t>(self), reinterpret_cast<uintptr_t>(Thread::Current()));
1051  CHECK(gpr_result != nullptr);
1052  CHECK(fpr_result != nullptr);
1053  // Instrumentation exit stub must not be entered with a pending exception.
1054  CHECK(!self->IsExceptionPending()) << "Enter instrumentation exit stub with pending exception "
1055                                     << self->GetException()->Dump();
1056  // Compute address of return PC and sanity check that it currently holds 0.
1057  size_t return_pc_offset = GetCalleeSaveReturnPcOffset(kRuntimeISA,
1058                                                        CalleeSaveType::kSaveEverything);
1059  uintptr_t* return_pc = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(sp) +
1060                                                      return_pc_offset);
1061  CHECK_EQ(*return_pc, 0U);
1062
1063  // Pop the frame filling in the return pc. The low half of the return value is 0 when
1064  // deoptimization shouldn't be performed with the high-half having the return address. When
1065  // deoptimization should be performed the low half is zero and the high-half the address of the
1066  // deoptimization entry point.
1067  instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1068  TwoWordReturn return_or_deoptimize_pc = instrumentation->PopInstrumentationStackFrame(
1069      self, return_pc, gpr_result, fpr_result);
1070  if (self->IsExceptionPending()) {
1071    return GetTwoWordFailureValue();
1072  }
1073  return return_or_deoptimize_pc;
1074}
1075
1076// Lazily resolve a method for quick. Called by stub code.
1077extern "C" const void* artQuickResolutionTrampoline(
1078    ArtMethod* called, mirror::Object* receiver, Thread* self, ArtMethod** sp)
1079    REQUIRES_SHARED(Locks::mutator_lock_) {
1080  // The resolution trampoline stashes the resolved method into the callee-save frame to transport
1081  // it. Thus, when exiting, the stack cannot be verified (as the resolved method most likely
1082  // does not have the same stack layout as the callee-save method).
1083  ScopedQuickEntrypointChecks sqec(self, kIsDebugBuild, false);
1084  // Start new JNI local reference state
1085  JNIEnvExt* env = self->GetJniEnv();
1086  ScopedObjectAccessUnchecked soa(env);
1087  ScopedJniEnvLocalRefState env_state(env);
1088  const char* old_cause = self->StartAssertNoThreadSuspension("Quick method resolution set up");
1089
1090  // Compute details about the called method (avoid GCs)
1091  ClassLinker* linker = Runtime::Current()->GetClassLinker();
1092  InvokeType invoke_type;
1093  MethodReference called_method(nullptr, 0);
1094  const bool called_method_known_on_entry = !called->IsRuntimeMethod();
1095  ArtMethod* caller = nullptr;
1096  if (!called_method_known_on_entry) {
1097    caller = QuickArgumentVisitor::GetCallingMethod(sp);
1098    called_method.dex_file = caller->GetDexFile();
1099
1100    InvokeType stack_map_invoke_type;
1101    uint32_t stack_map_dex_method_idx;
1102    const bool found_stack_map = QuickArgumentVisitor::GetInvokeType(sp,
1103                                                                     &stack_map_invoke_type,
1104                                                                     &stack_map_dex_method_idx);
1105    // For debug builds, we make sure both of the paths are consistent by also looking at the dex
1106    // code.
1107    if (!found_stack_map || kIsDebugBuild) {
1108      uint32_t dex_pc = QuickArgumentVisitor::GetCallingDexPc(sp);
1109      const DexFile::CodeItem* code;
1110      code = caller->GetCodeItem();
1111      CHECK_LT(dex_pc, code->insns_size_in_code_units_);
1112      const Instruction* instr = Instruction::At(&code->insns_[dex_pc]);
1113      Instruction::Code instr_code = instr->Opcode();
1114      bool is_range;
1115      switch (instr_code) {
1116        case Instruction::INVOKE_DIRECT:
1117          invoke_type = kDirect;
1118          is_range = false;
1119          break;
1120        case Instruction::INVOKE_DIRECT_RANGE:
1121          invoke_type = kDirect;
1122          is_range = true;
1123          break;
1124        case Instruction::INVOKE_STATIC:
1125          invoke_type = kStatic;
1126          is_range = false;
1127          break;
1128        case Instruction::INVOKE_STATIC_RANGE:
1129          invoke_type = kStatic;
1130          is_range = true;
1131          break;
1132        case Instruction::INVOKE_SUPER:
1133          invoke_type = kSuper;
1134          is_range = false;
1135          break;
1136        case Instruction::INVOKE_SUPER_RANGE:
1137          invoke_type = kSuper;
1138          is_range = true;
1139          break;
1140        case Instruction::INVOKE_VIRTUAL:
1141          invoke_type = kVirtual;
1142          is_range = false;
1143          break;
1144        case Instruction::INVOKE_VIRTUAL_RANGE:
1145          invoke_type = kVirtual;
1146          is_range = true;
1147          break;
1148        case Instruction::INVOKE_INTERFACE:
1149          invoke_type = kInterface;
1150          is_range = false;
1151          break;
1152        case Instruction::INVOKE_INTERFACE_RANGE:
1153          invoke_type = kInterface;
1154          is_range = true;
1155          break;
1156        default:
1157          LOG(FATAL) << "Unexpected call into trampoline: " << instr->DumpString(nullptr);
1158          UNREACHABLE();
1159      }
1160      called_method.dex_method_index = (is_range) ? instr->VRegB_3rc() : instr->VRegB_35c();
1161      // Check that the invoke matches what we expected, note that this path only happens for debug
1162      // builds.
1163      if (found_stack_map) {
1164        DCHECK_EQ(stack_map_invoke_type, invoke_type);
1165        if (invoke_type != kSuper) {
1166          // Super may be sharpened.
1167          DCHECK_EQ(stack_map_dex_method_idx, called_method.dex_method_index)
1168              << called_method.dex_file->PrettyMethod(stack_map_dex_method_idx) << " "
1169              << called_method.dex_file->PrettyMethod(called_method.dex_method_index);
1170        }
1171      } else {
1172        VLOG(dex) << "Accessed dex file for invoke " << invoke_type << " "
1173                  << called_method.dex_method_index;
1174      }
1175    } else {
1176      invoke_type = stack_map_invoke_type;
1177      called_method.dex_method_index = stack_map_dex_method_idx;
1178    }
1179  } else {
1180    invoke_type = kStatic;
1181    called_method.dex_file = called->GetDexFile();
1182    called_method.dex_method_index = called->GetDexMethodIndex();
1183  }
1184  uint32_t shorty_len;
1185  const char* shorty =
1186      called_method.dex_file->GetMethodShorty(
1187          called_method.dex_file->GetMethodId(called_method.dex_method_index), &shorty_len);
1188  RememberForGcArgumentVisitor visitor(sp, invoke_type == kStatic, shorty, shorty_len, &soa);
1189  visitor.VisitArguments();
1190  self->EndAssertNoThreadSuspension(old_cause);
1191  const bool virtual_or_interface = invoke_type == kVirtual || invoke_type == kInterface;
1192  // Resolve method filling in dex cache.
1193  if (!called_method_known_on_entry) {
1194    StackHandleScope<1> hs(self);
1195    mirror::Object* dummy = nullptr;
1196    HandleWrapper<mirror::Object> h_receiver(
1197        hs.NewHandleWrapper(virtual_or_interface ? &receiver : &dummy));
1198    DCHECK_EQ(caller->GetDexFile(), called_method.dex_file);
1199    called = linker->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
1200        self, called_method.dex_method_index, caller, invoke_type);
1201
1202    // Update .bss entry in oat file if any.
1203    if (called != nullptr && called_method.dex_file->GetOatDexFile() != nullptr) {
1204      const MethodBssMapping* mapping =
1205          called_method.dex_file->GetOatDexFile()->GetMethodBssMapping();
1206      if (mapping != nullptr) {
1207        auto pp = std::partition_point(
1208            mapping->begin(),
1209            mapping->end(),
1210            [called_method](const MethodBssMappingEntry& entry) {
1211              return entry.method_index < called_method.dex_method_index;
1212            });
1213        if (pp != mapping->end() && pp->CoversIndex(called_method.dex_method_index)) {
1214          size_t bss_offset = pp->GetBssOffset(called_method.dex_method_index,
1215                                               static_cast<size_t>(kRuntimePointerSize));
1216          DCHECK_ALIGNED(bss_offset, static_cast<size_t>(kRuntimePointerSize));
1217          const OatFile* oat_file = called_method.dex_file->GetOatDexFile()->GetOatFile();
1218          ArtMethod** method_entry = reinterpret_cast<ArtMethod**>(const_cast<uint8_t*>(
1219              oat_file->BssBegin() + bss_offset));
1220          DCHECK_GE(method_entry, oat_file->GetBssMethods().data());
1221          DCHECK_LT(method_entry,
1222                    oat_file->GetBssMethods().data() + oat_file->GetBssMethods().size());
1223          *method_entry = called;
1224        }
1225      }
1226    }
1227  }
1228  const void* code = nullptr;
1229  if (LIKELY(!self->IsExceptionPending())) {
1230    // Incompatible class change should have been handled in resolve method.
1231    CHECK(!called->CheckIncompatibleClassChange(invoke_type))
1232        << called->PrettyMethod() << " " << invoke_type;
1233    if (virtual_or_interface || invoke_type == kSuper) {
1234      // Refine called method based on receiver for kVirtual/kInterface, and
1235      // caller for kSuper.
1236      ArtMethod* orig_called = called;
1237      if (invoke_type == kVirtual) {
1238        CHECK(receiver != nullptr) << invoke_type;
1239        called = receiver->GetClass()->FindVirtualMethodForVirtual(called, kRuntimePointerSize);
1240      } else if (invoke_type == kInterface) {
1241        CHECK(receiver != nullptr) << invoke_type;
1242        called = receiver->GetClass()->FindVirtualMethodForInterface(called, kRuntimePointerSize);
1243      } else {
1244        DCHECK_EQ(invoke_type, kSuper);
1245        CHECK(caller != nullptr) << invoke_type;
1246        StackHandleScope<2> hs(self);
1247        Handle<mirror::DexCache> dex_cache(
1248            hs.NewHandle(caller->GetDeclaringClass()->GetDexCache()));
1249        Handle<mirror::ClassLoader> class_loader(
1250            hs.NewHandle(caller->GetDeclaringClass()->GetClassLoader()));
1251        // TODO Maybe put this into a mirror::Class function.
1252        ObjPtr<mirror::Class> ref_class = linker->LookupResolvedType(
1253            *dex_cache->GetDexFile(),
1254            dex_cache->GetDexFile()->GetMethodId(called_method.dex_method_index).class_idx_,
1255            dex_cache.Get(),
1256            class_loader.Get());
1257        if (ref_class->IsInterface()) {
1258          called = ref_class->FindVirtualMethodForInterfaceSuper(called, kRuntimePointerSize);
1259        } else {
1260          called = caller->GetDeclaringClass()->GetSuperClass()->GetVTableEntry(
1261              called->GetMethodIndex(), kRuntimePointerSize);
1262        }
1263      }
1264
1265      CHECK(called != nullptr) << orig_called->PrettyMethod() << " "
1266                               << mirror::Object::PrettyTypeOf(receiver) << " "
1267                               << invoke_type << " " << orig_called->GetVtableIndex();
1268    }
1269
1270    // Ensure that the called method's class is initialized.
1271    StackHandleScope<1> hs(soa.Self());
1272    Handle<mirror::Class> called_class(hs.NewHandle(called->GetDeclaringClass()));
1273    linker->EnsureInitialized(soa.Self(), called_class, true, true);
1274    if (LIKELY(called_class->IsInitialized())) {
1275      if (UNLIKELY(Dbg::IsForcedInterpreterNeededForResolution(self, called))) {
1276        // If we are single-stepping or the called method is deoptimized (by a
1277        // breakpoint, for example), then we have to execute the called method
1278        // with the interpreter.
1279        code = GetQuickToInterpreterBridge();
1280      } else if (UNLIKELY(Dbg::IsForcedInstrumentationNeededForResolution(self, caller))) {
1281        // If the caller is deoptimized (by a breakpoint, for example), we have to
1282        // continue its execution with interpreter when returning from the called
1283        // method. Because we do not want to execute the called method with the
1284        // interpreter, we wrap its execution into the instrumentation stubs.
1285        // When the called method returns, it will execute the instrumentation
1286        // exit hook that will determine the need of the interpreter with a call
1287        // to Dbg::IsForcedInterpreterNeededForUpcall and deoptimize the stack if
1288        // it is needed.
1289        code = GetQuickInstrumentationEntryPoint();
1290      } else {
1291        code = called->GetEntryPointFromQuickCompiledCode();
1292      }
1293    } else if (called_class->IsInitializing()) {
1294      if (UNLIKELY(Dbg::IsForcedInterpreterNeededForResolution(self, called))) {
1295        // If we are single-stepping or the called method is deoptimized (by a
1296        // breakpoint, for example), then we have to execute the called method
1297        // with the interpreter.
1298        code = GetQuickToInterpreterBridge();
1299      } else if (invoke_type == kStatic) {
1300        // Class is still initializing, go to oat and grab code (trampoline must be left in place
1301        // until class is initialized to stop races between threads).
1302        code = linker->GetQuickOatCodeFor(called);
1303      } else {
1304        // No trampoline for non-static methods.
1305        code = called->GetEntryPointFromQuickCompiledCode();
1306      }
1307    } else {
1308      DCHECK(called_class->IsErroneous());
1309    }
1310  }
1311  CHECK_EQ(code == nullptr, self->IsExceptionPending());
1312  // Fixup any locally saved objects may have moved during a GC.
1313  visitor.FixupReferences();
1314  // Place called method in callee-save frame to be placed as first argument to quick method.
1315  *sp = called;
1316
1317  return code;
1318}
1319
1320/*
1321 * This class uses a couple of observations to unite the different calling conventions through
1322 * a few constants.
1323 *
1324 * 1) Number of registers used for passing is normally even, so counting down has no penalty for
1325 *    possible alignment.
1326 * 2) Known 64b architectures store 8B units on the stack, both for integral and floating point
1327 *    types, so using uintptr_t is OK. Also means that we can use kRegistersNeededX to denote
1328 *    when we have to split things
1329 * 3) The only soft-float, Arm, is 32b, so no widening needs to be taken into account for floats
1330 *    and we can use Int handling directly.
1331 * 4) Only 64b architectures widen, and their stack is aligned 8B anyways, so no padding code
1332 *    necessary when widening. Also, widening of Ints will take place implicitly, and the
1333 *    extension should be compatible with Aarch64, which mandates copying the available bits
1334 *    into LSB and leaving the rest unspecified.
1335 * 5) Aligning longs and doubles is necessary on arm only, and it's the same in registers and on
1336 *    the stack.
1337 * 6) There is only little endian.
1338 *
1339 *
1340 * Actual work is supposed to be done in a delegate of the template type. The interface is as
1341 * follows:
1342 *
1343 * void PushGpr(uintptr_t):   Add a value for the next GPR
1344 *
1345 * void PushFpr4(float):      Add a value for the next FPR of size 32b. Is only called if we need
1346 *                            padding, that is, think the architecture is 32b and aligns 64b.
1347 *
1348 * void PushFpr8(uint64_t):   Push a double. We _will_ call this on 32b, it's the callee's job to
1349 *                            split this if necessary. The current state will have aligned, if
1350 *                            necessary.
1351 *
1352 * void PushStack(uintptr_t): Push a value to the stack.
1353 *
1354 * uintptr_t PushHandleScope(mirror::Object* ref): Add a reference to the HandleScope. This _will_ have nullptr,
1355 *                                          as this might be important for null initialization.
1356 *                                          Must return the jobject, that is, the reference to the
1357 *                                          entry in the HandleScope (nullptr if necessary).
1358 *
1359 */
1360template<class T> class BuildNativeCallFrameStateMachine {
1361 public:
1362#if defined(__arm__)
1363  // TODO: These are all dummy values!
1364  static constexpr bool kNativeSoftFloatAbi = true;
1365  static constexpr size_t kNumNativeGprArgs = 4;  // 4 arguments passed in GPRs, r0-r3
1366  static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
1367
1368  static constexpr size_t kRegistersNeededForLong = 2;
1369  static constexpr size_t kRegistersNeededForDouble = 2;
1370  static constexpr bool kMultiRegistersAligned = true;
1371  static constexpr bool kMultiFPRegistersWidened = false;
1372  static constexpr bool kMultiGPRegistersWidened = false;
1373  static constexpr bool kAlignLongOnStack = true;
1374  static constexpr bool kAlignDoubleOnStack = true;
1375#elif defined(__aarch64__)
1376  static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
1377  static constexpr size_t kNumNativeGprArgs = 8;  // 6 arguments passed in GPRs.
1378  static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
1379
1380  static constexpr size_t kRegistersNeededForLong = 1;
1381  static constexpr size_t kRegistersNeededForDouble = 1;
1382  static constexpr bool kMultiRegistersAligned = false;
1383  static constexpr bool kMultiFPRegistersWidened = false;
1384  static constexpr bool kMultiGPRegistersWidened = false;
1385  static constexpr bool kAlignLongOnStack = false;
1386  static constexpr bool kAlignDoubleOnStack = false;
1387#elif defined(__mips__) && !defined(__LP64__)
1388  static constexpr bool kNativeSoftFloatAbi = true;  // This is a hard float ABI.
1389  static constexpr size_t kNumNativeGprArgs = 4;  // 4 arguments passed in GPRs.
1390  static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
1391
1392  static constexpr size_t kRegistersNeededForLong = 2;
1393  static constexpr size_t kRegistersNeededForDouble = 2;
1394  static constexpr bool kMultiRegistersAligned = true;
1395  static constexpr bool kMultiFPRegistersWidened = true;
1396  static constexpr bool kMultiGPRegistersWidened = false;
1397  static constexpr bool kAlignLongOnStack = true;
1398  static constexpr bool kAlignDoubleOnStack = true;
1399#elif defined(__mips__) && defined(__LP64__)
1400  // Let the code prepare GPRs only and we will load the FPRs with same data.
1401  static constexpr bool kNativeSoftFloatAbi = true;
1402  static constexpr size_t kNumNativeGprArgs = 8;
1403  static constexpr size_t kNumNativeFprArgs = 0;
1404
1405  static constexpr size_t kRegistersNeededForLong = 1;
1406  static constexpr size_t kRegistersNeededForDouble = 1;
1407  static constexpr bool kMultiRegistersAligned = false;
1408  static constexpr bool kMultiFPRegistersWidened = false;
1409  static constexpr bool kMultiGPRegistersWidened = true;
1410  static constexpr bool kAlignLongOnStack = false;
1411  static constexpr bool kAlignDoubleOnStack = false;
1412#elif defined(__i386__)
1413  // TODO: Check these!
1414  static constexpr bool kNativeSoftFloatAbi = false;  // Not using int registers for fp
1415  static constexpr size_t kNumNativeGprArgs = 0;  // 6 arguments passed in GPRs.
1416  static constexpr size_t kNumNativeFprArgs = 0;  // 8 arguments passed in FPRs.
1417
1418  static constexpr size_t kRegistersNeededForLong = 2;
1419  static constexpr size_t kRegistersNeededForDouble = 2;
1420  static constexpr bool kMultiRegistersAligned = false;  // x86 not using regs, anyways
1421  static constexpr bool kMultiFPRegistersWidened = false;
1422  static constexpr bool kMultiGPRegistersWidened = false;
1423  static constexpr bool kAlignLongOnStack = false;
1424  static constexpr bool kAlignDoubleOnStack = false;
1425#elif defined(__x86_64__)
1426  static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
1427  static constexpr size_t kNumNativeGprArgs = 6;  // 6 arguments passed in GPRs.
1428  static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
1429
1430  static constexpr size_t kRegistersNeededForLong = 1;
1431  static constexpr size_t kRegistersNeededForDouble = 1;
1432  static constexpr bool kMultiRegistersAligned = false;
1433  static constexpr bool kMultiFPRegistersWidened = false;
1434  static constexpr bool kMultiGPRegistersWidened = false;
1435  static constexpr bool kAlignLongOnStack = false;
1436  static constexpr bool kAlignDoubleOnStack = false;
1437#else
1438#error "Unsupported architecture"
1439#endif
1440
1441 public:
1442  explicit BuildNativeCallFrameStateMachine(T* delegate)
1443      : gpr_index_(kNumNativeGprArgs),
1444        fpr_index_(kNumNativeFprArgs),
1445        stack_entries_(0),
1446        delegate_(delegate) {
1447    // For register alignment, we want to assume that counters (gpr_index_, fpr_index_) are even iff
1448    // the next register is even; counting down is just to make the compiler happy...
1449    static_assert(kNumNativeGprArgs % 2 == 0U, "Number of native GPR arguments not even");
1450    static_assert(kNumNativeFprArgs % 2 == 0U, "Number of native FPR arguments not even");
1451  }
1452
1453  virtual ~BuildNativeCallFrameStateMachine() {}
1454
1455  bool HavePointerGpr() const {
1456    return gpr_index_ > 0;
1457  }
1458
1459  void AdvancePointer(const void* val) {
1460    if (HavePointerGpr()) {
1461      gpr_index_--;
1462      PushGpr(reinterpret_cast<uintptr_t>(val));
1463    } else {
1464      stack_entries_++;  // TODO: have a field for pointer length as multiple of 32b
1465      PushStack(reinterpret_cast<uintptr_t>(val));
1466      gpr_index_ = 0;
1467    }
1468  }
1469
1470  bool HaveHandleScopeGpr() const {
1471    return gpr_index_ > 0;
1472  }
1473
1474  void AdvanceHandleScope(mirror::Object* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
1475    uintptr_t handle = PushHandle(ptr);
1476    if (HaveHandleScopeGpr()) {
1477      gpr_index_--;
1478      PushGpr(handle);
1479    } else {
1480      stack_entries_++;
1481      PushStack(handle);
1482      gpr_index_ = 0;
1483    }
1484  }
1485
1486  bool HaveIntGpr() const {
1487    return gpr_index_ > 0;
1488  }
1489
1490  void AdvanceInt(uint32_t val) {
1491    if (HaveIntGpr()) {
1492      gpr_index_--;
1493      if (kMultiGPRegistersWidened) {
1494        DCHECK_EQ(sizeof(uintptr_t), sizeof(int64_t));
1495        PushGpr(static_cast<int64_t>(bit_cast<int32_t, uint32_t>(val)));
1496      } else {
1497        PushGpr(val);
1498      }
1499    } else {
1500      stack_entries_++;
1501      if (kMultiGPRegistersWidened) {
1502        DCHECK_EQ(sizeof(uintptr_t), sizeof(int64_t));
1503        PushStack(static_cast<int64_t>(bit_cast<int32_t, uint32_t>(val)));
1504      } else {
1505        PushStack(val);
1506      }
1507      gpr_index_ = 0;
1508    }
1509  }
1510
1511  bool HaveLongGpr() const {
1512    return gpr_index_ >= kRegistersNeededForLong + (LongGprNeedsPadding() ? 1 : 0);
1513  }
1514
1515  bool LongGprNeedsPadding() const {
1516    return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1517        kAlignLongOnStack &&                  // and when it needs alignment
1518        (gpr_index_ & 1) == 1;                // counter is odd, see constructor
1519  }
1520
1521  bool LongStackNeedsPadding() const {
1522    return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1523        kAlignLongOnStack &&                  // and when it needs 8B alignment
1524        (stack_entries_ & 1) == 1;            // counter is odd
1525  }
1526
1527  void AdvanceLong(uint64_t val) {
1528    if (HaveLongGpr()) {
1529      if (LongGprNeedsPadding()) {
1530        PushGpr(0);
1531        gpr_index_--;
1532      }
1533      if (kRegistersNeededForLong == 1) {
1534        PushGpr(static_cast<uintptr_t>(val));
1535      } else {
1536        PushGpr(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1537        PushGpr(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1538      }
1539      gpr_index_ -= kRegistersNeededForLong;
1540    } else {
1541      if (LongStackNeedsPadding()) {
1542        PushStack(0);
1543        stack_entries_++;
1544      }
1545      if (kRegistersNeededForLong == 1) {
1546        PushStack(static_cast<uintptr_t>(val));
1547        stack_entries_++;
1548      } else {
1549        PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1550        PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1551        stack_entries_ += 2;
1552      }
1553      gpr_index_ = 0;
1554    }
1555  }
1556
1557  bool HaveFloatFpr() const {
1558    return fpr_index_ > 0;
1559  }
1560
1561  void AdvanceFloat(float val) {
1562    if (kNativeSoftFloatAbi) {
1563      AdvanceInt(bit_cast<uint32_t, float>(val));
1564    } else {
1565      if (HaveFloatFpr()) {
1566        fpr_index_--;
1567        if (kRegistersNeededForDouble == 1) {
1568          if (kMultiFPRegistersWidened) {
1569            PushFpr8(bit_cast<uint64_t, double>(val));
1570          } else {
1571            // No widening, just use the bits.
1572            PushFpr8(static_cast<uint64_t>(bit_cast<uint32_t, float>(val)));
1573          }
1574        } else {
1575          PushFpr4(val);
1576        }
1577      } else {
1578        stack_entries_++;
1579        if (kRegistersNeededForDouble == 1 && kMultiFPRegistersWidened) {
1580          // Need to widen before storing: Note the "double" in the template instantiation.
1581          // Note: We need to jump through those hoops to make the compiler happy.
1582          DCHECK_EQ(sizeof(uintptr_t), sizeof(uint64_t));
1583          PushStack(static_cast<uintptr_t>(bit_cast<uint64_t, double>(val)));
1584        } else {
1585          PushStack(static_cast<uintptr_t>(bit_cast<uint32_t, float>(val)));
1586        }
1587        fpr_index_ = 0;
1588      }
1589    }
1590  }
1591
1592  bool HaveDoubleFpr() const {
1593    return fpr_index_ >= kRegistersNeededForDouble + (DoubleFprNeedsPadding() ? 1 : 0);
1594  }
1595
1596  bool DoubleFprNeedsPadding() const {
1597    return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1598        kAlignDoubleOnStack &&                  // and when it needs alignment
1599        (fpr_index_ & 1) == 1;                  // counter is odd, see constructor
1600  }
1601
1602  bool DoubleStackNeedsPadding() const {
1603    return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1604        kAlignDoubleOnStack &&                  // and when it needs 8B alignment
1605        (stack_entries_ & 1) == 1;              // counter is odd
1606  }
1607
1608  void AdvanceDouble(uint64_t val) {
1609    if (kNativeSoftFloatAbi) {
1610      AdvanceLong(val);
1611    } else {
1612      if (HaveDoubleFpr()) {
1613        if (DoubleFprNeedsPadding()) {
1614          PushFpr4(0);
1615          fpr_index_--;
1616        }
1617        PushFpr8(val);
1618        fpr_index_ -= kRegistersNeededForDouble;
1619      } else {
1620        if (DoubleStackNeedsPadding()) {
1621          PushStack(0);
1622          stack_entries_++;
1623        }
1624        if (kRegistersNeededForDouble == 1) {
1625          PushStack(static_cast<uintptr_t>(val));
1626          stack_entries_++;
1627        } else {
1628          PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1629          PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1630          stack_entries_ += 2;
1631        }
1632        fpr_index_ = 0;
1633      }
1634    }
1635  }
1636
1637  uint32_t GetStackEntries() const {
1638    return stack_entries_;
1639  }
1640
1641  uint32_t GetNumberOfUsedGprs() const {
1642    return kNumNativeGprArgs - gpr_index_;
1643  }
1644
1645  uint32_t GetNumberOfUsedFprs() const {
1646    return kNumNativeFprArgs - fpr_index_;
1647  }
1648
1649 private:
1650  void PushGpr(uintptr_t val) {
1651    delegate_->PushGpr(val);
1652  }
1653  void PushFpr4(float val) {
1654    delegate_->PushFpr4(val);
1655  }
1656  void PushFpr8(uint64_t val) {
1657    delegate_->PushFpr8(val);
1658  }
1659  void PushStack(uintptr_t val) {
1660    delegate_->PushStack(val);
1661  }
1662  uintptr_t PushHandle(mirror::Object* ref) REQUIRES_SHARED(Locks::mutator_lock_) {
1663    return delegate_->PushHandle(ref);
1664  }
1665
1666  uint32_t gpr_index_;      // Number of free GPRs
1667  uint32_t fpr_index_;      // Number of free FPRs
1668  uint32_t stack_entries_;  // Stack entries are in multiples of 32b, as floats are usually not
1669                            // extended
1670  T* const delegate_;             // What Push implementation gets called
1671};
1672
1673// Computes the sizes of register stacks and call stack area. Handling of references can be extended
1674// in subclasses.
1675//
1676// To handle native pointers, use "L" in the shorty for an object reference, which simulates
1677// them with handles.
1678class ComputeNativeCallFrameSize {
1679 public:
1680  ComputeNativeCallFrameSize() : num_stack_entries_(0) {}
1681
1682  virtual ~ComputeNativeCallFrameSize() {}
1683
1684  uint32_t GetStackSize() const {
1685    return num_stack_entries_ * sizeof(uintptr_t);
1686  }
1687
1688  uint8_t* LayoutCallStack(uint8_t* sp8) const {
1689    sp8 -= GetStackSize();
1690    // Align by kStackAlignment.
1691    sp8 = reinterpret_cast<uint8_t*>(RoundDown(reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1692    return sp8;
1693  }
1694
1695  uint8_t* LayoutCallRegisterStacks(uint8_t* sp8, uintptr_t** start_gpr, uint32_t** start_fpr)
1696      const {
1697    // Assumption is OK right now, as we have soft-float arm
1698    size_t fregs = BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeFprArgs;
1699    sp8 -= fregs * sizeof(uintptr_t);
1700    *start_fpr = reinterpret_cast<uint32_t*>(sp8);
1701    size_t iregs = BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeGprArgs;
1702    sp8 -= iregs * sizeof(uintptr_t);
1703    *start_gpr = reinterpret_cast<uintptr_t*>(sp8);
1704    return sp8;
1705  }
1706
1707  uint8_t* LayoutNativeCall(uint8_t* sp8, uintptr_t** start_stack, uintptr_t** start_gpr,
1708                            uint32_t** start_fpr) const {
1709    // Native call stack.
1710    sp8 = LayoutCallStack(sp8);
1711    *start_stack = reinterpret_cast<uintptr_t*>(sp8);
1712
1713    // Put fprs and gprs below.
1714    sp8 = LayoutCallRegisterStacks(sp8, start_gpr, start_fpr);
1715
1716    // Return the new bottom.
1717    return sp8;
1718  }
1719
1720  virtual void WalkHeader(
1721      BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm ATTRIBUTE_UNUSED)
1722      REQUIRES_SHARED(Locks::mutator_lock_) {
1723  }
1724
1725  void Walk(const char* shorty, uint32_t shorty_len) REQUIRES_SHARED(Locks::mutator_lock_) {
1726    BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize> sm(this);
1727
1728    WalkHeader(&sm);
1729
1730    for (uint32_t i = 1; i < shorty_len; ++i) {
1731      Primitive::Type cur_type_ = Primitive::GetType(shorty[i]);
1732      switch (cur_type_) {
1733        case Primitive::kPrimNot:
1734          // TODO: fix abuse of mirror types.
1735          sm.AdvanceHandleScope(
1736              reinterpret_cast<mirror::Object*>(0x12345678));
1737          break;
1738
1739        case Primitive::kPrimBoolean:
1740        case Primitive::kPrimByte:
1741        case Primitive::kPrimChar:
1742        case Primitive::kPrimShort:
1743        case Primitive::kPrimInt:
1744          sm.AdvanceInt(0);
1745          break;
1746        case Primitive::kPrimFloat:
1747          sm.AdvanceFloat(0);
1748          break;
1749        case Primitive::kPrimDouble:
1750          sm.AdvanceDouble(0);
1751          break;
1752        case Primitive::kPrimLong:
1753          sm.AdvanceLong(0);
1754          break;
1755        default:
1756          LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty;
1757          UNREACHABLE();
1758      }
1759    }
1760
1761    num_stack_entries_ = sm.GetStackEntries();
1762  }
1763
1764  void PushGpr(uintptr_t /* val */) {
1765    // not optimizing registers, yet
1766  }
1767
1768  void PushFpr4(float /* val */) {
1769    // not optimizing registers, yet
1770  }
1771
1772  void PushFpr8(uint64_t /* val */) {
1773    // not optimizing registers, yet
1774  }
1775
1776  void PushStack(uintptr_t /* val */) {
1777    // counting is already done in the superclass
1778  }
1779
1780  virtual uintptr_t PushHandle(mirror::Object* /* ptr */) {
1781    return reinterpret_cast<uintptr_t>(nullptr);
1782  }
1783
1784 protected:
1785  uint32_t num_stack_entries_;
1786};
1787
1788class ComputeGenericJniFrameSize FINAL : public ComputeNativeCallFrameSize {
1789 public:
1790  explicit ComputeGenericJniFrameSize(bool critical_native)
1791    : num_handle_scope_references_(0), critical_native_(critical_native) {}
1792
1793  // Lays out the callee-save frame. Assumes that the incorrect frame corresponding to RefsAndArgs
1794  // is at *m = sp. Will update to point to the bottom of the save frame.
1795  //
1796  // Note: assumes ComputeAll() has been run before.
1797  void LayoutCalleeSaveFrame(Thread* self, ArtMethod*** m, void* sp, HandleScope** handle_scope)
1798      REQUIRES_SHARED(Locks::mutator_lock_) {
1799    ArtMethod* method = **m;
1800
1801    DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
1802
1803    uint8_t* sp8 = reinterpret_cast<uint8_t*>(sp);
1804
1805    // First, fix up the layout of the callee-save frame.
1806    // We have to squeeze in the HandleScope, and relocate the method pointer.
1807
1808    // "Free" the slot for the method.
1809    sp8 += sizeof(void*);  // In the callee-save frame we use a full pointer.
1810
1811    // Under the callee saves put handle scope and new method stack reference.
1812    size_t handle_scope_size = HandleScope::SizeOf(num_handle_scope_references_);
1813    size_t scope_and_method = handle_scope_size + sizeof(ArtMethod*);
1814
1815    sp8 -= scope_and_method;
1816    // Align by kStackAlignment.
1817    sp8 = reinterpret_cast<uint8_t*>(RoundDown(reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1818
1819    uint8_t* sp8_table = sp8 + sizeof(ArtMethod*);
1820    *handle_scope = HandleScope::Create(sp8_table, self->GetTopHandleScope(),
1821                                        num_handle_scope_references_);
1822
1823    // Add a slot for the method pointer, and fill it. Fix the pointer-pointer given to us.
1824    uint8_t* method_pointer = sp8;
1825    auto** new_method_ref = reinterpret_cast<ArtMethod**>(method_pointer);
1826    *new_method_ref = method;
1827    *m = new_method_ref;
1828  }
1829
1830  // Adds space for the cookie. Note: may leave stack unaligned.
1831  void LayoutCookie(uint8_t** sp) const {
1832    // Reference cookie and padding
1833    *sp -= 8;
1834  }
1835
1836  // Re-layout the callee-save frame (insert a handle-scope). Then add space for the cookie.
1837  // Returns the new bottom. Note: this may be unaligned.
1838  uint8_t* LayoutJNISaveFrame(Thread* self, ArtMethod*** m, void* sp, HandleScope** handle_scope)
1839      REQUIRES_SHARED(Locks::mutator_lock_) {
1840    // First, fix up the layout of the callee-save frame.
1841    // We have to squeeze in the HandleScope, and relocate the method pointer.
1842    LayoutCalleeSaveFrame(self, m, sp, handle_scope);
1843
1844    // The bottom of the callee-save frame is now where the method is, *m.
1845    uint8_t* sp8 = reinterpret_cast<uint8_t*>(*m);
1846
1847    // Add space for cookie.
1848    LayoutCookie(&sp8);
1849
1850    return sp8;
1851  }
1852
1853  // WARNING: After this, *sp won't be pointing to the method anymore!
1854  uint8_t* ComputeLayout(Thread* self, ArtMethod*** m, const char* shorty, uint32_t shorty_len,
1855                         HandleScope** handle_scope, uintptr_t** start_stack, uintptr_t** start_gpr,
1856                         uint32_t** start_fpr)
1857      REQUIRES_SHARED(Locks::mutator_lock_) {
1858    Walk(shorty, shorty_len);
1859
1860    // JNI part.
1861    uint8_t* sp8 = LayoutJNISaveFrame(self, m, reinterpret_cast<void*>(*m), handle_scope);
1862
1863    sp8 = LayoutNativeCall(sp8, start_stack, start_gpr, start_fpr);
1864
1865    // Return the new bottom.
1866    return sp8;
1867  }
1868
1869  uintptr_t PushHandle(mirror::Object* /* ptr */) OVERRIDE;
1870
1871  // Add JNIEnv* and jobj/jclass before the shorty-derived elements.
1872  void WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) OVERRIDE
1873      REQUIRES_SHARED(Locks::mutator_lock_);
1874
1875 private:
1876  uint32_t num_handle_scope_references_;
1877  const bool critical_native_;
1878};
1879
1880uintptr_t ComputeGenericJniFrameSize::PushHandle(mirror::Object* /* ptr */) {
1881  num_handle_scope_references_++;
1882  return reinterpret_cast<uintptr_t>(nullptr);
1883}
1884
1885void ComputeGenericJniFrameSize::WalkHeader(
1886    BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) {
1887  // First 2 parameters are always excluded for @CriticalNative.
1888  if (UNLIKELY(critical_native_)) {
1889    return;
1890  }
1891
1892  // JNIEnv
1893  sm->AdvancePointer(nullptr);
1894
1895  // Class object or this as first argument
1896  sm->AdvanceHandleScope(reinterpret_cast<mirror::Object*>(0x12345678));
1897}
1898
1899// Class to push values to three separate regions. Used to fill the native call part. Adheres to
1900// the template requirements of BuildGenericJniFrameStateMachine.
1901class FillNativeCall {
1902 public:
1903  FillNativeCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) :
1904      cur_gpr_reg_(gpr_regs), cur_fpr_reg_(fpr_regs), cur_stack_arg_(stack_args) {}
1905
1906  virtual ~FillNativeCall() {}
1907
1908  void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) {
1909    cur_gpr_reg_ = gpr_regs;
1910    cur_fpr_reg_ = fpr_regs;
1911    cur_stack_arg_ = stack_args;
1912  }
1913
1914  void PushGpr(uintptr_t val) {
1915    *cur_gpr_reg_ = val;
1916    cur_gpr_reg_++;
1917  }
1918
1919  void PushFpr4(float val) {
1920    *cur_fpr_reg_ = val;
1921    cur_fpr_reg_++;
1922  }
1923
1924  void PushFpr8(uint64_t val) {
1925    uint64_t* tmp = reinterpret_cast<uint64_t*>(cur_fpr_reg_);
1926    *tmp = val;
1927    cur_fpr_reg_ += 2;
1928  }
1929
1930  void PushStack(uintptr_t val) {
1931    *cur_stack_arg_ = val;
1932    cur_stack_arg_++;
1933  }
1934
1935  virtual uintptr_t PushHandle(mirror::Object*) REQUIRES_SHARED(Locks::mutator_lock_) {
1936    LOG(FATAL) << "(Non-JNI) Native call does not use handles.";
1937    UNREACHABLE();
1938  }
1939
1940 private:
1941  uintptr_t* cur_gpr_reg_;
1942  uint32_t* cur_fpr_reg_;
1943  uintptr_t* cur_stack_arg_;
1944};
1945
1946// Visits arguments on the stack placing them into a region lower down the stack for the benefit
1947// of transitioning into native code.
1948class BuildGenericJniFrameVisitor FINAL : public QuickArgumentVisitor {
1949 public:
1950  BuildGenericJniFrameVisitor(Thread* self,
1951                              bool is_static,
1952                              bool critical_native,
1953                              const char* shorty,
1954                              uint32_t shorty_len,
1955                              ArtMethod*** sp)
1956     : QuickArgumentVisitor(*sp, is_static, shorty, shorty_len),
1957       jni_call_(nullptr, nullptr, nullptr, nullptr, critical_native),
1958       sm_(&jni_call_) {
1959    ComputeGenericJniFrameSize fsc(critical_native);
1960    uintptr_t* start_gpr_reg;
1961    uint32_t* start_fpr_reg;
1962    uintptr_t* start_stack_arg;
1963    bottom_of_used_area_ = fsc.ComputeLayout(self, sp, shorty, shorty_len,
1964                                             &handle_scope_,
1965                                             &start_stack_arg,
1966                                             &start_gpr_reg, &start_fpr_reg);
1967
1968    jni_call_.Reset(start_gpr_reg, start_fpr_reg, start_stack_arg, handle_scope_);
1969
1970    // First 2 parameters are always excluded for CriticalNative methods.
1971    if (LIKELY(!critical_native)) {
1972      // jni environment is always first argument
1973      sm_.AdvancePointer(self->GetJniEnv());
1974
1975      if (is_static) {
1976        sm_.AdvanceHandleScope((**sp)->GetDeclaringClass());
1977      }  // else "this" reference is already handled by QuickArgumentVisitor.
1978    }
1979  }
1980
1981  void Visit() REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE;
1982
1983  void FinalizeHandleScope(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1984
1985  StackReference<mirror::Object>* GetFirstHandleScopeEntry() {
1986    return handle_scope_->GetHandle(0).GetReference();
1987  }
1988
1989  jobject GetFirstHandleScopeJObject() const REQUIRES_SHARED(Locks::mutator_lock_) {
1990    return handle_scope_->GetHandle(0).ToJObject();
1991  }
1992
1993  void* GetBottomOfUsedArea() const {
1994    return bottom_of_used_area_;
1995  }
1996
1997 private:
1998  // A class to fill a JNI call. Adds reference/handle-scope management to FillNativeCall.
1999  class FillJniCall FINAL : public FillNativeCall {
2000   public:
2001    FillJniCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args,
2002                HandleScope* handle_scope, bool critical_native)
2003      : FillNativeCall(gpr_regs, fpr_regs, stack_args),
2004                       handle_scope_(handle_scope),
2005        cur_entry_(0),
2006        critical_native_(critical_native) {}
2007
2008    uintptr_t PushHandle(mirror::Object* ref) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_);
2009
2010    void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args, HandleScope* scope) {
2011      FillNativeCall::Reset(gpr_regs, fpr_regs, stack_args);
2012      handle_scope_ = scope;
2013      cur_entry_ = 0U;
2014    }
2015
2016    void ResetRemainingScopeSlots() REQUIRES_SHARED(Locks::mutator_lock_) {
2017      // Initialize padding entries.
2018      size_t expected_slots = handle_scope_->NumberOfReferences();
2019      while (cur_entry_ < expected_slots) {
2020        handle_scope_->GetMutableHandle(cur_entry_++).Assign(nullptr);
2021      }
2022
2023      if (!critical_native_) {
2024        // Non-critical natives have at least the self class (jclass) or this (jobject).
2025        DCHECK_NE(cur_entry_, 0U);
2026      }
2027    }
2028
2029    bool CriticalNative() const {
2030      return critical_native_;
2031    }
2032
2033   private:
2034    HandleScope* handle_scope_;
2035    size_t cur_entry_;
2036    const bool critical_native_;
2037  };
2038
2039  HandleScope* handle_scope_;
2040  FillJniCall jni_call_;
2041  void* bottom_of_used_area_;
2042
2043  BuildNativeCallFrameStateMachine<FillJniCall> sm_;
2044
2045  DISALLOW_COPY_AND_ASSIGN(BuildGenericJniFrameVisitor);
2046};
2047
2048uintptr_t BuildGenericJniFrameVisitor::FillJniCall::PushHandle(mirror::Object* ref) {
2049  uintptr_t tmp;
2050  MutableHandle<mirror::Object> h = handle_scope_->GetMutableHandle(cur_entry_);
2051  h.Assign(ref);
2052  tmp = reinterpret_cast<uintptr_t>(h.ToJObject());
2053  cur_entry_++;
2054  return tmp;
2055}
2056
2057void BuildGenericJniFrameVisitor::Visit() {
2058  Primitive::Type type = GetParamPrimitiveType();
2059  switch (type) {
2060    case Primitive::kPrimLong: {
2061      jlong long_arg;
2062      if (IsSplitLongOrDouble()) {
2063        long_arg = ReadSplitLongParam();
2064      } else {
2065        long_arg = *reinterpret_cast<jlong*>(GetParamAddress());
2066      }
2067      sm_.AdvanceLong(long_arg);
2068      break;
2069    }
2070    case Primitive::kPrimDouble: {
2071      uint64_t double_arg;
2072      if (IsSplitLongOrDouble()) {
2073        // Read into union so that we don't case to a double.
2074        double_arg = ReadSplitLongParam();
2075      } else {
2076        double_arg = *reinterpret_cast<uint64_t*>(GetParamAddress());
2077      }
2078      sm_.AdvanceDouble(double_arg);
2079      break;
2080    }
2081    case Primitive::kPrimNot: {
2082      StackReference<mirror::Object>* stack_ref =
2083          reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
2084      sm_.AdvanceHandleScope(stack_ref->AsMirrorPtr());
2085      break;
2086    }
2087    case Primitive::kPrimFloat:
2088      sm_.AdvanceFloat(*reinterpret_cast<float*>(GetParamAddress()));
2089      break;
2090    case Primitive::kPrimBoolean:  // Fall-through.
2091    case Primitive::kPrimByte:     // Fall-through.
2092    case Primitive::kPrimChar:     // Fall-through.
2093    case Primitive::kPrimShort:    // Fall-through.
2094    case Primitive::kPrimInt:      // Fall-through.
2095      sm_.AdvanceInt(*reinterpret_cast<jint*>(GetParamAddress()));
2096      break;
2097    case Primitive::kPrimVoid:
2098      LOG(FATAL) << "UNREACHABLE";
2099      UNREACHABLE();
2100  }
2101}
2102
2103void BuildGenericJniFrameVisitor::FinalizeHandleScope(Thread* self) {
2104  // Clear out rest of the scope.
2105  jni_call_.ResetRemainingScopeSlots();
2106  if (!jni_call_.CriticalNative()) {
2107    // Install HandleScope.
2108    self->PushHandleScope(handle_scope_);
2109  }
2110}
2111
2112#if defined(__arm__) || defined(__aarch64__)
2113extern "C" const void* artFindNativeMethod();
2114#else
2115extern "C" const void* artFindNativeMethod(Thread* self);
2116#endif
2117
2118static uint64_t artQuickGenericJniEndJNIRef(Thread* self,
2119                                            uint32_t cookie,
2120                                            bool fast_native ATTRIBUTE_UNUSED,
2121                                            jobject l,
2122                                            jobject lock) {
2123  // TODO: add entrypoints for @FastNative returning objects.
2124  if (lock != nullptr) {
2125    return reinterpret_cast<uint64_t>(JniMethodEndWithReferenceSynchronized(l, cookie, lock, self));
2126  } else {
2127    return reinterpret_cast<uint64_t>(JniMethodEndWithReference(l, cookie, self));
2128  }
2129}
2130
2131static void artQuickGenericJniEndJNINonRef(Thread* self,
2132                                           uint32_t cookie,
2133                                           bool fast_native,
2134                                           jobject lock) {
2135  if (lock != nullptr) {
2136    JniMethodEndSynchronized(cookie, lock, self);
2137    // Ignore "fast_native" here because synchronized functions aren't very fast.
2138  } else {
2139    if (UNLIKELY(fast_native)) {
2140      JniMethodFastEnd(cookie, self);
2141    } else {
2142      JniMethodEnd(cookie, self);
2143    }
2144  }
2145}
2146
2147/*
2148 * Initializes an alloca region assumed to be directly below sp for a native call:
2149 * Create a HandleScope and call stack and fill a mini stack with values to be pushed to registers.
2150 * The final element on the stack is a pointer to the native code.
2151 *
2152 * On entry, the stack has a standard callee-save frame above sp, and an alloca below it.
2153 * We need to fix this, as the handle scope needs to go into the callee-save frame.
2154 *
2155 * The return of this function denotes:
2156 * 1) How many bytes of the alloca can be released, if the value is non-negative.
2157 * 2) An error, if the value is negative.
2158 */
2159extern "C" TwoWordReturn artQuickGenericJniTrampoline(Thread* self, ArtMethod** sp)
2160    REQUIRES_SHARED(Locks::mutator_lock_) {
2161  ArtMethod* called = *sp;
2162  DCHECK(called->IsNative()) << called->PrettyMethod(true);
2163  // Fix up a callee-save frame at the bottom of the stack (at `*sp`,
2164  // above the alloca region) while we check for optimization
2165  // annotations, thus allowing stack walking until the completion of
2166  // the JNI frame creation.
2167  //
2168  // Note however that the Generic JNI trampoline does not expect
2169  // exception being thrown at that stage.
2170  *sp = Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
2171  self->SetTopOfStack(sp);
2172  uint32_t shorty_len = 0;
2173  const char* shorty = called->GetShorty(&shorty_len);
2174  // Optimization annotations lookup does not try to resolve classes,
2175  // as this may throw an exception, which is not supported by the
2176  // Generic JNI trampoline at this stage; instead, method's
2177  // annotations' classes are looked up in the bootstrap class
2178  // loader's resolved types (which won't trigger an exception).
2179  bool critical_native = called->IsAnnotatedWithCriticalNative();
2180  // ArtMethod::IsAnnotatedWithCriticalNative should not throw
2181  // an exception; clear it if it happened anyway.
2182  // TODO: Revisit this code path and turn this into a CHECK(!self->IsExceptionPending()).
2183  if (self->IsExceptionPending()) {
2184    self->ClearException();
2185  }
2186  bool fast_native = called->IsAnnotatedWithFastNative();
2187  // ArtMethod::IsAnnotatedWithFastNative should not throw
2188  // an exception; clear it if it happened anyway.
2189  // TODO: Revisit this code path and turn this into a CHECK(!self->IsExceptionPending()).
2190  if (self->IsExceptionPending()) {
2191    self->ClearException();
2192  }
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 = Instruction::At(&code_item->insns_[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 = Instruction::At(&code->insns_[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<5> 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::Class> caller_class(hs.NewHandle(caller_method->GetDeclaringClass()));
2626  Handle<mirror::MethodType> method_type(hs.NewHandle(linker->ResolveMethodType(
2627      *dex_file, proto_idx,
2628      hs.NewHandle<mirror::DexCache>(caller_class->GetDexCache()),
2629      hs.NewHandle<mirror::ClassLoader>(caller_class->GetClassLoader()))));
2630  // This implies we couldn't resolve one or more types in this method handle.
2631  if (UNLIKELY(method_type.IsNull())) {
2632    CHECK(self->IsExceptionPending());
2633    return static_cast<uintptr_t>('V');
2634  }
2635
2636  DCHECK_EQ(ArtMethod::NumArgRegisters(shorty) + 1u, (uint32_t)inst->VRegA());
2637  DCHECK_EQ(resolved_method->IsStatic(), kMethodIsStatic);
2638
2639  // Fix references before constructing the shadow frame.
2640  gc_visitor.FixupReferences();
2641
2642  // Construct shadow frame placing arguments consecutively from |first_arg|.
2643  const bool is_range = (inst->Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE);
2644  const size_t num_vregs = is_range ? inst->VRegA_4rcc() : inst->VRegA_45cc();
2645  const size_t first_arg = 0;
2646  ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
2647      CREATE_SHADOW_FRAME(num_vregs, /* link */ nullptr, resolved_method, dex_pc);
2648  ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
2649  ScopedStackedShadowFramePusher
2650      frame_pusher(self, shadow_frame, StackedShadowFrameType::kShadowFrameUnderConstruction);
2651  BuildQuickShadowFrameVisitor shadow_frame_builder(sp,
2652                                                    kMethodIsStatic,
2653                                                    shorty,
2654                                                    strlen(shorty),
2655                                                    shadow_frame,
2656                                                    first_arg);
2657  shadow_frame_builder.VisitArguments();
2658
2659  // Push a transition back into managed code onto the linked list in thread.
2660  ManagedStack fragment;
2661  self->PushManagedStackFragment(&fragment);
2662
2663  // Call DoInvokePolymorphic with |is_range| = true, as shadow frame has argument registers in
2664  // consecutive order.
2665  uint32_t unused_args[Instruction::kMaxVarArgRegs] = {};
2666  uint32_t first_callee_arg = first_arg + 1;
2667  if (!DoInvokePolymorphic<true /* is_range */>(self,
2668                                                resolved_method,
2669                                                *shadow_frame,
2670                                                method_handle,
2671                                                method_type,
2672                                                unused_args,
2673                                                first_callee_arg,
2674                                                result)) {
2675    DCHECK(self->IsExceptionPending());
2676  }
2677
2678  // Pop transition record.
2679  self->PopManagedStackFragment(fragment);
2680
2681  return static_cast<uintptr_t>(shorty[0]);
2682}
2683
2684}  // namespace art
2685