Debian Codegraph @

rpython/translator/c/gc.py

raw symbols SCIP
1 import sys
2 from rpython.flowspace.model import Constant
3 from rpython.rtyper.lltypesystem.lltype import (RttiStruct,
4 RuntimeTypeInfo)
5 from rpython.translator.c.node import ContainerNode
6 from rpython.translator.c.support import cdecl
7 from rpython.translator.tool.cbuild import ExternalCompilationInfo
8
9 class BasicGcPolicy(object):
10
11 def __init__(self, db, thread_enabled=False):
12 self.db = db
13 self.thread_enabled = thread_enabled
14
15 def common_gcheader_definition(self, defnode):
16 if defnode.db.gctransformer is not None:
17 return defnode.db.gctransformer.HDR
18 return None
19
20 def struct_gcheader_definition(self, defnode):
21 return self.common_gcheader_definition(defnode)
22
23 def array_gcheader_definition(self, defnode):
24 return self.common_gcheader_definition(defnode)
25
26 def compilation_info(self):
27 if not self.db:
28 return ExternalCompilationInfo()
29
30 gct = self.db.gctransformer
31 return ExternalCompilationInfo(
32 pre_include_bits=['/* using %s */' % (gct.__class__.__name__,),
33 '#define MALLOC_ZERO_FILLED %d' % (gct.malloc_zero_filled,),
34 ]
35 )
36
37 def need_no_typeptr(self):
38 return False
39
40 def gc_startup_code(self):
41 return []
42
43 def struct_setup(self, structdefnode, rtti):
44 return None
45
46 def array_setup(self, arraydefnode):
47 return None
48
49 def rtti_type(self):
50 return ''
51
52 def OP_GC_SET_MAX_HEAP_SIZE(self, funcgen, op):
53 return ''
54
55 def OP_GC_THREAD_PREPARE(self, funcgen, op):
56 return ''
57
58 def OP_GC_THREAD_RUN(self, funcgen, op):
59 # The gc transformer leaves this operation in the graphs
60 # in all cases except with framework+shadowstack. In that
61 # case the operation is removed because redundant with
62 # rthread.get_or_make_ident().
63 return 'RPY_THREADLOCALREF_ENSURE();'
64
65 def OP_GC_THREAD_START(self, funcgen, op):
66 return ''
67
68 def OP_GC_THREAD_DIE(self, funcgen, op):
69 # The gc transformer leaves this operation in the graphs
70 # (but may insert a call to a gcrootfinder-specific
71 # function just before).
72 return 'RPython_ThreadLocals_ThreadDie();'
73
74 def OP_GC_THREAD_BEFORE_FORK(self, funcgen, op):
75 return '%s = NULL;' % funcgen.expr(op.result)
76
77 def OP_GC_THREAD_AFTER_FORK(self, funcgen, op):
78 return ''
79
80 def OP_GC_WRITEBARRIER(self, funcgen, op):
81 return ''
82
83 def OP_GC_STACK_BOTTOM(self, funcgen, op):
84 return ''
85
86 def OP_GC_GCFLAG_EXTRA(self, funcgen, op):
87 return '%s = 0; /* gc_gcflag_extra%r */' % (
88 funcgen.expr(op.result),
89 op.args[0])
90
91
92 class RefcountingInfo:
93 static_deallocator = None
94
95 class RefcountingGcPolicy(BasicGcPolicy):
96
97 def gettransformer(self, translator, gchooks):
98 from rpython.memory.gctransform import refcounting
99 return refcounting.RefcountingGCTransformer(translator)
100
101 # for structs
102
103 def struct_setup(self, structdefnode, rtti):
104 if rtti is not None:
105 transformer = structdefnode.db.gctransformer
106 fptr = transformer.static_deallocation_funcptr_for_type(
107 structdefnode.STRUCT)
108 structdefnode.gcinfo = RefcountingInfo()
109 structdefnode.gcinfo.static_deallocator = structdefnode.db.get(fptr)
110
111 # for arrays
112
113 def array_setup(self, arraydefnode):
114 pass
115
116 # for rtti node
117
118 def rtti_type(self):
119 return 'void (@)(void *)' # void dealloc_xx(struct xx *)
120
121 def rtti_node_factory(self):
122 return RefcountingRuntimeTypeInfo_OpaqueNode
123
124 # zero malloc impl
125
126 def OP_GC_CALL_RTTI_DESTRUCTOR(self, funcgen, op):
127 args = [funcgen.expr(v) for v in op.args]
128 line = '%s(%s);' % (args[0], ', '.join(args[1:]))
129 return line
130
131 def OP_GC_FREE(self, funcgen, op):
132 args = [funcgen.expr(v) for v in op.args]
133 return 'OP_FREE(%s);' % (args[0], )
134
135 def OP_GC__COLLECT(self, funcgen, op):
136 return ''
137
138 def OP_GC__DISABLE_FINALIZERS(self, funcgen, op):
139 return ''
140
141 def OP_GC__ENABLE_FINALIZERS(self, funcgen, op):
142 return ''
143
144
145 class RefcountingRuntimeTypeInfo_OpaqueNode(ContainerNode):
146 nodekind = 'refcnt rtti'
147 globalcontainer = True
148 typename = 'void (@)(void *)'
149 _funccodegen_owner = None
150
151 def __init__(self, db, T, obj):
152 assert T == RuntimeTypeInfo
153 assert isinstance(obj.about, RttiStruct)
154 self.db = db
155 self.T = T
156 self.obj = obj
157 defnode = db.gettypedefnode(obj.about)
158 self.implementationtypename = 'void (@)(void *)'
159 self.name = defnode.gcinfo.static_deallocator
160
161 def getptrname(self):
162 return '((void (*)(void *)) %s)' % (self.name,)
163
164 def enum_dependencies(self):
165 return []
166
167 def implementation(self):
168 return []
169
170
171
172 class BoehmInfo:
173 finalizer = None
174
175
176 class BoehmGcPolicy(BasicGcPolicy):
177
178 def gettransformer(self, translator, gchooks):
179 from rpython.memory.gctransform import boehm
180 return boehm.BoehmGCTransformer(translator)
181
182 def array_setup(self, arraydefnode):
183 pass
184
185 def struct_setup(self, structdefnode, rtti):
186 pass
187
188 def rtti_type(self):
189 return BoehmGcRuntimeTypeInfo_OpaqueNode.typename
190
191 def rtti_node_factory(self):
192 return BoehmGcRuntimeTypeInfo_OpaqueNode
193
194 def compilation_info(self):
195 eci = BasicGcPolicy.compilation_info(self)
196
197 from rpython.rtyper.tool.rffi_platform import configure_boehm
198 eci = eci.merge(configure_boehm())
199
200 pre_include_bits = []
201 if sys.platform.startswith('linux'):
202 pre_include_bits += ["#define _REENTRANT 1",
203 "#define GC_LINUX_THREADS 1"]
204 if sys.platform != "win32" and not sys.platform.startswith("openbsd"):
205 # GC_REDIRECT_TO_LOCAL is not supported on Win32 by gc6.8
206 pre_include_bits += ["#define GC_REDIRECT_TO_LOCAL 1"]
207
208 hdr_flag = ''
209 if not getattr(self.db.gctransformer, 'NO_HEADER', False):
210 hdr_flag = '-DPYPY_BOEHM_WITH_HEADER'
211
212 eci = eci.merge(ExternalCompilationInfo(
213 pre_include_bits=pre_include_bits,
214 # The following define is required by the thread module,
215 # See module/thread/test/test_rthread.py
216 compile_extra=['-DPYPY_USING_BOEHM_GC', hdr_flag],
217 ))
218
219 gct = self.db.gctransformer
220 gct.finalizer_triggers = tuple(gct.finalizer_triggers) # stop changing
221 sourcelines = ['']
222 for trig in gct.finalizer_triggers:
223 sourcelines.append('RPY_EXTERN void %s(void);' % (
224 self.db.get(trig),))
225 sourcelines.append('')
226 sourcelines.append('void (*boehm_fq_trigger[])(void) = {')
227 for trig in gct.finalizer_triggers:
228 sourcelines.append('\t%s,' % (self.db.get(trig),))
229 sourcelines.append('\tNULL')
230 sourcelines.append('};')
231 sourcelines.append('struct boehm_fq_s *boehm_fq_queues[%d];' % (
232 len(gct.finalizer_triggers) or 1,))
233 sourcelines.append('')
234 eci = eci.merge(ExternalCompilationInfo(
235 separate_module_sources=['\n'.join(sourcelines)]))
236
237 return eci
238
239 def gc_startup_code(self):
240 if sys.platform == 'win32':
241 pass # yield 'assert(GC_all_interior_pointers == 0);'
242 else:
243 yield 'GC_all_interior_pointers = 0;'
244 yield 'boehm_gc_startup_code();'
245
246 def get_real_weakref_type(self):
247 return self.db.gctransformer.WEAKLINK
248
249 def convert_weakref_to(self, ptarget):
250 return self.db.gctransformer.convert_weakref_to(ptarget)
251
252 def OP_GC__COLLECT(self, funcgen, op):
253 return 'GC_gcollect();'
254
255 def OP_GC_SET_MAX_HEAP_SIZE(self, funcgen, op):
256 nbytes = funcgen.expr(op.args[0])
257 return 'GC_set_max_heap_size(%s);' % (nbytes,)
258
259 def GC_KEEPALIVE(self, funcgen, v):
260 return 'pypy_asm_keepalive(%s);' % funcgen.expr(v)
261
262 class BoehmGcRuntimeTypeInfo_OpaqueNode(ContainerNode):
263 nodekind = 'boehm rtti'
264 globalcontainer = True
265 typename = 'char @'
266 _funccodegen_owner = None
267
268 def __init__(self, db, T, obj):
269 assert T == RuntimeTypeInfo
270 assert isinstance(obj.about, RttiStruct)
271 self.db = db
272 self.T = T
273 self.obj = obj
274 defnode = db.gettypedefnode(obj.about)
275 self.implementationtypename = self.typename
276 self.name = self.db.namespace.uniquename('g_rtti_v_'+ defnode.barename)
277
278 def getptrname(self):
279 return '(&%s)' % (self.name,)
280
281 def enum_dependencies(self):
282 return []
283
284 def implementation(self):
285 yield 'char %s /* uninitialized */;' % self.name
286
287 class FrameworkGcRuntimeTypeInfo_OpaqueNode(BoehmGcRuntimeTypeInfo_OpaqueNode):
288 nodekind = 'framework rtti'
289
290
291 # to get an idea how it looks like with no refcount/gc at all
292
293 class NoneGcPolicy(BoehmGcPolicy):
294
295 gc_startup_code = RefcountingGcPolicy.gc_startup_code.im_func
296
297 def compilation_info(self):
298 eci = BasicGcPolicy.compilation_info(self)
299 eci = eci.merge(ExternalCompilationInfo(
300 post_include_bits=['#define PYPY_USING_NO_GC_AT_ALL'],
301 ))
302 return eci
303
304
305 class BasicFrameworkGcPolicy(BasicGcPolicy):
306
307 def gettransformer(self, translator, gchooks):
308 if hasattr(self, 'transformerclass'): # for rpython/memory tests
309 return self.transformerclass(translator, gchooks=gchooks)
310 raise NotImplementedError
311
312 def struct_setup(self, structdefnode, rtti):
313 if rtti is not None and hasattr(rtti._obj, 'destructor_funcptr'):
314 gctransf = self.db.gctransformer
315 TYPE = structdefnode.STRUCT
316 fptrs = gctransf.special_funcptr_for_type(TYPE)
317 # make sure this is seen by the database early, i.e. before
318 # finish_helpers() on the gctransformer
319 destrptr = rtti._obj.destructor_funcptr
320 self.db.get(destrptr)
321 # the following, on the other hand, will only discover ll_finalizer
322 # helpers. The get() sees and records a delayed pointer. It is
323 # still important to see it so that it can be followed as soon as
324 # the mixlevelannotator resolves it.
325 for fptr in fptrs.values():
326 self.db.get(fptr)
327
328 def array_setup(self, arraydefnode):
329 pass
330
331 def rtti_type(self):
332 return FrameworkGcRuntimeTypeInfo_OpaqueNode.typename
333
334 def rtti_node_factory(self):
335 return FrameworkGcRuntimeTypeInfo_OpaqueNode
336
337 def gc_startup_code(self):
338 fnptr = self.db.gctransformer.frameworkgc_setup_ptr.value
339 yield '%s();' % (self.db.get(fnptr),)
340
341 def get_real_weakref_type(self):
342 from rpython.memory.gctypelayout import WEAKREF
343 return WEAKREF
344
345 def convert_weakref_to(self, ptarget):
346 from rpython.memory.gctypelayout import convert_weakref_to
347 return convert_weakref_to(ptarget)
348
349 def OP_GC_RELOAD_POSSIBLY_MOVED(self, funcgen, op):
350 if isinstance(op.args[1], Constant):
351 return '/* %s */' % (op,)
352 else:
353 args = [funcgen.expr(v) for v in op.args]
354 return '%s = %s; /* for moving GCs */' % (args[1], args[0])
355
356 def need_no_typeptr(self):
357 config = self.db.translator.config
358 return config.translation.gcremovetypeptr
359
360 def header_type(self, extra='*'):
361 # Fish out the C name of the 'struct pypy_header0'
362 HDR = self.db.gctransformer.HDR
363 return self.db.gettype(HDR).replace('@', extra)
364
365 def tid_fieldname(self, tid_field='tid'):
366 # Fish out the C name of the tid field.
367 HDR = self.db.gctransformer.HDR
368 hdr_node = self.db.gettypedefnode(HDR)
369 return hdr_node.c_struct_field_name(tid_field)
370
371 def OP_GC_GETTYPEPTR_GROUP(self, funcgen, op):
372 # expands to a number of steps, as per rpython/lltypesystem/opimpl.py,
373 # all implemented by a single call to a C macro.
374 [v_obj, c_grpptr, c_skipoffset, c_vtableinfo] = op.args
375 tid_field = c_vtableinfo.value[2]
376 typename = funcgen.db.gettype(op.result.concretetype)
377 return (
378 '%s = (%s)_OP_GET_NEXT_GROUP_MEMBER(%s, (pypy_halfword_t)%s->'
379 '_gcheader.%s, %s);'
380 % (funcgen.expr(op.result),
381 cdecl(typename, ''),
382 funcgen.expr(c_grpptr),
383 funcgen.expr(v_obj),
384 self.tid_fieldname(tid_field),
385 funcgen.expr(c_skipoffset)))
386
387 def OP_GC_WRITEBARRIER(self, funcgen, op):
388 raise Exception("the FramewokGCTransformer should handle this")
389
390 def OP_GC_GCFLAG_EXTRA(self, funcgen, op):
391 subopnum = op.args[0].value
392 if subopnum != 4:
393 gcflag_extra = self.db.gctransformer.gcdata.gc.gcflag_extra
394 else:
395 gcflag_extra = self.db.gctransformer.gcdata.gc.gcflag_dummy
396 #
397 if gcflag_extra == 0:
398 return BasicGcPolicy.OP_GC_GCFLAG_EXTRA(self, funcgen, op)
399 if subopnum == 1:
400 return '%s = 1; /* has_gcflag_extra */' % (
401 funcgen.expr(op.result),)
402 hdrfield = '((%s)%s)->%s' % (self.header_type(),
403 funcgen.expr(op.args[1]),
404 self.tid_fieldname())
405 parts = ['%s = (%s & %dL) != 0;' % (funcgen.expr(op.result),
406 hdrfield,
407 gcflag_extra)]
408 if subopnum == 2: # get_gcflag_extra
409 parts.append('/* get_gcflag_extra */')
410 elif subopnum == 3: # toggle_gcflag_extra
411 parts.insert(0, '%s ^= %dL;' % (hdrfield,
412 gcflag_extra))
413 parts.append('/* toggle_gcflag_extra */')
414 elif subopnum == 4: # get_gcflag_dummy
415 parts.append('/* get_gcflag_dummy */')
416 else:
417 raise AssertionError(subopnum)
418 return ' '.join(parts)
419
420 def OP_GC_BIT(self, funcgen, op):
421 # This is a two-arguments operation (x, y) where x is a
422 # pointer and y is a constant power of two. It returns 0 if
423 # "(*(Signed*)x) & y == 0", and non-zero if it is "== y".
424 #
425 # On x86-64, emitting this is better than emitting a load
426 # followed by an INT_AND for the case where y doesn't fit in
427 # 32 bits. I've seen situations where a register was wasted
428 # to contain the constant 2**32 throughout a complete messy
429 # function; the goal of this GC_BIT is to avoid that.
430 #
431 # Don't abuse, though. If you need to check several bits in
432 # sequence, then it's likely better to load the whole Signed
433 # first; using GC_BIT would result in multiple accesses to
434 # memory.
435 #
436 bitmask = op.args[1].value
437 assert bitmask > 0 and (bitmask & (bitmask - 1)) == 0
438 offset = 0
439 while bitmask >= 0x100:
440 offset += 1
441 bitmask >>= 8
442 if sys.byteorder == 'big':
443 offset = 'sizeof(Signed)-%s' % (offset+1)
444 return '%s = ((char *)%s)[%s] & %d;' % (funcgen.expr(op.result),
445 funcgen.expr(op.args[0]),
446 offset, bitmask)
447
448 class ShadowStackFrameworkGcPolicy(BasicFrameworkGcPolicy):
449
450 def gettransformer(self, translator, gchooks):
451 from rpython.memory.gctransform import shadowstack
452 return shadowstack.ShadowStackFrameworkGCTransformer(translator, gchooks)
453
454 def enter_roots_frame(self, funcgen, (c_gcdata, c_numcolors)):
455 numcolors = c_numcolors.value
456 # XXX hard-code the field name here
457 gcpol_ss = '%s->gcd_inst_root_stack_top' % funcgen.expr(c_gcdata)
458 #
459 yield ('typedef struct { char %s; } pypy_ss_t;'
460 % ', '.join(['*s%d' % i for i in range(numcolors)]))
461 funcgen.gcpol_ss = gcpol_ss
462
463 def OP_GC_PUSH_ROOTS(self, funcgen, op):
464 raise Exception("gc_push_roots should be removed by postprocess_graph")
465
466 def OP_GC_POP_ROOTS(self, funcgen, op):
467 raise Exception("gc_pop_roots should be removed by postprocess_graph")
468
469 def OP_GC_ENTER_ROOTS_FRAME(self, funcgen, op):
470 # avoid arithmatic on void*
471 return '({0}) = (char*)({0}) + sizeof(pypy_ss_t);'.format(funcgen.gcpol_ss,)
472
473 def OP_GC_LEAVE_ROOTS_FRAME(self, funcgen, op):
474 # avoid arithmatic on void*
475 return '({0}) = (char*)({0}) - sizeof(pypy_ss_t);'.format(funcgen.gcpol_ss,)
476
477 def OP_GC_SAVE_ROOT(self, funcgen, op):
478 num = op.args[0].value
479 exprvalue = funcgen.expr(op.args[1])
480 return '((pypy_ss_t *)%s)[-1].s%d = (char *)%s;' % (
481 funcgen.gcpol_ss, num, exprvalue)
482
483 def OP_GC_RESTORE_ROOT(self, funcgen, op):
484 num = op.args[0].value
485 exprvalue = funcgen.expr(op.args[1])
486 typename = funcgen.db.gettype(op.args[1].concretetype)
487 result = '%s = (%s)((pypy_ss_t *)%s)[-1].s%d;' % (
488 exprvalue, cdecl(typename, ''), funcgen.gcpol_ss, num)
489 if isinstance(op.args[1], Constant):
490 return '/* %s */' % result
491 else:
492 return result
493
494
495 name_to_gcpolicy = {
496 'boehm': BoehmGcPolicy,
497 'ref': RefcountingGcPolicy,
498 'none': NoneGcPolicy,
499 'framework+shadowstack': ShadowStackFrameworkGcPolicy,
500 }
501
502