Debian Codegraph @

rpython/memory/gctransform/shadowcolor.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import lltype, llmemory
2 from rpython.flowspace.model import mkentrymap, checkgraph, Block, Link
3 from rpython.flowspace.model import Variable, Constant, SpaceOperation
4 from rpython.tool.algo.regalloc import perform_register_allocation
5 from rpython.tool.algo.unionfind import UnionFind
6 from rpython.translator.unsimplify import varoftype, insert_empty_block
7 from rpython.translator.unsimplify import insert_empty_startblock, split_block
8 from rpython.translator.simplify import join_blocks
9 from rpython.rlib.rarithmetic import intmask
10 from collections import defaultdict
11
12
13 def is_trivial_rewrite(op):
14 return (op.opname in ('same_as', 'cast_pointer', 'cast_opaque_ptr')
15 and isinstance(op.args[0], Variable))
16
17
18 def find_predecessors(graph, pending_pred):
19 """Return the set of variables whose content can end up inside one
20 of the 'pending_pred', which is a list of (block, var) tuples.
21 """
22 entrymap = mkentrymap(graph)
23 if len(entrymap[graph.startblock]) != 1:
24 insert_empty_startblock(graph)
25 entrymap = mkentrymap(graph)
26
27 pred = set([v for block, v in pending_pred])
28
29 def add(block, v):
30 if isinstance(v, Variable):
31 if v not in pred:
32 pending_pred.append((block, v))
33 pred.add(v)
34
35 while pending_pred:
36 block, v = pending_pred.pop()
37 if v in block.inputargs:
38 var_index = block.inputargs.index(v)
39 for link in entrymap[block]:
40 prevblock = link.prevblock
41 if prevblock is not None:
42 add(prevblock, link.args[var_index])
43 else:
44 for op in block.operations:
45 if op.result is v:
46 if is_trivial_rewrite(op):
47 add(block, op.args[0])
48 break
49 return pred
50
51
52 def find_successors(graph, pending_succ):
53 """Return the set of variables where one of the 'pending_succ' can
54 end up. 'block_succ' is a list of (block, var) tuples.
55 """
56 succ = set([v for block, v in pending_succ])
57
58 def add(block, v):
59 if isinstance(v, Variable):
60 if v not in succ:
61 pending_succ.append((block, v))
62 succ.add(v)
63
64 while pending_succ:
65 block, v = pending_succ.pop()
66 for op in block.operations:
67 if op.args and v is op.args[0] and is_trivial_rewrite(op):
68 add(block, op.result)
69 for link in block.exits:
70 for i, v1 in enumerate(link.args):
71 if v1 is v:
72 add(link.target, link.target.inputargs[i])
73 return succ
74
75
76 def find_interesting_variables(graph):
77 # Decide which variables are "interesting" or not. Interesting
78 # variables contain at least the ones that appear in gc_push_roots
79 # and gc_pop_roots.
80 pending_pred = []
81 pending_succ = []
82 interesting_vars = set()
83 for block in graph.iterblocks():
84 for op in block.operations:
85 if op.opname == 'gc_push_roots':
86 for v in op.args:
87 if not isinstance(v, Variable):
88 continue
89 interesting_vars.add(v)
90 pending_pred.append((block, v))
91 elif op.opname == 'gc_pop_roots':
92 for v in op.args:
93 if not isinstance(v, Variable):
94 continue
95 assert v in interesting_vars # must be pushed just above
96 pending_succ.append((block, v))
97 if not interesting_vars:
98 return None
99
100 # If there is a path from a gc_pop_roots(v) to a subsequent
101 # gc_push_roots(w) where w contains the same value as v along that
102 # path, then we consider all intermediate blocks along that path
103 # which contain a copy of the same value, and add these variables
104 # as "interesting", too. Formally, a variable in a block is
105 # "interesting" if it is both a "predecessor" and a "successor",
106 # where predecessors are variables which (sometimes) end in a
107 # gc_push_roots, and successors are variables which (sometimes)
108 # come from a gc_pop_roots.
109 pred = find_predecessors(graph, pending_pred)
110 succ = find_successors(graph, pending_succ)
111 interesting_vars |= (pred & succ)
112
113 return interesting_vars
114
115
116 def allocate_registers(graph):
117 interesting_vars = find_interesting_variables(graph)
118 if not interesting_vars:
119 return None
120 regalloc = perform_register_allocation(graph, interesting_vars.__contains__)
121 assert regalloc.graph is graph
122 regalloc.find_num_colors()
123 return regalloc
124
125
126 def _gc_save_root(index, var):
127 c_index = Constant(index, lltype.Signed)
128 return SpaceOperation('gc_save_root', [c_index, var],
129 varoftype(lltype.Void))
130
131 def _gc_restore_root(index, var):
132 c_index = Constant(index, lltype.Signed)
133 return SpaceOperation('gc_restore_root', [c_index, var],
134 varoftype(lltype.Void))
135
136 def make_bitmask(filled, graph='?'):
137 n = filled.count(False)
138 if n == 0:
139 return (None, None)
140 bitmask = 0
141 last_index = 0
142 for i in range(len(filled)):
143 if not filled[i]:
144 bitmask <<= (i - last_index)
145 last_index = i
146 bitmask |= 1
147 assert bitmask & 1
148 if bitmask != intmask(bitmask):
149 raise GCBitmaskTooLong("the graph %r is too complex: cannot create "
150 "a bitmask telling than more than 31/63 "
151 "shadowstack entries are unused" % (graph,))
152 # the mask is always a positive value, but it is replaced by a
153 # negative value during a minor collection root walking. Then,
154 # if the next minor collection finds an already-negative value,
155 # we know we can stop. So that's why we don't include here an
156 # optimization to not re-write a same-valued mask: it is important
157 # to re-write the value, to turn it from potentially negative back
158 # to positive, in order to mark this shadow frame as modified.
159 assert bitmask > 0
160 return (last_index, bitmask)
161
162
163 def expand_one_push_roots(regalloc, args):
164 if regalloc is None:
165 assert len(args) == 0
166 else:
167 filled = [False] * regalloc.numcolors
168 for v in args:
169 index = regalloc.getcolor(v)
170 assert not filled[index]
171 filled[index] = True
172 yield _gc_save_root(index, v)
173 bitmask_index, bitmask = make_bitmask(filled, regalloc.graph)
174 if bitmask_index is not None:
175 # xxx we might in some cases avoid this gc_save_root
176 # entirely, if we know we're after another gc_push/gc_pop
177 # that wrote exactly the same mask at the same index
178 bitmask_c = Constant(bitmask, lltype.Signed)
179 yield _gc_save_root(bitmask_index, bitmask_c)
180
181 def expand_one_pop_roots(regalloc, args):
182 if regalloc is None:
183 assert len(args) == 0
184 else:
185 for v in args:
186 index = regalloc.getcolor(v)
187 yield _gc_restore_root(index, v)
188
189
190 def expand_push_roots(graph, regalloc):
191 """Expand gc_push_roots into a series of gc_save_root, including
192 writing a bitmask tag to mark some entries as not-in-use.
193 (If regalloc is None, it will still remove empty gc_push_roots.)
194 """
195 for block in graph.iterblocks():
196 any_change = False
197 newops = []
198 for op in block.operations:
199 if op.opname == 'gc_push_roots':
200 args = [v for v in op.args if isinstance(v, Variable)]
201 newops += expand_one_push_roots(regalloc, args)
202 any_change = True
203 else:
204 newops.append(op)
205 if any_change:
206 block.operations = newops
207
208
209 def move_pushes_earlier(graph, regalloc):
210 """gc_push_roots and gc_pop_roots are pushes/pops to the shadowstack,
211 immediately enclosing the operation that needs them (typically a call).
212 Here, we try to move individual pushes earlier.
213
214 Should run after expand_push_roots(), but before expand_pop_roots(),
215 so that it sees individual 'gc_save_root' operations but bulk
216 'gc_pop_roots' operations.
217 """
218 # Concrete example (assembler tested on x86-64 gcc 5.3 and clang 3.7):
219 #
220 # ----original---- ----move_pushes_earlier----
221 #
222 # while (a > 10) { *foo = b;
223 # *foo = b; while (a > 10) {
224 # a = g(a); a = g(a);
225 # b = *foo; b = *foo;
226 # // *foo = b;
227 # } }
228 # return b; return b;
229 #
230 # => the store and the => the store is before, and gcc/clang
231 # load are in the loop, moves the load after the loop
232 # even in the assembler (the commented-out '*foo=b' is removed
233 # here, but gcc/clang would also remove it)
234
235 # Draft of the algorithm: see shadowcolor.txt
236
237 if not regalloc:
238 return
239
240 entrymap = mkentrymap(graph)
241 assert len(entrymap[graph.startblock]) == 1
242
243 inputvars = {} # {inputvar: (its block, its index in inputargs)}
244 for block in graph.iterblocks():
245 for i, v in enumerate(block.inputargs):
246 inputvars[v] = (block, i)
247
248 Plist = []
249
250 for index in range(regalloc.numcolors):
251 U = UnionFind()
252
253 S = set()
254 for block in graph.iterblocks():
255 for op in reversed(block.operations):
256 if op.opname == 'gc_pop_roots':
257 break
258 else:
259 continue # no gc_pop_roots in this block
260 for v in op.args:
261 if isinstance(v, Variable) and regalloc.checkcolor(v, index):
262 break
263 else:
264 continue # no variable goes into index i
265
266 succ = set()
267 pending_succ = [(block, v)]
268 while pending_succ:
269 block1, v1 = pending_succ.pop()
270 assert regalloc.checkcolor(v1, index)
271 for op1 in block1.operations:
272 if is_trivial_rewrite(op1) and op1.args[0] is v1:
273 if regalloc.checkcolor(op1.result, index):
274 pending_succ.append((block1, op1.result))
275 for link1 in block1.exits:
276 for i2, v2 in enumerate(link1.args):
277 if v2 is not v1:
278 continue
279 block2 = link1.target
280 w2 = block2.inputargs[i2]
281 if w2 in succ or not regalloc.checkcolor(w2, index):
282 continue
283 succ.add(w2)
284 for op2 in block2.operations:
285 if op2.opname in ('gc_save_root', 'gc_pop_roots'):
286 break
287 else:
288 pending_succ.append((block2, w2))
289 U.union_list(list(succ))
290 S.update(succ)
291
292 G = defaultdict(set)
293 for block in graph.iterblocks():
294 found = False
295 for opindex, op in enumerate(block.operations):
296 if op.opname == 'gc_save_root':
297 if (isinstance(op.args[1], Constant) and
298 op.args[1].concretetype == lltype.Signed):
299 break
300 elif op.args[0].value == index:
301 found = True
302 break
303 if not found or not isinstance(op.args[1], Variable):
304 continue # no matching gc_save_root in this block
305
306 key = (block, op)
307 pred = set()
308 pending_pred = [(block, op.args[1], opindex)]
309 while pending_pred:
310 block1, v1, opindex1 = pending_pred.pop()
311 assert regalloc.getcolor(v1) == index
312 for i in range(opindex1-1, -1, -1):
313 op1 = block1.operations[i]
314 if op1.opname == 'gc_pop_roots':
315 break # stop
316 if op1.result is v1:
317 if not is_trivial_rewrite(op1):
318 break # stop
319 if not regalloc.checkcolor(op1.args[0], index):
320 break # stop
321 v1 = op1.args[0]
322 else:
323 varindex = block1.inputargs.index(v1)
324 if v1 in pred:
325 continue # already done
326 pred.add(v1)
327 for link1 in entrymap[block1]:
328 prevblock1 = link1.prevblock
329 if prevblock1 is not None:
330 w1 = link1.args[varindex]
331 if isinstance(w1, Variable) and w1 not in pred:
332 if regalloc.checkcolor(w1, index):
333 pending_pred.append((prevblock1, w1,
334 len(prevblock1.operations)))
335 U.union_list(list(pred))
336 for v1 in pred:
337 G[v1].add(key)
338
339 M = S.intersection(G)
340
341 parts_target = {}
342 for v in M:
343 vp = U.find_rep(v)
344 if vp not in parts_target:
345 new_part = (index, set(), set())
346 # (index,
347 # subset P of variables,
348 # set of (block, gc_save_root))
349 Plist.append(new_part)
350 parts_target[vp] = new_part
351 part = parts_target[vp]
352 part[1].add(v)
353 part[2].update(G[v])
354
355 # Sort P so that it prefers places that would avoid multiple
356 # gcsaveroots (smaller 'heuristic' result, so first in sorted
357 # order); but also prefers smaller overall pieces, because it
358 # might be possible to remove several small-scale pieces instead
359 # of one big-scale one.
360 def heuristic((index, P, gcsaveroots)):
361 return float(len(P)) / len(gcsaveroots)
362 Plist.sort(key=heuristic)
363
364 variables_along_changes = {}
365 live_at_start_of_block = set() # set of (block, index)
366 insert_gc_push_root = defaultdict(list)
367
368 for index, P, gcsaveroots in Plist:
369 # if this Plist entry is not valid any more because of changes
370 # done by the previous entries, drop it
371 if any((inputvars[v][0], index) in live_at_start_of_block for v in P):
372 continue
373 if any(op not in block.operations for block, op in gcsaveroots):
374 continue
375 for v in P:
376 assert regalloc.getcolor(v) == index
377 assert v not in variables_along_changes
378
379 success_count = 0
380 mark = []
381
382 for v in P:
383 block, varindex = inputvars[v]
384 for link in entrymap[block]:
385 w = link.args[varindex]
386 if link.prevblock is not None:
387 prevoperations = link.prevblock.operations
388 else:
389 prevoperations = []
390 for op in reversed(prevoperations):
391 if op.opname == 'gc_pop_roots':
392 # it is possible to have gc_pop_roots() without
393 # w in the args, if w is the result of the call
394 # that comes just before.
395 if (isinstance(w, Variable) and
396 w in op.args and
397 regalloc.checkcolor(w, index)):
398 success_count += 1
399 else:
400 mark.append((index, link, varindex))
401 break
402 if op.result is w:
403 if is_trivial_rewrite(op) and (
404 regalloc.checkcolor(op.args[0], index)):
405 w = op.args[0]
406 else:
407 mark.append((index, link, varindex))
408 break
409 else:
410 if not isinstance(w, Variable) or w not in P:
411 mark.append((index, link, varindex))
412
413 if success_count > 0:
414 for block, op in gcsaveroots:
415 newops = list(block.operations)
416 newops.remove(op)
417 block.operations = newops
418 for index, link, varindex in mark:
419 insert_gc_push_root[link].append((index, link.args[varindex]))
420 for v in P:
421 block, varindex = inputvars[v]
422 variables_along_changes[v] = block, index
423 live_at_start_of_block.add((block, index))
424
425 for link in insert_gc_push_root:
426 newops = [_gc_save_root(index, v)
427 for index, v in sorted(insert_gc_push_root[link])]
428 insert_empty_block(link, newops=newops)
429
430
431 def expand_pop_roots(graph, regalloc):
432 """gc_pop_roots => series of gc_restore_root; this is done after
433 move_pushes_earlier() because that one doesn't work correctly if
434 a completely-empty gc_pop_roots is removed.
435
436 Also notice in-block code sequences like gc_pop_roots(v) followed
437 by a gc_save_root(v), and drop the gc_save_root.
438 """
439 drop = {}
440 for block in graph.iterblocks():
441 any_change = False
442 newops = []
443 for op in block.operations:
444 if op.opname == 'gc_pop_roots':
445 args = [v for v in op.args if isinstance(v, Variable)]
446 expanded = list(expand_one_pop_roots(regalloc, args))
447 drop = {}
448 for op1 in expanded:
449 if isinstance(op1.args[1], Variable):
450 drop[op1.args[1]] = op1.args[0].value
451 newops += expanded
452 any_change = True
453 elif (op.opname == 'gc_save_root' and
454 drop.get(op.args[1]) == op.args[0].value):
455 any_change = True # kill the operation
456 else:
457 newops.append(op)
458 if any_change:
459 block.operations = newops
460
461
462 def add_enter_leave_roots_frame(graph, regalloc, c_gcdata):
463 # put 'gc_enter_roots_frame' as late as possible, but before the
464 # first 'gc_save_root' is reached.
465 #
466 # put the 'gc_leave_roots_frame' operations as early as possible,
467 # that is, just after the last 'gc_restore_root' reached. This is
468 # done by putting it along a link, such that the previous block
469 # contains a 'gc_restore_root' and from the next block it is not
470 # possible to reach any extra 'gc_restore_root'; then, as doing
471 # this is not as precise as we'd like, we first break every block
472 # just after their last 'gc_restore_root'.
473 if regalloc is None:
474 return
475
476 # break blocks after their last 'gc_restore_root', unless they
477 # are already at the last position
478 for block in graph.iterblocks():
479 ops = block.operations
480 for i in range(len(ops)-1, -1, -1):
481 if ops[i].opname == 'gc_restore_root':
482 if i < len(ops) - 1:
483 split_block(block, i + 1)
484 break
485 # done
486
487 insert_empty_startblock(graph)
488 entrymap = mkentrymap(graph)
489
490 # helpers
491
492 def is_interesting_op(op):
493 if op.opname == 'gc_restore_root':
494 return True
495 if op.opname == 'gc_save_root':
496 # ignore saves that say "everything is free"
497 return not (isinstance(op.args[1], Constant) and
498 isinstance(op.args[1].value, int) and
499 op.args[1].value == bitmask_all_free)
500 return False
501 bitmask_all_free = (1 << regalloc.numcolors) - 1
502
503 def insert_along_link(link, opname, args, cache):
504 b2 = link.target
505 if b2 not in cache:
506 newblock = Block([v.copy() for v in b2.inputargs])
507 newblock.operations.append(
508 SpaceOperation(opname, args, varoftype(lltype.Void)))
509 newblock.closeblock(Link(list(newblock.inputargs), b2))
510 cache[b2] = newblock
511 link.target = cache[b2]
512
513 # make a list of blocks with gc_save_root/gc_restore_root in them
514 interesting_blocks = []
515 for block in graph.iterblocks():
516 for op in block.operations:
517 if is_interesting_op(op):
518 assert block is not graph.startblock
519 assert block is not graph.returnblock
520 interesting_blocks.append(block)
521 break # interrupt this block, go to the next one
522
523 # compute the blocks such that 'gc_save_root/gc_restore_root'
524 # exist anywhere before the start of this block
525 before_blocks = set()
526 pending = list(interesting_blocks)
527 seen = set(pending)
528 while pending:
529 block = pending.pop()
530 for link in block.exits:
531 before_blocks.add(link.target)
532 if link.target not in seen:
533 seen.add(link.target)
534 pending.append(link.target)
535 assert graph.startblock not in before_blocks
536
537 # compute the blocks such that 'gc_save_root/gc_restore_root'
538 # exist anywhere after the start of this block
539 after_blocks = set(interesting_blocks)
540 pending = list(interesting_blocks)
541 while pending:
542 block = pending.pop()
543 for link in entrymap[block]:
544 if link.prevblock is not None:
545 if link.prevblock not in after_blocks:
546 after_blocks.add(link.prevblock)
547 pending.append(link.prevblock)
548 assert graph.returnblock not in after_blocks
549
550 # this is the set of blocks such that, at the start of the block,
551 # we're "in frame", i.e. there are 'gc_save_root/gc_restore_root'
552 # both before and after the start of the block.
553 inside_blocks = before_blocks & after_blocks
554 inside_or_interesting_blocks = set(interesting_blocks) | inside_blocks
555
556 # if a block contains gc_save_root/gc_restore_root but is not
557 # an "inside_block", then add gc_enter_roots_frame where needed
558 c_num = Constant(regalloc.numcolors, lltype.Signed)
559 for block in interesting_blocks:
560 if block not in inside_blocks:
561 i = 0
562 while not is_interesting_op(block.operations[i]):
563 i += 1
564 block.operations.insert(i,
565 SpaceOperation('gc_enter_roots_frame', [c_gcdata, c_num],
566 varoftype(lltype.Void)))
567
568 # If a link goes from a "non-inside, non-interesting block"
569 # straight to an "inside_block", insert a gc_enter_roots_frame
570 # along the link. Similarly, if a block is a "inside-or-
571 # interesting_block" and exits with a link going to a
572 # "non-inside_block", then insert a gc_leave_roots_frame along the
573 # link.
574 cache1 = {}
575 cache2 = {}
576 for block in list(graph.iterblocks()):
577 if block not in inside_or_interesting_blocks:
578 for link in block.exits:
579 if link.target in inside_blocks:
580 insert_along_link(link, 'gc_enter_roots_frame',
581 [c_gcdata, c_num], cache1)
582 else:
583 for link in block.exits:
584 if link.target not in inside_blocks:
585 insert_along_link(link, 'gc_leave_roots_frame',
586 [], cache2)
587
588 # check all blocks not in "inside_block": they might contain a
589 # gc_save_root() that writes the bitmask meaning "everything is
590 # free". Look only before gc_enter_roots_frame, if there is one
591 # in that block. Remove these out-of-frame gc_save_root().
592 for block in graph.iterblocks():
593 if block not in inside_blocks:
594 newops = []
595 for i, op in enumerate(block.operations):
596 if op.opname == 'gc_enter_roots_frame':
597 newops.extend(block.operations[i:])
598 break
599 if op.opname == 'gc_save_root' and not is_interesting_op(op):
600 pass # don't add in newops
601 else:
602 newops.append(op)
603 if len(newops) < len(block.operations):
604 block.operations = newops
605
606 join_blocks(graph) # for the extra new blocks made in this function
607
608
609 class GCBitmaskTooLong(Exception):
610 pass
611
612 class PostProcessCheckError(Exception):
613 pass
614
615 def postprocess_double_check(graph):
616 # Debugging only: double-check that the placement is correct.
617 # Assumes that every gc_restore_root() indicates that the variable
618 # must be saved at the given position in the shadowstack frame (in
619 # practice it may have moved because of the GC, but in theory it
620 # is still the "same" object). So we build the set of all known
621 # valid-in-all-paths saved locations, and check that.
622
623 saved = {} # {var-from-inputargs: location} where location is:
624 # <unset>: we haven't seen this variable so far
625 # set-of-indexes: says where the variable is always
626 # saved at the start of this block
627 # empty-set: same as above, so: "saved nowhere"
628
629 in_frame = {} # {block: bool}, tells if, at the start of this block,
630 # we're in status "frame entered" or not
631
632 in_frame[graph.startblock] = False
633 pending = set([graph.startblock])
634 while pending:
635 block = pending.pop()
636 locsaved = {}
637 currently_in_frame = in_frame[block]
638 if currently_in_frame:
639 for v in block.inputargs:
640 locsaved[v] = saved[v]
641 for op in block.operations:
642 if op.opname == 'gc_restore_root':
643 if not currently_in_frame:
644 raise PostProcessCheckError(graph, block, op, 'no frame!')
645 if isinstance(op.args[1], Constant):
646 continue
647 num = op.args[0].value
648 if num not in locsaved[op.args[1]]:
649 raise PostProcessCheckError(graph, block, op, num, locsaved)
650 elif op.opname == 'gc_save_root':
651 if not currently_in_frame:
652 raise PostProcessCheckError(graph, block, op, 'no frame!')
653 num = op.args[0].value
654 # first, cancel any other variable that would be saved in 'num'
655 for v in locsaved:
656 locsaved[v] = locsaved[v].difference([num])
657 #
658 v = op.args[1]
659 if isinstance(v, Variable):
660 locsaved[v] = locsaved[v].union([num])
661 else:
662 if v.concretetype != lltype.Signed:
663 locsaved[v] = locsaved.get(v, frozenset()).union([num])
664 continue
665 bitmask = v.value
666 if bitmask != 1:
667 # cancel any variable that would be saved in any
668 # position shown by the bitmask, not just 'num'
669 assert bitmask & 1
670 assert 1 < bitmask < (2<<num)
671 nummask = [i for i in range(num+1)
672 if bitmask & (1<<(num-i))]
673 assert nummask[-1] == num
674 for v in locsaved:
675 locsaved[v] = locsaved[v].difference(nummask)
676 elif op.opname == 'gc_enter_roots_frame':
677 if currently_in_frame:
678 raise PostProcessCheckError(graph, block, op,'double enter')
679 currently_in_frame = True
680 # initialize all local variables so far with "not seen anywhere"
681 # (already done, apart from block.inputargs)
682 for v in block.inputargs:
683 locsaved[v] = frozenset()
684 elif op.opname == 'gc_leave_roots_frame':
685 if not currently_in_frame:
686 raise PostProcessCheckError(graph, block, op, 'not entered')
687 currently_in_frame = False
688 elif is_trivial_rewrite(op) and currently_in_frame:
689 locsaved[op.result] = locsaved[op.args[0]]
690 else:
691 locsaved[op.result] = frozenset()
692 for link in block.exits:
693 changed = False
694 if link.target not in in_frame:
695 in_frame[link.target] = currently_in_frame
696 changed = True
697 else:
698 if in_frame[link.target] != currently_in_frame:
699 raise PostProcessCheckError(graph, link.target,
700 'inconsistent in_frame')
701 if currently_in_frame:
702 for i, v in enumerate(link.args):
703 try:
704 loc = locsaved[v]
705 except KeyError:
706 assert isinstance(v, Constant)
707 loc = frozenset()
708 w = link.target.inputargs[i]
709 if w in saved:
710 if loc == saved[w]:
711 continue # already up-to-date
712 loc = loc.intersection(saved[w])
713 saved[w] = loc
714 changed = True
715 if changed:
716 pending.add(link.target)
717
718 if in_frame.get(graph.returnblock, False):
719 raise PostProcessCheckError(graph, 'missing gc_leave_roots_frame')
720 assert graph.getreturnvar() not in saved # missing gc_leave_roots_frame?
721
722
723 def postprocess_graph(graph, c_gcdata):
724 """Collect information about the gc_push_roots and gc_pop_roots
725 added in this complete graph, and replace them with real operations.
726 """
727 regalloc = allocate_registers(graph)
728 expand_push_roots(graph, regalloc)
729 move_pushes_earlier(graph, regalloc)
730 expand_pop_roots(graph, regalloc)
731 add_enter_leave_roots_frame(graph, regalloc, c_gcdata)
732 checkgraph(graph)
733 postprocess_double_check(graph)
734 return (regalloc is not None)
735
736
737 def postprocess_inlining(graph):
738 """We first write calls to GC functions with gc_push_roots(...) and
739 gc_pop_roots(...) around. Then we inline some of these functions.
740 As a result, the gc_push_roots and gc_pop_roots are no longer in
741 the same block. Fix that by moving the gc_push_roots/gc_pop_roots
742 inside the inlined portion of the graph, around every call.
743
744 We could also get a correct result by doing things in a different
745 order, e.g. first postprocess_graph() and then inlining. However,
746 this order brings an important benefit: if the inlined graph has a
747 fast-path, like malloc_fixedsize(), then there are no gc_push_roots
748 and gc_pop_roots left along the fast-path.
749 """
750 for block in graph.iterblocks():
751 for i in range(len(block.operations)-1, -1, -1):
752 op = block.operations[i]
753 if op.opname == 'gc_pop_roots':
754 break
755 if op.opname == 'gc_push_roots':
756 _fix_graph_after_inlining(graph, block, i)
757 break
758 checkgraph(graph)
759
760 def _fix_graph_after_inlining(graph, initial_block, initial_index):
761 op = initial_block.operations.pop(initial_index)
762 assert op.opname == 'gc_push_roots'
763 seen = set()
764 pending = [(initial_block, initial_index, op.args)]
765 while pending:
766 block, start_index, track_args = pending.pop()
767 if block in seen:
768 continue
769 seen.add(block)
770 assert block.operations != () # did not find the gc_pop_roots?
771 new_operations = block.operations[:start_index]
772 stop = False
773 for i in range(start_index, len(block.operations)):
774 op = block.operations[i]
775 if op.opname == 'gc_push_roots':
776 raise Exception("%r: seems to have inlined inside it another "
777 "graph which also uses GC roots" % (graph,))
778 if op.opname == 'gc_pop_roots':
779 # end of the inlined graph, drop gc_pop_roots, keep the tail
780 new_operations += block.operations[i + 1:]
781 stop = True
782 break
783 if op.opname in ('direct_call', 'indirect_call'):
784 new_operations.append(SpaceOperation('gc_push_roots',
785 track_args[:],
786 varoftype(lltype.Void)))
787 new_operations.append(op)
788 new_operations.append(SpaceOperation('gc_pop_roots',
789 track_args[:],
790 varoftype(lltype.Void)))
791 else:
792 new_operations.append(op)
793 block.operations = new_operations
794 if not stop:
795 for link in block.exits:
796 track_next = []
797 for v in track_args:
798 if not isinstance(v, Variable):
799 continue
800 i = link.args.index(v) # should really be here
801 w = link.target.inputargs[i]
802 track_next.append(w)
803 pending.append((link.target, 0, track_next))