/* Part of SWI-Prolog Author: Jan Wielemaker E-mail: jan@swi-prolog.org WWW: http://www.swi-prolog.org Copyright (c) 2026, SWI-Prolog Solutions b.v. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(prolog_auto_table, [ auto_table/0, auto_table/1, % +Options auto_table_analysis/3, % +Spec, -Analysis, +Options auto_table_learn/2, % :Goals, +Options auto_table_learn/3 % :Goals, -Result, +Options ]). :- use_module(library(prolog_wrap), [wrap_predicate/4]). :- if(exists_source(library(time))). :- use_module(library(time), [call_with_time_limit/2]). :- endif. :- use_module(library(prolog_call_cycles), [call_graph/2, call_graph_sccs/3, left_recursion/3]). :- use_module(library(apply), [maplist/2, maplist/3, foldl/4, include/3, exclude/3, partition/4]). :- use_module(library(assoc), [list_to_assoc/2, get_assoc/3]). :- use_module(library(lists), [member/2, append/3, append/2, sum_list/2, last/2, subtract/3, reverse/2, min_member/2, selectchk/3]). :- use_module(library(prolog_code), [comma_list/2]). :- use_module(library(wfs), [call_delays/2]). :- use_module(library(pairs), [pairs_keys_values/3, pairs_keys/2, pairs_values/2, group_pairs_by_key/2]). :- use_module(library(aggregate), [aggregate_all/3]). :- autoload(library(prolog_xref), [xref_source/2, xref_mode/3, xref_current_source/1, xref_clean/1]). :- use_module(library(dcg/high_order), [sequence//2, sequence//3]). :- use_module(library(option), [option/2, option/3]). :- use_module(library(ugraphs), [vertices_edges_to_ugraph/3]). :- use_module(library(error), [must_be/2, permission_error/3]). /** Automatic tabling This library provides the XSB compatible directive auto_table/0, which tables enough predicates of the file in which it appears to make sure that every cycle in the static call graph of the file contains a tabled predicate. It uses library(prolog_call_cycles) to find the recursion in the static call graph of the file. In addition, auto_table_learn/3 learns which predicates to table and in which mode by running goals. For each strongly connected component of the call graph, the analysis selects a set of predicates to table such that removing these predicates breaks all cycles (a _feedback vertex set_). Among the possible sets it chooses the one with the lowest estimated number of tabled variants. This estimate is based on how the predicates are called inside the component: calls with fresh variables or ground arguments create few variants, while calls with arguments that are built from data, notably accumulators, create many. Left recursion (recursion where no call to a non-built-in predicate precedes the recursive call) is always reported, as it is guaranteed to loop under Prolog's SLD resolution. Like XSB, a predicate is also tabled if it is called through tnot/1. A tabled goal that waits for an incomplete table suspends by capturing its continuation using shift/1. It cannot do so through findall/3 and the other predicates that collect all solutions, aggregate_all/3 or a predicate defined in C (see the `barrier` key of call_graph_sccs/2). Recursion through such a predicate is therefore not tabled: if its call passes a proper subterm or a computed value of the head it is assumed to terminate, otherwise nothing in the strongly connected component is tabled and auto_table/0 prints a warning. The analysis is static. Calls through meta-calls that cannot be resolved at compile time are not seen. Tabling guarantees termination only if the number of call variants and answers is finite. */ :- dynamic auto_tabled/2. % File, PI %! auto_table is det. %! auto_table(+Options) is det. % % Directive that tables predicates of the current file such that % each loop in the static call graph of the file contains at least % one tabled predicate. The analysis is performed after the file % has been loaded completely. Options: % % - cycles(+Which) % One of `all` (default) or `left`. If `left`, only left % recursive cycles are broken. % - structural(+Bool) % If `true` (default `false`), assume that directly recursive % calls on a proper subterm of an argument of the head terminate. % This is true if the argument is sufficiently instantiated when % the predicate is called. Without this option, this is only % assumed if a mode declaration says the argument is input % (`+` or `++`). Mode declarations are given using mode/1 or % using PlDoc structured comments, e.g. `%! len(+List, -Len)`. % - verbose(+Bool) % If `true` (default), print a message for each predicate that % is tabled. % % When the file is reloaded, the predicates tabled by the previous % analysis are untabled before the new analysis is performed. % % @compat XSB. XSB only provides auto_table/0. As with XSB, `:- % mode` declarations avoid tabling directly recursive predicates % whose recursion decreases an input argument. The XSB dialect maps % XSB `:- mode` declarations to mode/1. auto_table :- auto_table([]). auto_table(Options) :- must_be(list, Options), ( prolog_load_context(source, File), prolog_load_context(module, Module) -> untable_previous(File), initialization(auto_table_file(File, Module, Options)) ; permission_error(execute, directive, auto_table/0) ). untable_previous(File) :- forall(retract(auto_tabled(File, PI)), untable(PI)). %! auto_table_file(+File, +Module, +Options) is det. % % Analyse File and table the predicates selected by the analysis. auto_table_file(File, _Module, Options) :- catch(auto_table_analysis(file(File), Analysis, Options), E, ( print_message(warning, E), fail )), !, option(verbose(Verbose), Options, true), ( Verbose == true -> Level = informational ; Level = silent ), print_message(Level, auto_table(analysis(Analysis))), forall(member(PI-_, Analysis.selected), ( table(PI), assertz(auto_tabled(File, PI)) )), forall(( member(SCC, Analysis.sccs), member(Edge, SCC.cuts) ), print_message(warning, auto_table(illegal_cut(Edge)))), forall(( member(SCC, Analysis.sccs), SCC.barriers \== [] ), print_message(warning, auto_table(barrier(SCC)))). auto_table_file(_, _, _). /******************************* * ANALYSIS * *******************************/ :- meta_predicate auto_table_analysis(:, -, +). %! auto_table_analysis(:Spec, -Analysis:dict, +Options) is det. % % Determine the predicates to table for Spec, which is one of % file(File), module(Module) or goal(Goal). The latter analyses the % predicates reachable from Goal. The options files(FileOrFiles) % and module(ModuleOrModules) restrict these to the predicates % defined in the given files or modules (see call_graph/2). % Analysis is a dict with the keys below. Options are those of % auto_table/1 plus the options of call_graph/2. % % - selected % List of `PI-Reason` for each predicate that must be tabled, % where `Reason` is one of `tnot` or `cycle`. % - sccs % List of dicts describing each strongly connected component, % holding the keys `members`, `tabled` (predicates in the SCC % that were already tabled), `selected` (predicates selected for % tabling), `cost` (estimated cost of the selection), % `left_recursion` (list of left recursion dicts, see % left_recursion/3), `terminating` (directly recursive % predicates that are not tabled because their recursion is % known to terminate), `barriers` (edges through a barrier for % suspending a tabled goal that are not known to terminate; if % this is not empty, nothing is selected) and `cuts` (if the SCC % contains tabled % predicates, the edges of the SCC whose call can be pruned by a % cut, which raises an error if the call is to an incomplete % table; see the `pruned` key of call_graph_sccs/2). auto_table_analysis(M:Spec, Analysis, Options) :- graph_options(Spec, M, GraphOptions, Options), call_graph(Graph, [external(true)|GraphOptions]), call_graph_sccs(Graph, SCCs, GraphOptions), tnot_called(Graph, TNot), option(structural(Structural), Options, false), mode_db(Structural, SCCs, ModeDB), maplist(analyse_scc(Options, TNot, ModeDB), SCCs, SCCResults), findall(PI-tnot, member(PI, TNot), TNotTable), findall(PI-cycle, ( member(R, SCCResults), member(PI, R.selected) ), CycleTable), append(TNotTable, CycleTable, Table), Analysis = auto_table{selected:Table, sccs:SCCResults}. graph_options(file(File), _, [files(File)|Options], Options) :- !. graph_options(module(M), _, [module(M)|Options], Options) :- !. graph_options(goal(G), M, [goal(M:G)|Options], Options) :- !. graph_options(File, _, [files(File)|Options], Options). %! tnot_called(+Graph, -PIs) is det. % % PIs is the set of predicates in scope that are called through % tnot/1 and are not yet tabled. tnot_called(Graph, PIs) :- list_to_assoc_set(Graph.vertices, VSet), findall(PI, ( member(E, Graph.external), E.to = _:tnot/1, E.goal = M:tnot(G), callable(G), strip_module(M:G, GM, Plain), resolve_pi(GM:Plain, PI), get_assoc(PI, VSet, _), \+ tabled(PI) ), PIs0), sort(PIs0, PIs). resolve_pi(M:Goal, IM:Name/Arity) :- ( predicate_property(M:Goal, imported_from(IM)) -> true ; IM = M ), functor(Goal, Name, Arity). tabled(M:Name/Arity) :- functor(Head, Name, Arity), predicate_property(M:Head, tabled). list_to_assoc_set(List, Assoc) :- findall(K-true, member(K, List), Pairs), list_to_assoc(Pairs, Assoc). %! analyse_scc(+Options, +TNot, +ModeDB, +SCC, -Result) is det. analyse_scc(Options, TNot, ModeDB, SCC, Result) :- option(cycles(Cycles), Options, all), must_be(oneof([all,left]), Cycles), partition(tabled, SCC.members, Tabled, Untabled0), subtract(Untabled0, TNot, Untabled), findall(L, left_recursion([SCC], L, []), LeftRecs), partition(barrier_edge, SCC.edges, BarrierEdges, PlainEdges), partition(progress_edge, BarrierEdges, TermBarriers, Barriers), include(relevant_edge(Cycles, Untabled), PlainEdges, Edges0), option(structural(Structural), Options, false), partition(terminating_edge(Structural, ModeDB), Edges0, TermEdges, Edges1), ( Barriers == [] -> Edges = Edges1 ; Edges = [] % tabling would raise an error ), append(TermEdges, TermBarriers, TermAll), findall(PI, (member(E, TermAll), PI = E.from), Term0), sort(Term0, Terminating), node_costs(Untabled, Edges, Costs), feedback_vertex_set(Untabled, Edges, Costs, FVS, Cost), illegal_cuts(SCC, Tabled, TNot, FVS, Cuts), Result = scc{members:SCC.members, tabled:Tabled, selected:FVS, cost:Cost, left_recursion:LeftRecs, terminating:Terminating, barriers:Barriers, cuts:Cuts}. %! barrier_edge(+Edge) is semidet. % % True if the call of Edge is made through a barrier for suspending a % tabled goal, e.g., findall/3. A cycle through it cannot be broken % by tabling: a tabled goal in it that waits for an incomplete table % raises an error. barrier_edge(Edge) :- Edge.barrier \== none. %! progress_edge(+Edge) is semidet. % % True if the call of Edge passes a proper subterm or a computed % value of the head, so the recursion through it is assumed to % terminate. progress_edge(Edge) :- ( Edge.decreasing == true -> true ; Args = Edge.args, is_list(Args), ( memberchk(subterm, Args) -> true ; memberchk(computed, Args) ) ). %! illegal_cuts(+SCC, +Tabled, +TNot, +Selected, -Cuts) is det. % % If the SCC contains tabled predicates, Cuts is the list of edges % in the SCC whose call can be pruned by a cut. Each tabled % predicate is reachable from every call in the SCC, so such a cut % may prune a call to an incomplete table, which raises a permission % error. illegal_cuts(SCC, Tabled, TNot, Selected, Cuts) :- ( ( Tabled \== [] ; Selected \== [] ; member(PI, TNot), memberchk(PI, SCC.members) ) -> include(pruned_edge, SCC.edges, Cuts) ; Cuts = [] ). pruned_edge(Edge) :- Edge.pruned == true. relevant_edge(Cycles, Untabled, Edge) :- memberchk(Edge.from, Untabled), memberchk(Edge.to, Untabled), ( Cycles == left -> Edge.left == true ; true ). %! terminating_edge(+Structural, +ModeDB, +Edge) is semidet. % % True if Edge is a directly recursive call that decreases an % argument that is declared as input (`+` or `++`) by a mode % declaration (see mode_db/3). If Structural is `true`, any % directly recursive call that decreases an argument is considered % terminating. terminating_edge(Structural, ModeDB, Edge) :- Edge.from == Edge.to, Edge.decreasing == true, ( Structural == true -> true ; mode_terminating(ModeDB, Edge) ). %! mode_terminating(+ModeDB, +Edge) is semidet. % % True if the predicate has mode declarations and, for each of % them, Edge passes a proper subterm of the head at an input % argument. mode_terminating(ModeDB, Edge) :- get_assoc(Edge.to, ModeDB, Modes), Edge.args = Args, is_list(Args), forall(member(Mode, Modes), nth_decreasing_input(Args, Mode)). nth_decreasing_input(Args, Modes) :- Modes =.. [_|ModeList], nth_input_subterm(Args, ModeList). nth_input_subterm([subterm|_], [Ind|_]) :- input_mode(Ind), !. nth_input_subterm([_|As], [_|Ms]) :- nth_input_subterm(As, Ms). input_mode(+). input_mode(++). %! mode_db(+Structural, +SCCs, -ModeDB) is det. % % ModeDB is an assoc mapping the directly recursive predicates of % SCCs that recurse on a proper subterm to their mode declarations, % a non-empty list of terms Name(Ind, ...), where `Ind` is a mode % indicator such as `+`, `-` or `?`. Mode declarations are taken % from the first of these sources that provides them: % % 1. A mode/1 declaration, as reported by the predicate property % mode(Head). This also covers XSB `:- mode` declarations % (see library(dialect/xsb)). % 2. PlDoc structured comments. If PlDoc was active while % loading, these are available as '$mode'/2 facts. Otherwise % the source file is cross-referenced using xref_source/2. mode_db(true, _, ModeDB) :- !, list_to_assoc([], ModeDB). mode_db(_, SCCs, ModeDB) :- findall(PI, ( member(SCC, SCCs), member(E, SCC.edges), E.from == E.to, E.decreasing == true, PI = E.to ), PIs0), sort(PIs0, PIs), foldl(declared_modes, PIs, Nested, [], Missing), append(Nested, Pairs), xref_modes(Missing, XrefPairs), append(Pairs, XrefPairs, AllPairs), list_to_assoc(AllPairs, ModeDB). declared_modes(PI, Pairs, Missing0, Missing) :- PI = M:Name/Arity, functor(Head, Name, Arity), ( predicate_property(M:Head, mode(Mode)) -> Pairs = [PI-[Mode]], Missing = Missing0 ; findall(Mode, pldoc_mode(M:Head, Mode), Modes), Modes \== [] -> Pairs = [PI-Modes], Missing = Missing0 ; Pairs = [], Missing = [PI|Missing0] ). pldoc_mode(M:Head, Mode) :- current_predicate(M:'$mode'/2), \+ predicate_property(M:'$mode'(_,_), imported_from(_)), M:'$mode'(Mode0, _), strip_module(Mode0, _, Plain), Plain \= //(_), functor(Plain, Name, Arity), functor(Head, Name, Arity), pldoc_mode_indicators(Plain, Mode). pldoc_mode_indicators(PlDocMode, Mode) :- PlDocMode =.. [Name|Args0], maplist(mode_indicator, Args0, Args), Mode =.. [Name|Args]. mode_indicator(Arg, Ind) :- compound(Arg), compound_name_arity(Arg, Ind, 1), !. mode_indicator(_, ?). %! xref_modes(+PIs, -Pairs) is det. % % Find PlDoc mode declarations for PIs by cross-referencing the % files that define them. Files that were not cross-referenced % before are cleaned afterwards. xref_modes([], []) :- !. xref_modes(PIs, Pairs) :- findall(File-PI, ( member(PI, PIs), PI = M:Name/Arity, functor(Head, Name, Arity), predicate_property(M:Head, file(File)) ), FilePIs0), keysort(FilePIs0, FilePIs), group_pairs_by_key(FilePIs, Grouped), foldl(file_modes, Grouped, Pairs, []). file_modes(File-PIs, Pairs, Tail) :- ( xref_current_source(File) -> file_modes_(File, PIs, Pairs, Tail) ; setup_call_cleanup( catch(xref_source(File, [comments(store), silent(true)]), _, fail), file_modes_(File, PIs, Pairs, Tail), xref_clean(File)) -> true ; Pairs = Tail ). file_modes_(File, PIs, Pairs, Tail) :- foldl(xref_pi_modes(File), PIs, Pairs, Tail). xref_pi_modes(File, PI, Pairs, Tail) :- PI = _:Name/Arity, findall(Mode, ( xref_mode(File, Mode0, _), strip_module(Mode0, _, Plain), functor(Plain, Name, Arity), pldoc_mode_indicators(Plain, Mode) ), Modes), ( Modes == [] -> Pairs = Tail ; Pairs = [PI-Modes|Tail] ). /******************************* * COST * *******************************/ %! node_costs(+Nodes, +Edges, -Costs) is det. % % Costs is an assoc mapping each node to a cost term % c(Variants, NotExported, Arity). `Variants` estimates the % number of tabled variants if this node is tabled, based on the % argument abstraction of the calls to the node. The other two % fields implement XSB's tie breaking: prefer exported predicates % and predicates with a low arity. node_costs(Nodes, Edges, Costs) :- maplist(node_cost(Edges), Nodes, Pairs), list_to_assoc(Pairs, Costs). node_cost(Edges, PI, PI-c(Variants, NotExported, Arity)) :- findall(C, ( member(E, Edges), E.to == PI, call_cost(E.args, C) ), Cs), sum_list(Cs, Variants0), Variants is Variants0+1, PI = M:Name/Arity, functor(Head, Name, Arity), ( predicate_property(M:Head, exported) -> NotExported = 0 ; NotExported = 1 ). call_cost(unknown, 3) :- !. call_cost(Args, Cost) :- foldl(arg_cost, Args, 0, Cost). arg_cost(Class, C0, C) :- arg_class_cost(Class, AC), C is C0+AC. arg_class_cost(fresh, 0). arg_class_cost(ground, 0). arg_class_cost(pass, 1). arg_class_cost(subterm, 2). arg_class_cost(bound_earlier, 3). arg_class_cost(computed, 3). arg_class_cost(distinct, 3). arg_class_cost(constructed, 10). add_cost(c(V1,E1,A1), c(V2,E2,A2), c(V,E,A)) :- V is V1+V2, E is E1+E2, A is A1+A2. /******************************* * FEEDBACK VERTEX SET * *******************************/ %! feedback_vertex_set(+Nodes, +Edges, +Costs, -FVS, -Cost) is det. % % Find a set of nodes FVS with minimal total Cost such that the % graph Nodes/Edges without FVS has no cycles. We use branch and % bound: find a shortest cycle in the remaining graph; one of its % nodes must be in the FVS. If the search exceeds its budget we % use the best solution found so far, starting with a greedy one. feedback_vertex_set(Nodes, Edges, Costs, FVS, Cost) :- findall(F-T, (member(E, Edges), F = E.from, T = E.to), Pairs0), sort(Pairs0, Pairs), vertices_edges_to_ugraph(Nodes, Pairs, Graph), greedy_fvs(Graph, Costs, Greedy), set_cost(Greedy, Costs, GreedyCost), State = best(Greedy, GreedyCost, 10000), catch(bb_fvs(Graph, Costs, [], c(0,0,0), State), fvs_budget_exceeded, true), arg(1, State, FVS0), arg(2, State, Cost), sort(FVS0, FVS). set_cost(Set, Costs, Cost) :- foldl(node_set_cost(Costs), Set, c(0,0,0), Cost). node_set_cost(Costs, Node, C0, C) :- get_assoc(Node, Costs, NC), add_cost(C0, NC, C). bb_fvs(Graph, Costs, Set, Cost, State) :- arg(3, State, Budget), ( Budget =< 0 -> throw(fvs_budget_exceeded) ; Budget1 is Budget-1, nb_setarg(3, State, Budget1) ), arg(2, State, Best), ( Cost @>= Best -> true ; find_cycle(Graph, Cycle) -> forall(member(Node, Cycle), ( get_assoc(Node, Costs, NC), add_cost(Cost, NC, Cost1), del_vertex(Graph, Node, Graph1), bb_fvs(Graph1, Costs, [Node|Set], Cost1, State) )) ; nb_setarg(1, State, Set), nb_setarg(2, State, Cost) ). %! greedy_fvs(+Graph, +Costs, -FVS) is det. % % Greedy approximation: repeatedly remove the node of a cycle that % has the best ratio between the number of edges it is involved in % and its cost, then remove redundant nodes. greedy_fvs(Graph, Costs, FVS) :- greedy_fvs_(Graph, Costs, [], FVS0), prune_fvs(FVS0, FVS0, Graph, FVS). greedy_fvs_(Graph0, Costs, FVS0, FVS) :- reduce_graph(Graph0, Graph), ( Graph == [] -> FVS = FVS0 ; member(V-Ns, Graph), memberchk(V, Ns) -> del_vertex(Graph, V, Graph1), greedy_fvs_(Graph1, Costs, [V|FVS0], FVS) ; findall(Score-V, ( member(V-Out, Graph), length(Out, NOut), aggregate_all(count, (member(_-Ns, Graph), memberchk(V, Ns)), NIn), get_assoc(V, Costs, c(Vars,_,_)), Score is -(NIn*NOut)/(Vars+1) ), Scored), keysort(Scored, [_-V|_]), del_vertex(Graph, V, Graph1), greedy_fvs_(Graph1, Costs, [V|FVS0], FVS) ). prune_fvs([], FVS, _, FVS). prune_fvs([V|Vs], FVS0, Graph, FVS) :- subtract(FVS0, [V], FVS1), ( foldl(del_vertex_, FVS1, Graph, G1), \+ find_cycle(G1, _) -> prune_fvs(Vs, FVS1, Graph, FVS) ; prune_fvs(Vs, FVS0, Graph, FVS) ). del_vertex_(V, G0, G) :- del_vertex(G0, V, G). %! reduce_graph(+Graph0, -Graph) is det. % % Remove vertices without incoming or outgoing edges, as they % cannot be part of a cycle. reduce_graph(Graph0, Graph) :- findall(V, ( member(V-Out, Graph0), ( Out == [] ; \+ (member(_-Ns, Graph0), memberchk(V, Ns)) ) ), Dead), ( Dead == [] -> Graph = Graph0 ; foldl(del_vertex_, Dead, Graph0, Graph1), reduce_graph(Graph1, Graph) ). del_vertex(Graph0, V, Graph) :- foldl(del_vertex_edge(V), Graph0, [], RevGraph), reverse(RevGraph, Graph). del_vertex_edge(V, W-Ns0, G0, G) :- ( W == V -> G = G0 ; subtract(Ns0, [V], Ns), G = [W-Ns|G0] ). %! find_cycle(+Graph, -Cycle) is semidet. % % Find a shortest cycle in Graph. Cycle is a list of vertices. find_cycle(Graph0, Cycle) :- reduce_graph(Graph0, Graph), Graph \== [], ( member(V-Ns, Graph), memberchk(V, Ns) -> Cycle = [V] ; findall(Len-C, ( member(V-_, Graph), bfs_cycle(Graph, V, C), length(C, Len) ), Cycles), keysort(Cycles, [_-Cycle|_]) ). bfs_cycle(Graph, Start, Cycle) :- bfs([Start-[Start]], Graph, Start, [Start], Path), reverse(Path, Cycle). bfs([V-Path|Queue], Graph, Start, Visited, Cycle) :- memberchk(V-Ns, Graph), ( memberchk(Start, Ns) -> Cycle = Path ; foldl(bfs_next(Path), Ns, Queue-Visited, Queue1-Visited1), bfs(Queue1, Graph, Start, Visited1, Cycle) ). bfs_next(Path, W, Q0-V0, Q-V) :- ( memberchk(W, V0) -> Q = Q0, V = V0 ; V = [W|V0], append(Q0, [W-[W|Path]], Q) ). /******************************* * LEARNING * *******************************/ %! auto_table_learn(:Goals, +Options) is det. %! auto_table_learn(:Goals, -Result:dict, +Options) is det. % % Run Goals (a goal or list of goals) to learn which predicates must % be tabled. The first phase runs Goals without (additional) tabling % while observing the recursion: a call that is a variant of one of % its ancestors is a loop. Such a call is recorded and fails, so % the run continues. This also finds recursion that is not visible % to the static analysis, such as recursion through meta-calls or % recursion in the data interpreted by a meta-interpreter. The % observed loops are combined into a graph for which we compute a % feedback vertex set using the observed number of call variants as % cost. % % auto_table_learn/2 prints the result. Options: % % - modules(+Modules) % Observe the predicates of the given modules. Default are all % modules of class `user`. % - predicates(+PIs) % Observe the given predicates. % - time_limit(+Seconds) % Time limit for each run of a goal. Default 60. This option % is ignored if library(time) is not available, which is the % case in single threaded versions and WASM. % - inference_limit(+Count) % Inference limit for each run of a goal. Default `infinite`. % - max_depth(+Depth) % Treat recursion deeper than Depth as a loop. Default 10,000. % - ancestor_depth(+Depth) % Only check the nearest Depth ancestors for variants. Default % 1,000. % - hot(+Count) % Report statistics for the Count predicates with the most call % variants. Default 10. % - search(+Bool) % If `true` (default), run the second phase (see below). % - objective(+Objective) % What to optimise in the second phase. One of `time` (CPU % time), `memory` (table space) or `balanced` (default, the sum % of both relative to the initial configuration). % - max_runs(+Count) % Maximum number of configurations to try. Default 50. % - modes(+Modes) % Tabling modes to try. Default `[variant,subsumptive]`. % - apply(+Bool) % If `true`, leave the program tabled according to the best % configuration. Default `false`, restoring the original % tabling. % - output(+File) % Write the table directives for the best configuration to File. % % The second phase searches for the best configuration, a mapping % from predicates to `variant`, `subsumptive` or not tabled. It % starts with the predicates that were already tabled plus the % selected predicates of the first phase. Each configuration is % evaluated by running Goals with fresh tables, measuring CPU time % and table space. A configuration is rejected if a goal does not % complete or produces different answers than the initial % configuration. If the initial configuration fails, e.g., because % a cut prunes a call to an incomplete table, the search starts from % the original tabling. If that fails too, the best configuration is % the original tabling. The search moves are: untable all tabled % predicates that are not involved in any observed loop (if this % fails, try halves), untable a single predicate, switch between % variant and subsumptive tabling, and table a predicate that is % often called with the same arguments. % % Result is a dict with the keys below. % % - selected % List of predicates that must be tabled to break all observed % loops. % - loops % List of observed loops. Each loop is a list of predicate % indicators. % - barrier_loops % List of `Loop-Barrier` for the observed loops that pass a % barrier for suspending a tabled goal, such as findall/3 or a % predicate defined in C (see shift/1). Tabling cannot break % these loops, so their predicates are not selected. % - predicates % List of dicts with statistics for each predicate that is % involved in a loop. Keys are `pi`, `calls`, `variants`, % `args` (number of distinct values per argument), `tabled` % (whether the predicate was already tabled) and `loops` (number % of loop detections). % - goals % List of `Goal-Status`, where `Status` is the result of running % the goal: `true`, `false`, `time_limit_exceeded`, % `inference_limit_exceeded` or an error. % - hot % Statistics for the predicates with the most call variants. % - config % The best configuration found by the second phase, a list of % `PI-Mode`, where `Mode` is `variant` or `subsumptive`. % - runs % List of dicts describing each configuration that was tried. % - directives % List of table directives for the best configuration. :- meta_predicate auto_table_learn(:, +), auto_table_learn(:, -, +). auto_table_learn(Goals, Options) :- auto_table_learn(Goals, Result, Options), print_message(informational, auto_table(learned(Result))). auto_table_learn(M:Goals0, Result, Options) :- goal_list(Goals0, M, Goals), candidate_predicates(Options, Candidates), original_tabling(Candidates, Original, Fixed), discover(Goals, Candidates, Discovery, Options), learned_selection(Discovery, Selected), Result0 = Discovery.put(selected, Selected), ( option(search(true), Options, true) -> search(Goals, Result0, Original, Fixed, Result, Options) ; Result = Result0 ). goal_list(Var, _, _) :- var(Var), !, instantiation_error(Var). goal_list(List, M, Goals) :- is_list(List), !, maplist(qualify_goal(M), List, Goals). goal_list(Goal, M, [QGoal]) :- qualify_goal(M, Goal, QGoal). qualify_goal(M, Goal, QGoal) :- strip_module(M:Goal, GM, Plain), QGoal = GM:Plain. instantiation_error(Var) :- must_be(callable, Var). %! candidate_predicates(+Options, -PIs) is det. % % Find the predicates we observe while learning. candidate_predicates(Options, PIs) :- option(predicates(PIs0), Options), !, must_be(list, PIs0), include(observable, PIs0, PIs). candidate_predicates(Options, PIs) :- ( option(modules(Modules), Options) -> must_be(list(atom), Modules) ; findall(M, module_property(M, class(user)), Modules) ), findall(M:Name/Arity, ( member(M, Modules), current_predicate(M:Name/Arity), observable(M:Name/Arity) ), PIs0), sort(PIs0, PIs). observable(M:Name/Arity) :- functor(Head, Name, Arity), \+ predicate_property(M:Head, imported_from(_)), \+ predicate_property(M:Head, foreign), predicate_property(M:Head, number_of_rules(N)), N > 0, \+ internal_predicate(Name/Arity). internal_predicate('$tabled'/2). internal_predicate('$table_mode'/3). internal_predicate('$table_update'/4). /******************************* * DISCOVERY * *******************************/ %! discover(+Goals, +Candidates, -Discovery, +Options) is det. % % Run Goals with all Candidates wrapped to observe the recursion. discover(Goals, Candidates, Discovery, Options) :- limits(Options, Limits), option(max_depth(MaxDepth), Options, 10 000), option(ancestor_depth(AncDepth), Options, 1 000), length(Candidates, Count), length(Slots, Count), maplist(new_slot, Candidates, Slots), State =.. [slots|Slots], trie_new(Loops), trie_new(BarrierLoops), setup_call_cleanup( ( nb_setval(auto_table_learn, ctx(State, Loops, BarrierLoops, MaxDepth, AncDepth)), wrap_candidates(Candidates, 1) ), ( maplist(run_goal(Limits), Goals, Statuses), nb_getval(auto_table_learn, ctx(FinalState, _, _, _, _)) ), ( unwrap_candidates(Candidates), nb_delete(auto_table_learn) )), findall(Loop, trie_gen(Loops, Loop), LoopList0), findall(Loop-Barrier, trie_gen(BarrierLoops, Loop-Barrier), BarrierList), pairs_keys(BarrierList, BarrierLoopList), append(LoopList0, BarrierLoopList, AllLoops), sort(AllLoops, LoopList), loop_predicates(LoopList, Candidates, FinalState, Preds), option(hot(NHot), Options, 10), hot_predicates(FinalState, NHot, Hot), pairs_keys_values(GoalStatus, Goals, Statuses), Discovery = learned{loops:LoopList, barrier_loops:BarrierList, predicates:Preds, hot:Hot, goals:GoalStatus}. new_slot(PI, slot(PI, 0, 0, Trie, ArgTries)) :- PI = _:_/Arity, trie_new(Trie), length(ArgTries0, Arity), maplist(trie_new, ArgTries0), ArgTries =.. [args|ArgTries0]. wrap_candidates([], _). wrap_candidates([PI|PIs], I) :- PI = M:Name/Arity, functor(Head, Name, Arity), wrap_predicate(M:Head, auto_table_learn, Wrapped, prolog_auto_table:observe_call(I, Head, Wrapped)), I2 is I+1, wrap_candidates(PIs, I2). unwrap_candidates(PIs) :- forall(member(PI, PIs), ignore(unwrap_predicate(PI, auto_table_learn))). :- public observe_call/3. :- meta_predicate observe_call(+, +, 0). %! observe_call(+Index, +Head, :Wrapped) % % Wrapper body. The ancestor stack is kept in the backtrackable % global variable `auto_table_stack` as a term % `s(Depth, Index, HeadCopy, Parent, Frame)` or `[]`, where Frame is % the frame that runs the ancestor. The learning state is in the % global variable `auto_table_learn`. We must access it using % nb_getval/2 such that we can update it destructively. % % A loop that passes a barrier for suspending a tabled goal, such as % findall/3, cannot be broken by tabling. It is recorded separately % (see shift_barrier/2). observe_call(I, Head, Wrapped) :- nb_getval(auto_table_learn, ctx(State, Loops, BarrierLoops, MaxDepth, AncDepth)), arg(I, State, Slot), count_call(Slot, Head), ( nb_current(auto_table_stack, Stack) -> true ; Stack = [] ), ( Stack = s(Depth, _, _, _, _) -> true ; Depth = 0 ), ( ancestor_variant(Stack, I, Head, AncDepth, Path, AncFrame) -> prolog_current_frame(Frame), ( frame_barrier(Frame, AncFrame, Barrier) -> record_loop(Path, I, State, BarrierLoops, Barrier) ; record_loop(Path, I, State, Loops) ), ( arg(1, Slot, PI), tabled(PI) -> call_observed(Depth, I, Head, Stack, Wrapped) ; fail ) ; Depth >= MaxDepth -> deep_loop(Stack, I, State, Loops), fail ; call_observed(Depth, I, Head, Stack, Wrapped) ). call_observed(Depth, I, Head, Stack, Wrapped) :- Depth1 is Depth+1, copy_term(Head, Copy), prolog_current_frame(Frame), b_setval(auto_table_stack, s(Depth1, I, Copy, Stack, Frame)), call(Wrapped), b_setval(auto_table_stack, Stack). count_call(Slot, Head) :- arg(2, Slot, C0), C is C0+1, nb_setarg(2, Slot, C), arg(4, Slot, Trie), insert_variant(Trie, Head), arg(5, Slot, ArgTries), forall(( compound(ArgTries), arg(AI, ArgTries, ArgTrie) ), ( arg(AI, Head, A), insert_variant(ArgTrie, A) )). insert_variant(Trie, Term) :- ( catch(trie_insert(Trie, Term), _, true) -> true ; true ). %! ancestor_variant(+Stack, +I, +Head, +MaxCheck, -Path, -Frame) %! is semidet. % % True if Stack contains a call to predicate I that is a variant of % Head. Path is the list of predicate indexes from that ancestor % to the current call and Frame is the frame that runs the ancestor. ancestor_variant(Stack, I, Head, MaxCheck, Path, Frame) :- ancestor_variant_(Stack, I, Head, MaxCheck, [], Path, Frame). ancestor_variant_(s(_, J, Copy, Parent, Frame0), I, Head, Max, Path0, Path, Frame) :- Max > 0, ( J == I, Copy =@= Head -> Path = [J|Path0], Frame = Frame0 ; Max1 is Max-1, ancestor_variant_(Parent, I, Head, Max1, [J|Path0], Path, Frame) ). %! frame_barrier(+Frame, +AncFrame, -Barrier) is semidet. % % True if a frame between Frame and its ancestor AncFrame runs a % barrier for suspending a tabled goal (see shift/1): a predicate % with the attribute `shift_barrier`, such as findall/3, or a % predicate defined in C that called Prolog. Barrier is its % predicate indicator. frame_barrier(Frame, AncFrame, Barrier) :- prolog_frame_attribute(Frame, parent, Parent), Parent \== AncFrame, ( prolog_frame_attribute(Parent, predicate_indicator, PI0), barrier_frame_pi(PI0, Barrier) -> true ; frame_barrier(Parent, AncFrame, Barrier) ). barrier_frame_pi(PI0, Barrier) :- ( PI0 = M:Name/Arity -> true ; PI0 = Name/Arity, M = user ), functor(Head, Name, Arity), ( predicate_property(M:Head, shift_barrier) -> true ; predicate_property(M:Head, foreign) ), ( bags_loop(M:Name/Arity, Public) -> Barrier = Public ; M == '$bags' -> Barrier = Name/Arity ; M == system -> Barrier = Name/Arity ; Barrier = M:Name/Arity ). bags_loop('$bags':findall_loop/4, findall/3). bags_loop('$bags':findnsols_loop/5, findnsols/4). record_loop(Path, I, State, Loops) :- loop_cycle(Path, I, State, Cycle), insert_variant(Loops, Cycle). record_loop(Path, I, State, Loops, Barrier) :- loop_cycle(Path, I, State, Cycle), insert_variant(Loops, Cycle-Barrier). loop_cycle(Path, I, State, Cycle) :- arg(I, State, Slot), arg(3, Slot, L0), L is L0+1, nb_setarg(3, Slot, L), maplist(slot_pi(State), Path, PIs), canonical_cycle(PIs, Cycle). slot_pi(State, I, PI) :- arg(I, State, Slot), arg(1, Slot, PI). %! deep_loop(+Stack, +I, +State, +Loops) % % The recursion exceeded max_depth. Record the shortest repeating % sequence of predicates on top of the stack as a loop. deep_loop(Stack, I, State, Loops) :- stack_indexes(Stack, 100, Top), ( append(Cycle0, [I|_], Top), \+ memberchk(I, Cycle0) -> record_loop([I|Cycle0], I, State, Loops) ; true ). stack_indexes(s(_, J, _, Parent, _), Max, [J|T]) :- Max > 0, !, Max1 is Max-1, stack_indexes(Parent, Max1, T). stack_indexes(_, _, []). %! canonical_cycle(+PIs, -Cycle) is det. % % Rotate a cycle such that it starts with its smallest element and % remove the duplicate end. canonical_cycle([PI], [PI]) :- !. canonical_cycle([First|Rest], Cycle) :- ( last(Rest, First) -> append(Ring, [First], Rest), Ring1 = [First|Ring] ; Ring1 = [First|Rest] ), min_member(Min, Ring1), append(Before, [Min|After], Ring1), !, append([Min|After], Before, Cycle). %! run_goal(+Limits, :Goal, -Status) is det. run_goal(Limits, Goal, Status) :- abolish_all_tables, b_setval(auto_table_stack, []), catch(call_with_limits(Limits, ( forall(Goal, true) -> Status = true ; Status = false )), E, Status = E), nb_delete(auto_table_stack). %! limits(+Options, -Limits) is det. % % Limits is a term limits(Time, Inferences) holding the limits for a % single run of a goal. Each is a number or `infinite`. limits(Options, limits(Time, Inferences)) :- option(inference_limit(Inferences), Options, infinite), ( Inferences == infinite -> true ; must_be(positive_integer, Inferences) ), ( has_time_limit -> option(time_limit(Time), Options, 60), must_be(number, Time) ; Time = infinite ). %! call_with_limits(+Limits, :Goal) % % Run Goal as once/1 subject to Limits (see limits/2). Raises the % exception `time_limit_exceeded` or `inference_limit_exceeded` if % a limit is exceeded. call_with_limits(limits(Time, Inferences), Goal) :- call_with_time_limit_opt(Time, inference_limited(Inferences, Goal)). inference_limited(infinite, Goal) :- !, once(Goal). inference_limited(Inferences, Goal) :- call_with_inference_limit(Goal, Inferences, Result), ( Result == inference_limit_exceeded -> throw(inference_limit_exceeded) ; true ). :- if(current_predicate(call_with_time_limit/2)). has_time_limit. call_with_time_limit_opt(infinite, Goal) :- !, call(Goal). call_with_time_limit_opt(Time, Goal) :- call_with_time_limit(Time, Goal). :- else. has_time_limit :- fail. call_with_time_limit_opt(infinite, Goal) :- call(Goal). :- endif. %! scale_limits(+Limits0, +Run, -Limits) is det. % % Limit a run of a new configuration to three times the time and % inferences used by Run, the best configuration so far. scale_limits(limits(Time0, Inf0), Run, limits(Time, Inf)) :- ( Time0 == infinite -> Time = infinite ; Time is min(Time0, max(1, 3*Run.time)) ), MaxInf is max(1 000 000, 3*Run.inferences), ( Inf0 == infinite -> Inf = MaxInf ; Inf is min(Inf0, MaxInf) ). %! loop_predicates(+Loops, +Candidates, +State, -Preds) is det. loop_predicates(Loops, _Candidates, State, Preds) :- append(Loops, PIs0), sort(PIs0, PIs), maplist(pred_stats(State), PIs, Preds). %! hot_predicates(+State, +N, -Hot) is det. % % Hot is a list of statistics dicts for the N predicates with the % most call variants. hot_predicates(State, N, Hot) :- State =.. [_|Slots], findall(V-Slot, ( member(Slot, Slots), arg(4, Slot, Trie), trie_count(Trie, V), V > 0 ), Pairs), keysort(Pairs, Sorted), reverse(Sorted, Desc), length(Desc, Len), Take is min(N, Len), length(Top, Take), append(Top, _, Desc), pairs_values(Top, TopSlots), maplist(slot_stats, TopSlots, Hot). pred_stats(State, PI, Stats) :- State =.. [_|Slots], member(Slot, Slots), arg(1, Slot, PI), !, slot_stats(Slot, Stats). slot_stats(Slot, Stats) :- Slot = slot(PI, Calls, LoopCount, Trie, ArgTries), trie_count(Trie, Variants), ( compound(ArgTries) -> ArgTries =.. [_|ArgTrieList] ; ArgTrieList = [] ), maplist(trie_count, ArgTrieList, ArgCounts), ( tabled(PI) -> Tabled = true ; Tabled = false ), Stats = pred{pi:PI, calls:Calls, variants:Variants, args:ArgCounts, tabled:Tabled, loops:LoopCount}. trie_count(Trie, Count) :- ( trie_property(Trie, value_count(Count)) -> true ; Count = 0 ). %! learned_selection(+Discovery, -Selected) is det. % % Compute the predicates to table from the observed loops. Loops % through predicates that are already tabled are considered broken. % The predicates of a loop through a barrier for suspending a tabled % goal (see frame_barrier/3) are not tabled, so the loops through % them are not broken. learned_selection(Discovery, Selected) :- Preds = Discovery.predicates, pairs_keys(Discovery.barrier_loops, BarrierLoops), append(BarrierLoops, Blocked0), sort(Blocked0, Blocked), exclude(tabled_stats, Preds, Untabled0), exclude(blocked_stats(Blocked), Untabled0, Untabled), maplist(get_dict(pi), Untabled, Nodes), findall(edge{from:F, to:T}, ( member(Loop, Discovery.loops), \+ ( member(PI, Loop), member(P, Preds), P.pi == PI, P.tabled == true ), \+ ( member(PI, Loop), memberchk(PI, Blocked) ), loop_edge(Loop, F, T) ), Edges), maplist(stats_cost, Untabled, CostPairs), list_to_assoc(CostPairs, Costs), feedback_vertex_set(Nodes, Edges, Costs, Selected, _Cost). blocked_stats(Blocked, Stats) :- memberchk(Stats.pi, Blocked). tabled_stats(Stats) :- Stats.tabled == true. loop_edge([PI], PI, PI) :- !. loop_edge(Loop, F, T) :- Loop = [First|_], append(Loop, [First], Closed), append(_, [F,T|_], Closed). stats_cost(Stats, PI-c(Variants, NotExported, Arity)) :- PI = Stats.pi, Variants = Stats.variants, PI = M:Name/Arity, functor(Head, Name, Arity), ( predicate_property(M:Head, exported) -> NotExported = 0 ; NotExported = 1 ). /******************************* * SEARCH * *******************************/ %! original_tabling(+Candidates, -Original, -Fixed) is det. % % Original is a list of `PI-t(Mode, Extra)` for the tabled % candidates we may change, where `Mode` is `variant` or % `subsumptive` and `Extra` is a list of additional table options % (incremental, shared, ...). Fixed is a list of tabled candidates % we do not change: predicates with mode-directed tabling. original_tabling(Candidates, Original, Fixed) :- include(tabled, Candidates, Tabled), partition(moded_tabled, Tabled, Fixed, Tunable), maplist(table_state, Tunable, Original). moded_tabled(M:Name/Arity) :- functor(Head, Name, Arity), '$tbl_implementation'(M:Head, IM:IHead), catch(IM:'$table_mode'(IHead, Variant, _), _, fail), IHead \=@= Variant. table_state(PI, PI-t(Mode, Extra)) :- PI = M:Name/Arity, functor(Head, Name, Arity), ( predicate_property(M:Head, tabled(subsumptive)) -> Mode = subsumptive ; Mode = variant ), findall(X, ( extra_table_flag(X), predicate_property(M:Head, tabled(X)) ), Extra). extra_table_flag(incremental). extra_table_flag(shared). extra_table_flag(monotonic). %! search(+Goals, +Result0, +Original, +Fixed, -Result, +Options) search(Goals, Result0, Original, Fixed, Result, Options) :- option(apply(Apply), Options, false), pairs_keys_values(Original, OrigPIs, OrigStates), maplist(state_mode, OrigStates, OrigModes), pairs_keys_values(Config00, OrigPIs, OrigModes), findall(PI-variant, ( member(PI, Result0.selected), \+ memberchk(PI-_, Config00) ), Added), append(Config00, Added, Config0), sort(Config0, Initial), State = search(Original, [], Options), ( Apply == true -> run_search(Goals, Initial, Result0, Fixed, State, Search), apply_config(Search.config, State) ; setup_call_cleanup( true, run_search(Goals, Initial, Result0, Fixed, State, Search), restore_tabling(Original, State)) ), directives(Search.config, Directives), ( option(output(File), Options) -> write_directives(File, Directives) ; true ), Result = Result0.put(Search).put(directives, Directives). state_mode(t(Mode, _), Mode). restore_tabling(Original, State) :- pairs_keys_values(Original, PIs, States), maplist(state_mode, States, Modes), pairs_keys_values(Config, PIs, Modes), apply_config(Config, State), abolish_all_tables. %! run_search(+Goals, +Initial, +Result0, +Fixed, +State, -Search) % % Hill climbing from the Initial configuration. run_search(Goals, Initial, Result0, Fixed, State, Search) :- arg(3, State, Options), limits(Options, Limits), option(max_runs(MaxRuns), Options, 50), option(objective(Objective), Options, balanced), must_be(oneof([time,memory,balanced]), Objective), evaluate(Goals, Initial, initial, Limits, [], State, Run00), ( Run00.status == ok -> Start = Initial, Run0 = Run00, Runs0 = [Run00] ; print_message(warning, auto_table(initial_failed(Run00.status))), original_config(State, Original), Original \== Initial, evaluate(Goals, Original, original, Limits, [], State, Run01), Run01.status == ok -> Start = Original, Run0 = Run01, Runs0 = [Run01, Run00] ; true ), ( nonvar(Start) -> Ref = Run0.answers, Ctx = ctx(Goals, Ref, Run0, Objective, Fixed, Result0, State), length(Runs0, Used), Budget is MaxRuns-Used, moves(Start, Ctx, Moves), climb(Moves, Start, Run0, Ctx, Budget, Runs0, Best, Runs) ; original_config(State, Best), % no configuration works Runs = [Run00] ), reverse(Runs, RunsInOrder), maplist(public_run, RunsInOrder, PublicRuns), Search = #{config:Best, runs:PublicRuns}. %! original_config(+State, -Config) is det. % % Config is the configuration with the original tabling of the % candidates. original_config(State, Config) :- arg(1, State, Original), pairs_keys_values(Original, PIs, States), maplist(state_mode, States, Modes), pairs_keys_values(Config0, PIs, Modes), sort(Config0, Config). public_run(Run, Public) :- del_dict(answers, Run, _, Public). %! climb(+Moves, +Config, +Run, +Ctx, +Budget, +Runs0, -Best, -Runs) % % First improvement hill climbing. After an improving move, the % moves are recomputed for the new configuration. Moves that did % not improve are not tried again. climb(_, Config, _, _, Budget, Runs, Config, Runs) :- Budget =< 0, !. climb([], Config, _, _, _, Runs, Config, Runs). climb([Move|Moves], Config, Run, Ctx, Budget, Runs0, Best, Runs) :- apply_move(Move, Config, Config1), ( Config1 == Config -> climb(Moves, Config, Run, Ctx, Budget, Runs0, Best, Runs) ; Ctx = ctx(Goals, Ref, Run0, Objective, _Fixed, _Result0, State), arg(3, State, Options), limits(Options, Limits0), scale_limits(Limits0, Run, Limits), evaluate(Goals, Config1, Move, Limits, Ref, State, Run1), Budget1 is Budget-1, Runs1 = [Run1|Runs0], ( Run1.status == ok, accept(Objective, Run1, Run, Run0) -> moves(Config1, Ctx, NewMoves0), tried_moves(Runs1, Tried0), inverse_moves(Move, Config, Inverse), append(Inverse, Tried0, Tried), exclude(tried(Tried), NewMoves0, NewMoves), climb(NewMoves, Config1, Run1, Ctx, Budget1, Runs1, Best, Runs) ; Run1.status \== ok, Move = untable_all(PIs), PIs = [_,_|_] -> length(PIs, Len), Half is Len // 2, length(First, Half), append(First, Second, PIs), climb([untable_all(First), untable_all(Second)|Moves], Config, Run, Ctx, Budget1, Runs1, Best, Runs) ; climb(Moves, Config, Run, Ctx, Budget1, Runs1, Best, Runs) ) ). tried_moves(Runs, Moves) :- findall(M, (member(R, Runs), M = R.move), Moves). tried(Tried, Move) :- memberchk(Move, Tried). %! inverse_moves(+Move, +OldConfig, -Inverse) is det. % % Moves that undo Move. We do not try these after accepting Move. inverse_moves(mode(PI, _), Config, [mode(PI, Old)]) :- memberchk(PI-Old, Config), !. inverse_moves(untable(PI), Config, [table(PI, Old)]) :- memberchk(PI-Old, Config), !. inverse_moves(untable_all(PIs), Config, Inverse) :- !, findall(table(PI, Old), (member(PI, PIs), memberchk(PI-Old, Config)), Inverse). inverse_moves(table(PI, _), _, [untable(PI)]) :- !. inverse_moves(_, _, []). %! accept(+Objective, +New, +Current, +Initial) is semidet. % % True if we accept New over Current. This is the case if New is % better or New is about as good and tables fewer predicates. accept(Objective, New, Cur, Init) :- ( better(Objective, New, Cur, Init) -> true ; length(New.config, NN), length(Cur.config, NC), NN < NC, \+ worse(Objective, New, Cur, Init) ). worse(time, New, Cur, _) :- New.time > Cur.time*1.05. worse(memory, New, Cur, _) :- New.space > Cur.space*1.05. worse(balanced, New, Cur, Init) :- score(New, Init, SN), score(Cur, Init, SC), SN > SC*1.05. %! better(+Objective, +New, +Current, +Initial) is semidet. % % True if New is better than Current. Time measurements need to % improve by at least 5% to compensate for noise. better(time, New, Cur, _) :- New.time < Cur.time*0.95. better(memory, New, Cur, _) :- ( New.space < Cur.space -> true ; New.space =:= Cur.space, New.time < Cur.time*0.95 ). better(balanced, New, Cur, Init) :- score(New, Init, SN), score(Cur, Init, SC), SN < SC*0.95. score(Run, Init, Score) :- Score is (Run.time+0.001)/(Init.time+0.001) + (Run.space+1000)/(Init.space+1000). %! moves(+Config, +Ctx, -Moves) is det. % % Generate the moves for Config, in the order we try them. moves(Config, Ctx, Moves) :- Ctx = ctx(_Goals, _Ref, _Run0, _Objective, _Fixed, Result0, State), arg(3, State, Options), option(modes(Modes), Options, [variant,subsumptive]), pairs_keys(Config, Tabled), loop_preds(Result0, InLoop), exclude(in_set(InLoop), Tabled, NotInLoop), ( NotInLoop = [_,_|_] -> Bulk = [untable_all(NotInLoop)] ; Bulk = [] ), variant_order(Tabled, Result0, Ordered), findall(untable(PI), member(PI, Ordered), Untable), reverse(Ordered, ByVariants), findall(mode(PI, Mode), ( member(PI, ByVariants), memberchk(PI-Current, Config), member(Mode, Modes), Mode \== Current ), ModeMoves), findall(table(PI, variant), ( member(P, Result0.hot), PI = P.pi, \+ memberchk(PI-_, Config), P.tabled == false, P.calls >= 2*P.variants ), Add), append([Bulk, Untable, ModeMoves, Add], Moves). in_set(Set, X) :- memberchk(X, Set). loop_preds(Result, PIs) :- append(Result.loops, PIs0), sort(PIs0, PIs). %! variant_order(+PIs, +Result, -Ordered) is det. % % Order PIs by increasing number of observed call variants. Small % tables are the cheapest to try removing. variant_order(PIs, Result, Ordered) :- append(Result.predicates, Result.hot, Stats), maplist(variant_key(Stats), PIs, Keyed), keysort(Keyed, Sorted), pairs_values(Sorted, Ordered). variant_key(Stats, PI, V-PI) :- ( member(S, Stats), S.pi == PI -> V = S.variants ; V = 0 ). apply_move(untable_all(PIs), Config0, Config) :- exclude(pi_in(PIs), Config0, Config). apply_move(untable(PI), Config0, Config) :- exclude(pi_in([PI]), Config0, Config). apply_move(mode(PI, Mode), Config0, Config) :- ( selectchk(PI-_, Config0, Config1) -> sort([PI-Mode|Config1], Config) ; Config = Config0 ). apply_move(table(PI, Mode), Config0, Config) :- sort([PI-Mode|Config0], Config). pi_in(PIs, PI-_) :- memberchk(PI, PIs). %! evaluate(+Goals, +Config, +Move, +Limits, +RefAnswers, +State, %! -Run) is det. % % Apply Config and run Goals. Run is a dict with the keys `move`, % `config`, `status` (`ok`, `different_answers` or the error), % `time` (CPU seconds), `inferences`, `space` (memory used by the % tables in bytes), `tables` and `answers`. evaluate(Goals, Config, Move, Limits, Ref, State, Run) :- catch(apply_config(Config, State), E, true), ( var(E) -> abolish_all_tables, garbage_collect, statistics(cputime, T0), statistics(inferences, I0), maplist(goal_answers(Limits), Goals, Answers), statistics(cputime, T1), statistics(inferences, I1), table_space(Tables, Space), abolish_all_tables, Time is T1-T0, Inferences is I1-I0, ( member(error(Status0), Answers) -> Status = Status0 ; Ref \== [], Ref \== Answers -> Status = different_answers ; Status = ok ) ; Status = E, Time = 0, Inferences = 0, Space = 0, Tables = 0, Answers = [] ), Run = run{move:Move, config:Config, status:Status, time:Time, inferences:Inferences, space:Space, tables:Tables, answers:Answers}, print_message(silent, auto_table(run(Run))). %! table_space(-Count, -Bytes) is det. % % Count the tables and the memory they use. We sum the sizes of the % tables rather than using the table_space_used statistics because % the space of abolished tables is not always reclaimed immediately. % The size of a table includes its compiled answer representation. table_space(Count, Bytes) :- aggregate_all(count-sum(Size), ( current_table(_:_, Trie), trie_space(Trie, Size) ), Count-Bytes). trie_space(Trie, Size) :- ( trie_property(Trie, size(Size0)) -> true ; Size0 = 0 ), ( trie_property(Trie, compiled_size(Size1)) -> true ; Size1 = 0 ), Size is Size0+Size1. goal_answers(Limits, Goal, Answers) :- catch(call_with_limits( Limits, findall(Goal-Delays, call_delays(Goal, Delays), List)), E, true), ( var(E) -> answer_set(List, Answers) ; Answers = error(E) ). answer_set(List, Set) :- maplist(answer_hash, List, Hashes), sort(Hashes, Set). answer_hash(Answer, Hash) :- ( catch(variant_sha1(Answer, Hash), _, fail) -> true ; copy_term(Answer, Hash), numbervars(Hash, 0, _, [singletons(true)]) ). %! apply_config(+Config, +State) is det. % % Make the tabling of the predicates we manage agree with Config. % The managed predicates are those in Config, those that were % tabled originally and those of previously applied configurations. apply_config(Config, State) :- State = search(Original, Managed0, _Options), pairs_keys(Config, CPIs), pairs_keys(Original, OPIs), append([CPIs, OPIs, Managed0], All0), sort(All0, All), nb_setarg(2, State, All), maplist(apply_pi_config(Config, Original), All). apply_pi_config(Config, Original, PI) :- PI = M:Name/Arity, functor(Head, Name, Arity), ( memberchk(PI-Mode, Config) -> ( memberchk(PI-t(_, Extra), Original) -> true ; Extra = [] ), ( predicate_property(M:Head, tabled(Mode)), forall(member(X, Extra), predicate_property(M:Head, tabled(X))) -> true ; ( predicate_property(M:Head, tabled) -> untable(PI) ; true ), comma_list(Opts, [Mode|Extra]), table(PI as Opts) ) ; predicate_property(M:Head, tabled) -> untable(PI) ; true ). %! directives(+Config, -Directives) is det. directives(Config, Directives) :- maplist(directive, Config, Directives). directive(PI-variant, (:- table(PI))) :- !. directive(PI-Mode, (:- table(PI as Mode))). write_directives(File, Directives) :- setup_call_cleanup( open(File, write, Out), forall(member(D, Directives), portray_clause(Out, D)), close(Out)). /******************************* * MESSAGES * *******************************/ :- multifile prolog:message//1. prolog:message(auto_table(Msg)) --> message(Msg). message(learned(R)) --> { pairs_keys(R.get(barrier_loops, []), BarrierLoops), subtract(R.loops, BarrierLoops, Loops) }, learned_goals(R.goals), learned_loops(Loops), learned_barrier_loops(R.get(barrier_loops, [])), learned_preds(R.predicates), learned_hot(R.hot), learned_selected(R.selected), learned_runs(R.get(runs, [])), learned_directives(R.get(directives, -)). message(initial_failed(Status)) --> [ 'auto_table_learn/3: initial configuration failed: ~p'-[Status] ]. message(run(Run)) --> run(Run). message(analysis(Analysis)) --> { Analysis.selected == [] }, !, [ 'auto_table: no predicates need to be tabled' ]. message(analysis(Analysis)) --> { Table = Analysis.selected }, sequence(table_reason(Analysis), [nl], Table). message(illegal_cut(Edge)) --> [ 'auto_table: the call to ~q from ~q'-[Edge.to, Edge.from] ], location(Edge.location), [ ' can be pruned by a cut.', nl, 'This raises an error if the call is to an incomplete table.' ]. message(barrier(SCC)) --> sequence(barrier_edge_message, [nl], SCC.barriers), [ nl, 'A tabled goal cannot wait for an incomplete table through \c these calls. Not tabling ' ], sequence(pi, [', '], SCC.members). barrier_edge_message(Edge) --> [ 'auto_table: ~q calls ~q through ~q'-[Edge.from, Edge.to, Edge.barrier] ], location(Edge.location). table_reason(_, PI-tnot) --> [ 'auto_table: tabling ~q (called through tnot/1)'-[PI] ]. table_reason(Analysis, PI-cycle) --> { member(SCC, Analysis.sccs), memberchk(PI, SCC.selected), ! }, [ 'auto_table: tabling ~q'-[PI] ], left_recursion_reason(PI, SCC.left_recursion). left_recursion_reason(PI, LeftRecs) --> { member(L, LeftRecs), memberchk(PI, L.members), ! }, [ ' (breaks left recursion ' ], cycle(L.cycle), [ ')' ]. left_recursion_reason(_, _) --> [ ' (breaks recursion)' ]. cycle(Edges) --> { Edges = [E0|_], last(Edges, Last) }, [ '~q'-[E0.from] ], sequence(cycle_edge, Edges), location(Last.location). cycle_edge(E) --> [ ' -> ~q'-[E.to] ]. learned_goals(Goals) --> sequence(learned_goal, Goals). learned_goal(Goal-Status) --> [ 'Goal ~p: ~p'-[Goal, Status], nl ]. learned_loops([]) --> !, [ 'No loops observed', nl ]. learned_loops(Loops) --> { length(Loops, Count) }, [ 'Observed ~D loops:'-[Count], nl ], sequence(learned_loop, Loops). learned_barrier_loops([]) --> !. learned_barrier_loops(Loops) --> [ 'Loops through a barrier for suspending a tabled goal \c (not tabled):', nl ], sequence(learned_barrier_loop, Loops). learned_barrier_loop(Loop-Barrier) --> { Loop = [First|_] }, [ ' ' ], sequence(pi, [' -> '], Loop), [ ' -> ~q (through ~q)'-[First, Barrier], nl ]. learned_loop(Loop) --> { Loop = [First|_] }, [ ' ' ], sequence(pi, [' -> '], Loop), [ ' -> ~q'-[First], nl ]. pi(PI) --> [ '~q'-[PI] ]. learned_preds([]) --> !. learned_preds(Preds) --> [ 'Predicates in loops:', nl ], sequence(learned_pred, Preds). learned_pred(P) --> { (P.tabled == true -> Tabled = ' (tabled)' ; Tabled = '') }, [ ' ~q~w: ~D calls, ~D variants, args ~w'- [P.pi, Tabled, P.calls, P.variants, P.args], nl ]. learned_hot([]) --> !. learned_hot(Preds) --> [ 'Predicates with the most call variants:', nl ], sequence(learned_pred, Preds). learned_runs([]) --> !. learned_runs(Runs) --> [ nl, 'Configurations tried (CPU time, table space, tables):', nl ], sequence(run_line, Runs). run_line(Run) --> [ ' ' ], run(Run), [ nl ]. run(Run) --> { Run.status == ok }, !, [ '~p: ~3f sec, ~D bytes, ~D tables'- [Run.move, Run.time, Run.space, Run.tables] ]. run(Run) --> { ( Run.status = error(Formal, _) -> Status = Formal ; Status = Run.status ) }, [ '~p: ~p'-[Run.move, Status] ]. learned_directives(-) --> !. learned_directives([]) --> !, [ 'Best configuration: no tabling' ]. learned_directives(Directives) --> [ 'Best configuration:', nl ], sequence(directive_line, [nl], Directives). directive_line(Directive) --> { format(string(S), '~q.', [Directive]) }, [ ' ~s'-[S] ]. learned_selected([]) --> !, [ 'No (additional) predicates need to be tabled' ]. learned_selected(PIs) --> [ 'Table: ' ], sequence(pi, [', '], PIs). location(Loc) --> { get_dict(file, Loc, File), get_dict(line_count, Loc, Line) }, !, [ ' at ', url(File:Line) ]. location(_) --> [].