1 /*
2  * Copyright (C) 2011 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 #ifndef ART_COMPILER_UTILS_JNI_MACRO_ASSEMBLER_H_
18 #define ART_COMPILER_UTILS_JNI_MACRO_ASSEMBLER_H_
19 
20 #include <vector>
21 
22 #include <android-base/logging.h>
23 
24 #include "arch/instruction_set.h"
25 #include "base/arena_allocator.h"
26 #include "base/arena_object.h"
27 #include "base/array_ref.h"
28 #include "base/enums.h"
29 #include "base/macros.h"
30 #include "managed_register.h"
31 #include "offsets.h"
32 
33 namespace art HIDDEN {
34 
35 class ArenaAllocator;
36 class DebugFrameOpCodeWriterForAssembler;
37 class InstructionSetFeatures;
38 class MemoryRegion;
39 class JNIMacroLabel;
40 
41 enum class JNIMacroUnaryCondition {
42   kZero,
43   kNotZero
44 };
45 
46 class ArgumentLocation {
47  public:
ArgumentLocation(ManagedRegister reg,size_t size)48   ArgumentLocation(ManagedRegister reg, size_t size)
49       : reg_(reg), frame_offset_(0u), size_(size) {
50     DCHECK(reg.IsRegister());
51   }
52 
ArgumentLocation(FrameOffset frame_offset,size_t size)53   ArgumentLocation(FrameOffset frame_offset, size_t size)
54       : reg_(ManagedRegister::NoRegister()), frame_offset_(frame_offset), size_(size) {}
55 
IsRegister()56   bool IsRegister() const {
57     return reg_.IsRegister();
58   }
59 
GetRegister()60   ManagedRegister GetRegister() const {
61     DCHECK(IsRegister());
62     return reg_;
63   }
64 
GetFrameOffset()65   FrameOffset GetFrameOffset() const {
66     DCHECK(!IsRegister());
67     return frame_offset_;
68   }
69 
GetSize()70   size_t GetSize() const {
71     return size_;
72   }
73 
74  private:
75   ManagedRegister reg_;
76   FrameOffset frame_offset_;
77   size_t size_;
78 };
79 
80 template <PointerSize kPointerSize>
81 class JNIMacroAssembler : public DeletableArenaObject<kArenaAllocAssembler> {
82  public:
83   static std::unique_ptr<JNIMacroAssembler<kPointerSize>> Create(
84       ArenaAllocator* allocator,
85       InstructionSet instruction_set,
86       const InstructionSetFeatures* instruction_set_features = nullptr);
87 
88   // Finalize the code; emit slow paths, fixup branches, add literal pool, etc.
89   virtual void FinalizeCode() = 0;
90 
91   // Size of generated code
92   virtual size_t CodeSize() const = 0;
93 
94   // Copy instructions out of assembly buffer into the given region of memory
95   virtual void FinalizeInstructions(const MemoryRegion& region) = 0;
96 
97   // Emit code that will create an activation on the stack
98   virtual void BuildFrame(size_t frame_size,
99                           ManagedRegister method_reg,
100                           ArrayRef<const ManagedRegister> callee_save_regs) = 0;
101 
102   // Emit code that will remove an activation from the stack
103   //
104   // Argument `may_suspend` must be `true` if the compiled method may be
105   // suspended during its execution (otherwise `false`, if it is impossible
106   // to suspend during its execution).
107   virtual void RemoveFrame(size_t frame_size,
108                            ArrayRef<const ManagedRegister> callee_save_regs,
109                            bool may_suspend) = 0;
110 
111   virtual void IncreaseFrameSize(size_t adjust) = 0;
112   virtual void DecreaseFrameSize(size_t adjust) = 0;
113 
114   // Return the same core register but with correct size if the architecture-specific
115   // ManagedRegister has different representation for different sizes.
116   virtual ManagedRegister CoreRegisterWithSize(ManagedRegister src, size_t size) = 0;
117 
118   // Store routines
119   virtual void Store(FrameOffset offs, ManagedRegister src, size_t size) = 0;
120   virtual void Store(ManagedRegister base, MemberOffset offs, ManagedRegister src, size_t size) = 0;
121   virtual void StoreRawPtr(FrameOffset dest, ManagedRegister src) = 0;
122 
123   // Stores stack pointer by tagging it if required so we can walk the stack. In debuggable runtimes
124   // we use tag to tell if we are using JITed code or AOT code. In non-debuggable runtimes we never
125   // use JITed code when AOT code is present. So checking for AOT code is sufficient to detect which
126   // code is being executed. We avoid tagging in non-debuggable runtimes to reduce instructions.
127   virtual void StoreStackPointerToThread(ThreadOffset<kPointerSize> thr_offs, bool tag_sp) = 0;
128 
129   // Load routines
130   virtual void Load(ManagedRegister dest, FrameOffset src, size_t size) = 0;
131   virtual void Load(ManagedRegister dest, ManagedRegister base, MemberOffset offs, size_t size) = 0;
132 
133   virtual void LoadRawPtrFromThread(ManagedRegister dest, ThreadOffset<kPointerSize> offs) = 0;
134 
135   // Copying routines
136 
137   // Move arguments from `srcs` locations to `dests` locations.
138   //
139   // References shall be spilled to `refs` frame offsets (kInvalidReferenceOffset indicates
140   // a non-reference type) if they are in registers and corresponding `dests` shall be
141   // filled with `jobject` replacements. If the first argument is a reference, it is
142   // assumed to be `this` and cannot be null, all other reference arguments can be null.
143   virtual void MoveArguments(ArrayRef<ArgumentLocation> dests,
144                              ArrayRef<ArgumentLocation> srcs,
145                              ArrayRef<FrameOffset> refs) = 0;
146 
147   virtual void Move(ManagedRegister dest, ManagedRegister src, size_t size) = 0;
148 
149   virtual void Move(ManagedRegister dst, size_t value) = 0;
150 
151   // Sign extension
152   virtual void SignExtend(ManagedRegister mreg, size_t size) = 0;
153 
154   // Zero extension
155   virtual void ZeroExtend(ManagedRegister mreg, size_t size) = 0;
156 
157   // Exploit fast access in managed code to Thread::Current()
158   virtual void GetCurrentThread(ManagedRegister dest) = 0;
159   virtual void GetCurrentThread(FrameOffset dest_offset) = 0;
160 
161   // Decode JNI transition or local `jobject`. For (weak) global `jobject`, jump to slow path.
162   virtual void DecodeJNITransitionOrLocalJObject(ManagedRegister reg,
163                                                  JNIMacroLabel* slow_path,
164                                                  JNIMacroLabel* resume) = 0;
165 
166   // Heap::VerifyObject on src. In some cases (such as a reference to this) we
167   // know that src may not be null.
168   virtual void VerifyObject(ManagedRegister src, bool could_be_null) = 0;
169   virtual void VerifyObject(FrameOffset src, bool could_be_null) = 0;
170 
171   // Jump to address held at [base+offset] (used for tail calls).
172   virtual void Jump(ManagedRegister base, Offset offset) = 0;
173 
174   // Call to address held at [base+offset]
175   virtual void Call(ManagedRegister base, Offset offset) = 0;
176   virtual void CallFromThread(ThreadOffset<kPointerSize> offset) = 0;
177 
178   // Generate fast-path for transition to Native. Go to `label` if any thread flag is set.
179   // The implementation can use `scratch_regs` which should be callee save core registers
180   // (already saved before this call) and must preserve all argument registers.
181   virtual void TryToTransitionFromRunnableToNative(
182       JNIMacroLabel* label, ArrayRef<const ManagedRegister> scratch_regs) = 0;
183 
184   // Generate fast-path for transition to Runnable. Go to `label` if any thread flag is set.
185   // The implementation can use `scratch_regs` which should be core argument registers
186   // not used as return registers and it must preserve the `return_reg` if any.
187   virtual void TryToTransitionFromNativeToRunnable(JNIMacroLabel* label,
188                                                    ArrayRef<const ManagedRegister> scratch_regs,
189                                                    ManagedRegister return_reg) = 0;
190 
191   // Generate suspend check and branch to `label` if there is a pending suspend request.
192   virtual void SuspendCheck(JNIMacroLabel* label) = 0;
193 
194   // Generate code to check if Thread::Current()->exception_ is non-null
195   // and branch to the `label` if it is.
196   virtual void ExceptionPoll(JNIMacroLabel* label) = 0;
197   // Deliver pending exception.
198   virtual void DeliverPendingException() = 0;
199 
200   // Create a new label that can be used with Jump/Bind calls.
201   virtual std::unique_ptr<JNIMacroLabel> CreateLabel() = 0;
202   // Emit an unconditional jump to the label.
203   virtual void Jump(JNIMacroLabel* label) = 0;
204   // Emit a conditional jump to the label by applying a unary condition test to the GC marking flag.
205   virtual void TestGcMarking(JNIMacroLabel* label, JNIMacroUnaryCondition cond) = 0;
206   // Emit a conditional jump to the label by applying a unary condition test to object's mark bit.
207   virtual void TestMarkBit(ManagedRegister ref,
208                            JNIMacroLabel* label,
209                            JNIMacroUnaryCondition cond) = 0;
210   // Emit a conditional jump to label if the loaded value from specified locations is not zero.
211   virtual void TestByteAndJumpIfNotZero(uintptr_t address, JNIMacroLabel* label) = 0;
212   // Code at this offset will serve as the target for the Jump call.
213   virtual void Bind(JNIMacroLabel* label) = 0;
214 
~JNIMacroAssembler()215   virtual ~JNIMacroAssembler() {}
216 
217   /**
218    * @brief Buffer of DWARF's Call Frame Information opcodes.
219    * @details It is used by debuggers and other tools to unwind the call stack.
220    */
221   virtual DebugFrameOpCodeWriterForAssembler& cfi() = 0;
222 
SetEmitRunTimeChecksInDebugMode(bool value)223   void SetEmitRunTimeChecksInDebugMode(bool value) {
224     emit_run_time_checks_in_debug_mode_ = value;
225   }
226 
227   static constexpr FrameOffset kInvalidReferenceOffset = FrameOffset(0);
228 
229  protected:
JNIMacroAssembler()230   JNIMacroAssembler() {}
231 
232   // Should run-time checks be emitted in debug mode?
233   bool emit_run_time_checks_in_debug_mode_ = false;
234 };
235 
236 // A "Label" class used with the JNIMacroAssembler
237 // allowing one to use branches (jumping from one place to another).
238 //
239 // This is just an interface, so every platform must provide
240 // its own implementation of it.
241 //
242 // It is only safe to use a label created
243 // via JNIMacroAssembler::CreateLabel with that same macro assembler.
244 class JNIMacroLabel {
245  public:
246   virtual ~JNIMacroLabel() = 0;
247 
248   const InstructionSet isa_;
249  protected:
JNIMacroLabel(InstructionSet isa)250   explicit JNIMacroLabel(InstructionSet isa) : isa_(isa) {}
251 };
252 
~JNIMacroLabel()253 inline JNIMacroLabel::~JNIMacroLabel() {
254   // Compulsory definition for a pure virtual destructor
255   // to avoid linking errors.
256 }
257 
258 template <typename T, PointerSize kPointerSize>
259 class JNIMacroAssemblerFwd : public JNIMacroAssembler<kPointerSize> {
260  public:
FinalizeCode()261   void FinalizeCode() override {
262     asm_.FinalizeCode();
263   }
264 
CodeSize()265   size_t CodeSize() const override {
266     return asm_.CodeSize();
267   }
268 
FinalizeInstructions(const MemoryRegion & region)269   void FinalizeInstructions(const MemoryRegion& region) override {
270     asm_.FinalizeInstructions(region);
271   }
272 
cfi()273   DebugFrameOpCodeWriterForAssembler& cfi() override {
274     return asm_.cfi();
275   }
276 
277  protected:
JNIMacroAssemblerFwd(ArenaAllocator * allocator)278   explicit JNIMacroAssemblerFwd(ArenaAllocator* allocator) : asm_(allocator) {}
279 
280   T asm_;
281 };
282 
283 template <typename Self, typename PlatformLabel, InstructionSet kIsa>
284 class JNIMacroLabelCommon : public JNIMacroLabel {
285  public:
Cast(JNIMacroLabel * label)286   static Self* Cast(JNIMacroLabel* label) {
287     CHECK(label != nullptr);
288     CHECK_EQ(kIsa, label->isa_);
289 
290     return reinterpret_cast<Self*>(label);
291   }
292 
293  protected:
AsPlatformLabel()294   PlatformLabel* AsPlatformLabel() {
295     return &label_;
296   }
297 
JNIMacroLabelCommon()298   JNIMacroLabelCommon() : JNIMacroLabel(kIsa) {
299   }
300 
~JNIMacroLabelCommon()301   ~JNIMacroLabelCommon() override {}
302 
303  private:
304   PlatformLabel label_;
305 };
306 
307 }  // namespace art
308 
309 #endif  // ART_COMPILER_UTILS_JNI_MACRO_ASSEMBLER_H_
310