Debian Codegraph @

rpython/annotator/specialize.py

raw symbols SCIP
1 # specialization support
2 import py
3
4 from rpython.tool.sourcetools import func_with_new_name
5 from rpython.tool.algo.unionfind import UnionFind
6 from rpython.flowspace.model import Block, Link, Variable
7 from rpython.flowspace.model import checkgraph
8 from rpython.flowspace.operation import op
9 from rpython.annotator import model as annmodel
10 from rpython.flowspace.argument import Signature
11 from rpython.annotator.model import SomePBC, SomeImpossibleValue, SomeBool
12 from rpython.annotator.model import unionof
13
14 def flatten_star_args(funcdesc, args_s):
15 argnames, vararg, kwarg = funcdesc.signature
16 assert not kwarg, "functions with ** arguments are not supported"
17 if vararg:
18 # calls to *arg functions: create one version per number of args
19 assert len(args_s) == len(argnames) + 1
20 s_tuple = args_s[-1]
21 assert isinstance(s_tuple, annmodel.SomeTuple), (
22 "calls f(..., *arg) require 'arg' to be a tuple")
23 s_len = s_tuple.len()
24 assert s_len.is_constant(), "calls require known number of args"
25 nb_extra_args = s_len.const
26 flattened_s = list(args_s[:-1])
27 flattened_s.extend(s_tuple.items)
28
29 def builder(translator, func):
30 # build a hacked graph that doesn't take a *arg any more, but
31 # individual extra arguments
32 graph = translator.buildflowgraph(func)
33 argnames, vararg, kwarg = graph.signature
34 assert vararg, "graph should have a *arg at this point"
35 assert not kwarg, "where does this **arg come from??"
36 argscopy = [Variable(v) for v in graph.getargs()]
37 starargs = [Variable('stararg%d'%i) for i in range(nb_extra_args)]
38 newstartblock = Block(argscopy[:-1] + starargs)
39 newtup = op.newtuple(*starargs)
40 newtup.result = argscopy[-1]
41 newstartblock.operations.append(newtup)
42 newstartblock.closeblock(Link(argscopy, graph.startblock))
43 graph.startblock = newstartblock
44 argnames = argnames + ['.star%d' % i for i in range(nb_extra_args)]
45 graph.signature = Signature(argnames)
46 # note that we can mostly ignore defaults: if nb_extra_args > 0,
47 # then defaults aren't applied. if nb_extra_args == 0, then this
48 # just removes the *arg and the defaults keep their meaning.
49 if nb_extra_args > 0:
50 graph.defaults = None # shouldn't be used in this case
51 checkgraph(graph)
52 return graph
53
54 key = ('star', nb_extra_args)
55 return flattened_s, key, builder
56
57 else:
58 return args_s, None, None
59
60 def default_specialize(funcdesc, args_s):
61 # first flatten the *args
62 args_s, key, builder = flatten_star_args(funcdesc, args_s)
63 # two versions: a regular one and one for instances with 'access_directly'
64 jit_look_inside = getattr(funcdesc.pyobj, '_jit_look_inside_', True)
65 # change args_s in place, "official" interface
66 access_directly = False
67 for i, s_obj in enumerate(args_s):
68 if (isinstance(s_obj, annmodel.SomeInstance) and
69 'access_directly' in s_obj.flags):
70 if jit_look_inside:
71 access_directly = True
72 key = (AccessDirect, key)
73 break
74 else:
75 new_flags = s_obj.flags.copy()
76 del new_flags['access_directly']
77 new_s_obj = annmodel.SomeInstance(s_obj.classdef, s_obj.can_be_None,
78 flags = new_flags)
79 args_s[i] = new_s_obj
80
81 # done
82 graph = funcdesc.cachedgraph(key, builder=builder)
83 if access_directly:
84 graph.access_directly = True
85 return graph
86
87 class AccessDirect(object):
88 """marker for specialization: set when any arguments is a SomeInstance
89 which has the 'access_directly' flag set."""
90
91 def getuniquenondirectgraph(desc):
92 result = []
93 for key, graph in desc._cache.items():
94 if (type(key) is tuple and len(key) == 2 and
95 key[0] is AccessDirect):
96 continue
97 result.append(graph)
98 assert len(result) == 1
99 return result[0]
100
101 # ____________________________________________________________________________
102 # specializations
103
104 class MemoTable(object):
105 def __init__(self, funcdesc, args, value):
106 self.funcdesc = funcdesc
107 self.table = {args: value}
108 self.graph = None
109 self.do_not_process = False
110
111 def register_finish(self):
112 bookkeeper = self.funcdesc.bookkeeper
113 bookkeeper.pending_specializations.append(self.finish)
114
115 def absorb(self, other):
116 self.table.update(other.table)
117 assert self.graph is None, "too late for MemoTable merge!"
118 del other.graph # just in case
119 other.do_not_process = True
120
121 fieldnamecounter = 0
122
123 def getuniquefieldname(self):
124 name = self.funcdesc.name
125 fieldname = '$memofield_%s_%d' % (name, MemoTable.fieldnamecounter)
126 MemoTable.fieldnamecounter += 1
127 return fieldname
128
129 def finish(self):
130 if self.do_not_process:
131 return
132 assert self.graph is None, "MemoTable already finished"
133 # list of which argument positions can take more than one value
134 example_args, example_value = self.table.iteritems().next()
135 nbargs = len(example_args)
136 # list of sets of possible argument values -- one set per argument index
137 sets = [set() for i in range(nbargs)]
138 for args in self.table:
139 for i in range(nbargs):
140 sets[i].add(args[i])
141
142 bookkeeper = self.funcdesc.bookkeeper
143 annotator = bookkeeper.annotator
144 name = self.funcdesc.name
145 argnames = ['a%d' % i for i in range(nbargs)]
146
147 def make_helper(firstarg, stmt, miniglobals):
148 header = "def f(%s):" % (', '.join(argnames[firstarg:],))
149 source = py.code.Source(stmt)
150 source = source.putaround(header)
151 exec source.compile() in miniglobals
152 f = miniglobals['f']
153 return func_with_new_name(f, 'memo_%s_%d' % (name, firstarg))
154
155 def make_constant_subhelper(firstarg, result):
156 # make a function that just returns the constant answer 'result'
157 f = make_helper(firstarg, 'return result', {'result': result})
158 f.constant_result = result
159 return f
160
161 def make_subhelper(args_so_far=()):
162 firstarg = len(args_so_far)
163 if firstarg == nbargs:
164 # no argument left, return the known result
165 # (or a dummy value if none corresponds exactly)
166 result = self.table.get(args_so_far, example_value)
167 return make_constant_subhelper(firstarg, result)
168 else:
169 nextargvalues = list(sets[len(args_so_far)])
170 if nextargvalues == [True, False]:
171 nextargvalues = [False, True]
172 nextfns = [make_subhelper(args_so_far + (arg,))
173 for arg in nextargvalues]
174 # do all graphs return a constant?
175 try:
176 constants = [fn.constant_result for fn in nextfns]
177 except AttributeError:
178 constants = None # one of the 'fn' has no constant_result
179 restargs = ', '.join(argnames[firstarg+1:])
180
181 # is there actually only one possible value for the current arg?
182 if len(nextargvalues) == 1:
183 if constants: # is the result a constant?
184 result = constants[0]
185 return make_constant_subhelper(firstarg, result)
186 else:
187 # ignore the first argument and just call the subhelper
188 stmt = 'return subhelper(%s)' % restargs
189 return make_helper(firstarg, stmt,
190 {'subhelper': nextfns[0]})
191
192 # is the arg a bool?
193 elif nextargvalues == [False, True]:
194 stmt = ['if %s:' % argnames[firstarg]]
195 if hasattr(nextfns[True], 'constant_result'):
196 # the True branch has a constant result
197 case1 = nextfns[True].constant_result
198 stmt.append(' return case1')
199 else:
200 # must call the subhelper
201 case1 = nextfns[True]
202 stmt.append(' return case1(%s)' % restargs)
203 stmt.append('else:')
204 if hasattr(nextfns[False], 'constant_result'):
205 # the False branch has a constant result
206 case0 = nextfns[False].constant_result
207 stmt.append(' return case0')
208 else:
209 # must call the subhelper
210 case0 = nextfns[False]
211 stmt.append(' return case0(%s)' % restargs)
212
213 return make_helper(firstarg, '\n'.join(stmt),
214 {'case0': case0,
215 'case1': case1})
216
217 # the arg is a set of PBCs
218 else:
219 descs = [bookkeeper.getdesc(pbc) for pbc in nextargvalues]
220 fieldname = self.getuniquefieldname()
221 stmt = 'return getattr(%s, %r)' % (argnames[firstarg],
222 fieldname)
223 if constants:
224 # instead of calling these subhelpers indirectly,
225 # we store what they would return directly in the
226 # pbc memo fields
227 store = constants
228 else:
229 store = nextfns
230 # call the result of the getattr()
231 stmt += '(%s)' % restargs
232
233 # store the memo field values
234 for desc, value_to_store in zip(descs, store):
235 desc.create_new_attribute(fieldname, value_to_store)
236
237 return make_helper(firstarg, stmt, {})
238
239 entrypoint = make_subhelper(args_so_far = ())
240 self.graph = annotator.translator.buildflowgraph(entrypoint)
241 self.graph.defaults = self.funcdesc.defaults
242
243 # schedule this new graph for being annotated
244 args_s = []
245 for arg_types in sets:
246 values_s = [bookkeeper.immutablevalue(x) for x in arg_types]
247 args_s.append(unionof(*values_s))
248 annotator.addpendinggraph(self.graph, args_s)
249
250 def all_values(s):
251 """Return the exhaustive list of possible values matching annotation `s`.
252
253 Raises `AnnotatorError` if no such (reasonably small) finite list exists.
254 """
255 if s.is_constant():
256 return [s.const]
257 elif isinstance(s, SomePBC):
258 values = []
259 assert not s.can_be_None, "memo call: cannot mix None and PBCs"
260 for desc in s.descriptions:
261 if desc.pyobj is None:
262 raise annmodel.AnnotatorError(
263 "memo call with a class or PBC that has no "
264 "corresponding Python object (%r)" % (desc,))
265 values.append(desc.pyobj)
266 return values
267 elif isinstance(s, SomeImpossibleValue):
268 return []
269 elif isinstance(s, SomeBool):
270 return [False, True]
271 else:
272 raise annmodel.AnnotatorError("memo call: argument must be a class "
273 "or a frozen PBC, got %r" % (s,))
274
275 def memo(funcdesc, args_s):
276 # call the function now, and collect possible results
277
278 # the list of all possible tuples of arguments to give to the memo function
279 possiblevalues = cartesian_product([all_values(s_arg) for s_arg in args_s])
280
281 # a MemoTable factory -- one MemoTable per family of arguments that can
282 # be called together, merged via a UnionFind.
283 bookkeeper = funcdesc.bookkeeper
284 try:
285 memotables = bookkeeper.all_specializations[funcdesc]
286 except KeyError:
287 func = funcdesc.pyobj
288 if func is None:
289 raise annmodel.AnnotatorError("memo call: no Python function object"
290 "to call (%r)" % (funcdesc,))
291
292 def compute_one_result(args):
293 value = func(*args)
294 memotable = MemoTable(funcdesc, args, value)
295 memotable.register_finish()
296 return memotable
297
298 memotables = UnionFind(compute_one_result)
299 bookkeeper.all_specializations[funcdesc] = memotables
300
301 # merge the MemoTables for the individual argument combinations
302 firstvalues = possiblevalues.next()
303 _, _, memotable = memotables.find(firstvalues)
304 for values in possiblevalues:
305 _, _, memotable = memotables.union(firstvalues, values)
306
307 if memotable.graph is not None:
308 return memotable.graph # if already computed
309 else:
310 # otherwise, for now, return the union of each possible result
311 return unionof(*[bookkeeper.immutablevalue(v)
312 for v in memotable.table.values()])
313
314 def cartesian_product(lstlst):
315 if not lstlst:
316 yield ()
317 return
318 for tuple_tail in cartesian_product(lstlst[1:]):
319 for value in lstlst[0]:
320 yield (value,) + tuple_tail
321
322
323 def maybe_star_args(funcdesc, key, args_s):
324 args_s, key1, builder = flatten_star_args(funcdesc, args_s)
325 if key1 is not None:
326 key = key + key1
327 return funcdesc.cachedgraph(key, builder=builder)
328
329 def specialize_argvalue(funcdesc, args_s, *argindices):
330 from rpython.annotator.model import SomePBC
331 key = []
332 for i in argindices:
333 s = args_s[i]
334 if s.is_constant():
335 key.append(s.const)
336 elif isinstance(s, SomePBC) and len(s.descriptions) == 1:
337 # for test_specialize_arg_bound_method
338 desc, = s.descriptions
339 key.append(desc)
340 else:
341 raise annmodel.AnnotatorError("specialize:arg(%d): argument not "
342 "constant: %r" % (i, s))
343 key = tuple(key)
344 return maybe_star_args(funcdesc, key, args_s)
345
346 def specialize_arg_or_var(funcdesc, args_s, *argindices):
347 for argno in argindices:
348 if not args_s[argno].is_constant():
349 break
350 else:
351 # all constant
352 return specialize_argvalue(funcdesc, args_s, *argindices)
353 # some not constant
354 return maybe_star_args(funcdesc, None, args_s)
355
356 def specialize_argtype(funcdesc, args_s, *argindices):
357 key = tuple([args_s[i].knowntype for i in argindices])
358 return maybe_star_args(funcdesc, key, args_s)
359
360 def specialize_arglistitemtype(funcdesc, args_s, i):
361 s = args_s[i]
362 if s.knowntype is not list:
363 key = None
364 else:
365 key = s.listdef.listitem.s_value.knowntype
366 return maybe_star_args(funcdesc, key, args_s)
367
368 def specialize_call_location(funcdesc, args_s, op):
369 assert op is not None
370 return maybe_star_args(funcdesc, (op,), args_s)