Debian Codegraph @

rpython/jit/codewriter/flatten.py

raw symbols SCIP
1 from rpython.flowspace.model import Variable, Constant, c_last_exception
2 from rpython.jit.metainterp.history import AbstractDescr, getkind
3 from rpython.rtyper.lltypesystem import lltype
4
5
6 class SSARepr(object):
7 def __init__(self, name):
8 self.name = name
9 self.insns = []
10 self._insns_pos = None # after being assembled
11
12 class Label(object):
13 def __init__(self, name):
14 self.name = name
15 def __repr__(self):
16 return "Label(%r)" % (self.name, )
17 def __eq__(self, other):
18 return isinstance(other, Label) and other.name == self.name
19
20 class TLabel(object):
21 def __init__(self, name):
22 self.name = name
23 def __repr__(self):
24 return "TLabel(%r)" % (self.name, )
25 def __eq__(self, other):
26 return isinstance(other, TLabel) and other.name == self.name
27
28 class Register(object):
29 def __init__(self, kind, index):
30 self.kind = kind # 'int', 'ref' or 'float'
31 self.index = index
32 def __repr__(self):
33 return "%%%s%d" % (self.kind[0], self.index)
34
35 class ListOfKind(object):
36 # a list of Regs/Consts, all of the same 'kind'.
37 # We cannot use a plain list, because we wouldn't know what 'kind' of
38 # Regs/Consts would be expected in case the list is empty.
39 def __init__(self, kind, content):
40 assert kind in KINDS
41 self.kind = kind
42 self.content = tuple(content)
43 def __repr__(self):
44 return '%s%s' % (self.kind[0].upper(), list(self.content))
45 def __iter__(self):
46 return iter(self.content)
47 def __nonzero__(self):
48 return bool(self.content)
49 def __eq__(self, other):
50 return (isinstance(other, ListOfKind) and
51 self.kind == other.kind and self.content == other.content)
52
53 class IndirectCallTargets(object):
54 def __init__(self, lst):
55 self.lst = lst # list of JitCodes
56 def __repr__(self):
57 return '<IndirectCallTargets>'
58
59 KINDS = ['int', 'ref', 'float']
60
61 # ____________________________________________________________
62
63 def flatten_graph(graph, regallocs, _include_all_exc_links=False,
64 cpu=None):
65 """Flatten the graph into an SSARepr, with already-computed register
66 allocations. 'regallocs' in a dict {kind: RegAlloc}."""
67 flattener = GraphFlattener(graph, regallocs, _include_all_exc_links, cpu)
68 flattener.enforce_input_args()
69 flattener.generate_ssa_form()
70 return flattener.ssarepr
71
72
73 class GraphFlattener(object):
74
75 def __init__(self, graph, regallocs, _include_all_exc_links=False,
76 cpu=None):
77 self.graph = graph
78 self.regallocs = regallocs
79 self.cpu = cpu
80 self._include_all_exc_links = _include_all_exc_links
81 self.registers = {}
82 if graph:
83 name = graph.name
84 else:
85 name = '?'
86 self.ssarepr = SSARepr(name)
87
88 def enforce_input_args(self):
89 inputargs = self.graph.startblock.inputargs
90 numkinds = {}
91 for v in inputargs:
92 kind = getkind(v.concretetype)
93 if kind == 'void':
94 continue
95 curcol = self.regallocs[kind].getcolor(v)
96 realcol = numkinds.get(kind, 0)
97 numkinds[kind] = realcol + 1
98 if curcol != realcol:
99 assert curcol > realcol
100 self.regallocs[kind].swapcolors(realcol, curcol)
101
102 def generate_ssa_form(self):
103 self.seen_blocks = {}
104 self.make_bytecode_block(self.graph.startblock)
105
106 def make_bytecode_block(self, block, handling_ovf=False):
107 if block.exits == ():
108 self.make_return(block.inputargs)
109 return
110 if block in self.seen_blocks:
111 self.emitline("goto", TLabel(block))
112 self.emitline("---")
113 return
114 # inserting a goto not necessary, falling through
115 self.seen_blocks[block] = True
116 self.emitline(Label(block))
117 #
118 operations = block.operations
119 for i, op in enumerate(operations):
120 if '_ovf' in op.opname:
121 if (len(block.exits) not in (2, 3) or
122 block.exitswitch is not c_last_exception):
123 raise Exception("detected a block containing ovfcheck()"
124 " but no OverflowError is caught, this"
125 " is not legal in jitted blocks")
126 self.serialize_op(op)
127 #
128 self.insert_exits(block, handling_ovf)
129
130 def make_return(self, args):
131 if len(args) == 1:
132 # return from function
133 [v] = args
134 kind = getkind(v.concretetype)
135 if kind == 'void':
136 self.emitline("void_return")
137 else:
138 self.emitline("%s_return" % kind, self.getcolor(args[0]))
139 elif len(args) == 2:
140 # exception block, raising an exception from a function
141 if isinstance(args[1], Variable):
142 self.emitline("-live-") # xxx hack
143 self.emitline("raise", self.getcolor(args[1]))
144 else:
145 raise Exception("?")
146 self.emitline("---")
147
148 def make_link(self, link, handling_ovf):
149 if (link.target.exits == ()
150 and link.last_exception not in link.args
151 and link.last_exc_value not in link.args):
152 self.make_return(link.args) # optimization only
153 return
154 self.insert_renamings(link)
155 self.make_bytecode_block(link.target, handling_ovf)
156
157 def make_exception_link(self, link, handling_ovf):
158 # Like make_link(), but also introduces the 'last_exception' and
159 # 'last_exc_value' as variables if needed. Also check if the link
160 # is jumping directly to the re-raising exception block.
161 assert link.last_exception is not None
162 assert link.last_exc_value is not None
163 if link.target.operations == () and link.args == [link.last_exception,
164 link.last_exc_value]:
165 if handling_ovf:
166 exc_data = self.cpu.rtyper.exceptiondata
167 ll_ovf = exc_data.get_standard_ll_exc_instance_by_class(
168 OverflowError)
169 c = Constant(ll_ovf, concretetype=lltype.typeOf(ll_ovf))
170 self.emitline("raise", c)
171 else:
172 self.emitline("reraise")
173 self.emitline("---")
174 return # done
175 self.make_link(link, handling_ovf)
176
177 def insert_exits(self, block, handling_ovf=False):
178 if len(block.exits) == 1:
179 # A single link, fall-through
180 link = block.exits[0]
181 assert link.exitcase in (None, False, True)
182 # the cases False or True should not really occur, but can show
183 # up in the manually hacked graphs for generators...
184 self.make_link(link, handling_ovf)
185 #
186 elif block.canraise:
187 # An exception block. See test_exc_exitswitch in test_flatten.py
188 # for an example of what kind of code this makes.
189 index = -1
190 opname = block.operations[index].opname
191 if '_ovf' in opname:
192 # ovf checking operation as a lat thing, -live- should be
193 # one before it
194 line = self.popline()
195 self.emitline(opname[:7] + '_jump_if_ovf',
196 TLabel(block.exits[1]), *line[1:])
197 assert len(block.exits) in (2, 3)
198 self.make_link(block.exits[0], False)
199 self.emitline(Label(block.exits[1]))
200 self.make_exception_link(block.exits[1], True)
201 if len(block.exits) == 3:
202 assert block.exits[2].exitcase is Exception
203 self.make_exception_link(block.exits[2], False)
204 return
205 else:
206 while True:
207 lastopname = block.operations[index].opname
208 if lastopname != '-live-':
209 break
210 index -= 1
211 assert block.exits[0].exitcase is None # is this always True?
212 #
213 if not self._include_all_exc_links:
214 if index == -1:
215 # cannot raise: the last instruction is not
216 # actually a '-live-'
217 self.make_link(block.exits[0], False)
218 return
219 #
220 self.emitline('catch_exception', TLabel(block.exits[0]))
221 self.make_link(block.exits[0], False)
222 self.emitline(Label(block.exits[0]))
223 for link in block.exits[1:]:
224 if link.exitcase is Exception:
225 # this link captures all exceptions
226 self.make_exception_link(link, False)
227 break
228 self.emitline('goto_if_exception_mismatch',
229 Constant(link.llexitcase,
230 lltype.typeOf(link.llexitcase)),
231 TLabel(link))
232 self.make_exception_link(link, False)
233 self.emitline(Label(link))
234 else:
235 # no link captures all exceptions, so we have to put a reraise
236 # for the other exceptions
237 self.emitline("reraise")
238 self.emitline("---")
239 #
240 elif len(block.exits) == 2 and (
241 isinstance(block.exitswitch, tuple) or
242 block.exitswitch.concretetype == lltype.Bool):
243 # Two exit links with a boolean condition
244 linkfalse, linktrue = block.exits
245 if linkfalse.llexitcase == True:
246 linkfalse, linktrue = linktrue, linkfalse
247 opname = 'goto_if_not'
248 if isinstance(block.exitswitch, tuple):
249 # special case produced by jtransform.optimize_goto_if_not()
250 opname = 'goto_if_not_' + block.exitswitch[0]
251 opargs = block.exitswitch[1:]
252 if opargs[-1] == '-live-before':
253 opargs = opargs[:-1]
254 else:
255 assert block.exitswitch.concretetype == lltype.Bool
256 opargs = [block.exitswitch]
257 #
258 lst = self.flatten_list(opargs) + [TLabel(linkfalse)]
259 self.emitline('-live-')
260 self.emitline(opname, *lst)
261 #if not livebefore:
262 # self.emitline('-live-', TLabel(linkfalse))
263 # true path:
264 self.make_link(linktrue, handling_ovf)
265 # false path:
266 self.emitline(Label(linkfalse))
267 self.make_link(linkfalse, handling_ovf)
268 #
269 else:
270 # A switch.
271 #
272 switches = [link for link in block.exits
273 if link.exitcase != 'default']
274 switches.sort(key=lambda link: link.llexitcase)
275 kind = getkind(block.exitswitch.concretetype)
276 assert kind == 'int' # XXX
277 #
278 # A switch on an integer, implementable efficiently with the
279 # help of a SwitchDictDescr. We use this even if there are
280 # very few cases: in pyjitpl.py, opimpl_switch() will promote
281 # the int only if it matches one of the cases.
282 from rpython.jit.codewriter.jitcode import SwitchDictDescr
283 switchdict = SwitchDictDescr()
284 switchdict._labels = []
285 self.emitline('-live-') # for 'guard_value'
286 self.emitline('switch', self.getcolor(block.exitswitch),
287 switchdict)
288 # emit the default path
289 if block.exits[-1].exitcase == 'default':
290 self.make_link(block.exits[-1], handling_ovf)
291 else:
292 self.emitline("unreachable")
293 self.emitline("---")
294 #
295 for switch in switches:
296 key = lltype.cast_primitive(lltype.Signed,
297 switch.llexitcase)
298 switchdict._labels.append((key, TLabel(switch)))
299 # emit code for that path
300 # note: we need a -live- for all the 'guard_false' we produce
301 # if the switched value doesn't match any case.
302 self.emitline(Label(switch))
303 self.emitline('-live-')
304 self.make_link(switch, handling_ovf)
305
306 def insert_renamings(self, link):
307 renamings = {}
308 lst = [(self.getcolor(v), self.getcolor(link.target.inputargs[i]))
309 for i, v in enumerate(link.args)
310 if v.concretetype is not lltype.Void and
311 v not in (link.last_exception, link.last_exc_value)]
312 lst.sort(key=lambda(v, w): w.index)
313 for v, w in lst:
314 if v == w:
315 continue
316 frm, to = renamings.setdefault(w.kind, ([], []))
317 frm.append(v)
318 to.append(w)
319 for kind in KINDS:
320 if kind in renamings:
321 frm, to = renamings[kind]
322 # Produce a series of %s_copy. If there is a cycle, it
323 # is handled with a %s_push to save the first value of
324 # the cycle, some number of %s_copy, and finally a
325 # %s_pop to load the last value.
326 result = reorder_renaming_list(frm, to)
327 for v, w in result:
328 if w is None:
329 self.emitline('%s_push' % kind, v)
330 elif v is None:
331 self.emitline('%s_pop' % kind, "->", w)
332 else:
333 self.emitline('%s_copy' % kind, v, "->", w)
334 self.generate_last_exc(link, link.target.inputargs)
335
336 def generate_last_exc(self, link, inputargs):
337 # Write 'last_exc_xxx' operations that load the last exception
338 # directly into the locations specified by 'inputargs'. This
339 # must be done at the end of the link renamings.
340 if link.last_exception is link.last_exc_value is None:
341 return
342 for v, w in zip(link.args, inputargs):
343 if v is link.last_exception:
344 self.emitline("last_exception", "->", self.getcolor(w))
345 for v, w in zip(link.args, inputargs):
346 if v is link.last_exc_value:
347 self.emitline("last_exc_value", "->", self.getcolor(w))
348
349 def emitline(self, *line):
350 self.ssarepr.insns.append(line)
351
352 def popline(self):
353 return self.ssarepr.insns.pop()
354
355 def flatten_list(self, arglist):
356 args = []
357 for v in arglist:
358 if isinstance(v, Variable):
359 v = self.getcolor(v)
360 elif isinstance(v, Constant):
361 pass
362 elif isinstance(v, ListOfKind):
363 lst = [self.getcolor(x) for x in v]
364 v = ListOfKind(v.kind, lst)
365 elif isinstance(v, (AbstractDescr,
366 IndirectCallTargets)):
367 pass
368 else:
369 raise NotImplementedError(type(v))
370 args.append(v)
371 return args
372
373 def serialize_op(self, op):
374 args = self.flatten_list(op.args)
375 if op.result is not None:
376 kind = getkind(op.result.concretetype)
377 if kind != 'void':
378 args.append("->")
379 args.append(self.getcolor(op.result))
380 self.emitline(op.opname, *args)
381
382 def getcolor(self, v):
383 if isinstance(v, Constant):
384 return v
385 kind = getkind(v.concretetype)
386 col = self.regallocs[kind].getcolor(v) # if kind=='void', fix caller
387 try:
388 r = self.registers[kind, col]
389 except KeyError:
390 r = self.registers[kind, col] = Register(kind, col)
391 return r
392
393 # ____________________________________________________________
394
395 def reorder_renaming_list(frm, to):
396 result = []
397 pending_indices = range(len(to))
398 while pending_indices:
399 not_read = dict.fromkeys([frm[i] for i in pending_indices])
400 still_pending_indices = []
401 for i in pending_indices:
402 if to[i] not in not_read:
403 result.append((frm[i], to[i]))
404 else:
405 still_pending_indices.append(i)
406 if len(pending_indices) == len(still_pending_indices):
407 # no progress -- there is a cycle
408 assert None not in not_read
409 result.append((frm[pending_indices[0]], None))
410 frm[pending_indices[0]] = None
411 continue
412 pending_indices = still_pending_indices
413 return result