Debian Codegraph @

rpython/jit/backend/aarch64/assembler.py

raw symbols SCIP
1
2 from rpython.jit.backend.aarch64.arch import WORD, JITFRAME_FIXED_SIZE
3 from rpython.jit.backend.aarch64.codebuilder import InstrBuilder, OverwritingBuilder
4 from rpython.jit.backend.aarch64.locations import imm, StackLocation, get_fp_offset
5 #from rpython.jit.backend.arm.helper.regalloc import VMEM_imm_size
6 from rpython.jit.backend.aarch64.opassembler import ResOpAssembler
7 from rpython.jit.backend.aarch64.regalloc import (Regalloc, check_imm_arg,
8 operations as regalloc_operations, guard_operations, comp_operations,
9 CoreRegisterManager, VFPRegisterManager)
10 from rpython.jit.backend.aarch64 import registers as r
11 from rpython.jit.backend.arm import conditions as c
12 from rpython.jit.backend.llsupport import jitframe, rewrite
13 from rpython.jit.backend.llsupport.assembler import BaseAssembler
14 from rpython.jit.backend.llsupport.regalloc import get_scale, valid_addressing_size
15 from rpython.jit.backend.llsupport.asmmemmgr import MachineDataBlockWrapper
16 from rpython.jit.backend.model import CompiledLoopToken
17 from rpython.jit.codewriter.effectinfo import EffectInfo
18 from rpython.jit.metainterp.history import AbstractFailDescr, FLOAT, INT, VOID
19 from rpython.jit.metainterp.resoperation import rop
20 from rpython.rlib.debug import debug_print, debug_start, debug_stop
21 from rpython.rlib.jit import AsmInfo
22 from rpython.rlib.objectmodel import we_are_translated, specialize, compute_unique_id
23 from rpython.rlib.rarithmetic import r_uint
24 from rpython.rtyper.annlowlevel import llhelper, cast_instance_to_gcref
25 from rpython.rtyper.lltypesystem import lltype, rffi
26 from rpython.rtyper.lltypesystem.lloperation import llop
27 from rpython.rlib.rjitlog import rjitlog as jl
28 from rpython.rlib import rgc, rmmap
29
30
31 class AssemblerARM64(ResOpAssembler):
32 def __init__(self, cpu, translate_support_code=False):
33 ResOpAssembler.__init__(self, cpu, translate_support_code)
34 self.failure_recovery_code = [0, 0, 0, 0]
35 self.wb_slowpath = [0, 0, 0, 0, 0]
36 self.stack_check_slowpath = 0
37
38 @rgc.no_release_gil
39 def assemble_loop(self, jd_id, unique_id, logger, loopname, inputargs,
40 operations, looptoken, log):
41 rmmap.enter_assembler_writing()
42 try:
43 return self._assemble_loop(jd_id, unique_id, logger, loopname, inputargs,
44 operations, looptoken, log)
45 finally:
46 rmmap.leave_assembler_writing()
47
48 def _assemble_loop(self, jd_id, unique_id, logger, loopname, inputargs,
49 operations, looptoken, log):
50 clt = CompiledLoopToken(self.cpu, looptoken.number)
51 clt._debug_nbargs = len(inputargs)
52 looptoken.compiled_loop_token = clt
53
54 if not we_are_translated():
55 # Arguments should be unique
56 assert len(set(inputargs)) == len(inputargs)
57
58 self.setup(looptoken)
59 if self.cpu.HAS_CODEMAP:
60 self.codemap_builder.enter_portal_frame(jd_id, unique_id,
61 self.mc.get_relative_pos())
62
63 frame_info = self.datablockwrapper.malloc_aligned(
64 jitframe.JITFRAMEINFO_SIZE, alignment=WORD)
65 clt.frame_info = rffi.cast(jitframe.JITFRAMEINFOPTR, frame_info)
66 clt.frame_info.clear() # for now
67
68 if log:
69 operations = self._inject_debugging_code(looptoken, operations,
70 'e', looptoken.number)
71
72 regalloc = Regalloc(assembler=self)
73 allgcrefs = []
74 operations = regalloc.prepare_loop(inputargs, operations, looptoken,
75 allgcrefs)
76 self.reserve_gcref_table(allgcrefs)
77 functionpos = self.mc.get_relative_pos()
78
79 self._call_header_with_stack_check()
80 self._check_frame_depth_debug(self.mc)
81
82 loop_head = self.mc.get_relative_pos()
83 looptoken._ll_loop_code = loop_head
84 #
85 frame_depth_no_fixed_size = self._assemble(regalloc, inputargs, operations)
86 self.update_frame_depth(frame_depth_no_fixed_size + JITFRAME_FIXED_SIZE)
87 #
88 size_excluding_failure_stuff = self.mc.get_relative_pos()
89
90 self.write_pending_failure_recoveries()
91
92 full_size = self.mc.get_relative_pos()
93 rawstart = self.materialize_loop(looptoken)
94 looptoken._ll_function_addr = rawstart + functionpos
95
96 self.patch_gcref_table(looptoken, rawstart)
97 self.process_pending_guards(rawstart)
98 self.fixup_target_tokens(rawstart)
99
100 if log and not we_are_translated():
101 self.mc._dump_trace(rawstart,
102 'loop.asm')
103
104 ops_offset = self.mc.ops_offset
105
106 if logger:
107 log = logger.log_trace(jl.MARK_TRACE_ASM, None, self.mc)
108 log.write(inputargs, operations, ops_offset=ops_offset)
109
110 # legacy
111 if logger.logger_ops:
112 logger.logger_ops.log_loop(inputargs, operations, 0,
113 "rewritten", name=loopname,
114 ops_offset=ops_offset)
115
116 self.teardown()
117
118 debug_start("jit-backend-addr")
119 debug_print("Loop %d (%s) has address 0x%x to 0x%x (bootstrap 0x%x)" % (
120 looptoken.number, loopname,
121 r_uint(rawstart + loop_head),
122 r_uint(rawstart + size_excluding_failure_stuff),
123 r_uint(rawstart + functionpos)))
124 debug_print(" gc table: 0x%x" % r_uint(rawstart))
125 debug_print(" function: 0x%x" % r_uint(rawstart + functionpos))
126 debug_print(" resops: 0x%x" % r_uint(rawstart + loop_head))
127 debug_print(" failures: 0x%x" % r_uint(rawstart +
128 size_excluding_failure_stuff))
129 debug_print(" end: 0x%x" % r_uint(rawstart + full_size))
130 debug_stop("jit-backend-addr")
131
132 return AsmInfo(ops_offset, rawstart + loop_head,
133 size_excluding_failure_stuff - loop_head)
134
135 @rgc.no_release_gil
136 def assemble_bridge(self, logger, faildescr, inputargs, operations,
137 original_loop_token, log):
138 rmmap.enter_assembler_writing()
139 try:
140 return self._assemble_bridge(logger, faildescr, inputargs, operations,
141 original_loop_token, log)
142 finally:
143 rmmap.leave_assembler_writing()
144
145 def _assemble_bridge(self, logger, faildescr, inputargs, operations,
146 original_loop_token, log):
147 if not we_are_translated():
148 # Arguments should be unique
149 assert len(set(inputargs)) == len(inputargs)
150
151 self.setup(original_loop_token)
152 if self.cpu.HAS_CODEMAP:
153 self.codemap_builder.inherit_code_from_position(
154 faildescr.adr_jump_offset)
155
156 descr_number = compute_unique_id(faildescr)
157 if log:
158 operations = self._inject_debugging_code(faildescr, operations,
159 'b', descr_number)
160
161 assert isinstance(faildescr, AbstractFailDescr)
162
163 arglocs = self.rebuild_faillocs_from_descr(faildescr, inputargs)
164
165 regalloc = Regalloc(assembler=self)
166 allgcrefs = []
167 operations = regalloc.prepare_bridge(inputargs, arglocs,
168 operations,
169 allgcrefs,
170 self.current_clt.frame_info)
171 self.reserve_gcref_table(allgcrefs)
172 startpos = self.mc.get_relative_pos()
173
174 self._check_frame_depth(self.mc, regalloc.get_gcmap())
175
176 bridgestartpos = self.mc.get_relative_pos()
177 frame_depth_no_fixed_size = self._assemble(regalloc, inputargs, operations)
178
179 codeendpos = self.mc.get_relative_pos()
180
181 self.write_pending_failure_recoveries()
182
183 fullsize = self.mc.get_relative_pos()
184 rawstart = self.materialize_loop(original_loop_token)
185
186 self.patch_gcref_table(original_loop_token, rawstart)
187 self.process_pending_guards(rawstart)
188
189 debug_start("jit-backend-addr")
190 debug_print("bridge out of Guard 0x%x has address 0x%x to 0x%x" %
191 (r_uint(descr_number), r_uint(rawstart + startpos),
192 r_uint(rawstart + codeendpos)))
193 debug_print(" gc table: 0x%x" % r_uint(rawstart))
194 debug_print(" jump target: 0x%x" % r_uint(rawstart + startpos))
195 debug_print(" resops: 0x%x" % r_uint(rawstart + bridgestartpos))
196 debug_print(" failures: 0x%x" % r_uint(rawstart + codeendpos))
197 debug_print(" end: 0x%x" % r_uint(rawstart + fullsize))
198 debug_stop("jit-backend-addr")
199
200 # patch the jump from original guard
201 self.patch_trace(faildescr, original_loop_token,
202 rawstart + startpos, regalloc)
203
204 self.patch_stack_checks(frame_depth_no_fixed_size + JITFRAME_FIXED_SIZE,
205 rawstart)
206 if not we_are_translated():
207 if log:
208 self.mc._dump_trace(rawstart, 'bridge.asm')
209
210 ops_offset = self.mc.ops_offset
211 frame_depth = max(self.current_clt.frame_info.jfi_frame_depth,
212 frame_depth_no_fixed_size + JITFRAME_FIXED_SIZE)
213 self.fixup_target_tokens(rawstart)
214 self.update_frame_depth(frame_depth)
215
216 if logger:
217 log = logger.log_trace(jl.MARK_TRACE_ASM, None, self.mc)
218 log.write(inputargs, operations, ops_offset)
219 # log that the already written bridge is stitched to a descr!
220 logger.log_patch_guard(descr_number, rawstart)
221
222 # legacy
223 if logger.logger_ops:
224 logger.logger_ops.log_bridge(inputargs, operations, "rewritten",
225 faildescr, ops_offset=ops_offset)
226
227 self.teardown()
228
229 return AsmInfo(ops_offset, startpos + rawstart, codeendpos - startpos)
230
231 def setup(self, looptoken):
232 BaseAssembler.setup(self, looptoken)
233 assert self.memcpy_addr != 0, 'setup_once() not called?'
234 if we_are_translated():
235 self.debug = False
236 self.current_clt = looptoken.compiled_loop_token
237 self.mc = InstrBuilder()
238 self.pending_guards = []
239 #assert self.datablockwrapper is None --- but obscure case
240 # possible, e.g. getting MemoryError and continuing
241 allblocks = self.get_asmmemmgr_blocks(looptoken)
242 self.datablockwrapper = MachineDataBlockWrapper(self.cpu.asmmemmgr,
243 allblocks)
244 self.mc.datablockwrapper = self.datablockwrapper
245 self.target_tokens_currently_compiling = {}
246 self.frame_depth_to_patch = []
247
248 def teardown(self):
249 self.current_clt = None
250 self._regalloc = None
251 self.mc = None
252 self.pending_guards = None
253
254 def _push_all_regs_to_jitframe(self, mc, ignored_regs, withfloats,
255 callee_only=False):
256 # Push general purpose registers
257 base_ofs = self.cpu.get_baseofs_of_frame_field()
258 if callee_only:
259 regs = CoreRegisterManager.save_around_call_regs
260 else:
261 regs = CoreRegisterManager.all_regs
262 # XXX add special case if ignored_regs are a block at the start of regs
263 if not ignored_regs: # we want to push a contiguous block of regs
264 assert base_ofs < 0x100
265 for i, reg in enumerate(regs):
266 mc.STR_ri(reg.value, r.fp.value, base_ofs + i * WORD)
267 else:
268 for reg in ignored_regs:
269 assert not reg.is_vfp_reg() # sanity check
270 # we can have holes in the list of regs
271 for i, gpr in enumerate(regs):
272 if gpr in ignored_regs:
273 continue
274 self.store_reg(mc, gpr, r.fp, base_ofs + i * WORD)
275
276 if withfloats:
277 # Push VFP regs
278 regs = VFPRegisterManager.all_regs
279 ofs = len(CoreRegisterManager.all_regs) * WORD
280 for reg in regs:
281 mc.STR_di(reg.value, r.fp.value, ofs + base_ofs + reg.value * WORD)
282
283 def _pop_all_regs_from_jitframe(self, mc, ignored_regs, withfloats,
284 callee_only=False):
285 # Pop general purpose registers
286 base_ofs = self.cpu.get_baseofs_of_frame_field()
287 if callee_only:
288 regs = CoreRegisterManager.save_around_call_regs
289 else:
290 regs = CoreRegisterManager.all_regs
291 # XXX add special case if ignored_regs are a block at the start of regs
292 if not ignored_regs: # we want to pop a contiguous block of regs
293 assert base_ofs < 0x100
294 for i, reg in enumerate(regs):
295 mc.LDR_ri(reg.value, r.fp.value, base_ofs + i * WORD)
296 else:
297 for reg in ignored_regs:
298 assert not reg.is_vfp_reg() # sanity check
299 # we can have holes in the list of regs
300 for i, gpr in enumerate(regs):
301 if gpr in ignored_regs:
302 continue
303 ofs = i * WORD + base_ofs
304 self.load_reg(mc, gpr, r.fp, ofs)
305 if withfloats:
306 # Pop VFP regs
307 regs = VFPRegisterManager.all_regs
308 ofs = len(CoreRegisterManager.all_regs) * WORD
309 for reg in regs:
310 mc.LDR_di(reg.value, r.fp.value, ofs + base_ofs + reg.value * WORD)
311
312 def _build_failure_recovery(self, exc, withfloats=False):
313 mc = InstrBuilder()
314 self._push_all_regs_to_jitframe(mc, [], withfloats)
315
316 if exc:
317 # We might have an exception pending. Load it into r4
318 # (this is a register saved across calls)
319 mc.gen_load_int(r.x5.value, self.cpu.pos_exc_value())
320 mc.LDR_ri(r.x4.value, r.x5.value, 0)
321 # clear the exc flags
322 mc.gen_load_int(r.x6.value, 0)
323 mc.STR_ri(r.x6.value, r.x5.value, 0) # pos_exc_value is still in r5
324 mc.gen_load_int(r.x5.value, self.cpu.pos_exception())
325 mc.STR_ri(r.x6.value, r.x5.value, 0)
326 # save r4 into 'jf_guard_exc'
327 offset = self.cpu.get_ofs_of_frame_field('jf_guard_exc')
328 assert check_imm_arg(abs(offset))
329 mc.STR_ri(r.x4.value, r.fp.value, offset)
330 # now we return from the complete frame, which starts from
331 # _call_header_with_stack_check(). The LEA in _call_footer below
332 # throws away most of the frame, including all the PUSHes that we
333 # did just above.
334
335 # set return value
336 mc.MOV_rr(r.x0.value, r.fp.value)
337
338 self.gen_func_epilog(mc)
339 rawstart = mc.materialize(self.cpu, [])
340 self.failure_recovery_code[exc + 2 * withfloats] = rawstart
341
342 def propagate_memoryerror_if_reg_is_null(self, reg_loc):
343 # see ../x86/assembler.py:genop_discard_check_memory_error()
344 self.mc.CMP_ri(reg_loc.value, 0)
345 self.mc.B_ofs_cond(6 * 4, c.NE)
346 self.mc.B(self.propagate_exception_path)
347
348 def _build_wb_slowpath(self, withcards, withfloats=False, for_frame=False):
349 descr = self.cpu.gc_ll_descr.write_barrier_descr
350 if descr is None:
351 return
352 if not withcards:
353 func = descr.get_write_barrier_fn(self.cpu)
354 else:
355 if descr.jit_wb_cards_set == 0:
356 return
357 func = descr.get_write_barrier_from_array_fn(self.cpu)
358 if func == 0:
359 return
360 #
361 # This builds a helper function called from the slow path of
362 # write barriers. It must save all registers, and optionally
363 # all vfp registers. It takes a single argument which is in x0.
364 # It must keep stack alignment accordingly.
365 mc = InstrBuilder()
366 #
367 mc.SUB_ri(r.sp.value, r.sp.value, 2 * WORD)
368 mc.STR_ri(r.lr.value, r.sp.value, 0)
369 if not for_frame:
370 self._push_all_regs_to_jitframe(mc, [], withfloats, callee_only=True)
371 else:
372 # NOTE: don't save registers on the jitframe here! It might
373 # override already-saved values that will be restored
374 # later...
375 #
376 # we're possibly called from the slowpath of malloc
377 # save the caller saved registers
378 # assuming we do not collect here
379 exc0, exc1 = r.x19, r.x20
380 mc.SUB_ri(r.sp.value, r.sp.value, (len(r.caller_resp) + 2 + len(r.caller_vfp_resp)) * WORD)
381 cur_stack = 0
382 for i in range(0, len(r.caller_resp), 2):
383 mc.STP_rri(r.caller_resp[i].value, r.caller_resp[i + 1].value, r.sp.value, i * WORD)
384 cur_stack = len(r.caller_resp)
385 mc.STP_rri(exc0.value, exc1.value, r.sp.value, cur_stack * WORD)
386 cur_stack += 2
387 for i in range(len(r.caller_vfp_resp)):
388 mc.STR_di(r.caller_vfp_resp[i].value, r.sp.value, cur_stack * WORD)
389 cur_stack += 1
390
391 self._store_and_reset_exception(mc, exc0, exc1)
392 mc.BL(func)
393 #
394 if not for_frame:
395 self._pop_all_regs_from_jitframe(mc, [], withfloats, callee_only=True)
396 else:
397 exc0, exc1 = r.x19, r.x20
398 self._restore_exception(mc, exc0, exc1)
399
400 cur_stack = 0
401 for i in range(0, len(r.caller_resp), 2):
402 mc.LDP_rri(r.caller_resp[i].value, r.caller_resp[i + 1].value, r.sp.value, i * WORD)
403 cur_stack = len(r.caller_resp)
404 mc.LDP_rri(exc0.value, exc1.value, r.sp.value, cur_stack * WORD)
405 cur_stack += 2
406 for i in range(len(r.caller_vfp_resp)):
407 mc.LDR_di(r.caller_vfp_resp[i].value, r.sp.value, cur_stack * WORD)
408 cur_stack += 1
409
410 assert exc0 is not None
411 assert exc1 is not None
412
413 mc.ADD_ri(r.sp.value, r.sp.value, (len(r.caller_resp) + 2 + len(r.caller_vfp_resp)) * WORD)
414
415 #
416 if withcards:
417 # A final TEST8 before the RET, for the caller. Careful to
418 # not follow this instruction with another one that changes
419 # the status of the CPU flags!
420 mc.LDRB_ri(r.ip0.value, r.x0.value, descr.jit_wb_if_flag_byteofs)
421 mc.MOVZ_r_u16(r.ip1.value, 0x80, 0)
422 mc.TST_rr_shift(r.ip0.value, r.ip1.value, 0)
423 #
424 mc.LDR_ri(r.ip1.value, r.sp.value, 0)
425 mc.ADD_ri(r.sp.value, r.sp.value, 2 * WORD)
426 mc.RET_r(r.ip1.value)
427 #
428 rawstart = mc.materialize(self.cpu, [])
429 if for_frame:
430 self.wb_slowpath[4] = rawstart
431 else:
432 self.wb_slowpath[withcards + 2 * withfloats] = rawstart
433
434 def build_frame_realloc_slowpath(self):
435 # this code should do the following steps
436 # a) store all registers in the jitframe
437 # b) fish for the arguments passed by the caller
438 # c) store the gcmap in the jitframe
439 # d) call realloc_frame
440 # e) set the fp to point to the new jitframe
441 # f) store the address of the new jitframe in the shadowstack
442 # c) set the gcmap field to 0 in the new jitframe
443 # g) restore registers and return
444 mc = InstrBuilder()
445 self._push_all_regs_to_jitframe(mc, [], self.cpu.supports_floats)
446 # this is the gcmap stored by push_gcmap(mov=True) in _check_stack_frame
447 # and the expected_size pushed in _check_stack_frame
448 # pop the values passed on the stack, gcmap -> r0, expected_size -> r1
449 mc.LDP_rri(r.x0.value, r.x1.value, r.sp.value, 0)
450
451 mc.STR_ri(r.lr.value, r.sp.value, 0)
452
453 # store the current gcmap(r0) in the jitframe
454 gcmap_ofs = self.cpu.get_ofs_of_frame_field('jf_gcmap')
455 mc.STR_ri(r.x0.value, r.fp.value, gcmap_ofs)
456
457 # set first arg, which is the old jitframe address
458 mc.MOV_rr(r.x0.value, r.fp.value)
459
460 # store a possibly present exception
461 self._store_and_reset_exception(mc, None, r.x19, on_frame=True)
462
463 # call realloc_frame, it takes two arguments
464 # arg0: the old jitframe
465 # arg1: the new size
466 #
467 mc.BL(self.cpu.realloc_frame)
468
469 # set fp to the new jitframe returned from the previous call
470 mc.MOV_rr(r.fp.value, r.x0.value)
471
472 # restore a possibly present exception
473 self._restore_exception(mc, None, r.x19)
474
475 gcrootmap = self.cpu.gc_ll_descr.gcrootmap
476 if gcrootmap and gcrootmap.is_shadow_stack:
477 self._load_shadowstack_top(mc, r.x19, gcrootmap)
478 # store the new jitframe addr in the shadowstack
479 mc.SUB_ri(r.x19.value, r.x19.value, WORD)
480 mc.STR_ri(r.x0.value, r.x19.value, 0)
481
482 # reset the jf_gcmap field in the jitframe
483 mc.gen_load_int(r.ip0.value, 0)
484 mc.STR_ri(r.ip0.value, r.fp.value, gcmap_ofs)
485
486 # restore registers
487 self._pop_all_regs_from_jitframe(mc, [], self.cpu.supports_floats)
488
489 # return
490 mc.LDR_ri(r.lr.value, r.sp.value, 0)
491 mc.ADD_ri(r.sp.value, r.sp.value, 2*WORD)
492 mc.RET_r(r.lr.value)
493 self._frame_realloc_slowpath = mc.materialize(self.cpu, [])
494
495 def _load_shadowstack_top(self, mc, reg, gcrootmap):
496 rst = gcrootmap.get_root_stack_top_addr()
497 mc.gen_load_int(reg.value, rst)
498 self.load_reg(mc, reg, reg)
499 return rst
500
501 def _store_and_reset_exception(self, mc, excvalloc=None, exctploc=None,
502 on_frame=False):
503 """ Resest the exception. If excvalloc is None, then store it on the
504 frame in jf_guard_exc
505 """
506 assert excvalloc is not r.ip0
507 assert exctploc is not r.ip0
508 tmpreg = r.ip1
509 mc.gen_load_int(r.ip0.value, self.cpu.pos_exc_value())
510 if excvalloc is not None: # store
511 assert excvalloc.is_core_reg()
512 self.load_reg(mc, excvalloc, r.ip0)
513 if on_frame:
514 # store exc_value in JITFRAME
515 ofs = self.cpu.get_ofs_of_frame_field('jf_guard_exc')
516 assert check_imm_arg(ofs)
517 #
518 self.load_reg(mc, r.ip0, r.ip0, helper=tmpreg)
519 #
520 self.store_reg(mc, r.ip0, r.fp, ofs, helper=tmpreg)
521 if exctploc is not None:
522 # store pos_exception in exctploc
523 assert exctploc.is_core_reg()
524 mc.gen_load_int(r.ip0.value, self.cpu.pos_exception())
525 self.load_reg(mc, exctploc, r.ip0, helper=tmpreg)
526
527 if on_frame or exctploc is not None:
528 mc.gen_load_int(r.ip0.value, self.cpu.pos_exc_value())
529
530 # reset exception
531 mc.gen_load_int(tmpreg.value, 0)
532
533 self.store_reg(mc, tmpreg, r.ip0, 0)
534
535 mc.gen_load_int(r.ip0.value, self.cpu.pos_exception())
536 self.store_reg(mc, tmpreg, r.ip0, 0)
537
538 def _restore_exception(self, mc, excvalloc, exctploc):
539 assert excvalloc is not r.ip0
540 assert exctploc is not r.ip0
541 mc.gen_load_int(r.ip0.value, self.cpu.pos_exc_value())
542 if excvalloc is not None:
543 assert excvalloc.is_core_reg()
544 self.store_reg(mc, excvalloc, r.ip0)
545 else:
546 assert exctploc is not r.fp
547 # load exc_value from JITFRAME and put it in pos_exc_value
548 ofs = self.cpu.get_ofs_of_frame_field('jf_guard_exc')
549 self.load_reg(mc, r.ip1, r.fp, ofs)
550 self.store_reg(mc, r.ip1, r.ip0)
551 # reset exc_value in the JITFRAME
552 mc.gen_load_int(r.ip1.value, 0)
553 self.store_reg(mc, r.ip1, r.fp, ofs)
554
555 # restore pos_exception from exctploc register
556 mc.gen_load_int(r.ip0.value, self.cpu.pos_exception())
557 self.store_reg(mc, exctploc, r.ip0)
558
559 def _build_propagate_exception_path(self):
560 mc = InstrBuilder()
561 self._store_and_reset_exception(mc, r.x0)
562 ofs = self.cpu.get_ofs_of_frame_field('jf_guard_exc')
563 # make sure ofs fits into a register
564 assert check_imm_arg(ofs)
565 self.store_reg(mc, r.x0, r.fp, ofs)
566 propagate_exception_descr = rffi.cast(lltype.Signed,
567 cast_instance_to_gcref(self.cpu.propagate_exception_descr))
568 # put propagate_exception_descr into frame
569 ofs = self.cpu.get_ofs_of_frame_field('jf_descr')
570 # make sure ofs fits into a register
571 assert check_imm_arg(ofs)
572 mc.gen_load_int(r.x0.value, propagate_exception_descr)
573 self.store_reg(mc, r.x0, r.fp, ofs)
574 mc.MOV_rr(r.x0.value, r.fp.value)
575 self.gen_func_epilog(mc)
576 rawstart = mc.materialize(self.cpu, [])
577 self.propagate_exception_path = rawstart
578
579 def _build_cond_call_slowpath(self, supports_floats, callee_only):
580 """ This builds a general call slowpath, for whatever call happens to
581 come.
582
583 The address of function to call comes in ip1. the result is also stored
584 in ip1 or ivfp
585 """
586 mc = InstrBuilder()
587 #
588 self._push_all_regs_to_jitframe(mc, [], self.cpu.supports_floats, callee_only)
589 ## args are in their respective positions
590 mc.SUB_ri(r.sp.value, r.sp.value, 2 * WORD)
591 mc.STR_ri(r.ip0.value, r.sp.value, WORD)
592 mc.STR_ri(r.lr.value, r.sp.value, 0)
593 mc.BLR_r(r.ip1.value)
594 # callee saved
595 self._reload_frame_if_necessary(mc) # <- this will not touch x0
596 mc.MOV_rr(r.ip1.value, r.x0.value)
597 self._pop_all_regs_from_jitframe(mc, [], supports_floats,
598 callee_only) # <- this does not touch ip1
599 # return
600 mc.LDR_ri(r.ip0.value, r.sp.value, 0)
601 mc.ADD_ri(r.sp.value, r.sp.value, 2 * WORD)
602 mc.RET_r(r.ip0.value)
603 return mc.materialize(self.cpu, [])
604
605 def _build_malloc_slowpath(self, kind):
606 """ While arriving on slowpath, we have a gcpattern on stack 0.
607 The arguments are passed in r0 and r10, as follows:
608
609 kind == 'fixed': nursery_head in r0 and the size in r1 - r0.
610
611 kind == 'str/unicode': length of the string to allocate in r0.
612
613 kind == 'var': length to allocate in r1, tid in r0,
614 and itemsize on the stack.
615
616 This function must preserve all registers apart from r0 and r1.
617 """
618 assert kind in ['fixed', 'str', 'unicode', 'var']
619 mc = InstrBuilder()
620 #
621 self._push_all_regs_to_jitframe(mc, [r.x0, r.x1], True)
622 #
623 if kind == 'fixed':
624 addr = self.cpu.gc_ll_descr.get_malloc_slowpath_addr()
625 elif kind == 'str':
626 addr = self.cpu.gc_ll_descr.get_malloc_fn_addr('malloc_str')
627 elif kind == 'unicode':
628 addr = self.cpu.gc_ll_descr.get_malloc_fn_addr('malloc_unicode')
629 else:
630 addr = self.cpu.gc_ll_descr.get_malloc_slowpath_array_addr()
631 if kind == 'fixed':
632 # At this point we know that the values we need to compute the size
633 # are stored in x0 and x1.
634 mc.SUB_rr(r.x0.value, r.x1.value, r.x0.value) # compute the size we want
635
636 if hasattr(self.cpu.gc_ll_descr, 'passes_frame'):
637 mc.MOV_rr(r.x1.value, r.fp.value)
638 elif kind == 'str' or kind == 'unicode':
639 mc.MOV_rr(r.x0.value, r.x1.value)
640 else: # var
641 # tid is in x0
642 # length is in x1
643 # gcmap in ip1
644 # itemsize in ip2
645 mc.MOV_rr(r.x2.value, r.x1.value)
646 mc.MOV_rr(r.x1.value, r.x0.value)
647 mc.MOV_rr(r.x0.value, r.ip2.value) # load itemsize, ip2 now free
648 # store the gc pattern
649 ofs = self.cpu.get_ofs_of_frame_field('jf_gcmap')
650 mc.STR_ri(r.ip1.value, r.fp.value, ofs)
651 #
652 mc.SUB_ri(r.sp.value, r.sp.value, 2 * WORD)
653 mc.STR_ri(r.lr.value, r.sp.value, 0)
654 #
655 mc.BL(addr)
656 #
657 # If the slowpath malloc failed, we raise a MemoryError that
658 # always interrupts the current loop, as a "good enough"
659 # approximation.
660 mc.CMP_ri(r.x0.value, 0)
661 mc.B_ofs_cond(4 * 6, c.NE)
662 mc.B(self.propagate_exception_path)
663 # jump here
664 self._reload_frame_if_necessary(mc)
665 self._pop_all_regs_from_jitframe(mc, [r.x0, r.x1], self.cpu.supports_floats)
666 #
667 nursery_free_adr = self.cpu.gc_ll_descr.get_nursery_free_addr()
668 mc.gen_load_int(r.x1.value, nursery_free_adr)
669 mc.LDR_ri(r.x1.value, r.x1.value, 0)
670 # clear the gc pattern
671 mc.gen_load_int(r.ip0.value, 0)
672 self.store_reg(mc, r.ip0, r.fp, ofs)
673 # return
674 mc.LDR_ri(r.lr.value, r.sp.value, 0)
675 mc.ADD_ri(r.sp.value, r.sp.value, 2 * WORD)
676 mc.RET_r(r.lr.value)
677
678 #
679 rawstart = mc.materialize(self.cpu, [])
680 return rawstart
681
682 def malloc_cond(self, nursery_free_adr, nursery_top_adr, size, gcmap):
683 assert size & (WORD-1) == 0
684
685 self.mc.gen_load_int(r.x0.value, nursery_free_adr)
686 self.mc.LDR_ri(r.x0.value, r.x0.value, 0)
687
688 if check_imm_arg(size):
689 self.mc.ADD_ri(r.x1.value, r.x0.value, size)
690 else:
691 self.mc.gen_load_int(r.x1.value, size)
692 self.mc.ADD_rr(r.x1.value, r.x0.value, r.x1.value)
693
694 self.mc.gen_load_int(r.ip0.value, nursery_top_adr)
695 self.mc.LDR_ri(r.ip0.value, r.ip0.value, 0)
696
697 self.mc.CMP_rr(r.x1.value, r.ip0.value)
698
699 # We load into r0 the address stored at nursery_free_adr We calculate
700 # the new value for nursery_free_adr and store in r1 The we load the
701 # address stored in nursery_top_adr into IP If the value in r1 is
702 # (unsigned) bigger than the one in ip we conditionally call
703 # malloc_slowpath in case we called malloc_slowpath, which returns the
704 # new value of nursery_free_adr in r1 and the adr of the new object in
705 # r0.
706
707 self.mc.B_ofs_cond(10 * 4, c.LS) # 4 for gcmap load, 5 for BL, 1 for B_ofs_cond
708 self.mc.gen_load_int_full(r.ip1.value, rffi.cast(lltype.Signed, gcmap))
709
710 self.mc.BL(self.malloc_slowpath)
711
712 self.mc.gen_load_int(r.ip0.value, nursery_free_adr)
713 self.mc.STR_ri(r.x1.value, r.ip0.value, 0)
714
715 def malloc_cond_varsize_frame(self, nursery_free_adr, nursery_top_adr,
716 sizeloc, gcmap):
717 if sizeloc is r.x0:
718 self.mc.MOV_rr(r.x1.value, r.x0.value)
719 sizeloc = r.x1
720 self.mc.gen_load_int(r.x0.value, nursery_free_adr)
721 self.mc.LDR_ri(r.x0.value, r.x0.value, 0)
722 #
723 self.mc.ADD_rr(r.x1.value, r.x0.value, sizeloc.value)
724 #
725 self.mc.gen_load_int(r.ip0.value, nursery_top_adr)
726 self.mc.LDR_ri(r.ip0.value, r.ip0.value, 0)
727
728 self.mc.CMP_rr(r.x1.value, r.ip0.value)
729 #
730 self.mc.B_ofs_cond(40, c.LS) # see calculations in malloc_cond
731 self.mc.gen_load_int_full(r.ip1.value, rffi.cast(lltype.Signed, gcmap))
732
733 self.mc.BL(self.malloc_slowpath)
734
735 self.mc.gen_load_int(r.ip0.value, nursery_free_adr)
736 self.mc.STR_ri(r.x1.value, r.ip0.value, 0)
737
738 def malloc_cond_varsize(self, kind, nursery_free_adr, nursery_top_adr,
739 lengthloc, itemsize, maxlength, gcmap,
740 arraydescr):
741 from rpython.jit.backend.llsupport.descr import ArrayDescr
742 assert isinstance(arraydescr, ArrayDescr)
743
744 # lengthloc is the length of the array, which we must not modify!
745 assert lengthloc is not r.x0 and lengthloc is not r.x1
746 if lengthloc.is_core_reg():
747 varsizeloc = lengthloc
748 else:
749 assert lengthloc.is_stack()
750 self.regalloc_mov(lengthloc, r.x1)
751 varsizeloc = r.x1
752 #
753 if check_imm_arg(maxlength):
754 self.mc.CMP_ri(varsizeloc.value, maxlength)
755 else:
756 self.mc.gen_load_int(r.ip0.value, maxlength)
757 self.mc.CMP_rr(varsizeloc.value, r.ip0.value)
758 jmp_adr0 = self.mc.currpos() # jump to (large)
759 self.mc.BRK()
760 #
761 self.mc.gen_load_int(r.x0.value, nursery_free_adr)
762 self.mc.LDR_ri(r.x0.value, r.x0.value, 0)
763
764
765 if valid_addressing_size(itemsize):
766 shiftsize = get_scale(itemsize)
767 else:
768 shiftsize = self._mul_const_scaled(self.mc, r.lr, varsizeloc,
769 itemsize)
770 varsizeloc = r.lr
771 # now varsizeloc is a register != x0. The size of
772 # the variable part of the array is (varsizeloc << shiftsize)
773 assert arraydescr.basesize >= self.gc_minimal_size_in_nursery
774 constsize = arraydescr.basesize + self.gc_size_of_header
775 force_realignment = (itemsize % WORD) != 0
776 if force_realignment:
777 constsize += WORD - 1
778 self.mc.gen_load_int(r.ip0.value, constsize)
779 # constsize + (varsizeloc << shiftsize)
780 self.mc.ADD_rr_shifted(r.x1.value, r.ip0.value, varsizeloc.value,
781 shiftsize)
782 self.mc.ADD_rr(r.x1.value, r.x1.value, r.x0.value)
783 if force_realignment:
784 # -WORD = 0xfffffffffffffff8
785 self.mc.gen_load_int(r.ip0.value, -WORD)
786 self.mc.AND_rr(r.x1.value, r.x1.value, r.ip0.value)
787 # now x1 contains the total size in bytes, rounded up to a multiple
788 # of WORD, plus nursery_free_adr
789 #
790 self.mc.gen_load_int(r.ip0.value, nursery_top_adr)
791 self.mc.LDR_ri(r.ip0.value, r.ip0.value, 0)
792
793 self.mc.CMP_rr(r.x1.value, r.ip0.value)
794 jmp_adr1 = self.mc.currpos() # jump to (after-call)
795 self.mc.BRK()
796 #
797 # (large)
798 currpos = self.mc.currpos()
799 pmc = OverwritingBuilder(self.mc, jmp_adr0, WORD)
800 pmc.B_ofs_cond(currpos - jmp_adr0, c.GT)
801 #
802 # save the gcmap
803 self.mc.gen_load_int_full(r.ip1.value, rffi.cast(lltype.Signed, gcmap))
804 #
805
806 if kind == rewrite.FLAG_ARRAY:
807 self.mc.gen_load_int(r.x0.value, arraydescr.tid)
808 self.regalloc_mov(lengthloc, r.x1)
809 self.mc.gen_load_int(r.ip2.value, itemsize)
810 addr = self.malloc_slowpath_varsize
811 else:
812 if kind == rewrite.FLAG_STR:
813 addr = self.malloc_slowpath_str
814 else:
815 assert kind == rewrite.FLAG_UNICODE
816 addr = self.malloc_slowpath_unicode
817 self.regalloc_mov(lengthloc, r.x1)
818 self.mc.BL(addr)
819 #
820 jmp_location = self.mc.currpos() # jump to (done)
821 self.mc.BRK()
822 # (after-call)
823 currpos = self.mc.currpos()
824 pmc = OverwritingBuilder(self.mc, jmp_adr1, WORD)
825 pmc.B_ofs_cond(currpos - jmp_adr1, c.LS)
826 #
827 # write down the tid, but not if it's the result of the CALL
828 self.mc.gen_load_int(r.ip0.value, arraydescr.tid)
829 self.mc.STR_ri(r.ip0.value, r.x0.value, 0)
830
831 # while we're at it, this line is not needed if we've done the CALL
832 self.mc.gen_load_int(r.ip0.value, nursery_free_adr)
833 self.mc.STR_ri(r.x1.value, r.ip0.value, 0)
834 # (done)
835 # skip instructions after call
836 currpos = self.mc.currpos()
837 pmc = OverwritingBuilder(self.mc, jmp_location, WORD)
838 pmc.B_ofs(currpos - jmp_location)
839
840 def _mul_const_scaled(self, mc, targetreg, sourcereg, itemsize):
841 """Produce one operation to do roughly
842 targetreg = sourcereg * itemsize
843 except that the targetreg may still need shifting by 0,1,2,3.
844 """
845 if (itemsize & 7) == 0:
846 shiftsize = 3
847 elif (itemsize & 3) == 0:
848 shiftsize = 2
849 elif (itemsize & 1) == 0:
850 shiftsize = 1
851 else:
852 shiftsize = 0
853 itemsize >>= shiftsize
854 #
855 if valid_addressing_size(itemsize - 1):
856 self.mc.ADD_rr_shifted(targetreg.value, sourcereg.value, sourcereg.value,
857 get_scale(itemsize - 1))
858 elif valid_addressing_size(itemsize):
859 self.mc.LSL_ri(targetreg.value, sourcereg.value,
860 get_scale(itemsize))
861 else:
862 mc.gen_load_int(targetreg.value, itemsize)
863 mc.MUL_rr(targetreg.value, sourcereg.value, targetreg.value)
864 #
865 return shiftsize
866
867
868 def _build_stack_check_slowpath(self):
869 _, _, slowpathaddr = self.cpu.insert_stack_check()
870 if slowpathaddr == 0 or not self.cpu.propagate_exception_descr:
871 return # no stack check (for tests, or non-translated)
872 #
873 # make a "function" that is called immediately at the start of
874 # an assembler function. In particular, the stack looks like:
875 #
876 # | retaddr of caller | <-- aligned to a multiple of 16
877 # | saved argument regs |
878 # | my own retaddr | <-- sp
879 # +-----------------------+
880 #
881 mc = InstrBuilder()
882 # save argument registers and return address
883 mc.SUB_ri(r.sp.value, r.sp.value, (len(r.argument_regs) + 2) * WORD)
884 mc.STR_ri(r.lr.value, r.sp.value, 0)
885 for i in range(0, len(r.argument_regs), 2):
886 mc.STP_rri(r.argument_regs[i].value, r.argument_regs[i + 1].value,
887 r.sp.value, (i + 2) * WORD)
888 # stack is aligned here
889 # Pass current stack pointer as argument to the call
890 mc.SUB_ri(r.x0.value, r.sp.value, 0)
891 #
892 mc.BL(slowpathaddr)
893
894 # check for an exception
895 mc.gen_load_int(r.x0.value, self.cpu.pos_exception())
896 mc.LDR_ri(r.x0.value, r.x0.value, 0)
897 mc.TST_rr_shift(r.x0.value, r.x0.value, 0)
898 #
899 # restore registers and return
900 # We check for c.EQ here, meaning all bits zero in this case
901
902 jmp = mc.currpos()
903 mc.BRK()
904
905 for i in range(0, len(r.argument_regs), 2):
906 mc.LDP_rri(r.argument_regs[i].value, r.argument_regs[i + 1].value,
907 r.sp.value, (i + 2) * WORD)
908 mc.LDR_ri(r.ip0.value, r.sp.value, 0)
909 mc.ADD_ri(r.sp.value, r.sp.value, (len(r.argument_regs) + 2) * WORD)
910 mc.RET_r(r.ip0.value)
911
912 # jump here
913
914 pmc = OverwritingBuilder(mc, jmp, WORD)
915 pmc.B_ofs_cond(mc.currpos() - jmp, c.NE)
916
917 mc.ADD_ri(r.sp.value, r.sp.value, (len(r.argument_regs) + 2) * WORD)
918 mc.B(self.propagate_exception_path)
919 #
920
921 rawstart = mc.materialize(self.cpu, [])
922 self.stack_check_slowpath = rawstart
923
924 def _check_frame_depth_debug(self, mc):
925 pass
926
927 def _check_frame_depth(self, mc, gcmap, expected_size=-1):
928 """ check if the frame is of enough depth to follow this bridge.
929 Otherwise reallocate the frame in a helper.
930 There are other potential solutions
931 to that, but this one does not sound too bad.
932 """
933 descrs = self.cpu.gc_ll_descr.getframedescrs(self.cpu)
934 ofs = self.cpu.unpack_fielddescr(descrs.arraydescr.lendescr)
935 mc.LDR_ri(r.ip0.value, r.fp.value, ofs)
936 stack_check_cmp_ofs = mc.currpos()
937 if expected_size == -1:
938 for _ in range(mc.get_max_size_of_gen_load_int()):
939 mc.NOP()
940 else:
941 mc.gen_load_int(r.ip1.value, expected_size)
942 mc.CMP_rr(r.ip0.value, r.ip1.value)
943
944 jg_location = mc.currpos()
945 mc.BRK()
946
947 # the size value is still stored in ip1
948 mc.SUB_ri(r.sp.value, r.sp.value, 2*WORD)
949 mc.STR_ri(r.ip1.value, r.sp.value, WORD)
950
951 mc.gen_load_int(r.ip0.value, rffi.cast(lltype.Signed, gcmap))
952 mc.STR_ri(r.ip0.value, r.sp.value, 0)
953
954 mc.BL(self._frame_realloc_slowpath)
955
956 # patch jg_location above
957 currpos = mc.currpos()
958 pmc = OverwritingBuilder(mc, jg_location, WORD)
959 pmc.B_ofs_cond(currpos - jg_location, c.GE)
960
961 self.frame_depth_to_patch.append(stack_check_cmp_ofs)
962
963 def update_frame_depth(self, frame_depth):
964 baseofs = self.cpu.get_baseofs_of_frame_field()
965 self.current_clt.frame_info.update_frame_depth(baseofs, frame_depth)
966
967 def _reload_frame_if_necessary(self, mc):
968 gcrootmap = self.cpu.gc_ll_descr.gcrootmap
969 if gcrootmap and gcrootmap.is_shadow_stack:
970 rst = gcrootmap.get_root_stack_top_addr()
971 mc.gen_load_int(r.ip0.value, rst)
972 self.load_reg(mc, r.ip0, r.ip0)
973 mc.SUB_ri(r.ip0.value, r.ip0.value, WORD)
974 mc.LDR_ri(r.fp.value, r.ip0.value, 0)
975 wbdescr = self.cpu.gc_ll_descr.write_barrier_descr
976 if gcrootmap and wbdescr:
977 # frame never uses card marking, so we enforce this is not
978 # an array
979 self._write_barrier_fastpath(mc, wbdescr, [r.fp], array=False,
980 is_frame=True)
981
982 def generate_quick_failure(self, guardtok):
983 startpos = self.mc.currpos()
984 faildescrindex, target = self.store_info_on_descr(startpos, guardtok)
985 self.load_from_gc_table(r.ip0.value, faildescrindex)
986 ofs = self.cpu.get_ofs_of_frame_field('jf_descr')
987 self.store_reg(self.mc, r.ip0, r.fp, ofs)
988 self.push_gcmap(self.mc, gcmap=guardtok.gcmap)
989 assert target
990 self.mc.BL(target)
991 return startpos
992
993 def push_gcmap(self, mc, gcmap, store=True):
994 assert store
995 ofs = self.cpu.get_ofs_of_frame_field('jf_gcmap')
996 ptr = rffi.cast(lltype.Signed, gcmap)
997 mc.gen_load_int(r.ip0.value, ptr)
998 self.store_reg(mc, r.ip0, r.fp, ofs)
999
1000 def pop_gcmap(self, mc):
1001 ofs = self.cpu.get_ofs_of_frame_field('jf_gcmap')
1002 mc.gen_load_int(r.ip0.value, 0)
1003 self.store_reg(mc, r.ip0, r.fp, ofs)
1004
1005 def write_pending_failure_recoveries(self):
1006 for tok in self.pending_guards:
1007 #generate the exit stub and the encoded representation
1008 tok.pos_recovery_stub = self.generate_quick_failure(tok)
1009
1010 def reserve_gcref_table(self, allgcrefs):
1011 gcref_table_size = len(allgcrefs) * WORD
1012 # align to a multiple of 16 and reserve space at the beginning
1013 # of the machine code for the gc table. This lets us write
1014 # machine code with relative addressing (LDR literal).
1015 gcref_table_size = (gcref_table_size + 15) & ~15
1016 mc = self.mc
1017 assert mc.get_relative_pos() == 0
1018 for i in range(gcref_table_size):
1019 mc.writechar('\x00')
1020 self.setup_gcrefs_list(allgcrefs)
1021
1022 def patch_gcref_table(self, looptoken, rawstart):
1023 # the gc table is at the start of the machine code
1024 self.gc_table_addr = rawstart
1025 tracer = self.cpu.gc_ll_descr.make_gcref_tracer(rawstart,
1026 self._allgcrefs)
1027 gcreftracers = self.get_asmmemmgr_gcreftracers(looptoken)
1028 gcreftracers.append(tracer) # keepalive
1029 self.teardown_gcrefs_list()
1030
1031 def patch_stack_checks(self, framedepth, rawstart):
1032 for ofs in self.frame_depth_to_patch:
1033 mc = InstrBuilder()
1034 mc.gen_load_int(r.ip1.value, framedepth)
1035 mc.copy_to_raw_memory(ofs + rawstart)
1036
1037 def load_from_gc_table(self, regnum, index):
1038 address_in_buffer = index * WORD # at the start of the buffer
1039 p_location = self.mc.get_relative_pos(break_basic_block=False)
1040 offset = address_in_buffer - p_location
1041 self.mc.LDR_r_literal(regnum, offset)
1042
1043 def materialize_loop(self, looptoken):
1044 self.datablockwrapper.done() # finish using cpu.asmmemmgr
1045 self.datablockwrapper = None
1046 allblocks = self.get_asmmemmgr_blocks(looptoken)
1047 size = self.mc.get_relative_pos()
1048 res = self.mc.materialize(self.cpu, allblocks,
1049 self.cpu.gc_ll_descr.gcrootmap)
1050 self.cpu.codemap.register_codemap(
1051 self.codemap_builder.get_final_bytecode(res, size))
1052 return res
1053
1054 def patch_trace(self, faildescr, looptoken, bridge_addr, regalloc):
1055 b = InstrBuilder()
1056 patch_addr = faildescr.adr_jump_offset
1057 assert patch_addr != 0
1058 b.BL(bridge_addr)
1059 b.copy_to_raw_memory(patch_addr)
1060 faildescr.adr_jump_offset = 0
1061
1062 def process_pending_guards(self, block_start):
1063 clt = self.current_clt
1064 for tok in self.pending_guards:
1065 descr = tok.faildescr
1066 assert isinstance(descr, AbstractFailDescr)
1067 failure_recovery_pos = block_start + tok.pos_recovery_stub
1068 descr.adr_jump_offset = failure_recovery_pos
1069 relative_offset = tok.pos_recovery_stub - tok.offset
1070 guard_pos = block_start + tok.offset
1071 if not tok.guard_not_invalidated():
1072 # patch the guard jump to the stub
1073 # overwrite the generate BRK with a B_offs to the pos of the
1074 # stub
1075 mc = InstrBuilder()
1076 mc.B_ofs_cond(relative_offset, c.get_opposite_of(tok.fcond))
1077 mc.copy_to_raw_memory(guard_pos)
1078 if tok.extra_offset != -1:
1079 mc = InstrBuilder()
1080 relative_offset = tok.pos_recovery_stub - tok.extra_offset
1081 guard_pos = block_start + tok.extra_offset
1082 mc.B_ofs_cond(relative_offset, c.get_opposite_of(tok.extra_cond))
1083 mc.copy_to_raw_memory(guard_pos)
1084 else:
1085 clt.invalidate_positions.append((guard_pos, relative_offset))
1086
1087 def fixup_target_tokens(self, rawstart):
1088 for targettoken in self.target_tokens_currently_compiling:
1089 targettoken._ll_loop_code += rawstart
1090 self.target_tokens_currently_compiling = None
1091
1092 def _call_header_with_stack_check(self):
1093 self._call_header()
1094 if self.stack_check_slowpath == 0:
1095 pass # no stack check (e.g. not translated)
1096 else:
1097 endaddr, lengthaddr, _ = self.cpu.insert_stack_check()
1098 # load stack end
1099 self.mc.gen_load_int(r.lr.value, endaddr) # load lr, [end]
1100 self.mc.LDR_ri(r.lr.value, r.lr.value, 0) # LDR lr, lr
1101 # load stack length
1102 self.mc.gen_load_int(r.ip1.value, lengthaddr) # load ip1, lengh
1103 self.mc.LDR_ri(r.ip1.value, r.ip1.value, 0) # ldr ip1, *lengh
1104 # calculate ofs
1105 self.mc.SUB_ri(r.ip0.value, r.sp.value, 0) # ip0 = sp
1106 # otherwise we can't use sp
1107 self.mc.SUB_rr(r.lr.value, r.lr.value, r.ip0.value) # lr = lr - ip0
1108 # if ofs
1109 self.mc.CMP_rr(r.lr.value, r.ip1.value) # CMP ip0, ip1
1110 pos = self.mc.currpos()
1111 self.mc.BRK()
1112 self.mc.BL(self.stack_check_slowpath) # call if ip0 > ip1
1113 pmc = OverwritingBuilder(self.mc, pos, WORD)
1114 pmc.B_ofs_cond(self.mc.currpos() - pos, c.LS)
1115
1116 def _call_header(self):
1117 stack_size = (len(r.callee_saved_registers) + 8) * WORD
1118 self.mc.STP_rr_preindex(r.lr.value, r.fp.value, r.sp.value, -stack_size)
1119 for i in range(0, len(r.callee_saved_registers), 2):
1120 self.mc.STP_rri(r.callee_saved_registers[i].value,
1121 r.callee_saved_registers[i + 1].value,
1122 r.sp.value,
1123 (i + 8) * WORD)
1124
1125 if self.cpu.translate_support_code:
1126 self._call_header_vmprof()
1127
1128 self.saved_threadlocal_addr = 3 * WORD # at offset 3 from location 'sp'
1129 self.mc.STR_ri(r.x1.value, r.sp.value, 3 * WORD)
1130
1131 # set fp to point to the JITFRAME, passed in argument 'x0'
1132 self.mc.MOV_rr(r.fp.value, r.x0.value)
1133 #
1134
1135 gcrootmap = self.cpu.gc_ll_descr.gcrootmap
1136 if gcrootmap and gcrootmap.is_shadow_stack:
1137 self.gen_shadowstack_header(gcrootmap)
1138
1139 def _call_header_vmprof(self):
1140 # this uses values 0, 1 and 2 on stack as vmprof next
1141 from rpython.rlib.rvmprof.rvmprof import cintf, VMPROF_JITTED_TAG
1142
1143 # tloc = address of pypy_threadlocal_s
1144 tloc = r.x1
1145 # ip0 = current value of vmprof_tl_stack
1146 offset = cintf.vmprof_tl_stack.getoffset()
1147 self.mc.LDR_ri(r.ip0.value, tloc.value, offset)
1148 # stack->next = old
1149 self.mc.STR_ri(r.ip0.value, r.sp.value, 4 * WORD)
1150 # stack->value = my sp
1151 self.mc.ADD_ri(r.ip1.value, r.sp.value, 0)
1152 self.mc.STR_ri(r.ip1.value, r.sp.value, (4 + 1) * WORD)
1153 # stack->kind = VMPROF_JITTED_TAG
1154 self.mc.gen_load_int(r.ip0.value, VMPROF_JITTED_TAG)
1155 self.mc.STR_ri(r.ip0.value, r.sp.value, (4 + 2) * WORD)
1156 # save in vmprof_tl_stack the new eax
1157 self.mc.ADD_ri(r.ip0.value, r.sp.value, 4 * WORD)
1158 self.mc.STR_ri(r.ip0.value, tloc.value, offset)
1159
1160
1161 def _assemble(self, regalloc, inputargs, operations):
1162 #self.guard_success_cc = c.cond_none
1163 regalloc.compute_hint_frame_locations(operations)
1164 self._walk_operations(inputargs, operations, regalloc)
1165 #assert self.guard_success_cc == c.cond_none
1166 frame_depth = regalloc.get_final_frame_depth()
1167 jump_target_descr = regalloc.jump_target_descr
1168 if jump_target_descr is not None:
1169 tgt_depth = jump_target_descr._arm_clt.frame_info.jfi_frame_depth
1170 target_frame_depth = tgt_depth - JITFRAME_FIXED_SIZE
1171 frame_depth = max(frame_depth, target_frame_depth)
1172 return frame_depth
1173
1174 def _walk_operations(self, inputargs, operations, regalloc):
1175 self._regalloc = regalloc
1176 regalloc.operations = operations
1177 while regalloc.position() < len(operations) - 1:
1178 regalloc.next_instruction()
1179 i = regalloc.position()
1180 op = operations[i]
1181 self.mc.mark_op(op)
1182 opnum = op.getopnum()
1183 if rop.has_no_side_effect(opnum) and op not in regalloc.longevity:
1184 regalloc.possibly_free_vars_for_op(op)
1185 elif not we_are_translated() and op.getopnum() == rop.FORCE_SPILL:
1186 regalloc.force_spill_var(op.getarg(0))
1187 elif ((rop.returns_bool_result(opnum) or op.is_ovf()) and
1188 i < len(operations) - 1 and
1189 regalloc.next_op_can_accept_cc(operations, i) or
1190 operations[i].is_ovf()):
1191 if operations[i].is_ovf():
1192 assert operations[i + 1].getopnum() in [rop.GUARD_OVERFLOW,
1193 rop.GUARD_NO_OVERFLOW]
1194 guard_op = operations[i + 1]
1195 guard_num = guard_op.getopnum()
1196 arglocs, fcond = guard_operations[guard_num](regalloc, guard_op, op)
1197 if arglocs is not None:
1198 asm_guard_operations[guard_num](self, op, guard_op, fcond, arglocs)
1199 regalloc.next_instruction() # advance one more
1200 if guard_op.is_guard(): # can be also cond_call
1201 regalloc.possibly_free_vars(guard_op.getfailargs())
1202 regalloc.possibly_free_vars_for_op(guard_op)
1203 elif (rop.is_call_may_force(op.getopnum()) or
1204 rop.is_call_release_gil(op.getopnum()) or
1205 rop.is_call_assembler(op.getopnum())):
1206 guard_op = operations[i + 1] # has to exist
1207 guard_num = guard_op.getopnum()
1208 assert guard_num in (rop.GUARD_NOT_FORCED, rop.GUARD_NOT_FORCED_2)
1209 arglocs, fcond = guard_operations[guard_num](regalloc, guard_op, op)
1210 if arglocs is not None:
1211 asm_guard_operations[guard_num](self, op, guard_op, fcond, arglocs)
1212 # fcond is abused here to pass the number of args
1213 regalloc.next_instruction() # advance one more
1214 regalloc.possibly_free_vars(guard_op.getfailargs())
1215 regalloc.possibly_free_vars_for_op(guard_op)
1216 else:
1217 arglocs = regalloc_operations[opnum](regalloc, op)
1218 if arglocs is not None:
1219 asm_operations[opnum](self, op, arglocs)
1220 if rop.is_guard(opnum):
1221 regalloc.possibly_free_vars(op.getfailargs())
1222 if op.type != 'v':
1223 regalloc.possibly_free_var(op)
1224 regalloc.possibly_free_vars_for_op(op)
1225 regalloc.free_temp_vars()
1226 regalloc._check_invariants()
1227 if not we_are_translated():
1228 self.mc.BRK()
1229 self.mc.mark_op(None) # end of the loop
1230 regalloc.operations = None
1231
1232 def dispatch_comparison(self, op):
1233 opnum = op.getopnum()
1234 arglocs = comp_operations[opnum](self._regalloc, op, True)
1235 assert arglocs is not None
1236 return asm_comp_operations[opnum](self, op, arglocs)
1237
1238 # regalloc support
1239 def load(self, loc, value):
1240 """load an immediate value into a register"""
1241 assert (loc.is_core_reg() and value.is_imm()
1242 or loc.is_vfp_reg() and value.is_imm_float())
1243 if value.is_imm():
1244 self.mc.gen_load_int(loc.value, value.getint())
1245 elif value.is_imm_float():
1246 self.mc.gen_load_int(r.ip0.value, value.getint())
1247 self.mc.LDR_di(loc.value, r.ip0.value, 0)
1248
1249 def _mov_stack_to_loc(self, prev_loc, loc):
1250 offset = prev_loc.value
1251 if loc.is_core_reg():
1252 assert prev_loc.type != FLOAT, 'trying to load from an \
1253 incompatible location into a core register'
1254 # unspill a core register
1255 assert 0 <= offset <= (1<<15) - 1
1256 self.mc.LDR_ri(loc.value, r.fp.value, offset)
1257 return
1258 if loc.is_vfp_reg():
1259 assert prev_loc.type == FLOAT, 'trying to load from an \
1260 incompatible location into a float register'
1261 assert 0 <= offset <= (1 << 15) - 1
1262 self.mc.LDR_di(loc.value, r.fp.value, offset)
1263 return
1264 assert False
1265 # elif loc.is_vfp_reg():
1266 # assert prev_loc.type == FLOAT, 'trying to load from an \
1267 # incompatible location into a float register'
1268 # # load spilled value into vfp reg
1269 # is_imm = check_imm_arg(offset)
1270 # helper, save = self.get_tmp_reg()
1271 # save_helper = not is_imm and save
1272 # elif loc.is_raw_sp():
1273 # assert (loc.type == prev_loc.type == FLOAT
1274 # or (loc.type != FLOAT and prev_loc.type != FLOAT))
1275 # tmp = loc
1276 # if loc.is_float():
1277 # loc = r.vfp_ip
1278 # else:
1279 # loc, save_helper = self.get_tmp_reg()
1280 # assert not save_helper
1281 # helper, save_helper = self.get_tmp_reg([loc])
1282 # assert not save_helper
1283 # else:
1284 # assert 0, 'unsupported case'
1285
1286 # if save_helper:
1287 # self.mc.PUSH([helper.value], cond=cond)
1288 # self.load_reg(self.mc, loc, r.fp, offset, cond=cond, helper=helper)
1289 # if save_helper:
1290 # self.mc.POP([helper.value], cond=cond)
1291
1292 def _mov_reg_to_loc(self, prev_loc, loc):
1293 if loc.is_core_reg():
1294 self.mc.MOV_rr(loc.value, prev_loc.value)
1295 elif loc.is_stack():
1296 self.mc.STR_ri(prev_loc.value, r.fp.value, loc.value)
1297 else:
1298 assert False
1299
1300 def _mov_imm_to_loc(self, prev_loc, loc):
1301 if loc.is_core_reg():
1302 self.mc.gen_load_int(loc.value, prev_loc.value)
1303 elif loc.is_stack():
1304 self.mc.gen_load_int(r.ip0.value, prev_loc.value)
1305 self.mc.STR_ri(r.ip0.value, r.fp.value, loc.value)
1306 else:
1307 assert False
1308
1309 def new_stack_loc(self, i, tp):
1310 base_ofs = self.cpu.get_baseofs_of_frame_field()
1311 return StackLocation(i, get_fp_offset(base_ofs, i), tp)
1312
1313 def mov_loc_to_raw_stack(self, loc, pos):
1314 if loc.is_core_reg():
1315 self.mc.STR_ri(loc.value, r.sp.value, pos)
1316 elif loc.is_stack():
1317 self.mc.LDR_ri(r.ip0.value, r.fp.value, loc.value)
1318 self.mc.STR_ri(r.ip0.value, r.sp.value, pos)
1319 elif loc.is_vfp_reg():
1320 self.mc.STR_di(loc.value, r.sp.value, pos)
1321 elif loc.is_imm():
1322 self.mc.gen_load_int(r.ip0.value, loc.value)
1323 self.mc.STR_ri(r.ip0.value, r.sp.value, pos)
1324 else:
1325 assert False, "wrong loc"
1326
1327 def mov_raw_stack_to_loc(self, pos, loc):
1328 if loc.is_core_reg():
1329 self.mc.LDR_ri(loc.value, r.sp.value, pos)
1330 elif loc.is_stack():
1331 self.mc.LDR_ri(r.ip0.value, r.sp.value, pos)
1332 self.mc.STR_ri(r.ip0.value, r.fp.value, loc.value)
1333 elif loc.is_vfp_reg():
1334 self.mc.LDR_di(loc.value, r.sp.value, pos)
1335 else:
1336 assert False, "wrong loc"
1337
1338 def _mov_imm_float_to_loc(self, prev_loc, loc):
1339 if loc.is_vfp_reg():
1340 self.load(loc, prev_loc)
1341 elif loc.is_stack():
1342 self.load(r.vfp_ip, prev_loc)
1343 self._mov_vfp_reg_to_loc(r.vfp_ip, loc)
1344 else:
1345 assert False, "wrong loc"
1346
1347 def _mov_vfp_reg_to_loc(self, prev_loc, loc):
1348 if loc.is_stack():
1349 self.mc.STR_di(prev_loc.value, r.fp.value, loc.value)
1350 elif loc.is_vfp_reg():
1351 self.mc.FMOV_dd(loc.value, prev_loc.value)
1352 else:
1353 assert False, "wrong loc"
1354
1355 def push_locations(self, locs):
1356 if not locs:
1357 return
1358 depth = len(locs) * WORD
1359 depth += depth & WORD # align
1360 self.mc.SUB_ri(r.sp.value, r.sp.value, depth)
1361 for i, loc in enumerate(locs):
1362 self.mov_loc_to_raw_stack(loc, i * WORD)
1363
1364 def pop_locations(self, locs):
1365 if not locs:
1366 return
1367 depth = len(locs) * WORD
1368 depth += depth & WORD # align
1369 for i, loc in enumerate(locs):
1370 self.mov_raw_stack_to_loc(i * WORD, loc)
1371 self.mc.ADD_ri(r.sp.value, r.sp.value, depth)
1372
1373 def regalloc_mov(self, prev_loc, loc):
1374 """Moves a value from a previous location to some other location"""
1375 if prev_loc.is_imm():
1376 return self._mov_imm_to_loc(prev_loc, loc)
1377 elif prev_loc.is_core_reg():
1378 self._mov_reg_to_loc(prev_loc, loc)
1379 elif prev_loc.is_stack():
1380 self._mov_stack_to_loc(prev_loc, loc)
1381 elif prev_loc.is_imm_float():
1382 self._mov_imm_float_to_loc(prev_loc, loc)
1383 elif prev_loc.is_vfp_reg():
1384 self._mov_vfp_reg_to_loc(prev_loc, loc)
1385 else:
1386 assert 0, 'unsupported case'
1387 mov_loc_loc = regalloc_mov
1388
1389 def gen_func_epilog(self, mc=None):
1390 gcrootmap = self.cpu.gc_ll_descr.gcrootmap
1391 if mc is None:
1392 mc = self.mc
1393 if gcrootmap and gcrootmap.is_shadow_stack:
1394 self.gen_footer_shadowstack(gcrootmap, mc)
1395
1396 if self.cpu.translate_support_code:
1397 self._call_footer_vmprof(mc)
1398 # pop all callee saved registers
1399
1400 stack_size = (len(r.callee_saved_registers) + 8) * WORD
1401
1402 for i in range(0, len(r.callee_saved_registers), 2):
1403 mc.LDP_rri(r.callee_saved_registers[i].value,
1404 r.callee_saved_registers[i + 1].value,
1405 r.sp.value,
1406 (i + 8) * WORD)
1407 mc.LDP_rr_postindex(r.lr.value, r.fp.value, r.sp.value, stack_size)
1408
1409
1410 mc.RET_r(r.lr.value)
1411
1412 def _call_footer_vmprof(self, mc):
1413 from rpython.rlib.rvmprof.rvmprof import cintf
1414 # ip0 = address of pypy_threadlocal_s
1415 mc.LDR_ri(r.ip0.value, r.sp.value, 3 * WORD)
1416 # ip1 = (our local vmprof_tl_stack).next
1417 mc.LDR_ri(r.ip1.value, r.sp.value, 4 * WORD)
1418 # save in vmprof_tl_stack the value eax
1419 offset = cintf.vmprof_tl_stack.getoffset()
1420 mc.STR_ri(r.ip1.value, r.ip0.value, offset)
1421
1422 def gen_shadowstack_header(self, gcrootmap):
1423 # we push two words, like the x86 backend does:
1424 # the '1' is to benefit from the shadowstack 'is_minor' optimization
1425 rst = gcrootmap.get_root_stack_top_addr()
1426 self.mc.gen_load_int(r.ip1.value, rst)
1427 # x8 = *ip1
1428 self.load_reg(self.mc, r.x8, r.ip1)
1429 # x8[0] = 1
1430 self.mc.gen_load_int(r.ip0.value, 1)
1431 self.store_reg(self.mc, r.ip0, r.x8)
1432 # x8[1] = r.fp
1433 self.store_reg(self.mc, r.fp, r.x8, WORD)
1434 # *ip1 = x8 + 2 * WORD
1435 self.mc.ADD_ri(r.x8.value, r.x8.value, 2 * WORD)
1436 self.store_reg(self.mc, r.x8, r.ip1)
1437
1438 def gen_footer_shadowstack(self, gcrootmap, mc):
1439 rst = gcrootmap.get_root_stack_top_addr()
1440 mc.gen_load_int(r.ip0.value, rst)
1441 self.load_reg(mc, r.ip1, r.ip0)
1442 mc.SUB_ri(r.ip1.value, r.ip1.value, 2 * WORD) # two words, see above
1443 self.store_reg(mc, r.ip1, r.ip0)
1444
1445 def store_reg(self, mc, source, base, ofs=0, helper=None):
1446 if source.is_vfp_reg():
1447 return self._store_vfp_reg(mc, source, base, ofs)
1448 else:
1449 return self._store_core_reg(mc, source, base, ofs)
1450
1451 def _store_vfp_reg(self, mc, source, base, ofs):
1452 assert ofs <= (1 << 15) - 1
1453 mc.STR_di(source.value, base.value, ofs)
1454
1455 def _store_core_reg(self, mc, source, base, ofs):
1456 # XXX fix:
1457 assert ofs & 0x7 == 0
1458 assert 0 <= ofs < 32768
1459 mc.STR_ri(source.value, base.value, ofs)
1460 #if check_imm_arg(ofs):
1461 # mc.STR_ri(source.value, base.value, imm=ofs)
1462 #else:
1463 # mc.gen_load_int(r.ip1, ofs)
1464 # mc.STR_rr(source.value, base.value, r.ip1)
1465
1466 def load_reg(self, mc, target, base, ofs=0, helper=r.ip0):
1467 assert target.is_core_reg()
1468 if check_imm_arg(abs(ofs)):
1469 mc.LDR_ri(target.value, base.value, ofs)
1470 else:
1471 mc.gen_load_int(helper.value, ofs)
1472 mc.LDR_rr(target.value, base.value, helper.value)
1473
1474 def check_frame_before_jump(self, target_token):
1475 if target_token in self.target_tokens_currently_compiling:
1476 return
1477 if target_token._arm_clt is self.current_clt:
1478 return
1479 # We can have a frame coming from god knows where that's
1480 # passed to a jump to another loop. Make sure it has the
1481 # correct depth
1482 expected_size = target_token._arm_clt.frame_info.jfi_frame_depth
1483 self._check_frame_depth(self.mc, self._regalloc.get_gcmap(),
1484 expected_size=expected_size)
1485
1486 # ../x86/assembler.py:668
1487 @rgc.no_release_gil
1488 def redirect_call_assembler(self, oldlooptoken, newlooptoken):
1489 rmmap.enter_assembler_writing()
1490 try:
1491 # some minimal sanity checking
1492 old_nbargs = oldlooptoken.compiled_loop_token._debug_nbargs
1493 new_nbargs = newlooptoken.compiled_loop_token._debug_nbargs
1494 assert old_nbargs == new_nbargs
1495 # we overwrite the instructions at the old _ll_function_addr
1496 # to start with a JMP to the new _ll_function_addr.
1497 # Ideally we should rather patch all existing CALLs, but well.
1498 oldadr = oldlooptoken._ll_function_addr
1499 target = newlooptoken._ll_function_addr
1500 # copy frame-info data
1501 baseofs = self.cpu.get_baseofs_of_frame_field()
1502 newlooptoken.compiled_loop_token.update_frame_info(
1503 oldlooptoken.compiled_loop_token, baseofs)
1504 mc = InstrBuilder()
1505 mc.B(target)
1506 mc.copy_to_raw_memory(oldadr)
1507 #
1508 jl.redirect_assembler(oldlooptoken, newlooptoken, newlooptoken.number)
1509 finally:
1510 rmmap.leave_assembler_writing()
1511
1512
1513
1514 def not_implemented(msg):
1515 msg = '[ARM64/asm] %s\n' % msg
1516 if we_are_translated():
1517 llop.debug_print(lltype.Void, msg)
1518 raise NotImplementedError(msg)
1519
1520
1521 def notimplemented_op(self, op, arglocs):
1522 llop.debug_print(lltype.Void, "[ARM64/asm] %s not implemented" % op.getopname())
1523 raise NotImplementedError(op)
1524
1525 def notimplemented_comp_op(self, op, arglocs):
1526 llop.debug_print(lltype.Void, "[ARM64/asm] %s not implemented" % op.getopname())
1527 raise NotImplementedError(op)
1528
1529 def notimplemented_guard_op(self, op, guard_op, fcond, arglocs):
1530 llop.debug_print(lltype.Void, "[ARM64/asm] %s not implemented" % op.getopname())
1531 raise NotImplementedError(op)
1532
1533 asm_operations = [notimplemented_op] * (rop._LAST + 1)
1534 asm_guard_operations = [notimplemented_guard_op] * (rop._LAST + 1)
1535 asm_comp_operations = [notimplemented_comp_op] * (rop._LAST + 1)
1536 asm_extra_operations = {}
1537
1538 for name, value in ResOpAssembler.__dict__.iteritems():
1539 if name.startswith('emit_opx_'):
1540 opname = name[len('emit_opx_'):]
1541 num = getattr(EffectInfo, 'OS_' + opname.upper())
1542 asm_extra_operations[num] = value
1543 elif name.startswith('emit_op_'):
1544 opname = name[len('emit_op_'):]
1545 num = getattr(rop, opname.upper())
1546 asm_operations[num] = value
1547 elif name.startswith('emit_guard_op_'):
1548 opname = name[len('emit_guard_op_'):]
1549 num = getattr(rop, opname.upper())
1550 asm_guard_operations[num] = value
1551 elif name.startswith('emit_comp_op_'):
1552 opname = name[len('emit_comp_op_'):]
1553 num = getattr(rop, opname.upper())
1554 asm_comp_operations[num] = value