Debian Codegraph @

rpython/translator/backendopt/inline.py

raw symbols SCIP
1 import sys
2
3 from rpython.flowspace.model import (Variable, Constant, Block, Link,
4 SpaceOperation, FunctionGraph, mkentrymap)
5 from rpython.rtyper.lltypesystem.lltype import Bool, Signed, typeOf, Void, Ptr, normalizeptr
6 from rpython.tool.algo import sparsemat
7 from rpython.translator.backendopt import removenoops
8 from rpython.translator.backendopt.canraise import RaiseAnalyzer
9 from rpython.translator.backendopt.support import log, find_loop_blocks
10 from rpython.translator.simplify import join_blocks, cleanup_graph, get_graph
11 from rpython.translator.unsimplify import split_block
12
13
14 class CannotInline(Exception):
15 pass
16
17
18 class CanRaise(object):
19 def __init__(self, can_raise):
20 self.can_raise = can_raise
21
22
23 def collect_called_graphs(graph, translator):
24 graphs_or_something = set()
25 for block in graph.iterblocks():
26 for op in block.operations:
27 if op.opname == "direct_call":
28 graph = get_graph(op.args[0], translator)
29 if graph is not None:
30 graphs_or_something.add(graph)
31 else:
32 graphs_or_something.add(op.args[0])
33 if op.opname == "indirect_call":
34 graphs = op.args[-1].value
35 if graphs is None:
36 graphs_or_something.add(op.args[0])
37 else:
38 for graph in graphs:
39 graphs_or_something.add(graph)
40 return graphs_or_something
41
42 def iter_callsites(graph, calling_what):
43 for block in graph.iterblocks():
44 for i, op in enumerate(block.operations):
45 if op.opname == "direct_call":
46 funcobj = op.args[0].value._obj
47 else:
48 continue
49
50 graph = getattr(funcobj, 'graph', None)
51 # accept a function or a graph as 'inline_func'
52 if (calling_what is None or
53 graph is calling_what or
54 getattr(funcobj, '_callable', None) is calling_what):
55 yield graph, block, i
56
57 def find_callsites(graph, calling_what):
58 return list(iter_callsites(graph, calling_what))
59
60 def iter_first_callsites(graph, calling_what):
61 # restart the iter_callsites iterator every time, since the graph might
62 # have changed
63 while 1:
64 iterator = iter_callsites(graph, calling_what)
65 yield iterator.next()
66
67 def contains_call(graph, calling_what):
68 try:
69 iterator = iter_callsites(graph, calling_what)
70 iterator.next()
71 return True
72 except StopIteration:
73 return False
74
75 def inline_function(translator, inline_func, graph, lltype_to_classdef,
76 raise_analyzer, call_count_pred=None, cleanup=True):
77 inliner = Inliner(translator, graph, inline_func, lltype_to_classdef,
78 raise_analyzer=raise_analyzer,
79 call_count_pred=call_count_pred, cleanup=cleanup)
80 return inliner.inline_all()
81
82 def simple_inline_function(translator, inline_func, graph):
83 inliner = Inliner(translator, graph, inline_func,
84 translator.rtyper.lltype_to_classdef_mapping(),
85 raise_analyzer=RaiseAnalyzer(translator))
86 return inliner.inline_all()
87
88
89 def _find_exception_type(block):
90 #XXX slightly brittle: find the exception type for simple cases
91 #(e.g. if you do only raise XXXError) by doing pattern matching
92 currvar = block.exits[0].args[1]
93 ops = block.operations
94 i = len(ops) - 1
95 while True:
96 if isinstance(currvar, Constant):
97 value = currvar.value
98 TYPE = typeOf(normalizeptr(value))
99 return TYPE, block.exits[0]
100 if i < 0:
101 return None, None
102 op = ops[i]
103 i -= 1
104 if op.opname in ("same_as", "cast_pointer") and op.result is currvar:
105 currvar = op.args[0]
106 elif op.opname == "malloc" and op.result is currvar:
107 return Ptr(op.args[0].value), block.exits[0]
108
109 def does_raise_directly(graph, raise_analyzer):
110 """ this function checks, whether graph contains operations which can raise
111 and which are not exception guarded """
112 for block in graph.iterblocks():
113 if block is graph.exceptblock:
114 return True # the except block is reachable
115 if block.canraise:
116 consider_ops_to = -1
117 else:
118 consider_ops_to = len(block.operations)
119 for op in block.operations[:consider_ops_to]:
120 if raise_analyzer.can_raise(op):
121 return True
122 return False
123
124 def any_call_to_raising_graphs(from_graph, translator, raise_analyzer):
125 for graph_or_something in collect_called_graphs(from_graph, translator):
126 if isinstance(graph_or_something, FunctionGraph):
127 if does_raise_directly(graph_or_something, raise_analyzer):
128 return True
129 elif isinstance(graph_or_something, CanRaise):
130 if graph_or_something.can_raise:
131 return True
132 else:
133 return True # conservatively
134 for block in from_graph.iterblocks():
135 if block.canraise:
136 consider_ops_to = -1
137 else:
138 consider_ops_to = len(block.operations)
139 for op in block.operations[:consider_ops_to]:
140 if raise_analyzer.can_raise(op):
141 return True
142 return False
143
144 class BaseInliner(object):
145 def __init__(self, translator, graph, lltype_to_classdef,
146 inline_guarded_calls=False,
147 inline_guarded_calls_no_matter_what=False,
148 raise_analyzer=None,
149 call_count_pred=None,
150 cleanup=True):
151 self.translator = translator
152 self.graph = graph
153 self.do_cleanup = cleanup
154 self.inline_guarded_calls = inline_guarded_calls
155 # if this argument is set, the inliner will happily produce wrong code!
156 # it is used by the exception transformation
157 self.inline_guarded_calls_no_matter_what = inline_guarded_calls_no_matter_what
158 assert raise_analyzer is not None
159 self.raise_analyzer = raise_analyzer
160 self.lltype_to_classdef = lltype_to_classdef
161 self.call_count_pred = call_count_pred
162
163 def inline_all(self):
164 count = 0
165 non_recursive = {}
166 call_count_pred = self.call_count_pred
167 while self.block_to_index:
168 block, d = self.block_to_index.popitem()
169 index_operation, subgraph = d.popitem()
170 if d:
171 self.block_to_index[block] = d
172 if subgraph not in non_recursive and contains_call(subgraph, subgraph):
173 raise CannotInline("inlining a recursive function")
174 else:
175 non_recursive[subgraph] = True
176 if call_count_pred:
177 countop = block.operations[index_operation-1]
178 assert countop.opname == 'instrument_count'
179 assert countop.args[0].value == 'inline'
180 label = countop.args[1].value
181 if not call_count_pred(label):
182 continue
183 self.inline_once(block, index_operation)
184 count += 1
185 if self.do_cleanup:
186 self.cleanup()
187 return count
188
189 def get_graph_from_op(self, op):
190 assert op.opname == 'direct_call'
191 return self.op.args[0].value._obj.graph
192
193 def inline_once(self, block, index_operation):
194 self.varmap = {}
195 self._copied_blocks = {}
196 self.op = block.operations[index_operation]
197 self.graph_to_inline = self.get_graph_from_op(self.op)
198 self.exception_guarded = False
199 if self.op is block.raising_op:
200 self.exception_guarded = True
201 if self.inline_guarded_calls:
202 if (not self.inline_guarded_calls_no_matter_what and
203 does_raise_directly(self.graph_to_inline, self.raise_analyzer)):
204 raise CannotInline("can't inline because the call is exception guarded")
205 elif any_call_to_raising_graphs(self.graph_to_inline,
206 self.translator, self.raise_analyzer):
207 raise CannotInline("can't handle exceptions")
208 self._passon_vars = {}
209 self.entrymap = mkentrymap(self.graph_to_inline)
210 self.do_inline(block, index_operation)
211
212 def search_for_calls(self, block):
213 d = {}
214 for i, op in enumerate(block.operations):
215 if op.opname == "direct_call":
216 funcobj = op.args[0].value._obj
217 else:
218 continue
219 graph = getattr(funcobj, 'graph', None)
220 # accept a function or a graph as 'inline_func'
221 if (graph is self.inline_func or
222 getattr(funcobj, '_callable', None) is self.inline_func):
223 d[i] = graph
224 if d:
225 self.block_to_index[block] = d
226 else:
227 try:
228 del self.block_to_index[block]
229 except KeyError:
230 pass
231
232 def get_new_name(self, var):
233 if var is None:
234 return None
235 if isinstance(var, Constant):
236 return var
237 if var not in self.varmap:
238 self.varmap[var] = var.copy()
239 return self.varmap[var]
240
241 def passon_vars(self, cache_key):
242 if cache_key in self._passon_vars:
243 return self._passon_vars[cache_key]
244 result = [var.copy() for var in self.original_passon_vars]
245 self._passon_vars[cache_key] = result
246 return result
247
248 def copy_operation(self, op):
249 args = [self.get_new_name(arg) for arg in op.args]
250 result = SpaceOperation(op.opname, args, self.get_new_name(op.result))
251 return result
252
253 def copy_block(self, block):
254 if block in self._copied_blocks:
255 return self._copied_blocks[block]
256 args = ([self.get_new_name(var) for var in block.inputargs] +
257 self.passon_vars(block))
258 newblock = Block(args)
259 self._copied_blocks[block] = newblock
260 newblock.operations = [self.copy_operation(op) for op in block.operations]
261 newblock.closeblock(*[self.copy_link(link, block) for link in block.exits])
262 newblock.exitswitch = self.get_new_name(block.exitswitch)
263 self.search_for_calls(newblock)
264 return newblock
265
266 def copy_link(self, link, prevblock):
267 newargs = [self.get_new_name(a) for a in link.args] + self.passon_vars(prevblock)
268 newlink = Link(newargs, self.copy_block(link.target), link.exitcase)
269 newlink.last_exception = self.get_new_name(link.last_exception)
270 newlink.last_exc_value = self.get_new_name(link.last_exc_value)
271 if hasattr(link, 'llexitcase'):
272 newlink.llexitcase = link.llexitcase
273 return newlink
274
275 def find_args_in_exceptional_case(self, link, block, etype, evalue, afterblock, passon_vars):
276 linkargs = []
277 for arg in link.args:
278 if arg == link.last_exception:
279 linkargs.append(etype)
280 elif arg == link.last_exc_value:
281 linkargs.append(evalue)
282 elif isinstance(arg, Constant):
283 linkargs.append(arg)
284 else:
285 index = afterblock.inputargs.index(arg)
286 linkargs.append(passon_vars[index - 1])
287 return linkargs
288
289 def rewire_returnblock(self, afterblock):
290 copiedreturnblock = self.copy_block(self.graph_to_inline.returnblock)
291 linkargs = ([copiedreturnblock.inputargs[0]] +
292 self.passon_vars(self.graph_to_inline.returnblock))
293 linkfrominlined = Link(linkargs, afterblock)
294 copiedreturnblock.exitswitch = None
295 copiedreturnblock.recloseblock(linkfrominlined)
296 assert copiedreturnblock.exits[0].target == afterblock
297
298 def rewire_exceptblock(self, afterblock):
299 #let links to exceptblock of the graph to inline go to graphs exceptblock
300 copiedexceptblock = self.copy_block(self.graph_to_inline.exceptblock)
301 if not self.exception_guarded:
302 self.rewire_exceptblock_no_guard(afterblock, copiedexceptblock)
303 else:
304 # first try to match exceptions using a very simple heuristic
305 self.rewire_exceptblock_with_guard(afterblock, copiedexceptblock)
306 # generate blocks that do generic matching for cases when the
307 # heuristic did not work
308 self.generic_exception_matching(afterblock, copiedexceptblock)
309
310 def rewire_exceptblock_no_guard(self, afterblock, copiedexceptblock):
311 # find all copied links that go to copiedexceptblock
312 for link in self.entrymap[self.graph_to_inline.exceptblock]:
313 copiedblock = self.copy_block(link.prevblock)
314 for copiedlink in copiedblock.exits:
315 if copiedlink.target is copiedexceptblock:
316 copiedlink.args = copiedlink.args[:2]
317 copiedlink.target = self.graph.exceptblock
318 for a1, a2 in zip(copiedlink.args,
319 self.graph.exceptblock.inputargs):
320 if hasattr(a2, 'concretetype'):
321 assert a1.concretetype == a2.concretetype
322 else:
323 # if self.graph.exceptblock was never used before
324 a2.concretetype = a1.concretetype
325
326 def rewire_exceptblock_with_guard(self, afterblock, copiedexceptblock):
327 # this rewiring does not always succeed. in the cases where it doesn't
328 # there will be generic code inserted
329 from rpython.rtyper import rclass
330 excdata = self.translator.rtyper.exceptiondata
331 exc_match = excdata.fn_exception_match
332 for link in self.entrymap[self.graph_to_inline.exceptblock]:
333 if link.prevblock.exits[0] is not link:
334 continue
335 copiedblock = self.copy_block(link.prevblock)
336 VALUE, copiedlink = _find_exception_type(copiedblock)
337 #print copiedblock.operations
338 if VALUE is None or VALUE not in self.lltype_to_classdef:
339 continue
340 classdef = self.lltype_to_classdef[VALUE]
341 rtyper = self.translator.rtyper
342 classrepr = rclass.getclassrepr(rtyper, classdef)
343 vtable = classrepr.getruntime(excdata.lltype_of_exception_type)
344 var_etype = copiedlink.args[0]
345 var_evalue = copiedlink.args[1]
346 for exceptionlink in afterblock.exits[1:]:
347 if exc_match(vtable, exceptionlink.llexitcase):
348 passon_vars = self.passon_vars(link.prevblock)
349 copiedlink.target = exceptionlink.target
350 linkargs = self.find_args_in_exceptional_case(
351 exceptionlink, link.prevblock, var_etype, var_evalue, afterblock, passon_vars)
352 copiedlink.args = linkargs
353 break
354
355 def generic_exception_matching(self, afterblock, copiedexceptblock):
356 #XXXXX don't look: insert blocks that do exception matching
357 #for the cases where direct matching did not work
358 blocks = []
359 for i, link in enumerate(afterblock.exits[1:]):
360 etype = copiedexceptblock.inputargs[0].copy()
361 evalue = copiedexceptblock.inputargs[1].copy()
362 passon_vars = self.passon_vars(i)
363 block = Block([etype, evalue] + passon_vars)
364 cexitcase = Constant(link.llexitcase)
365 cexitcase.concretetype = typeOf(cexitcase.value)
366 res = self.translator.rtyper.exceptiondata.generate_exception_match(
367 block.operations, etype, cexitcase)
368 block.exitswitch = res
369 linkargs = self.find_args_in_exceptional_case(link, link.target,
370 etype, evalue, afterblock,
371 passon_vars)
372 l = Link(linkargs, link.target)
373 l.prevblock = block
374 l.exitcase = True
375 l.llexitcase = True
376 block.closeblock(l)
377 if i > 0:
378 l = Link(blocks[-1].inputargs, block)
379 l.exitcase = False
380 l.llexitcase = False
381 blocks[-1].recloseblock(l, *blocks[-1].exits)
382 blocks.append(block)
383
384 blocks[-1].recloseblock(*blocks[-1].exits[:1])
385 blocks[-1].operations = []
386 blocks[-1].exitswitch = None
387 blocks[-1].exits[0].exitcase = None
388 del blocks[-1].exits[0].llexitcase
389 linkargs = copiedexceptblock.inputargs
390 copiedexceptblock.recloseblock(Link(linkargs, blocks[0]))
391
392 def do_inline(self, block, index_operation):
393 splitlink = split_block(block, index_operation)
394 afterblock = splitlink.target
395 # these variables have to be passed along all the links in the inlined
396 # graph because the original function needs them in the blocks after
397 # the inlined function
398 # for every inserted block we need a new copy of these variables,
399 # this copy is created with the method passon_vars
400 self.original_passon_vars = [arg for arg in block.exits[0].args
401 if isinstance(arg, Variable)]
402 assert afterblock.operations[0].opname == self.op.opname
403 self.op = afterblock.operations.pop(0)
404 #vars that need to be passed through the blocks of the inlined function
405 linktoinlined = splitlink
406 copiedstartblock = self.copy_block(self.graph_to_inline.startblock)
407 #find args passed to startblock of inlined function
408 passon_args = []
409 for arg in self.op.args[1:]:
410 if isinstance(arg, Constant):
411 passon_args.append(arg)
412 else:
413 index = afterblock.inputargs.index(arg)
414 passon_args.append(linktoinlined.args[index])
415 passon_args += self.original_passon_vars
416
417 #rewire blocks
418 linktoinlined.target = copiedstartblock
419 linktoinlined.args = passon_args
420 afterblock.inputargs = [self.op.result] + afterblock.inputargs
421 if self.graph_to_inline.returnblock in self.entrymap:
422 self.rewire_returnblock(afterblock)
423 if self.graph_to_inline.exceptblock in self.entrymap:
424 self.rewire_exceptblock(afterblock)
425 if self.exception_guarded:
426 assert afterblock.exits[0].exitcase is None
427 afterblock.recloseblock(afterblock.exits[0])
428 afterblock.exitswitch = None
429 self.search_for_calls(afterblock)
430 self.search_for_calls(block)
431
432 def cleanup(self):
433 """ cleaning up -- makes sense to be done after inlining, because the
434 inliner inserted quite some empty blocks and blocks that can be
435 joined. """
436 cleanup_graph(self.graph)
437
438
439 class Inliner(BaseInliner):
440 def __init__(self, translator, graph, inline_func, lltype_to_classdef,
441 inline_guarded_calls=False,
442 inline_guarded_calls_no_matter_what=False,
443 raise_analyzer=None,
444 call_count_pred=None,
445 cleanup=True):
446 BaseInliner.__init__(self, translator, graph, lltype_to_classdef,
447 inline_guarded_calls,
448 inline_guarded_calls_no_matter_what,
449 raise_analyzer,
450 call_count_pred,
451 cleanup)
452 self.inline_func = inline_func
453 # to simplify exception matching
454 join_blocks(graph)
455 # find callsites *after* joining blocks...
456 callsites = find_callsites(graph, inline_func)
457 self.block_to_index = {}
458 for g, block, i in callsites:
459 self.block_to_index.setdefault(block, {})[i] = g
460
461 class OneShotInliner(BaseInliner):
462 def search_for_calls(self, block):
463 pass
464
465
466 # ____________________________________________________________
467 #
468 # Automatic inlining
469
470 OP_WEIGHTS = {'same_as': 0,
471 'cast_pointer': 0,
472 'malloc': 2,
473 'instrument_count': 0,
474 'debug_assert': -1,
475 'jit_force_virtualizable': 0,
476 }
477
478 def block_weight(block, weights=OP_WEIGHTS):
479 total = 0
480 for op in block.operations:
481 if op.opname == "direct_call":
482 total += 1.5 + len(op.args) / 2
483 elif op.opname == "indirect_call":
484 total += 2 + len(op.args) / 2
485 total += weights.get(op.opname, 1)
486 if block.exitswitch is not None:
487 total += 1
488 return max(0, total)
489
490
491 def measure_median_execution_cost(graph):
492 blocks = []
493 blockmap = {}
494 for block in graph.iterblocks():
495 blockmap[block] = len(blocks)
496 blocks.append(block)
497 loops = find_loop_blocks(graph)
498 M = sparsemat.SparseMatrix(len(blocks))
499 vector = []
500 for i, block in enumerate(blocks):
501 vector.append(block_weight(block))
502 M[i, i] = 1
503 if block.exits:
504 if block not in loops:
505 current_loop_start = None
506 else:
507 current_loop_start = loops[block]
508 loop_exits = []
509 for link in block.exits:
510 if (link.target in loops and
511 loops[link.target] is current_loop_start):
512 loop_exits.append(link)
513 if len(loop_exits) and len(loop_exits) < len(block.exits):
514 f = 0.3 / (len(block.exits) - len(loop_exits))
515 b = 0.7 / len(loop_exits)
516 else:
517 b = f = 1.0 / len(block.exits)
518 for link in block.exits:
519 if (link.target in loops and
520 loops[link.target] is current_loop_start):
521 M[i, blockmap[link.target]] -= b
522 else:
523 M[i, blockmap[link.target]] -= f
524 try:
525 Solution = M.solve(vector)
526 except ValueError:
527 return sys.maxint
528 else:
529 res = Solution[blockmap[graph.startblock]]
530 return max(res, 0.0) # may be NaN
531
532 def static_instruction_count(graph):
533 count = 0
534 for block in graph.iterblocks():
535 count += block_weight(block)
536 return count
537
538 def inlining_heuristic(graph):
539 # XXX ponderation factors?
540 count = static_instruction_count(graph)
541 if count >= 200:
542 return count, True
543 return (0.9999 * measure_median_execution_cost(graph) +
544 count), True # may be NaN
545
546 def inlinable_static_callers(graphs, store_calls=False, ok_to_call=None):
547 if ok_to_call is None:
548 ok_to_call = set(graphs)
549 result = []
550 def add(parentgraph, block, op, graph):
551 if store_calls:
552 result.append((parentgraph, block, op, graph))
553 else:
554 result.append((parentgraph, graph))
555 #
556 for parentgraph in graphs:
557 for block in parentgraph.iterblocks():
558 for op in block.operations:
559 if op.opname == "direct_call":
560 funcobj = op.args[0].value._obj
561 graph = getattr(funcobj, 'graph', None)
562 if graph is not None and graph in ok_to_call:
563 if getattr(getattr(funcobj, '_callable', None),
564 '_dont_inline_', False):
565 continue
566 add(parentgraph, block, op, graph)
567 return result
568
569 def instrument_inline_candidates(graphs, threshold):
570 cache = {None: False}
571 def candidate(graph):
572 try:
573 return cache[graph]
574 except KeyError:
575 res = static_instruction_count(graph) <= threshold
576 cache[graph] = res
577 return res
578 n = 0
579 for parentgraph in graphs:
580 for block in parentgraph.iterblocks():
581 ops = block.operations
582 i = len(ops) - 1
583 while i >= 0:
584 op = ops[i]
585 i -= 1
586 if op.opname == "direct_call":
587 funcobj = op.args[0].value._obj
588 graph = getattr(funcobj, 'graph', None)
589 if graph is not None:
590 if getattr(getattr(funcobj, '_callable', None),
591 '_dont_inline_', False):
592 continue
593 if candidate(graph):
594 tag = Constant('inline', Void)
595 label = Constant(n, Signed)
596 dummy = Variable()
597 dummy.concretetype = Void
598 count = SpaceOperation('instrument_count',
599 [tag, label], dummy)
600 ops.insert(i + 1, count)
601 n += 1
602 log.inlining("%d call sites instrumented" % n)
603
604 def always_inline(graph):
605 return (hasattr(graph, 'func') and
606 getattr(graph.func, '_always_inline_', None))
607
608 def auto_inlining(translator, threshold=None,
609 callgraph=None,
610 call_count_pred=None,
611 heuristic=inlining_heuristic):
612
613 assert threshold is not None and threshold != 1
614 to_cleanup = {}
615 from heapq import heappush, heappop, heapreplace, heapify
616 callers = {} # {graph: {graphs-that-call-it}}
617 callees = {} # {graph: {graphs-that-it-calls}}
618 if callgraph is None:
619 callgraph = inlinable_static_callers(translator.graphs)
620 for graph1, graph2 in callgraph:
621 callers.setdefault(graph2, {})[graph1] = True
622 callees.setdefault(graph1, {})[graph2] = True
623 # the -len(callers) change is OK
624 heap = [(0.0, -len(callers[graph]), graph) for graph in callers]
625 valid_weight = {}
626 try_again = {}
627 lltype_to_classdef = translator.rtyper.lltype_to_classdef_mapping()
628 raise_analyzer = RaiseAnalyzer(translator)
629 count = 0
630 while heap:
631 weight, _, graph = heap[0]
632 if not valid_weight.get(graph):
633 if always_inline(graph):
634 weight, fixed = 0.0, True
635 else:
636 weight, fixed = heuristic(graph)
637 # Don't let 'weight' be NaN past this point. If we do,
638 # then heapify() might (sometimes, rarely) not do its job
639 # correctly. I suspect it's because the algorithm gets
640 # confused by the fact that both 'a < b' and 'b < a' are
641 # false. A concrete example: [39.0, 0.0, 33.0, nan, nan]
642 # heapifies to [33.0, nan, 39.0, nan, 0.0], but 33.0 is
643 # not the smallest item.
644 if not (weight < 1e9):
645 weight = 1e9
646 #print ' + cost %7.2f %50s' % (weight, graph.name)
647 heapreplace(heap, (weight, -len(callers[graph]), graph))
648 valid_weight[graph] = True
649 if not fixed:
650 try_again[graph] = 'initial'
651 continue
652
653 if weight >= threshold:
654 # finished... unless some graphs not in valid_weight would now
655 # have a weight below the threshold. Re-insert such graphs
656 # at the start of the heap
657 finished = True
658 for i in range(len(heap)):
659 graph = heap[i][2]
660 if not valid_weight.get(graph):
661 heap[i] = (0.0, heap[i][1], graph)
662 finished = False
663 if finished:
664 break
665 else:
666 heapify(heap)
667 continue
668
669 heappop(heap)
670 if callers[graph]:
671 if translator.config.translation.verbose:
672 log.inlining('%7.2f %50s' % (weight, graph.name))
673 else:
674 log.dot()
675 for parentgraph in callers[graph]:
676 if parentgraph == graph:
677 continue
678 subcount = 0
679 try:
680 subcount = inline_function(translator, graph, parentgraph,
681 lltype_to_classdef, raise_analyzer,
682 call_count_pred, cleanup=False)
683 to_cleanup[parentgraph] = True
684 res = bool(subcount)
685 except CannotInline as e:
686 try_again[graph] = str(e)
687 res = CannotInline
688 if res is True:
689 count += subcount
690 # the parentgraph should now contain all calls that were
691 # done by 'graph'
692 for graph2 in callees.get(graph, {}):
693 callees[parentgraph][graph2] = True
694 callers[graph2][parentgraph] = True
695 if parentgraph in try_again:
696 # the parentgraph was previously uninlinable, but it has
697 # been modified. Maybe now we can inline it into further
698 # parents?
699 del try_again[parentgraph]
700 heappush(heap, (0.0, -len(callers[parentgraph]), parentgraph))
701 valid_weight[parentgraph] = False
702
703 invalid = [(graph, msg) for graph, msg in try_again.items()
704 if always_inline(graph) is True]
705 if invalid:
706 message = '\n'.join([
707 "%s has _always_inline_=True but inlining failed:\n\t%s" %
708 (graph, msg) for (graph, msg) in invalid])
709 raise CannotInline(message)
710
711 for graph in to_cleanup:
712 cleanup_graph(graph)
713 return count
714
715 def auto_inline_graphs(translator, graphs, threshold, call_count_pred=None,
716 heuristic=inlining_heuristic,
717 inline_graph_from_anywhere=False):
718 if inline_graph_from_anywhere:
719 # it's ok to inline calls to any graph, with the exception of
720 # graphs that would be already exception-transformed
721 ok_to_call = set([graph for graph in translator.graphs
722 if not hasattr(graph, 'exceptiontransformed')])
723 else:
724 ok_to_call = None
725 callgraph = inlinable_static_callers(graphs, ok_to_call=ok_to_call)
726 count = auto_inlining(translator, threshold, callgraph=callgraph,
727 heuristic=heuristic,
728 call_count_pred=call_count_pred)
729 log.inlining('inlined %d callsites.' % (count,))
730 for graph in graphs:
731 removenoops.remove_duplicate_casts(graph, translator)