Debian Codegraph @

rpython/translator/c/funcgen.py

raw symbols SCIP
1 import sys
2 from rpython.translator.c.support import cdecl
3 from rpython.translator.c.support import llvalue_from_constant, gen_assignments
4 from rpython.translator.c.support import c_string_constant, barebonearray
5 from rpython.flowspace.model import Variable, Constant, mkentrymap
6 from rpython.rtyper.lltypesystem.lltype import (Ptr, Void, Bool, Signed, Unsigned,
7 SignedLongLong, Float, UnsignedLongLong, Char, UniChar, ContainerType,
8 Array, FixedSizeArray, ForwardReference, FuncType, typeOf)
9 from rpython.rtyper.lltypesystem.rffi import INT
10 from rpython.rtyper.lltypesystem.llmemory import Address
11 from rpython.translator.backendopt.ssa import SSI_to_SSA
12 from rpython.translator.backendopt.innerloop import find_inner_loops
13 from rpython.tool.identity_dict import identity_dict
14 from rpython.rlib.objectmodel import CDefinedIntSymbolic
15
16
17 LOCALVAR = 'l_%s'
18
19 KEEP_INLINED_GRAPHS = False
20
21 def make_funcgen(graph, db, exception_policy, functionname):
22 graph._seen_by_the_backend = True
23 # apply the exception transformation
24 if db.exctransformer:
25 db.exctransformer.create_exception_handling(graph)
26 # apply the gc transformation
27 if db.gctransformer:
28 db.gctransformer.transform_graph(graph)
29 return FunctionCodeGenerator(graph, db, exception_policy, functionname)
30
31 class FunctionCodeGenerator(object):
32 """
33 Collects information about a function which we have to generate
34 from a flow graph.
35 """
36 def __init__(self, graph, db, exception_policy, functionname):
37 self.graph = graph
38 self.db = db
39 self.gcpolicy = db.gcpolicy
40 self.exception_policy = exception_policy
41 self.functionname = functionname
42
43 self.collect_var_and_types()
44 for v in self.vars:
45 T = v.concretetype
46 # obscure: skip forward references and hope for the best
47 # (needed for delayed function pointers)
48 if isinstance(T, Ptr) and T.TO.__class__ == ForwardReference:
49 continue
50 db.gettype(T) # force the type to be considered by the database
51
52 self.illtypes = None
53
54 def collect_var_and_types(self):
55 #
56 # collect all variables and constants used in the body,
57 # and get their types now
58 #
59 # NOTE: cannot use dictionaries with Constants as keys, because
60 # Constants may hash and compare equal but have different lltypes
61 self.all_cached_consts = None # will be filled after implementation_end
62 mix = [self.graph.getreturnvar()]
63 self.more_ll_values = []
64 for block in self.graph.iterblocks():
65 mix.extend(block.inputargs)
66 for op in block.operations:
67 mix.extend(op.args)
68 mix.append(op.result)
69 for link in block.exits:
70 mix.extend(link.getextravars())
71 mix.extend(link.args)
72 if hasattr(link, 'llexitcase'):
73 self.more_ll_values.append(link.llexitcase)
74 elif link.exitcase is not None:
75 mix.append(Constant(link.exitcase))
76
77 uniquemix = []
78 seen = identity_dict()
79 for v in mix:
80 if v not in seen:
81 uniquemix.append(v)
82 seen[v] = True
83 self.vars = uniquemix
84
85 def implementation_begin(self):
86 SSI_to_SSA(self.graph)
87 self.collect_var_and_types()
88 self.blocknum = {}
89 for block in self.graph.iterblocks():
90 self.blocknum[block] = len(self.blocknum)
91 db = self.db
92 lltypes = identity_dict()
93 for v in self.vars:
94 T = v.concretetype
95 typename = db.gettype(T)
96 lltypes[v] = T, typename
97 self.illtypes = lltypes
98 self.innerloops = {} # maps the loop's header block to a Loop()
99 for loop in find_inner_loops(self.graph, Bool):
100 self.innerloops[loop.headblock] = loop
101
102 def graphs_to_patch(self):
103 yield self.graph
104
105 def implementation_end(self):
106 self.all_cached_consts = list(self.allconstantvalues())
107 self.illtypes = None
108 self.vars = None
109 self.blocknum = None
110 self.innerloops = None
111
112 def argnames(self):
113 return [LOCALVAR % v.name for v in self.graph.getargs()]
114
115 def allvariables(self):
116 return [v for v in self.vars if isinstance(v, Variable)]
117
118 def allconstants(self):
119 return [c for c in self.vars if isinstance(c, Constant)]
120
121 def allconstantvalues(self):
122 for c in self.vars:
123 if isinstance(c, Constant):
124 yield llvalue_from_constant(c)
125 for llvalue in self.more_ll_values:
126 yield llvalue
127
128 def lltypemap(self, v):
129 T, typename = self.illtypes[v]
130 return T
131
132 def lltypename(self, v):
133 T, typename = self.illtypes[v]
134 return typename
135
136 def expr(self, v, special_case_void=True):
137 if isinstance(v, Variable):
138 if self.lltypemap(v) is Void and special_case_void:
139 return '/* nothing */'
140 else:
141 return LOCALVAR % v.name
142 elif isinstance(v, Constant):
143 value = llvalue_from_constant(v)
144 if value is None and not special_case_void:
145 return 'nothing'
146 else:
147 return self.db.get(value)
148 else:
149 raise TypeError("expr(%r)" % (v,))
150
151 # ____________________________________________________________
152
153 def cfunction_declarations(self):
154 # declare the local variables, excluding the function arguments
155 seen = set()
156 for a in self.graph.getargs():
157 seen.add(a.name)
158
159 result_by_name = []
160 for v in self.allvariables():
161 name = v.name
162 if name not in seen:
163 seen.add(name)
164 result = cdecl(self.lltypename(v), LOCALVAR % name) + ';'
165 if self.lltypemap(v) is Void:
166 continue #result = '/*%s*/' % result
167 result_by_name.append((v._name, result))
168 result_by_name.sort()
169 return [result for name, result in result_by_name]
170
171 # ____________________________________________________________
172
173 extra_return_text = None
174
175 def cfunction_body(self):
176 if self.db.reverse_debugger:
177 from rpython.translator.revdb import gencsupp
178 (extra_enter_text, self.extra_return_text) = (
179 gencsupp.prepare_function(self))
180 if extra_enter_text:
181 yield extra_enter_text
182 graph = self.graph
183
184 # ----- for gc_enter_roots_frame
185 _seen = set()
186 for block in graph.iterblocks():
187 for op in block.operations:
188 if op.opname == 'gc_enter_roots_frame':
189 _seen.add(tuple(op.args))
190 if _seen:
191 assert len(_seen) == 1, (
192 "multiple different gc_enter_roots_frame in %r" % (graph,))
193 for line in self.gcpolicy.enter_roots_frame(self, list(_seen)[0]):
194 yield line
195 # ----- done
196
197 # Locate blocks with a single predecessor, which can be written
198 # inline in place of a "goto":
199 entrymap = mkentrymap(graph)
200 self.inlinable_blocks = {
201 block for block in entrymap if len(entrymap[block]) == 1}
202
203 yield ''
204 for line in self.gen_goto(graph.startblock):
205 yield line
206
207 # Only blocks left are those that have more than one predecessor.
208 for block in graph.iterblocks():
209 if block in self.inlinable_blocks:
210 continue
211 for line in self.gen_block(block):
212 yield line
213
214 def gen_block(self, block):
215 if 1: # (preserve indentation)
216 self._current_block = block
217 myblocknum = self.blocknum[block]
218 if block in self.inlinable_blocks:
219 # debug comment
220 yield '/* block%d: (inlined) */' % myblocknum
221 else:
222 yield 'block%d:' % myblocknum
223 if block in self.innerloops:
224 for line in self.gen_while_loop_hack(block):
225 yield line
226 return
227 for i, op in enumerate(block.operations):
228 for line in self.gen_op(op):
229 yield line
230 if len(block.exits) == 0:
231 assert len(block.inputargs) == 1
232 # regular return block
233 retval = self.expr(block.inputargs[0])
234 if self.exception_policy != "exc_helper":
235 yield 'RPY_DEBUG_RETURN();'
236 if self.extra_return_text:
237 yield self.extra_return_text
238 yield 'return %s;' % retval
239 return
240 elif block.exitswitch is None:
241 # single-exit block
242 assert len(block.exits) == 1
243 for op in self.gen_link(block.exits[0]):
244 yield op
245 else:
246 assert not block.canraise
247 # block ending in a switch on a value
248 TYPE = self.lltypemap(block.exitswitch)
249 if TYPE == Bool:
250 expr = self.expr(block.exitswitch)
251 for link in block.exits[:0:-1]:
252 assert link.exitcase in (False, True)
253 if not link.exitcase:
254 expr = '!' + expr
255 yield 'if (%s) {' % expr
256 for op in self.gen_link(link):
257 yield '\t' + op
258 yield '}'
259 link = block.exits[0]
260 assert link.exitcase in (False, True)
261 for op in self.gen_link(link):
262 yield op
263 elif TYPE in (Signed, Unsigned, SignedLongLong,
264 UnsignedLongLong, Char, UniChar):
265 defaultlink = None
266 expr = self.expr(block.exitswitch)
267 yield 'switch (%s) {' % self.expr(block.exitswitch)
268 for link in block.exits:
269 if link.exitcase == 'default':
270 defaultlink = link
271 continue
272 yield 'case %s:' % self.db.get(link.llexitcase)
273 for op in self.gen_link(link):
274 yield '\t' + op
275 # 'break;' not needed, as gen_link ends in a 'goto'
276 # Emit default case
277 yield 'default:'
278 if defaultlink is None:
279 yield '\tassert(!"bad switch!!"); abort();'
280 else:
281 for op in self.gen_link(defaultlink):
282 yield '\t' + op
283
284 yield '}'
285 else:
286 raise TypeError("exitswitch type not supported"
287 " Got %r" % (TYPE,))
288
289 def gen_link(self, link):
290 "Generate the code to jump across the given Link."
291 assignments = []
292 for a1, a2 in zip(link.args, link.target.inputargs):
293 a2type, a2typename = self.illtypes[a2]
294 if a2type is Void:
295 continue
296 src = self.expr(a1)
297 dest = LOCALVAR % a2.name
298 assignments.append((a2typename, dest, src))
299 for line in gen_assignments(assignments):
300 yield line
301 for line in self.gen_goto(link.target, link):
302 yield line
303
304 def gen_goto(self, target, link=None):
305 """Recursively expand block with inlining or goto.
306
307 Blocks that have only one predecessor are inlined directly, all others
308 are reached via goto.
309 """
310 label = 'block%d' % self.blocknum[target]
311 if target in self.innerloops:
312 loop = self.innerloops[target]
313 if link is loop.links[-1]: # link that ends a loop
314 label += '_back'
315 if target in self.inlinable_blocks:
316 for line in self.gen_block(target):
317 yield line
318 else:
319 yield 'goto %s;' % label
320
321 def gen_op(self, op):
322 macro = 'OP_%s' % op.opname.upper()
323 line = None
324 if (op.opname.startswith('gc_') and
325 op.opname not in ('gc_load_indexed', 'gc_store',
326 'gc_store_indexed')):
327 meth = getattr(self.gcpolicy, macro, None)
328 if meth:
329 line = meth(self, op)
330 else:
331 meth = getattr(self, macro, None)
332 if meth:
333 line = meth(op)
334 if line is None:
335 lst = [self.expr(v) for v in op.args]
336 lst.append(self.expr(op.result))
337 line = '%s(%s);' % (macro, ', '.join(lst))
338 if self.db.reverse_debugger:
339 from rpython.translator.revdb import gencsupp
340 if op.opname in gencsupp.set_revdb_protected:
341 line = gencsupp.emit(line, self.lltypename(op.result),
342 self.expr(op.result))
343 if "\n" not in line:
344 yield line
345 else:
346 for line in line.splitlines():
347 yield line
348
349 def gen_while_loop_hack(self, headblock):
350 # a GCC optimization hack: generate 'while' statement in the
351 # source to convince the C compiler that it is really dealing
352 # with loops. For the head of a loop (i.e. the block where the
353 # decision is) we produce code like this:
354 #
355 # headblock:
356 # while (1) {
357 # ...headblock operations...
358 # if (!cond) break;
359 # goto firstbodyblock;
360 # headblock_back: ;
361 # }
362 #
363 # The real body of the loop is not syntactically within the
364 # scope of { }, but apparently this doesn't matter to GCC as
365 # long as it is within the { } via the chain of goto's starting
366 # at firstbodyblock: and ending at headblock_back:. We need to
367 # duplicate the operations of headblock, though, because the
368 # chain of gotos entering the loop must arrive outside the
369 # while() at the headblock: label and the chain of goto's that
370 # close the loop must arrive inside the while() at the
371 # headblock_back: label.
372
373 looplinks = self.innerloops[headblock].links
374 enterlink = looplinks[0]
375 assert len(headblock.exits) == 2
376 assert isinstance(headblock.exits[0].exitcase, bool)
377 assert isinstance(headblock.exits[1].exitcase, bool)
378 i = list(headblock.exits).index(enterlink)
379 exitlink = headblock.exits[1 - i]
380
381 yield 'while (1) {'
382
383 for i, op in enumerate(headblock.operations):
384 for line in self.gen_op(op):
385 yield '\t' + line
386
387 expr = self.expr(headblock.exitswitch)
388 if enterlink.exitcase == True:
389 expr = '!' + expr
390 yield '\tif (%s) break;' % expr
391 for op in self.gen_link(enterlink):
392 yield '\t' + op
393 yield ' block%d_back: ;' % self.blocknum[headblock]
394 yield '}'
395 for op in self.gen_link(exitlink):
396 yield op
397
398 # ____________________________________________________________
399
400 def generic_call(self, FUNC, fnexpr, args_v, v_result, targets=None):
401 args = []
402 assert len(args_v) == len(FUNC.TO.ARGS)
403 for v, ARGTYPE in zip(args_v, FUNC.TO.ARGS):
404 if ARGTYPE is Void:
405 continue # skip 'void' argument
406 args.append(self.expr(v))
407 # special case for rctypes: by-value container args:
408 # XXX is this still needed now that rctypes is gone
409 if isinstance(ARGTYPE, ContainerType):
410 args[-1] = '*%s' % (args[-1],)
411
412 line = '%s(%s);' % (fnexpr, ', '.join(args))
413 if self.lltypemap(v_result) is not Void:
414 # skip assignment of 'void' return value
415 r = self.expr(v_result)
416 line = '%s = %s' % (r, line)
417 else:
418 r = None
419 if targets is not None:
420 for graph in targets:
421 if getattr(graph, 'inhibit_tail_call', False):
422 line += '\nPYPY_INHIBIT_TAIL_CALL();'
423 break
424 elif self.db.reverse_debugger:
425 from rpython.translator.revdb import gencsupp
426 line = gencsupp.emit_residual_call(self, line, v_result, r)
427 return line
428
429 def OP_DIRECT_CALL(self, op):
430 fn = op.args[0]
431 try:
432 targets = [fn.value._obj.graph]
433 except AttributeError:
434 targets = None
435 FN_TYPE = fn.concretetype
436 if FN_TYPE is Void: # XXX no idea how this is possible
437 FN_TYPE = typeOf(fn.value)
438 return self.generic_call(FN_TYPE, self.expr(fn),
439 op.args[1:], op.result, targets)
440
441 def OP_INDIRECT_CALL(self, op):
442 fn = op.args[0]
443 return self.generic_call(fn.concretetype, self.expr(fn),
444 op.args[1:-1], op.result, op.args[-1].value)
445
446 def OP_ADR_CALL(self, op):
447 ARGTYPES = [v.concretetype for v in op.args[1:]]
448 RESTYPE = op.result.concretetype
449 FUNC = Ptr(FuncType(ARGTYPES, RESTYPE))
450 typename = self.db.gettype(FUNC)
451 fnaddr = op.args[0]
452 fnexpr = '((%s)%s)' % (cdecl(typename, ''), self.expr(fnaddr))
453 return self.generic_call(FUNC, fnexpr, op.args[1:], op.result)
454
455 def OP_JIT_CONDITIONAL_CALL(self, op):
456 return 'abort(); /* jit_conditional_call */'
457
458 def OP_JIT_CONDITIONAL_CALL_VALUE(self, op):
459 return 'abort(); /* jit_conditional_call_value */'
460
461 # low-level operations
462 def generic_get(self, op, sourceexpr, accessing_mem=True):
463 T = self.lltypemap(op.result)
464 newvalue = self.expr(op.result, special_case_void=False)
465 result = '%s = %s;' % (newvalue, sourceexpr)
466 if T is Void:
467 result = '/* %s */' % result
468 if self.db.reverse_debugger:
469 S = self.lltypemap(op.args[0]).TO
470 if (S._gckind != 'gc' and not S._hints.get('is_excdata')
471 and not S._hints.get('static_immutable')
472 and not S._hints.get('ignore_revdb')
473 and accessing_mem):
474 from rpython.translator.revdb import gencsupp
475 result = gencsupp.emit(result, self.lltypename(op.result),
476 newvalue)
477 return result
478
479 def generic_set(self, op, targetexpr):
480 newvalue = self.expr(op.args[-1], special_case_void=False)
481 result = '%s = %s;' % (targetexpr, newvalue)
482 T = self.lltypemap(op.args[-1])
483 if T is Void:
484 result = '/* %s */' % result
485 if self.db.reverse_debugger:
486 S = self.lltypemap(op.args[0]).TO
487 if S._gckind != 'gc' and not S._hints.get('is_excdata'):
488 from rpython.translator.revdb import gencsupp
489 result = gencsupp.emit_void(result)
490 return result
491
492 def _field_stat(self, op, structdef, access_kind):
493 prefix = ''
494 if self.db.all_field_names is not None:
495 if hasattr(structdef, 'c_struct_field_name'):
496 fieldname = structdef.c_struct_field_name(op.args[1].value)
497 self.db.all_field_names.add(fieldname)
498 prefix = 'rpy_access_stats.%s_%s++;\n' % (fieldname, access_kind)
499 return prefix
500
501 def OP_GETFIELD(self, op, ampersand='', accessing_mem=True):
502 assert isinstance(op.args[1], Constant)
503 STRUCT = self.lltypemap(op.args[0]).TO
504 structdef = self.db.gettypedefnode(STRUCT)
505 baseexpr_is_const = isinstance(op.args[0], Constant)
506 prefix = self._field_stat(op, structdef, "read")
507 expr = ampersand + structdef.ptr_access_expr(self.expr(op.args[0]),
508 op.args[1].value,
509 baseexpr_is_const)
510 return prefix + self.generic_get(op, expr, accessing_mem=accessing_mem)
511
512 def OP_BARE_SETFIELD(self, op):
513 assert isinstance(op.args[1], Constant)
514 STRUCT = self.lltypemap(op.args[0]).TO
515 structdef = self.db.gettypedefnode(STRUCT)
516 baseexpr_is_const = isinstance(op.args[0], Constant)
517 prefix = self._field_stat(op, structdef, "write")
518 expr = structdef.ptr_access_expr(self.expr(op.args[0]),
519 op.args[1].value,
520 baseexpr_is_const)
521 return prefix + self.generic_set(op, expr)
522
523 def OP_GETSUBSTRUCT(self, op):
524 RESULT = self.lltypemap(op.result).TO
525 if (isinstance(RESULT, FixedSizeArray) or
526 (isinstance(RESULT, Array) and barebonearray(RESULT))):
527 return self.OP_GETFIELD(op, ampersand='', accessing_mem=False)
528 else:
529 return self.OP_GETFIELD(op, ampersand='&', accessing_mem=False)
530
531 def OP_GETARRAYSIZE(self, op):
532 ARRAY = self.lltypemap(op.args[0]).TO
533 if isinstance(ARRAY, FixedSizeArray):
534 return '%s = %d;' % (self.expr(op.result),
535 ARRAY.length)
536 else:
537 return self.generic_get(op, '%s->length' % self.expr(op.args[0]))
538
539 def OP_GETARRAYITEM(self, op):
540 ARRAY = self.lltypemap(op.args[0]).TO
541 ptr = self.expr(op.args[0])
542 index = self.expr(op.args[1])
543 arraydef = self.db.gettypedefnode(ARRAY)
544 return self.generic_get(op, arraydef.itemindex_access_expr(ptr, index))
545
546 def OP_SETARRAYITEM(self, op):
547 ARRAY = self.lltypemap(op.args[0]).TO
548 ptr = self.expr(op.args[0])
549 index = self.expr(op.args[1])
550 arraydef = self.db.gettypedefnode(ARRAY)
551 return self.generic_set(op, arraydef.itemindex_access_expr(ptr, index))
552 OP_BARE_SETARRAYITEM = OP_SETARRAYITEM
553
554 def OP_GETARRAYSUBSTRUCT(self, op):
555 ARRAY = self.lltypemap(op.args[0]).TO
556 ptr = self.expr(op.args[0])
557 index = self.expr(op.args[1])
558 arraydef = self.db.gettypedefnode(ARRAY)
559 return '%s = &%s;' % (self.expr(op.result),
560 arraydef.itemindex_access_expr(ptr, index))
561
562 def interior_expr(self, args, rettype=False):
563 TYPE = args[0].concretetype.TO
564 expr = self.expr(args[0])
565 for i, arg in enumerate(args[1:]):
566 defnode = self.db.gettypedefnode(TYPE)
567 if arg.concretetype is Void:
568 fieldname = arg.value
569 if i == 0:
570 expr = defnode.ptr_access_expr(expr, fieldname)
571 else:
572 expr = defnode.access_expr(expr, fieldname)
573 if isinstance(TYPE, FixedSizeArray):
574 TYPE = TYPE.OF
575 else:
576 TYPE = getattr(TYPE, fieldname)
577 else:
578 indexexpr = self.expr(arg)
579 if i == 0:
580 expr = defnode.itemindex_access_expr(expr, indexexpr)
581 else:
582 expr = defnode.access_expr_varindex(expr, indexexpr)
583 TYPE = TYPE.OF
584 if rettype:
585 return expr, TYPE
586 else:
587 return expr
588
589 def OP_GETINTERIORFIELD(self, op):
590 return self.generic_get(op, self.interior_expr(op.args))
591
592 def OP_BARE_SETINTERIORFIELD(self, op):
593 return self.generic_set(op, self.interior_expr(op.args[:-1]))
594
595 def OP_GETINTERIORARRAYSIZE(self, op):
596 expr, ARRAY = self.interior_expr(op.args, True)
597 if isinstance(ARRAY, FixedSizeArray):
598 return '%s = %d;'%(self.expr(op.result), ARRAY.length)
599 else:
600 assert isinstance(ARRAY, Array)
601 return self.generic_get(op, '%s.length;' % expr)
602
603
604 def OP_PTR_NONZERO(self, op):
605 return '%s = (%s != NULL);' % (self.expr(op.result),
606 self.expr(op.args[0]))
607 def OP_PTR_ISZERO(self, op):
608 return '%s = (%s == NULL);' % (self.expr(op.result),
609 self.expr(op.args[0]))
610
611 def OP_PTR_EQ(self, op):
612 return '%s = (%s == %s);' % (self.expr(op.result),
613 self.expr(op.args[0]),
614 self.expr(op.args[1]))
615
616 def OP_PTR_NE(self, op):
617 return '%s = (%s != %s);' % (self.expr(op.result),
618 self.expr(op.args[0]),
619 self.expr(op.args[1]))
620
621 def _op_boehm_malloc(self, op, is_atomic):
622 expr_result = self.expr(op.result)
623 res = 'OP_BOEHM_ZERO_MALLOC(%s, %s, void*, %d, 0);' % (
624 self.expr(op.args[0]),
625 expr_result,
626 is_atomic)
627 if self.db.reverse_debugger:
628 from rpython.translator.revdb import gencsupp
629 res += gencsupp.record_malloc_uid(expr_result)
630 return res
631
632 def OP_BOEHM_MALLOC(self, op):
633 return self._op_boehm_malloc(op, 0)
634
635 def OP_BOEHM_MALLOC_ATOMIC(self, op):
636 return self._op_boehm_malloc(op, 1)
637
638 def OP_BOEHM_REGISTER_FINALIZER(self, op):
639 if self.db.reverse_debugger:
640 from rpython.translator.revdb import gencsupp
641 return gencsupp.boehm_register_finalizer(self, op)
642 return 'GC_REGISTER_FINALIZER(%s, (GC_finalization_proc)%s, NULL, NULL, NULL);' \
643 % (self.expr(op.args[0]), self.expr(op.args[1]))
644
645 def OP_DIRECT_FIELDPTR(self, op):
646 return self.OP_GETFIELD(op, ampersand='&', accessing_mem=False)
647
648 def OP_DIRECT_ARRAYITEMS(self, op):
649 ARRAY = self.lltypemap(op.args[0]).TO
650 items = self.expr(op.args[0])
651 if not isinstance(ARRAY, FixedSizeArray) and not barebonearray(ARRAY):
652 items += '->items'
653 return '%s = %s;' % (self.expr(op.result), items)
654
655 def OP_DIRECT_PTRADD(self, op):
656 ARRAY = self.lltypemap(op.args[0]).TO
657 if ARRAY._hints.get("render_as_void"):
658 return '%s = (char *)%s + %s;' % (
659 self.expr(op.result),
660 self.expr(op.args[0]),
661 self.expr(op.args[1]))
662 else:
663 return '%s = %s + %s;' % (
664 self.expr(op.result),
665 self.expr(op.args[0]),
666 self.expr(op.args[1]))
667
668 def _check_split_gc_address_space(self, op):
669 if self.db.split_gc_address_space:
670 TYPE = self.lltypemap(op.result)
671 TSRC = self.lltypemap(op.args[0])
672 gcdst = isinstance(TYPE, Ptr) and TYPE.TO._gckind == 'gc'
673 gcsrc = isinstance(TSRC, Ptr) and TSRC.TO._gckind == 'gc'
674 if gcsrc != gcdst:
675 raise Exception(
676 "cast between pointer types changes the address\n"
677 "space, but the 'split_gc_address_space' option is enabled:\n"
678 " func: %s\n"
679 " op: %s\n"
680 " from: %s\n"
681 " to: %s" % (self.graph, op, TSRC, TYPE))
682
683 def OP_CAST_POINTER(self, op):
684 self._check_split_gc_address_space(op)
685 TYPE = self.lltypemap(op.result)
686 typename = self.db.gettype(TYPE)
687 result = []
688 result.append('%s = (%s)%s;' % (self.expr(op.result),
689 cdecl(typename, ''),
690 self.expr(op.args[0])))
691 return '\t'.join(result)
692
693 OP_CAST_PTR_TO_ADR = OP_CAST_POINTER
694 OP_CAST_ADR_TO_PTR = OP_CAST_POINTER
695 OP_CAST_OPAQUE_PTR = OP_CAST_POINTER
696
697 def OP_CAST_PTR_TO_INT(self, op):
698 if self.db.reverse_debugger:
699 TSRC = self.lltypemap(op.args[0])
700 if isinstance(TSRC, Ptr) and TSRC.TO._gckind == 'gc':
701 from rpython.translator.revdb import gencsupp
702 return gencsupp.cast_gcptr_to_int(self, op)
703 return self.OP_CAST_POINTER(op)
704
705 def OP_REVDB_DO_NEXT_CALL(self, op):
706 self.revdb_do_next_call = True
707 return "/* revdb_do_next_call */"
708
709 def OP_LENGTH_OF_SIMPLE_GCARRAY_FROM_OPAQUE(self, op):
710 return ('%s = *(long *)(((char *)%s) + RPY_SIZE_OF_GCHEADER);'
711 ' /* length_of_simple_gcarray_from_opaque */'
712 % (self.expr(op.result), self.expr(op.args[0])))
713
714 def OP_CAST_INT_TO_PTR(self, op):
715 self._check_split_gc_address_space(op)
716 TYPE = self.lltypemap(op.result)
717 typename = self.db.gettype(TYPE)
718 return "%s = (%s)%s;" % (self.expr(op.result), cdecl(typename, ""),
719 self.expr(op.args[0]))
720
721 def OP_SAME_AS(self, op):
722 result = []
723 TYPE = self.lltypemap(op.result)
724 assert self.lltypemap(op.args[0]) == TYPE
725 if TYPE is not Void:
726 result.append('%s = %s;' % (self.expr(op.result),
727 self.expr(op.args[0])))
728 return '\t'.join(result)
729
730 def OP_HINT(self, op):
731 hints = op.args[1].value
732 return '%s\t/* hint: %r */' % (self.OP_SAME_AS(op), hints)
733
734 def OP_KEEPALIVE(self, op): # xxx what should be the sematics consequences of this
735 v = op.args[0]
736 TYPE = self.lltypemap(v)
737 if TYPE is Void:
738 return "/* kept alive: void */"
739 if isinstance(TYPE, Ptr) and TYPE.TO._gckind == 'gc':
740 meth = getattr(self.gcpolicy, 'GC_KEEPALIVE', None)
741 if meth:
742 return meth(self, v)
743 return "/* kept alive: %s */" % self.expr(v)
744
745 #address operations
746 def OP_RAW_STORE(self, op):
747 addr = self.expr(op.args[0])
748 offset = self.expr(op.args[1])
749 value = self.expr(op.args[2])
750 TYPE = op.args[2].concretetype
751 typename = cdecl(self.db.gettype(TYPE).replace('@', '*@'), '')
752 return (
753 '((%(typename)s) (((char *)%(addr)s) + %(offset)s))[0] = %(value)s;'
754 % locals())
755 OP_BARE_RAW_STORE = OP_RAW_STORE
756 OP_GC_STORE = OP_RAW_STORE # the difference is only in 'revdb_protect'
757
758 def OP_RAW_LOAD(self, op):
759 addr = self.expr(op.args[0])
760 offset = self.expr(op.args[1])
761 result = self.expr(op.result)
762 TYPE = op.result.concretetype
763 typename = cdecl(self.db.gettype(TYPE).replace('@', '*@'), '')
764 return (
765 "%(result)s = ((%(typename)s) (((char *)%(addr)s) + %(offset)s))[0];"
766 % locals())
767
768 def OP_GC_LOAD_INDEXED(self, op):
769 addr = self.expr(op.args[0])
770 index = self.expr(op.args[1])
771 scale = self.expr(op.args[2])
772 base_ofs = self.expr(op.args[3])
773 result = self.expr(op.result)
774 TYPE = op.result.concretetype
775 typename = cdecl(self.db.gettype(TYPE).replace('@', '*@'), '')
776 return (
777 "%(result)s = ((%(typename)s) (((char *)%(addr)s) + "
778 "%(base_ofs)s + %(scale)s * %(index)s))[0];"
779 % locals())
780
781 def OP_GC_STORE_INDEXED(self, op):
782 addr = self.expr(op.args[0])
783 index = self.expr(op.args[1])
784 value = self.expr(op.args[2])
785 scale = self.expr(op.args[3])
786 base_ofs = self.expr(op.args[4])
787 TYPE = op.args[2].concretetype
788 typename = cdecl(self.db.gettype(TYPE).replace('@', '*@'), '')
789 return (
790 "((%(typename)s) (((char *)%(addr)s) + "
791 "%(base_ofs)s + %(scale)s * %(index)s))[0] = %(value)s;"
792 % locals())
793
794 def OP_CAST_PRIMITIVE(self, op):
795 self._check_split_gc_address_space(op)
796 TYPE = self.lltypemap(op.result)
797 val = self.expr(op.args[0])
798 result = self.expr(op.result)
799 if TYPE == Bool:
800 return "%(result)s = !!%(val)s;" % locals()
801 ORIG = self.lltypemap(op.args[0])
802 if ORIG is Char:
803 val = "(unsigned char)%s" % val
804 elif ORIG is UniChar:
805 val = "(unsigned long)%s" % val
806 typename = cdecl(self.db.gettype(TYPE), '')
807 return "%(result)s = (%(typename)s)(%(val)s);" % locals()
808
809 OP_FORCE_CAST = OP_CAST_PRIMITIVE # xxx the same logic works
810
811 def OP_RESUME_POINT(self, op):
812 return '/* resume point %s */'%(op.args[0],)
813
814 def OP_DEBUG_PRINT(self, op):
815 # XXX
816 from rpython.rtyper.lltypesystem.rstr import STR
817 format = []
818 argv = []
819 if self.db.reverse_debugger:
820 format.append('{%d} ')
821 argv.append('(int)getpid()')
822 free_line = ""
823 for arg in op.args:
824 T = arg.concretetype
825 if T == Ptr(STR):
826 if isinstance(arg, Constant):
827 format.append(''.join(arg.value.chars).replace('%', '%%'))
828 else:
829 format.append('%s')
830 argv.append('RPyString_AsCharP(%s)' % self.expr(arg))
831 free_line = "RPyString_FreeCache();"
832 continue
833 elif T == Signed:
834 if sys.platform == 'win32':
835 format.append('%Id')
836 else:
837 format.append('%ld')
838 elif T == INT:
839 format.append('%d')
840 elif T == Unsigned:
841 if sys.platform == 'win32':
842 format.append('%Iu')
843 else:
844 format.append('%lu')
845 elif T == Float:
846 format.append('%f')
847 elif isinstance(T, Ptr) or T == Address:
848 format.append('%p')
849 elif T == Char:
850 if isinstance(arg, Constant):
851 format.append(arg.value.replace('%', '%%'))
852 continue
853 format.append('%c')
854 elif T == Bool:
855 format.append('%s')
856 argv.append('(%s) ? "True" : "False"' % self.expr(arg))
857 continue
858 elif T == SignedLongLong:
859 if sys.platform == 'win32':
860 format.append('%I64d')
861 else:
862 format.append('%lld')
863 elif T == UnsignedLongLong:
864 if sys.platform == 'win32':
865 format.append('%I64u')
866 else:
867 format.append('%llu')
868 else:
869 raise Exception("don't know how to debug_print %r" % (T,))
870 argv.append(self.expr(arg))
871 argv.insert(0, c_string_constant(' '.join(format) + '\n'))
872 return (
873 "if (PYPY_HAVE_DEBUG_PRINTS) { fprintf(PYPY_DEBUG_FILE, %s); %s}"
874 % (', '.join(argv), free_line))
875
876 def _op_debug(self, macro, op):
877 v_cat, v_timestamp = op.args
878 if isinstance(v_cat, Constant):
879 string_literal = c_string_constant(''.join(v_cat.value.chars))
880 return "%s = %s(%s, %s);" % (self.expr(op.result),
881 macro,
882 string_literal,
883 self.expr(v_timestamp))
884 else:
885 x = "%s = %s(RPyString_AsCharP(%s), %s);\n" % (self.expr(op.result),
886 macro,
887 self.expr(v_cat),
888 self.expr(v_timestamp))
889 x += "RPyString_FreeCache();"
890 return x
891
892 def OP_DEBUG_START(self, op):
893 return self._op_debug('PYPY_DEBUG_START', op)
894
895 def OP_DEBUG_STOP(self, op):
896 return self._op_debug('PYPY_DEBUG_STOP', op)
897
898 def OP_HAVE_DEBUG_PRINTS_FOR(self, op):
899 arg = op.args[0]
900 assert isinstance(arg, Constant) and isinstance(arg.value, str)
901 string_literal = c_string_constant(arg.value)
902 return '%s = pypy_have_debug_prints_for(%s);' % (
903 self.expr(op.result), string_literal)
904
905 def OP_DEBUG_ASSERT(self, op):
906 return 'RPyAssert(%s, %s);' % (self.expr(op.args[0]),
907 c_string_constant(op.args[1].value))
908
909 def OP_DEBUG_ASSERT_NOT_NONE(self, op):
910 return 'RPyAssert(%s != NULL, "ll_assert_not_none() failed");' % (
911 self.expr(op.args[0]),)
912
913 def OP_DEBUG_FATALERROR(self, op):
914 # XXX
915 from rpython.rtyper.lltypesystem.rstr import STR
916 msg = op.args[0]
917 assert msg.concretetype == Ptr(STR)
918 if isinstance(msg, Constant):
919 msg = c_string_constant(''.join(msg.value.chars))
920 else:
921 msg = 'RPyString_AsCharP(%s)' % self.expr(msg)
922
923 return 'fprintf(stderr, "%%s\\n", %s); abort();' % msg
924
925 def OP_DEBUG_LLINTERPCALL(self, op):
926 result = 'abort(); /* debug_llinterpcall should be unreachable */'
927 TYPE = self.lltypemap(op.result)
928 if TYPE is not Void:
929 typename = self.db.gettype(TYPE)
930 result += '\n%s = (%s)0;' % (self.expr(op.result),
931 cdecl(typename, ''))
932 return result
933
934 def OP_DEBUG_NONNULL_POINTER(self, op):
935 expr = self.expr(op.args[0])
936 return 'if ((-8192 <= (Signed)%s) && (((Signed)%s) < 8192)) abort();' % (
937 expr, expr)
938
939 def OP_INSTRUMENT_COUNT(self, op):
940 counter_label = op.args[1].value
941 self.db.instrument_ncounter = max(self.db.instrument_ncounter,
942 counter_label+1)
943 counter_label = self.expr(op.args[1])
944 return 'PYPY_INSTRUMENT_COUNT(%s);' % counter_label
945
946 def OP_IS_EARLY_CONSTANT(self, op):
947 return '%s = 0; /* IS_EARLY_CONSTANT */' % (self.expr(op.result),)
948
949 def OP_JIT_MARKER(self, op):
950 return '/* JIT_MARKER %s */' % op
951
952 def OP_JIT_FORCE_VIRTUALIZABLE(self, op):
953 return '/* JIT_FORCE_VIRTUALIZABLE %s */' % op
954
955 def OP_JIT_FORCE_VIRTUAL(self, op):
956 return '%s = %s; /* JIT_FORCE_VIRTUAL */' % (self.expr(op.result),
957 self.expr(op.args[0]))
958
959 def OP_JIT_IS_VIRTUAL(self, op):
960 return '%s = 0; /* JIT_IS_VIRTUAL */' % (self.expr(op.result),)
961
962 def OP_JIT_FORCE_QUASI_IMMUTABLE(self, op):
963 return '/* JIT_FORCE_QUASI_IMMUTABLE %s */' % op
964
965 def OP_JIT_FFI_SAVE_RESULT(self, op):
966 return '/* JIT_FFI_SAVE_RESULT %s */' % op
967
968 def OP_JIT_ENTER_PORTAL_FRAME(self, op):
969 return '/* JIT_ENTER_PORTAL_FRAME %s */' % op
970
971 def OP_JIT_LEAVE_PORTAL_FRAME(self, op):
972 return '/* JIT_LEAVE_PORTAL_FRAME %s */' % op
973
974 def OP_GET_GROUP_MEMBER(self, op):
975 typename = self.db.gettype(op.result.concretetype)
976 return '%s = (%s)_OP_GET_GROUP_MEMBER(%s, %s);' % (
977 self.expr(op.result),
978 cdecl(typename, ''),
979 self.expr(op.args[0]),
980 self.expr(op.args[1]))
981
982 def OP_GET_NEXT_GROUP_MEMBER(self, op):
983 typename = self.db.gettype(op.result.concretetype)
984 return '%s = (%s)_OP_GET_NEXT_GROUP_MEMBER(%s, %s, %s);' % (
985 self.expr(op.result),
986 cdecl(typename, ''),
987 self.expr(op.args[0]),
988 self.expr(op.args[1]),
989 self.expr(op.args[2]))
990
991 def getdebugfunctionname(self):
992 name = self.functionname
993 if name.startswith('pypy_g_'):
994 name = name[7:]
995 return name
996
997 def OP_DEBUG_RECORD_TRACEBACK(self, op):
998 return 'PYPY_DEBUG_RECORD_TRACEBACK("%s");' % (
999 self.getdebugfunctionname(),)
1000
1001 def OP_DEBUG_CATCH_EXCEPTION(self, op):
1002 gottype = self.expr(op.args[0])
1003 exprs = []
1004 for c_limited_type in op.args[1:]:
1005 exprs.append('%s == %s' % (gottype, self.expr(c_limited_type)))
1006 return 'PYPY_DEBUG_CATCH_EXCEPTION("%s", %s, %s);' % (
1007 self.getdebugfunctionname(), gottype, ' || '.join(exprs))
1008
1009 def OP_INT_BETWEEN(self, op):
1010 if (isinstance(op.args[0], Constant) and
1011 isinstance(op.args[2], Constant) and
1012 op.args[2].value - op.args[0].value == 1):
1013 # (a <= b < a+1) ----> (b == a)
1014 return '%s = (%s == %s); /* was INT_BETWEEN */' % (
1015 self.expr(op.result),
1016 self.expr(op.args[1]),
1017 self.expr(op.args[0]))
1018 else:
1019 return None # use the default
1020
1021 def OP_THREADLOCALREF_GET(self, op):
1022 if isinstance(op.args[0], Constant):
1023 typename = self.db.gettype(op.result.concretetype)
1024 assert isinstance(op.args[0].value, CDefinedIntSymbolic)
1025 fieldname = op.args[0].value.expr
1026 assert fieldname.startswith('RPY_TLOFS_')
1027 fieldname = fieldname[10:]
1028 return '%s = (%s)RPY_THREADLOCALREF_GET(%s);' % (
1029 self.expr(op.result),
1030 cdecl(typename, ''),
1031 fieldname)
1032 else:
1033 # this is used for the fall-back path in the JIT
1034 return self.OP_THREADLOCALREF_LOAD(op)
1035
1036 def OP_THREADLOCALREF_LOAD(self, op):
1037 typename = self.db.gettype(op.result.concretetype)
1038 return 'OP_THREADLOCALREF_LOAD(%s, %s, %s);' % (
1039 cdecl(typename, ''),
1040 self.expr(op.args[0]),
1041 self.expr(op.result))
1042
1043 def OP_THREADLOCALREF_STORE(self, op):
1044 typename = self.db.gettype(op.args[1].concretetype)
1045 return 'OP_THREADLOCALREF_STORE(%s, %s, %s);' % (
1046 cdecl(typename, ''),
1047 self.expr(op.args[0]),
1048 self.expr(op.args[1]))