1 /*
  2  * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifdef COMPILER2
 26 #include "asm/macroAssembler.hpp"
 27 #include "asm/macroAssembler.inline.hpp"
 28 #include "code/vmreg.hpp"
 29 #include "interpreter/interpreter.hpp"
 30 #include "opto/runtime.hpp"
 31 #include "runtime/sharedRuntime.hpp"
 32 #include "runtime/stubRoutines.hpp"
 33 #include "runtime/vframeArray.hpp"
 34 #include "utilities/globalDefinitions.hpp"
 35 #include "vmreg_x86.inline.hpp"
 36 
 37 class SimpleRuntimeFrame {
 38 
 39   public:
 40 
 41   // Most of the runtime stubs have this simple frame layout.
 42   // This class exists to make the layout shared in one place.
 43   // Offsets are for compiler stack slots, which are jints.
 44   enum layout {
 45     // The frame sender code expects that rbp will be in the "natural" place and
 46     // will override any oopMap setting for it. We must therefore force the layout
 47     // so that it agrees with the frame sender code.
 48     rbp_off = frame::arg_reg_save_area_bytes/BytesPerInt,
 49     rbp_off2,
 50     return_off, return_off2,
 51     framesize
 52   };
 53 };
 54 
 55 #define __ masm->
 56 
 57 //------------------------------generate_uncommon_trap_blob--------------------
 58 UncommonTrapBlob* OptoRuntime::generate_uncommon_trap_blob() {
 59   // Allocate space for the code
 60   ResourceMark rm;
 61   // Setup code generation tools
 62   const char* name = OptoRuntime::stub_name(OptoStubId::uncommon_trap_id);
 63   CodeBuffer buffer(name, 2048, 1024);
 64   if (buffer.blob() == nullptr) {
 65     return nullptr;
 66   }
 67   MacroAssembler* masm = new MacroAssembler(&buffer);
 68 
 69   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
 70 
 71   address start = __ pc();
 72 
 73   // Push self-frame.  We get here with a return address on the
 74   // stack, so rsp is 8-byte aligned until we allocate our frame.
 75   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog!
 76 
 77   // No callee saved registers. rbp is assumed implicitly saved
 78   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
 79 
 80   // compiler left unloaded_class_index in j_rarg0 move to where the
 81   // runtime expects it.
 82   __ movl(c_rarg1, j_rarg0);
 83 
 84   __ set_last_Java_frame(noreg, noreg, nullptr, rscratch1);
 85 
 86   // Call C code.  Need thread but NOT official VM entry
 87   // crud.  We cannot block on this call, no GC can happen.  Call should
 88   // capture callee-saved registers as well as return values.
 89   // Thread is in rdi already.
 90   //
 91   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
 92 
 93   __ mov(c_rarg0, r15_thread);
 94   __ movl(c_rarg2, Deoptimization::Unpack_uncommon_trap);
 95   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
 96 
 97   // Set an oopmap for the call site
 98   OopMapSet* oop_maps = new OopMapSet();
 99   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
100 
101   // location of rbp is known implicitly by the frame sender code
102 
103   oop_maps->add_gc_map(__ pc() - start, map);
104 
105   __ reset_last_Java_frame(false);
106 
107   // Load UnrollBlock* into rdi
108   __ mov(rdi, rax);
109 
110 #ifdef ASSERT
111   { Label L;
112     __ cmpptr(Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset()),
113               Deoptimization::Unpack_uncommon_trap);
114     __ jcc(Assembler::equal, L);
115     __ stop("OptoRuntime::generate_uncommon_trap_blob: expected Unpack_uncommon_trap");
116     __ bind(L);
117   }
118 #endif
119 
120   // Pop all the frames we must move/replace.
121   //
122   // Frame picture (youngest to oldest)
123   // 1: self-frame (no frame link)
124   // 2: deopting frame  (no frame link)
125   // 3: caller of deopting frame (could be compiled/interpreted).
126 
127   // Pop self-frame.  We have no frame, and must rely only on rax and rsp.
128   __ addptr(rsp, (SimpleRuntimeFrame::framesize - 2) << LogBytesPerInt); // Epilog!
129 
130   // Pop deoptimized frame (int)
131   __ movl(rcx, Address(rdi,
132                        Deoptimization::UnrollBlock::
133                        size_of_deoptimized_frame_offset()));
134   __ addptr(rsp, rcx);
135 
136   // rsp should be pointing at the return address to the caller (3)
137 
138   // Pick up the initial fp we should save
139   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
140   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset()));
141 
142 #ifdef ASSERT
143   // Compilers generate code that bang the stack by as much as the
144   // interpreter would need. So this stack banging should never
145   // trigger a fault. Verify that it does not on non product builds.
146   __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset()));
147   __ bang_stack_size(rbx, rcx);
148 #endif
149 
150   // Load address of array of frame pcs into rcx (address*)
151   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset()));
152 
153   // Trash the return pc
154   __ addptr(rsp, wordSize);
155 
156   // Load address of array of frame sizes into rsi (intptr_t*)
157   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock:: frame_sizes_offset()));
158 
159   // Counter
160   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock:: number_of_frames_offset())); // (int)
161 
162   // Now adjust the caller's stack to make up for the extra locals but
163   // record the original sp so that we can save it in the skeletal
164   // interpreter frame and the stack walking of interpreter_sender
165   // will get the unextended sp value and not the "real" sp value.
166 
167   const Register sender_sp = r8;
168 
169   __ mov(sender_sp, rsp);
170   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock:: caller_adjustment_offset())); // (int)
171   __ subptr(rsp, rbx);
172 
173   // Push interpreter frames in a loop
174   Label loop;
175   __ bind(loop);
176   __ movptr(rbx, Address(rsi, 0)); // Load frame size
177   __ subptr(rbx, 2 * wordSize);    // We'll push pc and rbp by hand
178   __ pushptr(Address(rcx, 0));     // Save return address
179   __ enter();                      // Save old & set new rbp
180   __ subptr(rsp, rbx);             // Prolog
181   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize),
182             sender_sp);            // Make it walkable
183   // This value is corrected by layout_activation_impl
184   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
185   __ mov(sender_sp, rsp);          // Pass sender_sp to next frame
186   __ addptr(rsi, wordSize);        // Bump array pointer (sizes)
187   __ addptr(rcx, wordSize);        // Bump array pointer (pcs)
188   __ decrementl(rdx);              // Decrement counter
189   __ jcc(Assembler::notZero, loop);
190   __ pushptr(Address(rcx, 0));     // Save final return address
191 
192   // Re-push self-frame
193   __ enter();                 // Save old & set new rbp
194   __ subptr(rsp, (SimpleRuntimeFrame::framesize - 4) << LogBytesPerInt);
195                               // Prolog
196 
197   // Use rbp because the frames look interpreted now
198   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
199   // Don't need the precise return PC here, just precise enough to point into this code blob.
200   address the_pc = __ pc();
201   __ set_last_Java_frame(noreg, rbp, the_pc, rscratch1);
202 
203   // Call C code.  Need thread but NOT official VM entry
204   // crud.  We cannot block on this call, no GC can happen.  Call should
205   // restore return values to their stack-slots with the new SP.
206   // Thread is in rdi already.
207   //
208   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
209 
210   __ andptr(rsp, -(StackAlignmentInBytes)); // Align SP as required by ABI
211   __ mov(c_rarg0, r15_thread);
212   __ movl(c_rarg1, Deoptimization::Unpack_uncommon_trap);
213   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
214 
215   // Set an oopmap for the call site
216   // Use the same PC we used for the last java frame
217   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
218 
219   // Clear fp AND pc
220   __ reset_last_Java_frame(true);
221 
222   // Pop self-frame.
223   __ leave();                 // Epilog
224 
225   // Jump to interpreter
226   __ ret(0);
227 
228   // Make sure all code is generated
229   masm->flush();
230 
231   return UncommonTrapBlob::create(&buffer, oop_maps,
232                                                  SimpleRuntimeFrame::framesize >> 1);
233 }
234 
235 //------------------------------generate_exception_blob---------------------------
236 // creates exception blob at the end
237 // Using exception blob, this code is jumped from a compiled method.
238 // (see emit_exception_handler in x86_64.ad file)
239 //
240 // Given an exception pc at a call we call into the runtime for the
241 // handler in this method. This handler might merely restore state
242 // (i.e. callee save registers) unwind the frame and jump to the
243 // exception handler for the nmethod if there is no Java level handler
244 // for the nmethod.
245 //
246 // This code is entered with a jmp.
247 //
248 // Arguments:
249 //   rax: exception oop
250 //   rdx: exception pc
251 //
252 // Results:
253 //   rax: exception oop
254 //   rdx: exception pc in caller or ???
255 //   destination: exception handler of caller
256 //
257 // Note: the exception pc MUST be at a call (precise debug information)
258 //       Registers rax, rdx, rcx, rsi, rdi, r8-r11 are not callee saved.
259 //
260 
261 ExceptionBlob* OptoRuntime::generate_exception_blob() {
262   assert(!OptoRuntime::is_callee_saved_register(RDX_num), "");
263   assert(!OptoRuntime::is_callee_saved_register(RAX_num), "");
264   assert(!OptoRuntime::is_callee_saved_register(RCX_num), "");
265 
266   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
267 
268   // Allocate space for the code
269   ResourceMark rm;
270   // Setup code generation tools
271   const char* name = OptoRuntime::stub_name(OptoStubId::exception_id);
272   CodeBuffer buffer(name, 2048, 1024);
273   if (buffer.blob() == nullptr) {
274     return nullptr;
275   }
276   MacroAssembler* masm = new MacroAssembler(&buffer);
277 
278 
279   address start = __ pc();
280 
281   // Exception pc is 'return address' for stack walker
282   __ push(rdx);
283   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Prolog
284 
285   // Save callee-saved registers.  See x86_64.ad.
286 
287   // rbp is an implicitly saved callee saved register (i.e., the calling
288   // convention will save/restore it in the prolog/epilog). Other than that
289   // there are no callee save registers now that adapter frames are gone.
290 
291   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
292 
293   // Store exception in Thread object. We cannot pass any arguments to the
294   // handle_exception call, since we do not want to make any assumption
295   // about the size of the frame where the exception happened in.
296   // c_rarg0 is either rdi (Linux) or rcx (Windows).
297   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()),rax);
298   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
299 
300   // This call does all the hard work.  It checks if an exception handler
301   // exists in the method.
302   // If so, it returns the handler address.
303   // If not, it prepares for stack-unwinding, restoring the callee-save
304   // registers of the frame being removed.
305   //
306   // address OptoRuntime::handle_exception_C(JavaThread* thread)
307 
308   // At a method handle call, the stack may not be properly aligned
309   // when returning with an exception.
310   address the_pc = __ pc();
311   __ set_last_Java_frame(noreg, noreg, the_pc, rscratch1);
312   __ mov(c_rarg0, r15_thread);
313   __ andptr(rsp, -(StackAlignmentInBytes));    // Align stack
314   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
315 
316   // Set an oopmap for the call site.  This oopmap will only be used if we
317   // are unwinding the stack.  Hence, all locations will be dead.
318   // Callee-saved registers will be the same as the frame above (i.e.,
319   // handle_exception_stub), since they were restored when we got the
320   // exception.
321 
322   OopMapSet* oop_maps = new OopMapSet();
323 
324   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
325 
326   __ reset_last_Java_frame(false);
327 
328   // Restore callee-saved registers
329 
330   // rbp is an implicitly saved callee-saved register (i.e., the calling
331   // convention will save restore it in prolog/epilog) Other than that
332   // there are no callee save registers now that adapter frames are gone.
333 
334   __ movptr(rbp, Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt));
335 
336   __ addptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog
337   __ pop(rdx);                  // No need for exception pc anymore
338 
339   // rax: exception handler
340 
341   // We have a handler in rax (could be deopt blob).
342   __ mov(r8, rax);
343 
344   // Get the exception oop
345   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
346   // Get the exception pc in case we are deoptimized
347   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
348 #ifdef ASSERT
349   __ movptr(Address(r15_thread, JavaThread::exception_handler_pc_offset()), NULL_WORD);
350   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), NULL_WORD);
351 #endif
352   // Clear the exception oop so GC no longer processes it as a root.
353   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), NULL_WORD);
354 
355   // rax: exception oop
356   // r8:  exception handler
357   // rdx: exception pc
358   // Jump to handler
359 
360   __ jmp(r8);
361 
362   // Make sure all code is generated
363   masm->flush();
364 
365   // Set exception blob
366   return ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
367 }
368 #endif // COMPILER2