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