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 void OptoRuntime::generate_uncommon_trap_blob() {
 59   // Allocate space for the code
 60   ResourceMark rm;
 61   // Setup code generation tools
 62   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
 63   MacroAssembler* masm = new MacroAssembler(&buffer);
 64 
 65   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
 66 
 67   address start = __ pc();
 68 
 69   // Push self-frame.  We get here with a return address on the
 70   // stack, so rsp is 8-byte aligned until we allocate our frame.
 71   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog!
 72 
 73   // No callee saved registers. rbp is assumed implicitly saved
 74   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
 75 
 76   // compiler left unloaded_class_index in j_rarg0 move to where the
 77   // runtime expects it.
 78   __ movl(c_rarg1, j_rarg0);
 79 
 80   __ set_last_Java_frame(noreg, noreg, nullptr, rscratch1);
 81 
 82   // Call C code.  Need thread but NOT official VM entry
 83   // crud.  We cannot block on this call, no GC can happen.  Call should
 84   // capture callee-saved registers as well as return values.
 85   // Thread is in rdi already.
 86   //
 87   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
 88 
 89   __ mov(c_rarg0, r15_thread);
 90   __ movl(c_rarg2, Deoptimization::Unpack_uncommon_trap);
 91   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
 92 
 93   // Set an oopmap for the call site
 94   OopMapSet* oop_maps = new OopMapSet();
 95   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
 96 
 97   // location of rbp is known implicitly by the frame sender code
 98 
 99   oop_maps->add_gc_map(__ pc() - start, map);
100 
101   __ reset_last_Java_frame(false);
102 
103   // Load UnrollBlock* into rdi
104   __ mov(rdi, rax);
105 
106 #ifdef ASSERT
107   { Label L;
108     __ cmpptr(Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset()),
109               Deoptimization::Unpack_uncommon_trap);
110     __ jcc(Assembler::equal, L);
111     __ stop("OptoRuntime::generate_uncommon_trap_blob: expected Unpack_uncommon_trap");
112     __ bind(L);
113   }
114 #endif
115 
116   // Pop all the frames we must move/replace.
117   //
118   // Frame picture (youngest to oldest)
119   // 1: self-frame (no frame link)
120   // 2: deopting frame  (no frame link)
121   // 3: caller of deopting frame (could be compiled/interpreted).
122 
123   // Pop self-frame.  We have no frame, and must rely only on rax and rsp.
124   __ addptr(rsp, (SimpleRuntimeFrame::framesize - 2) << LogBytesPerInt); // Epilog!
125 
126   // Pop deoptimized frame (int)
127   __ movl(rcx, Address(rdi,
128                        Deoptimization::UnrollBlock::
129                        size_of_deoptimized_frame_offset()));
130   __ addptr(rsp, rcx);
131 
132   // rsp should be pointing at the return address to the caller (3)
133 
134   // Pick up the initial fp we should save
135   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
136   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset()));
137 
138 #ifdef ASSERT
139   // Compilers generate code that bang the stack by as much as the
140   // interpreter would need. So this stack banging should never
141   // trigger a fault. Verify that it does not on non product builds.
142   __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset()));
143   __ bang_stack_size(rbx, rcx);
144 #endif
145 
146   // Load address of array of frame pcs into rcx (address*)
147   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset()));
148 
149   // Trash the return pc
150   __ addptr(rsp, wordSize);
151 
152   // Load address of array of frame sizes into rsi (intptr_t*)
153   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock:: frame_sizes_offset()));
154 
155   // Counter
156   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock:: number_of_frames_offset())); // (int)
157 
158   // Now adjust the caller's stack to make up for the extra locals but
159   // record the original sp so that we can save it in the skeletal
160   // interpreter frame and the stack walking of interpreter_sender
161   // will get the unextended sp value and not the "real" sp value.
162 
163   const Register sender_sp = r8;
164 
165   __ mov(sender_sp, rsp);
166   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock:: caller_adjustment_offset())); // (int)
167   __ subptr(rsp, rbx);
168 
169   // Push interpreter frames in a loop
170   Label loop;
171   __ bind(loop);
172   __ movptr(rbx, Address(rsi, 0)); // Load frame size
173   __ subptr(rbx, 2 * wordSize);    // We'll push pc and rbp by hand
174   __ pushptr(Address(rcx, 0));     // Save return address
175   __ enter();                      // Save old & set new rbp
176   __ subptr(rsp, rbx);             // Prolog
177   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize),
178             sender_sp);            // Make it walkable
179   // This value is corrected by layout_activation_impl
180   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
181   __ mov(sender_sp, rsp);          // Pass sender_sp to next frame
182   __ addptr(rsi, wordSize);        // Bump array pointer (sizes)
183   __ addptr(rcx, wordSize);        // Bump array pointer (pcs)
184   __ decrementl(rdx);              // Decrement counter
185   __ jcc(Assembler::notZero, loop);
186   __ pushptr(Address(rcx, 0));     // Save final return address
187 
188   // Re-push self-frame
189   __ enter();                 // Save old & set new rbp
190   __ subptr(rsp, (SimpleRuntimeFrame::framesize - 4) << LogBytesPerInt);
191                               // Prolog
192 
193   // Use rbp because the frames look interpreted now
194   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
195   // Don't need the precise return PC here, just precise enough to point into this code blob.
196   address the_pc = __ pc();
197   __ set_last_Java_frame(noreg, rbp, the_pc, rscratch1);
198 
199   // Call C code.  Need thread but NOT official VM entry
200   // crud.  We cannot block on this call, no GC can happen.  Call should
201   // restore return values to their stack-slots with the new SP.
202   // Thread is in rdi already.
203   //
204   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
205 
206   __ andptr(rsp, -(StackAlignmentInBytes)); // Align SP as required by ABI
207   __ mov(c_rarg0, r15_thread);
208   __ movl(c_rarg1, Deoptimization::Unpack_uncommon_trap);
209   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
210 
211   // Set an oopmap for the call site
212   // Use the same PC we used for the last java frame
213   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
214 
215   // Clear fp AND pc
216   __ reset_last_Java_frame(true);
217 
218   // Pop self-frame.
219   __ leave();                 // Epilog
220 
221   // Jump to interpreter
222   __ ret(0);
223 
224   // Make sure all code is generated
225   masm->flush();
226 
227   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
228                                                  SimpleRuntimeFrame::framesize >> 1);
229 }
230 
231 //------------------------------generate_exception_blob---------------------------
232 // creates exception blob at the end
233 // Using exception blob, this code is jumped from a compiled method.
234 // (see emit_exception_handler in x86_64.ad file)
235 //
236 // Given an exception pc at a call we call into the runtime for the
237 // handler in this method. This handler might merely restore state
238 // (i.e. callee save registers) unwind the frame and jump to the
239 // exception handler for the nmethod if there is no Java level handler
240 // for the nmethod.
241 //
242 // This code is entered with a jmp.
243 //
244 // Arguments:
245 //   rax: exception oop
246 //   rdx: exception pc
247 //
248 // Results:
249 //   rax: exception oop
250 //   rdx: exception pc in caller or ???
251 //   destination: exception handler of caller
252 //
253 // Note: the exception pc MUST be at a call (precise debug information)
254 //       Registers rax, rdx, rcx, rsi, rdi, r8-r11 are not callee saved.
255 //
256 
257 void OptoRuntime::generate_exception_blob() {
258   assert(!OptoRuntime::is_callee_saved_register(RDX_num), "");
259   assert(!OptoRuntime::is_callee_saved_register(RAX_num), "");
260   assert(!OptoRuntime::is_callee_saved_register(RCX_num), "");
261 
262   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
263 
264   // Allocate space for the code
265   ResourceMark rm;
266   // Setup code generation tools
267   CodeBuffer buffer("exception_blob", 2048, 1024);
268   MacroAssembler* masm = new MacroAssembler(&buffer);
269 
270 
271   address start = __ pc();
272 
273   // Exception pc is 'return address' for stack walker
274   __ push(rdx);
275   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Prolog
276 
277   // Save callee-saved registers.  See x86_64.ad.
278 
279   // rbp is an implicitly saved callee saved register (i.e., the calling
280   // convention will save/restore it in the prolog/epilog). Other than that
281   // there are no callee save registers now that adapter frames are gone.
282 
283   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
284 
285   // Store exception in Thread object. We cannot pass any arguments to the
286   // handle_exception call, since we do not want to make any assumption
287   // about the size of the frame where the exception happened in.
288   // c_rarg0 is either rdi (Linux) or rcx (Windows).
289   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()),rax);
290   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
291 
292   // This call does all the hard work.  It checks if an exception handler
293   // exists in the method.
294   // If so, it returns the handler address.
295   // If not, it prepares for stack-unwinding, restoring the callee-save
296   // registers of the frame being removed.
297   //
298   // address OptoRuntime::handle_exception_C(JavaThread* thread)
299 
300   // At a method handle call, the stack may not be properly aligned
301   // when returning with an exception.
302   address the_pc = __ pc();
303   __ set_last_Java_frame(noreg, noreg, the_pc, rscratch1);
304   __ mov(c_rarg0, r15_thread);
305   __ andptr(rsp, -(StackAlignmentInBytes));    // Align stack
306   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
307 
308   // Set an oopmap for the call site.  This oopmap will only be used if we
309   // are unwinding the stack.  Hence, all locations will be dead.
310   // Callee-saved registers will be the same as the frame above (i.e.,
311   // handle_exception_stub), since they were restored when we got the
312   // exception.
313 
314   OopMapSet* oop_maps = new OopMapSet();
315 
316   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
317 
318   __ reset_last_Java_frame(false);
319 
320   // Restore callee-saved registers
321 
322   // rbp is an implicitly saved callee-saved register (i.e., the calling
323   // convention will save restore it in prolog/epilog) Other than that
324   // there are no callee save registers now that adapter frames are gone.
325 
326   __ movptr(rbp, Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt));
327 
328   __ addptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog
329   __ pop(rdx);                  // No need for exception pc anymore
330 
331   // rax: exception handler
332 
333   // We have a handler in rax (could be deopt blob).
334   __ mov(r8, rax);
335 
336   // Get the exception oop
337   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
338   // Get the exception pc in case we are deoptimized
339   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
340 #ifdef ASSERT
341   __ movptr(Address(r15_thread, JavaThread::exception_handler_pc_offset()), NULL_WORD);
342   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), NULL_WORD);
343 #endif
344   // Clear the exception oop so GC no longer processes it as a root.
345   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), NULL_WORD);
346 
347   // rax: exception oop
348   // r8:  exception handler
349   // rdx: exception pc
350   // Jump to handler
351 
352   __ jmp(r8);
353 
354   // Make sure all code is generated
355   masm->flush();
356 
357   // Set exception blob
358   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
359 }
360 #endif // COMPILER2