Debian Codegraph @

rpython/translator/transform.py

raw symbols SCIP
1 """Flow Graph Transformation
2
3 The difference between simplification and transformation is that
4 transformation is based on annotations; it runs after the annotator
5 completed.
6 """
7
8 from rpython.flowspace.model import (
9 SpaceOperation, Variable, Constant, Link, checkgraph)
10 from rpython.annotator import model as annmodel
11 from rpython.rtyper.lltypesystem import lltype
12
13 def checkgraphs(self, blocks):
14 seen = set()
15 for block in blocks:
16 graph = self.annotated[block]
17 if graph not in seen:
18 checkgraph(graph)
19 seen.add(graph)
20
21 def fully_annotated_blocks(self):
22 """Ignore blocked blocks."""
23 for block, is_annotated in self.annotated.iteritems():
24 if is_annotated:
25 yield block
26
27 # XXX: Lots of duplicated codes. Fix this!
28
29 # [a] * b
30 # -->
31 # c = newlist(a)
32 # d = mul(c, b)
33 # -->
34 # d = alloc_and_set(b, a)
35
36 def transform_allocate(self, block_subset):
37 """Transforms [a] * b to alloc_and_set(b, a) where b is int."""
38 for block in block_subset:
39 length1_lists = {} # maps 'c' to 'a', in the above notation
40 for i in range(len(block.operations)):
41 op = block.operations[i]
42 if (op.opname == 'newlist' and
43 len(op.args) == 1):
44 length1_lists[op.result] = op.args[0]
45 elif (op.opname == 'mul' and
46 op.args[0] in length1_lists):
47 new_op = SpaceOperation('alloc_and_set',
48 (op.args[1], length1_lists[op.args[0]]),
49 op.result)
50 block.operations[i] = new_op
51
52 # lst += string[x:y]
53 # -->
54 # b = getslice(string, x, y)
55 # c = inplace_add(lst, b)
56 # -->
57 # c = extend_with_str_slice(lst, x, y, string)
58
59 def transform_extend_with_str_slice(self, block_subset):
60 """Transforms lst += string[x:y] to extend_with_str_slice"""
61 for block in block_subset:
62 slice_sources = {} # maps b to [string, slice] in the above notation
63 for i in range(len(block.operations)):
64 op = block.operations[i]
65 if (op.opname == 'getslice' and
66 self.gettype(op.args[0]) is str):
67 slice_sources[op.result] = op.args
68 elif (op.opname == 'inplace_add' and
69 op.args[1] in slice_sources and
70 self.gettype(op.args[0]) is list):
71 v_string, v_x, v_y = slice_sources[op.args[1]]
72 new_op = SpaceOperation('extend_with_str_slice',
73 [op.args[0], v_x, v_y, v_string],
74 op.result)
75 block.operations[i] = new_op
76
77 # lst += char*count [or count*char]
78 # -->
79 # b = mul(char, count) [or count, char]
80 # c = inplace_add(lst, b)
81 # -->
82 # c = extend_with_char_count(lst, char, count)
83
84 def transform_extend_with_char_count(self, block_subset):
85 """Transforms lst += char*count to extend_with_char_count"""
86 for block in block_subset:
87 mul_sources = {} # maps b to (char, count) in the above notation
88 for i in range(len(block.operations)):
89 op = block.operations[i]
90 if op.opname == 'mul':
91 s0 = self.annotation(op.args[0])
92 s1 = self.annotation(op.args[1])
93 if (isinstance(s0, annmodel.SomeChar) and
94 isinstance(s1, annmodel.SomeInteger)):
95 mul_sources[op.result] = op.args[0], op.args[1]
96 elif (isinstance(s1, annmodel.SomeChar) and
97 isinstance(s0, annmodel.SomeInteger)):
98 mul_sources[op.result] = op.args[1], op.args[0]
99 elif (op.opname == 'inplace_add' and
100 op.args[1] in mul_sources and
101 self.gettype(op.args[0]) is list):
102 v_char, v_count = mul_sources[op.args[1]]
103 new_op = SpaceOperation('extend_with_char_count',
104 [op.args[0], v_char, v_count],
105 op.result)
106 block.operations[i] = new_op
107
108 # x in [2, 3]
109 # -->
110 # b = newlist(2, 3)
111 # c = contains(b, x)
112 # -->
113 # c = contains(Constant((2, 3)), x)
114
115 def transform_list_contains(self, block_subset):
116 """Transforms x in [2, 3]"""
117 for block in block_subset:
118 newlist_sources = {} # maps b to [2, 3] in the above notation
119 for i in range(len(block.operations)):
120 op = block.operations[i]
121 if op.opname == 'newlist':
122 newlist_sources[op.result] = op.args
123 elif op.opname == 'contains' and op.args[0] in newlist_sources:
124 items = {}
125 for v in newlist_sources[op.args[0]]:
126 s = self.annotation(v)
127 if not s.is_immutable_constant():
128 break
129 items[s.const] = None
130 else:
131 # all arguments of the newlist are annotation constants
132 op.args[0] = Constant(items)
133 s_dict = self.annotation(op.args[0])
134 s_dict.dictdef.generalize_key(self.binding(op.args[1]))
135
136
137 def transform_dead_op_vars(ann, block_subset):
138 # we redo the same simplification from simplify.py,
139 # to kill dead (never-followed) links,
140 # which can possibly remove more variables.
141 from rpython.translator.simplify import transform_dead_op_vars_in_blocks
142 transform_dead_op_vars_in_blocks(block_subset, ann.translator.graphs,
143 ann.translator)
144
145 def transform_dead_code(self, block_subset):
146 """Remove dead code: these are the blocks that are not annotated at all
147 because the annotation considered that no conditional jump could reach
148 them."""
149 for block in block_subset:
150 for link in block.exits:
151 if link not in self.links_followed:
152 lst = list(block.exits)
153 lst.remove(link)
154 block.exits = tuple(lst)
155 if not block.exits:
156 # oups! cannot reach the end of this block
157 cutoff_alwaysraising_block(self, block)
158 elif block.canraise:
159 # exceptional exit
160 if block.exits[0].exitcase is not None:
161 # killed the non-exceptional path!
162 cutoff_alwaysraising_block(self, block)
163 if len(block.exits) == 1:
164 block.exitswitch = None
165 block.exits[0].exitcase = None
166
167 def cutoff_alwaysraising_block(self, block):
168 "Fix a block whose end can never be reached at run-time."
169 # search the operation that cannot succeed
170 can_succeed = [op for op in block.operations
171 if op.result.annotation is not None]
172 cannot_succeed = [op for op in block.operations
173 if op.result.annotation is None]
174 n = len(can_succeed)
175 # check consistency
176 assert can_succeed == block.operations[:n]
177 assert cannot_succeed == block.operations[n:]
178 assert 0 <= n < len(block.operations)
179 # chop off the unreachable end of the block
180 del block.operations[n+1:]
181 self.setbinding(block.operations[n].result, annmodel.s_ImpossibleValue)
182 # insert the equivalent of 'raise AssertionError'
183 graph = self.annotated[block]
184 msg = "Call to %r should have raised an exception" % (getattr(graph, 'func', None),)
185 c1 = Constant(AssertionError)
186 c2 = Constant(AssertionError(msg))
187 errlink = Link([c1, c2], graph.exceptblock)
188 block.recloseblock(errlink, *block.exits)
189 # record new link to make the transformation idempotent
190 self.links_followed[errlink] = True
191 # fix the annotation of the exceptblock.inputargs
192 etype, evalue = graph.exceptblock.inputargs
193 s_type = annmodel.SomeTypeOf([evalue])
194 s_value = annmodel.SomeInstance(self.bookkeeper.getuniqueclassdef(Exception))
195 self.setbinding(etype, s_type)
196 self.setbinding(evalue, s_value)
197 # make sure the bookkeeper knows about AssertionError
198 self.bookkeeper.getuniqueclassdef(AssertionError)
199
200 def insert_ll_stackcheck(translator):
201 from rpython.translator.backendopt.support import find_calls_from
202 from rpython.rlib.rstack import stack_check
203 from rpython.tool.algo.graphlib import Edge, make_edge_dict, break_cycles_v
204 rtyper = translator.rtyper
205 graph = rtyper.annotate_helper(stack_check, [])
206 rtyper.specialize_more_blocks()
207 stack_check_ptr = rtyper.getcallable(graph)
208 stack_check_ptr_const = Constant(stack_check_ptr, lltype.typeOf(stack_check_ptr))
209 edges = set()
210 insert_in = set()
211 block2graph = {}
212 for caller in translator.graphs:
213 pyobj = getattr(caller, 'func', None)
214 if pyobj is not None:
215 if getattr(pyobj, '_dont_insert_stackcheck_', False):
216 continue
217 for block, callee in find_calls_from(translator, caller):
218 if getattr(getattr(callee, 'func', None),
219 'insert_stack_check_here', False):
220 insert_in.add(callee.startblock)
221 block2graph[callee.startblock] = callee
222 continue
223 if block is not caller.startblock:
224 edges.add((caller.startblock, block))
225 block2graph[caller.startblock] = caller
226 edges.add((block, callee.startblock))
227 block2graph[block] = caller
228
229 edgelist = [Edge(block1, block2) for (block1, block2) in edges]
230 edgedict = make_edge_dict(edgelist)
231 for block in break_cycles_v(edgedict, edgedict):
232 insert_in.add(block)
233
234 for block in insert_in:
235 v = Variable()
236 v.concretetype = lltype.Void
237 unwind_op = SpaceOperation('direct_call', [stack_check_ptr_const], v)
238 block.operations.insert(0, unwind_op)
239 # prevents cycles of tail calls from occurring -- such cycles would
240 # not consume any stack, so would turn into potentially infinite loops
241 graph = block2graph[block]
242 graph.inhibit_tail_call = True
243 return len(insert_in)
244
245
246 default_extra_passes = [
247 transform_allocate,
248 transform_extend_with_str_slice,
249 transform_extend_with_char_count,
250 transform_list_contains,
251 ]
252
253 def transform_graph(ann, extra_passes=None, block_subset=None):
254 """Apply set of transformations available."""
255 # WARNING: this produces incorrect results if the graph has been
256 # modified by t.simplify() after it had been annotated.
257 if extra_passes is None:
258 extra_passes = default_extra_passes
259 if block_subset is None:
260 block_subset = fully_annotated_blocks(ann)
261 if not isinstance(block_subset, dict):
262 block_subset = dict.fromkeys(block_subset)
263 if ann.translator:
264 checkgraphs(ann, block_subset)
265 transform_dead_code(ann, block_subset)
266 for pass_ in extra_passes:
267 pass_(ann, block_subset)
268 # do this last, after the previous transformations had a
269 # chance to remove dependency on certain variables
270 transform_dead_op_vars(ann, block_subset)
271 if ann.translator:
272 checkgraphs(ann, block_subset)