1 % (c) 2016-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(b_operation_cache, [ %project_in_state/6,
6 %operation_computed/4,
7 compute_operation_on_expanded_store_cache/6,
8 check_invariant_violated_cache/2,
9 print_op_cache_profile/0,
10 get_op_cache_stats/1,
11 reset_b_operation_cache_with_statistics/0,
12 tcltk_op_cache_stats/1
13 ]).
14
15
16 :- use_module(probsrc(module_information)).
17 :- module_info(group,animator).
18 :- module_info(description,'This module caches B operation results on projected states. Used when preference try_operation_reuse different from false').
19
20 % difference with PGE (Partial Guard Evaluation) : it uses hash of projected state, not static keep/enables/disables info
21 % difference with -cache: results are not persisted to disk but in RAM; uses Prolog hash and not SHA1 hash
22
23 % TO DO:
24 % provide predecessor ID and operation to know which values are unchanged? -> reuse hash; know which ops are definitely disabled? (cf pge)
25 % Note: operation caching works better with COMPRESSION TRUE, as this way the values are pre-hashed. A simpler hash function is then used.
26 % Note: if we change the MAX_OPERATIONS preference, this will have no effect on already cached operations
27 % TODO: we could invalidate operation cache upon such a change; storing the value for each node is probably overkill
28 % TODO: operation caching does not detect common guards amongst operations
29
30 :- use_module(probsrc(self_check)).
31 :- use_module(extension('counter/counter')). % op_cache_id,... counter
32 :- use_module(probsrc(succeed_max),[succeed_max_call_id/3, reset_max_reached/1, max_reached/1, assert_max_reached/1]).
33 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
34 :- use_module(probsrc(error_manager)).
35 :- use_module(probsrc(debug),[formatsilent/2, debug_println/2, debug_mode/1, debug_format/3]).
36 :- use_module(probsrc(performance_messages),[perfmessage/2, perf_format/2]).
37 :- use_module(library(ordsets), [ord_subtract/3]).
38 :- use_module(probsrc(tools),[retract_with_statistics/2]).
39 :- use_module(probsrc(translate),[translate_bstate_limited/2, translate_event_with_limit/3]).
40 :- use_module(probsrc(preferences),[get_preference/2, set_preference/2]).
41 :- use_module(probsrc(specfile),[get_operation_name/2]).
42
43 b_operation_cache_startup :- % call once at startup to ensure all counters exist
44 counter_init,
45 new_counter(op_cache_id),
46 new_counter(inv_cache_nr),
47 new_counter(op_cached_failures),
48 new_counter(op_cached_successes),
49 new_counter(inv_cached_successes),
50 new_counter(op_cached_timeouts),
51 new_counter(op_cached_enum_warnings),
52 new_counter(op_cached_errors).
53
54
55 :- register_event_listener(startup_prob,b_operation_cache_startup,
56 'Initialise Operation Cache Counters.').
57 :- register_event_listener(reset_specification,reset_b_operation_cache,
58 'Reset Operation Cache.').
59 :- register_event_listener(clear_specification,reset_b_operation_cache, % necessary? as reset occurs before?
60 'Reset Operation Cache.').
61 :- register_event_listener(change_of_animation_mode,reset_b_operation_cache,
62 'Reset Operation Cache.').
63 :- register_event_listener(specification_initialised,auto_set_b_operation_cache,
64 'Determine if operation caching turned on/off in auto setting.').
65 :- register_event_listener(change_of_animation_mode,auto_set_b_operation_cache,
66 'Re-compute auto setting in case csp_with_bz_mode activated.').
67 % TO DO: also reset if maxNrOfEnablingsPerOperation changed ?
68
69
70 :- dynamic operation_read_projection_cache/5, operation_read_constants/2, operation_guard_read_info/3.
71 reset_b_operation_cache :-
72 retractall(operation_read_projection_cache(_,_,_,_,_)),
73 retractall(operation_read_constants(_,_)),
74 retractall(operation_guard_read_info(_,_,_)),
75 retractall(operation_computed(_,_,_,_,_)),
76 retractall(operation_cached_results(_,_,_,_)),
77 retractall(operation_cached_max_reached(_,_)),
78 retractall(operation_cached_time_out(_,_)),
79 retractall(operation_cached_enum_warning(_,_,_)),
80 retractall(op_guard_fails(_,_,_)),
81 reset_counter(op_cache_id),
82 reset_counter(inv_cache_nr),
83 reset_counter(op_cached_failures),
84 reset_counter(op_cached_successes),
85 reset_counter(inv_cached_successes),
86 reset_counter(op_cached_timeouts),
87 reset_counter(op_cached_enum_warnings),
88 reset_counter(op_cached_errors).
89
90
91 reset_b_operation_cache_with_statistics :-
92 retract_with_statistics(b_operation_cache,
93 [operation_read_projection_cache(_,_,_,_,_),
94 operation_read_constants(_,_),operation_guard_read_info(_,_,_),
95 operation_computed(_,_,_,_,_), operation_cached_results(_,_,_,_),
96 operation_cached_max_reached(_,_),
97 operation_cached_time_out(_,_),
98 operation_cached_enum_warning(_,_,_),
99 op_guard_fails(_,_,_)
100 ]
101 ),
102 reset_b_operation_cache.
103
104
105 auto_set_b_operation_cache :-
106 get_preference(try_operation_reuse,X),
107 compute_op_reuse_setting(X,Setting),
108 set_preference(operation_reuse_setting,Setting),
109 recompute_state_packing_preference. % will also re-compute it if SET_PREF_COMPRESSION was used
110
111
112 :- use_module(probsrc(specfile),[b_or_z_mode/0,csp_with_bz_mode/0]).
113 compute_op_reuse_setting(auto,Setting) :- !,
114 (b_or_z_mode,
115 \+ csp_with_bz_mode, % in CSP||B mode operation caching means we explore the B ops unconstrained,
116 % this can lead to enum warnings and much larger local state spaces, see test 1401
117 op_cache_useful(OpName,_ReadLen,_VLen)
118 -> Setting=true % TODO: more detailed check; maybe turn on full in some circumstances
119 ; Setting=false, OpName = no_operation),
120 debug_format(19,'Setting operation caching to ~w (useful for: ~w)~n',[Setting,OpName]).
121 compute_op_reuse_setting(X,X).
122
123
124 % -------------------------------------------------
125
126
127 % project the in-state for an operation onto the relevant variables
128 project_in_state(VarsInState,OpName,ProjectedInState) :-
129 get_opname_key(OpName,OpNameKey),
130 project_in_state_for_opname_key(VarsInState,OpNameKey,ProjectedInState).
131
132 :- use_module(probsrc(bmachine),[b_is_constant/1]).
133 :- use_module(library(lists),[exclude/3, include/3]).
134 project_in_state_for_opname_key(InState,OpNameKey,ProjectedInState) :-
135 get_operation_read_projection_infos(OpNameKey,_,InState,ProjVars,_,_),
136 (re_project_state(ProjVars,InState,Res) -> ProjectedInState=Res
137 ; add_internal_error('Re-Projection failed: ',re_project_state(ProjVars,InState,_)),
138 ProjectedInState = InState).
139
140 :- use_module(probsrc(b_read_write_info),[b_get_operation_read_guard_vars/4]).
141 :- use_module(probsrc(bmachine),[b_definition_prefixed/5]).
142
143
144 % get infos about cached operations (and compute the first time info requested for an operation)
145 get_operation_read_projection_infos(OpNameKey,OpName,_,ProjVars,IsReadingCsts,AdditionalOutVars) :-
146 operation_read_projection_cache(OpNameKey,OpName,ProjVars,IsReadingCsts,AdditionalOutVars),!,
147 ProjVars \= no_caching.
148 get_operation_read_projection_infos(OpNameKey,OpName,_,_,_,_) :- atom(OpName),
149 b_definition_prefixed(_, 'OPERATION_REUSE_OFF_', OpName, _DefName,_),
150 !,
151 formatsilent('Ignoring operation ~w for reuse~n',[OpName]),
152 assertz(operation_read_projection_cache(OpNameKey,OpName,no_caching,no_caching,[])),
153 fail.
154 get_operation_read_projection_infos(OpNameKey,OpName,InState,ProjVarsInOrder,IsReadingCsts,AdditionalOutVars) :-
155 api_get_operation_read_write_info(OpName,ReadVariables,ReadConstants,WrittenVariables),
156 (ReadConstants=[] -> IsReadingCsts=false ; IsReadingCsts=true),
157 debug_println(19,operation_reads_vars_consts(OpName,ReadVariables,ReadConstants)),
158 exclude(is_constant_binding,InState,VarState), % in case InState contains constants (e.g., from FindStateCommand)
159 (project_state_onto_vars(VarState,ReadVariables,ProjVarsInOrder,_RelevantState,0,NrDeleted)
160 -> % TO DO: if we have constants in the state which are deterministic anyway, then they should not count
161 % TO DO: statically pre-compute which operations are worthwhile for this treatment
162 (cache_operation(OpName,NrDeleted)
163 -> ord_subtract(WrittenVariables,ReadVariables,AdditionalOutVars), % vars written but not read
164 assertz(operation_read_projection_cache(OpNameKey,OpName,ProjVarsInOrder,IsReadingCsts,AdditionalOutVars)),
165 assertz(operation_read_constants(OpNameKey,ReadConstants)),
166 % ,print(proj(OpName,ProjVarsInOrder,AdditionalOutVars)),nl,
167 (get_preference(operation_reuse_setting,full),
168 b_get_operation_read_guard_vars(OpName,true,ReadVarsInGuard,precise),
169 exclude(member_ord(ReadVarsInGuard),ProjVarsInOrder,IrrelevantVars),
170 % TO DO: analyse if projection really useful
171 IrrelevantVars \= []
172 -> include(member_ord(ReadVarsInGuard),ProjVarsInOrder,ReadVarsInGuard),
173 debug_println(19,guard_reads_subset_of_vars(OpName,OpNameKey,ReadVarsInGuard,IrrelevantVars)),
174 assertz(operation_guard_read_info(OpNameKey,ReadVarsInGuard,IrrelevantVars))
175 ; true)
176 ; assertz(operation_read_projection_cache(OpNameKey,OpName,no_caching,no_caching,[])),
177 perfmessage('Not caching operation for reuse: ',OpName),
178 fail
179 )
180 ; add_internal_error('Projection failed for: ', project_state_onto_vars(VarState,ReadVariables,_,_,0,_)),
181 assertz(operation_read_projection_cache(OpNameKey,OpName,no_caching,no_caching,[])),
182 fail
183 ).
184 is_constant_binding(bind(ID,_)) :- b_is_constant(ID).
185
186 %TODO: also compute precise guard b_get_operation_read_guard_vars(Operation,JustVariables,VarsResult,VarsPrecise) if possible and if read vars in guard << ReadVariables also store this
187 % if operation call fails -> store only precise guard
188
189 % check if we should construct a local cache for this operation:
190 cache_operation(OpName,NrDeleted) :-
191 (inv_op_name(OpName)
192 -> get_preference(try_operation_reuse_for_invariants,true)
193 % TODO: we could limit the number of invariants; as large number of invariants also increases overhead due to call_cleanup
194 ; \+ b_operation_reads_output_variables(OpName,_,_) % see test 1787; operation caching does not handle this yet
195 % (we would need to values for output variables before call)
196 ),
197 (NrDeleted>0 % we project away at least one variable and thus hope to cache operation results
198 ; csp_with_bz_mode). % in CSP||B mode, the same operation may be called with different CSP controllers
199
200 % -------------------------------
201
202 % API to abstract operations so that we can use caching also for invariants, maybe later assertions, ...
203
204 % get atomic key to store operation info
205 get_opname_key(Name,Res) :- var(Name),!,
206 add_internal_error('Variable opname: ',get_opname_key(Name,Res)), Res=Name.
207 get_opname_key(check_invariant_violated(Nr),Key) :- !, Key=Nr.
208 get_opname_key(Name,Name).
209
210 api_get_operation_read_write_info(OpName,ReadVariables,ReadConstants,WrittenVariables) :-
211 ? api_get_op_rw_aux(OpName,ReadIds,WrittenVariables),
212 exclude(b_is_constant,ReadIds,ReadVariables),
213 include(b_is_constant,ReadIds,ReadConstants).
214 :- use_module(probsrc(bmachine),[b_nth1_non_ignored_invariant/3,b_get_operation_normalized_read_write_info/3]).
215 api_get_op_rw_aux(check_invariant_violated(Nr),UsedIds,Written) :- !, Written=[],
216 b_nth1_non_ignored_invariant(Nr,_Inv,UsedIds).
217 %write(inv(Nr,UsedIds)),nl, translate:print_bexpr(_Inv),nl.
218 api_get_op_rw_aux(OpName,ReadVariables,WrittenVariables) :-
219 ? b_get_operation_normalized_read_write_info(OpName,ReadVariables,WrittenVariables).
220
221
222 :- use_module(probsrc(b_interpreter),[b_execute_top_level_operation_update/5]).
223
224 % we use a trick using a mutable to detect when a time_out or exception has been thrown
225 % during caching; we could have used assert/retract or bb_put/bb_get instead
226 % note: call_cleanup induces an overhead; visible e.g. for prob-examples/TLC/Laws/ArithmeticLaws_TLC.mch with invariants
227
228 % uncached version of api_compute_operation_update_max
229 % there is no need to use call_cleanup to collect exceptions, ... and store them in cache
230 % this corresponds to what specfile:compute_operation_on_expanded_store2 does
231 % exceptions/timeouts will be stored with the current state
232 api_compute_operation_update_max_uncached(NewID,OpName,Operation,ProjInOutState,NewState,PathInfo,MaxForCall) :-
233 create_mutable(still_computing,Done),
234 com_op_update_max(NewID,OpName,Operation,ProjInOutState,NewState,PathInfo,MaxForCall,Done),
235 get_mutable(DVal,Done), DVal \= finished. % fail if we are Done;
236
237 % now the version for cached operations, where we collect special events and store them in the local cache
238 api_compute_operation_update_max(NewID,OpName,Operation,ProjInOutState,NewState,PathInfo,MaxForCall) :-
239 create_mutable(still_computing,Done),
240 %tools:start_ms_timer(Timer),
241 (event_occurred_in_error_scope(E)
242 -> add_message(b_operation_cache,'Error scope not fresh: ',E),
243 enter_new_error_scope(Level)
244 ; Level=none), % note: errors always come with an event (assert_real_error_in_current_block)
245 call_cleanup(
246 com_op_update_max(NewID,OpName,Operation,ProjInOutState,NewState,PathInfo,MaxForCall,Done),
247 (get_mutable(still_computing,Done)
248 -> formatsilent('Timeout, exception or virtual timeout occurred during caching for ~w (cache id ~w)~n',[OpName,NewID]),
249 % also happens during -execute due to cut!, hence we now disable preference in -execute
250 % stop_ms_timer_with_msg(Timer,'Runtime for computing'),
251 exit_scope(Level),
252 register_op_cache_time_out(NewID,OpName)
253 ; error_occurred_in_error_scope
254 -> formatsilent('Error occurred during caching for ~w (cache id ~w)~n',[OpName,NewID]),
255 invalidate_operation_cache(NewID,OpName),
256 exit_scope(Level)
257 ; event_occurred_in_error_scope(Event),
258 functor(Event,Kind,_),
259 formatsilent('Event ~w occurred during caching for ~w (cache id ~w)~n',[Kind,OpName,NewID]),
260 register_op_cache_enum_warning(NewID,OpName,Event),
261 exit_scope(Level),
262 fail
263 % TODO: should we also check if errors occurred
264 ; exit_scope(Level)
265 )),
266 get_mutable(DVal,Done), DVal \= finished. % fail if we are Done;
267
268 exit_scope(none) :- !.
269 exit_scope(Level) :- exit_error_scope(Level,_).
270
271 % we could do this: but we don't know if an exception, timeout or virtual time_out occurred
272 register_op_cache_time_out(ID,OpName) :-
273 inc_counter(op_cached_timeouts),
274 assertz(operation_cached_time_out(ID,OpName)).
275 register_op_cache_enum_warning(ID,OpName,Event) :-
276 inc_counter(op_cached_enum_warnings),
277 assertz(operation_cached_enum_warning(ID,OpName,Event)).
278 % as an alternative this removes the cached results:
279 invalidate_operation_cache(ID,OpName) :-
280 inc_counter(op_cached_errors),
281 retractall(operation_cached_results(ID,_Operation,_,_)),
282 retractall(operation_computed(_,OpName,_,_,ID)). % can be expensive
283
284
285
286 com_op_update_max(_,check_invariant_violated(Nr),Operation,ProjState,NewState,PathInfo,_,Done) :- !,
287 NewState =[], PathInfo=invariant, Operation=Nr, % values not used anyway for invariants
288 %print(check_invariant(Nr)),nl, bmachine:b_nth1_non_ignored_invariant(Nr,Inv,_UsedIds), translate:print_bexpr(Inv),nl,
289 (b_interpreter:check_nth1_invariant(Nr,ProjState )
290 -> update_mutable(finished,Done) % will lead to failure above; we store only violations
291 ; % invariant violation found
292 update_mutable(last_sol_found,Done)
293 ).
294 com_op_update_max(_,OpName,Operation,ProjInOutState,NewState,PathInfo,MaxForCall,_) :-
295 % for CSP||B: clear out any parameters; otherwise we also need to hash the parameters
296 reset_max_reached(OpName),
297 succeed_max_call_id(OpName,
298 b_execute_top_level_operation_update(OpName,Operation,ProjInOutState,NewState,PathInfo),
299 MaxForCall).
300 % TO DO: normalise_store out state values, to avoid re-normalising when storing updates
301 com_op_update_max(NewID,OpName,_,_,_,_,_,Done) :-
302 (NewID \= uncached,
303 max_reached(OpName)
304 -> assertz(operation_cached_max_reached(NewID,OpName)) % store that we reached max. nr of transitions for this node
305 ; true %format('No Timeout or virtual timeout occurred during caching for ~w leading to ~w~n',[OpName,NewID])
306 ),
307 update_mutable(finished,Done).
308
309
310
311 % entry point to cache invariant checking
312 check_invariant_violated_cache(Nr,State) :-
313 %get_store_and_info(State,FullStore,Infos),
314 compute_operation_on_expanded_store_cache(check_invariant_violated(Nr),_,State,_,_,-1).
315
316 :- use_module(probsrc(specfile),[expand_const_and_vars_to_full_store/2]).
317 %get_store_and_info(expanded_const_and_vars(_ConstID,_Vars,E,Info),FullStore,Info) :- !, FullStore=E.
318 %get_store_and_info(expanded_vars(E,Info),FullStore,Info) :- !, FullStore=E.
319 %get_store_and_info(Store,FullStore,[]) :- expand_const_and_vars_to_full_store(Store,FullStore).
320
321 % -------------------------------
322
323
324 % check if caching is worthwhile for this operation
325 %worthwhile_to_cache(OpName) :-
326 % get_read_write_info(OpName,ReadVariables,WrittenVariables),
327 % length(ReadVariables,NrRV),
328 % bmachine:b_machine_statistics(variables,NrVars),
329 % bmachine:b_machine_statistics(constants,NrConstants),
330 % Perc is (NrRV*100) // (NrVars+NrConstants),
331 % length(WrittenVariables,NrWV),
332 % format('Analyzing ~w, ~w %, read: ~w, written: ~w, tot vars: ~w, tot cst: ~w~n (read: ~w)~n',[OpName,Perc,NrRV,NrWV,NrVars,NrConstants,ReadVariables]),
333 % Perc < 95. % maybe provide as preference
334
335 :- use_module(library(ordsets),[ord_member/2]).
336 %is_read(ReadVariables,bind(Var,_)) :- ord_member(Var,ReadVariables).
337 member_ord(List,X) :- ord_member(X,List). % for maplist, exclude,...
338
339 % -------------------------------
340
341 % a variation of split_list which also returns a list of predicate results
342 % with re_project_state(L,ProjVarsInOrder,A) : we can split another list using the same pattern
343
344 :- assert_must_succeed((b_operation_cache:project_state_onto_vars([bind(x,1),bind(y,2),bind(b,3)],[b,y],
345 ProjVars,ProjState,0,NrDel),
346 ProjVars == [y,b], ProjState == [bind(y,2),bind(b,3)], NrDel==1)).
347
348 project_state_onto_vars([],_,[],[],Acc,Acc).
349 project_state_onto_vars([Elem|Rest],ReadVariables,ProjVars,ProjState,NrDelAcc,NrDel) :-
350 Elem = bind(Var,_),
351 (ord_member(Var,ReadVariables) % TO DO: we could improve performance by sorting Elements
352 -> ProjVars=[Var|PT], ProjState=[Elem|AR], ND1=NrDelAcc
353 ; ProjVars=PT, ProjState=AR, ND1 is NrDelAcc+1),
354 project_state_onto_vars(Rest,ReadVariables,PT,AR,ND1,NrDel).
355
356
357 % -------------------------------
358
359 :- assert_must_succeed((b_operation_cache:re_project_state([y,b],[bind(x,1),bind(y,2),bind(b,3)],Res),
360 Res == [bind(y,2),bind(b,3)])).
361
362 % project state(VarsInOrder,State,ProjectedState)
363 % faster than project_state_onto_vars
364 re_project_state([],_,[]).
365 re_project_state([VarToProject|PT],[Elem|Rest],A) :-
366 arg(1,Elem,Var), %Elem = bind(Var,_),
367 (VarToProject==Var
368 -> A=[Elem|AR],re_project_state(PT,Rest,AR)
369 ; re_project_state2(VarToProject,PT,Rest,A)).
370
371 re_project_state2(VarToProject,PT,[Elem|Rest],A) :-
372 arg(1,Elem,Var), %Elem = bind(Var,_),
373 (VarToProject==Var
374 -> A=[Elem|AR],re_project_state(PT,Rest,AR)
375 ; re_project_state2(VarToProject,PT,Rest,A)).
376
377 % -----------------------------
378
379 % Two utilities to optionally generate lemma facts for fast projection
380 % Does not seem to be worth it
381
382 % abstract away values, can be used to generate pre-compiled facts
383 %abstract_state([],[]).
384 %abstract_state([bind(Var,_)|T],[bind(Var,_)|AT]) :- abstract_state(T,AT).
385
386 % abstract away unused bindings, can be used to generate pre-compiled facts
387 %clear_unused_bindings([],_,_) :- !.
388 %clear_unused_bindings([VarToProject|PT],[bind(Var,V)|T],[bind(Var,V)|RT]) :-
389 % % we could clear out Variable name Var; but this creates a danger of successfully matching an erroneous state
390 % VarToProject==Var,!,
391 % clear_unused_bindings(PT,T,RT).
392 %clear_unused_bindings(Vars,[_|T],[_|RT]) :- % leave slot in result as fresh var
393 % clear_unused_bindings(Vars,T,RT).
394
395 % -------------------------------
396
397 :- use_module(probsrc(state_packing)).
398
399 :- dynamic operation_computed/5, operation_cached_results/4,
400 operation_cached_max_reached/2, operation_cached_time_out/2, operation_cached_enum_warning/3,
401 op_guard_fails/3.
402
403 % return Hash and check if operation computed
404 % TO DO: do not hash constants if single value exists ?
405 check_if_operation_was_computed(OpName,ConstID,State,Skel,Infos,PackedValList,IsReadingCsts,
406 HashConstID,Hash,Res) :-
407 (Infos = [packed_state/PS|_]
408 -> get_packed_vars(PS,OpName,PackedState),
409 remove_bind_skeleton(PackedState,Skel,PackedValList)
410 % packing already performed in prepare_state_for_specfile_trans
411 ; perf_format('No packed state info for operation ~w and constants id ~w~n',[OpName,ConstID]),
412 % shouldn't happen hopefully
413 project_in_state(State,OpName,ProjectedInState), % State contains just variables
414 pack_bind_list(ProjectedInState,Skel,PackedValList)
415 ),
416 (IsReadingCsts = false -> HashConstID=root ; HashConstID=ConstID),
417 op_hash(OpName,HashConstID,PackedValList,Hash),
418 (operation_computed(Hash,OpName,HashConstID,PackedValList,ID)
419 -> Res = ID
420 ; % operation_guard_read_info(OpKey,GuardVars,_), re_project_state(GuardVars,Skel,PackedValList,GuardPackedVals)
421 % op_hash(OpName,HashConstID,GuardPackedVals,GuardHash), op_guard_fails(GuardHash,OpName,GuardPackedVals,ID) -> true
422 Res= false).
423
424 % project a state or packed value list onto the variables relevant for the guard (if it is a subset)
425 project_onto_guard(OpName,OpKey,HashConstID,Skel,PackedValList,GuardPackedVals,GuardHash) :-
426 operation_guard_read_info(OpKey,_,IgnoredVars),
427 remove_ignored_vars(IgnoredVars,Skel,PackedValList,GuardPackedVals),
428 op_hash(OpName,HashConstID,GuardPackedVals,GuardHash).
429
430
431 % remove_ignored_vars(VarsToIgnore,SkeletonList,ValueList,Result)
432 remove_ignored_vars([],_,PackedVals,Res) :- !, Res=PackedVals.
433 remove_ignored_vars([ID|T],[ID|ST],[_|PackedVals],GuardPackedVals) :- !,
434 remove_ignored_vars(T,ST,PackedVals,GuardPackedVals).
435 remove_ignored_vars(Ignored,[_|ST],[PV|PackedVals],[PV|GuardPackedVals]) :-
436 remove_ignored_vars(Ignored,ST,PackedVals,GuardPackedVals).
437
438 get_packed_vars(const_and_vars(_,Vars),OpName,PackedVars) :- !, project_in_state(Vars,OpName,PackedVars).
439 get_packed_vars(PS,OpName,PackedVars) :- project_in_state(PS,OpName,PackedVars).
440
441 :- use_module(probsrc(hashing),[my_term_hash/2, sdbm_term_hash/2]).
442
443 op_hash(OpName,HashConstID,PackedValList,Hash) :- get_preference(use_state_packing,false),!,
444 my_term_hash((OpName,HashConstID,PackedValList),Hash). % will user super_hash
445 op_hash(OpName,HashConstID,PackedValList,Hash) :-
446 % we use state packing and thus replace AVL sets by identifiers, ...: a simpler hash suffices, but we get collisions for Train1_Lukas_POR (which do not seem to matter); we get an improvement for ifm18/Ref5_Switch_mch.eventb
447 sdbm_term_hash((OpName,HashConstID,PackedValList),Hash).
448 % [range(smallint),algorithm(sdbm),depth(infinite),if_var(ignore)], % djb2
449
450
451 % remove bind/2 wrappers and variable name for faster hashing
452 remove_bind_skeleton([],[],R) :- !, R=[].
453 remove_bind_skeleton([bind(Var,Val)|T],[Var|VT],[Val|RT]) :- !,
454 remove_bind_skeleton(T,VT,RT).
455 remove_bind_skeleton(L,V,R) :- add_internal_error('Illegal store: ',remove_bind_skeleton(L,V,R)), R=L.
456
457 % we could also peel a few infos not useful for hashing:
458 %peel_val('$stored_avl_packed'(Nr),Nr).
459 %peel_val('$avl_bv'(Nr,_),Nr). % correct because if we use a bit_vector we will never also use stored_avl_packed for the same type
460
461
462 get_new_operation_computed_id(OpName,ConstID,PackedValList,Hash,ID) :-
463 inc_counter(op_cache_id,ID),
464 (OpName=check_invariant_violated(_) -> inc_counter(inv_cache_nr,_) ; true),
465 assertz(operation_computed(Hash,OpName,ConstID,PackedValList,ID)).
466 % To reduce memory consumption we could use the following clause:
467 % can be useful if there are many operations with a large number of projected variables
468 % but does lead to noticable slowdown when looking up operations
469 %get_new_operation_computed_id(OpName,ConstID,_PackedValList,Hash,[_,state_id/ReferenceStateID],ID) :- !,
470 % inc_counter(op_cache_id,ID),
471 % assertz(operation_computed(Hash,OpName,ConstID,ReferenceStateID,ID)). % storing reference ID preserves memory
472 % when looking up operation_was_computed we would need to do something like:
473 % state_space:packed_visited_expression(StoredState,PS),
474 % get_packed_b_state_with_uncompressed_lists(PS,PUS),
475 % get_state_infos(PUS,ConstID,PackedList,_,_),
476 % project_in_state(PackedList,OpName,ProjectedStoredState),
477 % remove_bind_skeleton(ProjectedStoredState,Skel,ProjectedValList),
478 % ProjectedValList = PackedValList
479
480
481 :- use_module(probsrc(runtime_profiler),[profile_failure_driven_loop/1]).
482 % this is used when get_preference(try_operation_reuse,true/full)
483 % it is only called for operations, not for setup_constants or initalise_machine
484
485 % treat expanded_const_and_vars(ConstID,Vars,FullStore,Infos)
486
487 get_state_infos(expanded_const_and_vars(ID,Vars,FullStore,I),ConstID,Vars,FullStore,Infos) :- !,ConstID=ID,Infos=I.
488 get_state_infos(expanded_vars(V,I),ConstID,Vars,FullStore,Infos) :- !, ConstID=root,Vars=V,FullStore=V,Infos=I.
489 get_state_infos(const_and_vars(ConstID,Vars),ConstID,Vars,FullStore,Infos) :- !,
490 add_warning(get_state_infos,'State not prepared for caching: ',const_and_vars(ConstID,Vars)),
491 Infos=[],
492 expand_const_and_vars_to_full_store(const_and_vars(ConstID,Vars),FullStore).
493 get_state_infos(csp_and_b(_,State),ConstID,Vars,FullStore,Infos) :- !,
494 get_state_infos(State,ConstID,Vars,FullStore,Infos).
495 get_state_infos(Vars,unknown,Vars,Vars,[]).
496
497 % InState is either already an expanded list or expanded_const_and_vars, expanded_vars
498 compute_operation_on_expanded_store_cache(OpName,Operation,InState,NewState,PathInfo,MaxForCall) :-
499 get_state_infos(InState,ConstID,Vars,FullStore,Infos), % extract infos from the store
500 % TO DO: check if state_id in Infos and if OpName in equivalence class with same proj. vars
501 get_opname_key(OpName,OpNameKey),
502 get_operation_read_projection_infos(OpNameKey,OpName,Vars,ProjVarsInOrder,IsReadingCsts,AdditionalOutVars),
503 \+ constants_not_identifiable(IsReadingCsts,ConstID), % otherwise: use uncached version below
504 !,
505 % tools_printing:print_term_summary(proj(OpName,ConstID,ProjInState,FullStore)),nl,
506 check_if_operation_was_computed(OpName,ConstID,Vars,ProjVarsInOrder,Infos,PackedValList,IsReadingCsts,
507 HashConstID,Hash,ID),
508 (ID \= false
509 -> % we can reuse the stored operation effect
510 %print('+'),
511 %hit_profiler:add_hit(operation_reused,OpName),
512 (inv_op_name(OpName) -> inc_counter(inv_cached_successes)
513 ; inc_counter(op_cached_successes)),
514 (operation_cached_results(ID,Operation,PackedNewState,PathInfo),
515 unpack_values(PackedNewState,NewState)
516 ; operation_cached_max_reached(ID,OpName), % we did not compute all operations
517 assert_max_reached(OpName),
518 fail
519 ; operation_cached_enum_warning(ID,OpName,Event),
520 functor(Event,Kind,_),
521 formatsilent('Regenerating ~w for ~w and cache id ~w~n',[Kind,OpName,ID]),
522 add_new_event_in_error_scope(Event),
523 fail
524 ; operation_cached_time_out(ID,OpName),
525 formatsilent('Rethrowing cached time_out for ~w and cache id ~w~n',[OpName,ID]),
526 % could be virtual time-out, exception or real timeout
527 %throw(time_out) % mimics real-time out, but needs to be caught by time_out/3
528 throw(enumeration_warning(operation_cache_timeout,OpName,'','',critical)) % virtual time-out
529 )
530 ; % we have not computed solutions for this operation for this projected state
531 (project_onto_guard(OpName,OpNameKey,HashConstID,ProjVarsInOrder,PackedValList,GuardPackedVals,GuardHash)
532 -> true
533 ; GuardPackedVals = none),
534 (nonvar(GuardHash),
535 op_guard_fails(GuardHash,OpName,GuardPackedVals)
536 -> % we did already compute this operation for this projected state and it failed
537 inc_counter(op_cached_failures),
538 fail % the guard is guaranteed to fail
539 ; % we have not yet computed this operation; compute it and store solutions as we go
540 get_new_operation_computed_id(OpName,HashConstID,PackedValList,Hash,NewID),
541 %print('-'),
542 %hit_profiler:add_hit(operation_cache_computation,OpName),
543 (IsReadingCsts=false
544 -> % TO DO: check if this projection is worthwhile
545 project_in_state_for_opname_key(Vars,OpNameKey,ProjInState),
546 % Note: if no packed_state this projection was already performed in check_if_operation_was_computed
547 add_new_vars(AdditionalOutVars,ProjInState,ProjInOutState)
548 ; ProjInOutState = FullStore % use full store with constants
549 ),
550 profile_failure_driven_loop(OpName),
551 if(api_compute_operation_update_max(NewID,OpName,Operation,ProjInOutState,NewState,PathInfo,MaxForCall),
552 (% Normalise here or in update_max
553 pack_values(NewState,PackedNewState),
554 (PathInfo=invariant -> StoredPathInfo=Hash
555 ; filter_transition_path_info(PathInfo,StoredPathInfo)),
556 assertz(operation_cached_results(NewID,Operation,PackedNewState,StoredPathInfo))
557 ),
558 ((nonvar(GuardHash),
559 \+ operation_cached_enum_warning(NewID,OpName,_), % the failure may be due to incomplete enumeration
560 operation_computed(Hash,OpName,_,_,NewID) % not invalidated due to an error
561 % only store the guard failure if it is genuine; op_guard_fails does not regenerate events
562 -> %print(op_guard_fails(GuardHash,OpName,GuardPackedVals)),nl,
563 assertz(op_guard_fails(GuardHash,OpName,GuardPackedVals))
564 ; true),
565 fail
566 )
567 )
568 )
569 % TO DO: if we have no successors for ID and if the operation reads less IDs in the guard
570 % we can replace remaining identifier values by a variable
571 ).
572 compute_operation_on_expanded_store_cache(OpName,Operation,InState,NewState,PathInfo,MaxForCall) :-
573 %hit_profiler:add_hit(operation_not_cached,OpName),
574 % operation is not cached
575 get_state_infos(InState,_,_,FullStore,_),
576 api_compute_operation_update_max_uncached(uncached,OpName,Operation,FullStore,NewState,PathInfo,MaxForCall).
577
578 % the constants are not part of the hash, only the ConstID; for states which contain constants and variables
579 % in a single list (e.g., created by ProB2's FindStateCommand) we have no ConstID and cannot use the cache
580 constants_not_identifiable(true,ConstID) :- (ConstID==root ; ConstID==unknown), !.
581
582 % add written vars which are not read virtually to state to avoid error messages in store_intermediate_updates:
583 add_new_vars([],S,S).
584 add_new_vars([WrittenVar|T],State,[bind(WrittenVar,term(undefined))|ST]) :-
585 add_new_vars(T,State,ST).
586
587 :- use_module(probsrc(state_space),[keep_transition_info/1]).
588 filter_transition_path_info([],R) :- !, R=[].
589 filter_transition_path_info([H|T],Res) :- !,
590 (keep_transition_info(H) -> Res = [H|RT]
591 ; Res=RT), % by default we filter out possibly large path infos (in particular for Event-B)
592 filter_transition_path_info(T,RT).
593 filter_transition_path_info(H,Res) :-
594 (keep_transition_info(H) -> Res = H ; Res=[]).
595
596
597 invariant_op_key(OpKey,InvNr) :- operation_read_projection_cache(OpKey,check_invariant_violated(InvNr),_,_,_).
598
599 print_violated_invariants :-
600 operation_cached_results(ID,Nr,[],Hash),number(Nr),
601 b_nth1_non_ignored_invariant(Nr,Invariant,_UsedIds),
602 format('Invariant ~w violated (op-cache-id ~w)~n ',[Nr,ID]),
603 translate:print_bexpr(Invariant),nl,
604 % now try and recover state where it was violated:
605 operation_computed(Hash,OpName,ConstID,PackedValList,ID),
606 operation_read_projection_cache(_,OpName,Skel,_,_),
607 unpack_bind_list(PackedValList,Skel,State), translate_bstate_limited(State,StateDesc),
608 format(' in state (ConstID ~w) ~w~n',[ConstID,StateDesc]),
609 fail.
610 print_violated_invariants.
611
612 % small utility code to analyze hash collisions:
613 % b_operation_cache:analyze_hash_collisions.
614 :- public analyze_hash_collisions/0.
615 analyze_hash_collisions :-
616 operation_computed(Hash,OpName,ConstID,State,ID),
617 operation_computed(Hash,OpName2,ConstID2,State2,ID2),
618 (ConstID @> ConstID2 -> true ; ConstID=ConstID2, ID2 > ID),
619 format('Hash collision: ~w~n ~w:~w:~w:~w~n ~w:~w:~w:~w~n~n',
620 [Hash,OpName,ConstID,State,ID,OpName2,ConstID2,State2,ID2]),
621 fail.
622 analyze_hash_collisions.
623
624 get_op_name(Nr,check_invariant_violated(Nr)) :- number(Nr),!.
625 get_op_name(Op,OpName) :- get_operation_name(Op,OpName).
626 get_nr_next_state_calls(OpName,Nr) :- findall(1,operation_computed(_Hash,OpName,_,_,_ID),Ls), length(Ls,Nr).
627 get_nr_cache_results(OpName,RNr) :-
628 findall(1,(operation_cached_results(_ID,Op,_,_),get_op_name(Op,OpName)),Rs), length(Rs,RNr).
629
630 :- use_module(probsrc(bmachine),[b_get_machine_variables/1, b_operation_reads_output_variables/3,
631 b_top_level_feasible_operation/1]).
632 % b_operation_cache:print_op_cache_profile
633
634 op_cache_useful(OpName,ReadLen,VLen) :-
635 b_get_machine_variables(Var),length(Var,VLen),
636 (get_preference(use_po,false), get_preference(try_operation_reuse_for_invariants,true)
637 -> true % also look for invariants which are projected
638 ; not_inv_op_name(OpName)), % use co-routine, otherwise cut will be executed
639 ? api_get_operation_read_write_info(OpName,ReadVariables,_ReadConstants,_WrittenVariables),
640 length(ReadVariables,ReadLen),
641 ReadLen < VLen,
642 % TODO: cf. check_all_variables_written -> if we project away only variables that are not written by any operation and deterministically initialised, this is not useful (see B/PerformanceTests/CommonSubexpressions/CSE_Test2.mch)
643 (inv_op_name(OpName) -> true ; b_top_level_feasible_operation(OpName)),
644 \+ b_operation_reads_output_variables(OpName,_,_), % see test 1787; operation caching cannot handle this
645 \+ specfile:max_operations_zero_for_operation(OpName). % execute by predicate fails if MAX_OPERATIONS(_OpName) == 0 is set (FIXME?). This check does not cover the case where MAX_OPERATION_OpName2 != 0 and op_cache_useful(OpName2,_,_).
646
647 check_if_op_cache_useful :-
648 op_cache_useful(OpName,ReadLen,VLen),
649 format('Operation reuse potentially useful: ~w reads ~w/~w variables~n',[OpName,ReadLen,VLen]),
650 fail.
651 check_if_op_cache_useful.
652
653 inv_op_name(check_invariant_violated(_)).
654
655 :- block not_inv_op_name(-).
656 not_inv_op_name(X) :- \+ inv_op_name(X).
657
658 print_op_cache_profile :- \+ operation_computed(_,_,_,_,_),!, % print nothing
659 (get_preference(try_operation_reuse,false)
660 -> format('OPERATION_REUSE preference set to FALSE~n',[])
661 ; true),
662 format('No operation cached (in memory) for OPERATION_REUSE~n',[]),
663 check_if_op_cache_useful.
664 print_op_cache_profile :-
665 b_get_machine_variables(Var),length(Var,VLen),
666 operation_read_projection_cache(OpKey,OpName,ProjVars,_,WV), (ProjVars = [] ; ProjVars = [_|_]),
667 length(ProjVars,Len),
668 operation_read_constants(OpKey,ReadConstants),
669 (operation_guard_read_info(OpKey,_,IrrelevantVars)
670 -> format('Operation ~w cached onto ~w/~w variables: ~w (not relevant for guard: ~w, only written: ~w, constants read: ~w)~n',[OpName,Len,VLen,ProjVars,IrrelevantVars,WV,ReadConstants])
671 ; format('Operation ~w cached onto ~w/~w variables: ~w (only written: ~w, constants read: ~w)~n',[OpName,Len,VLen,ProjVars,WV,ReadConstants])
672 ),fail.
673 print_op_cache_profile :- findall(OpName,operation_read_projection_cache(_,OpName,no_caching,_,_),Ls),
674 format('Operations not cached: ~w~n',[Ls]),fail.
675 print_op_cache_profile :- operation_read_projection_cache(OpKey,OpName,ProjVars,_,_), ProjVars = [_|_],
676 get_nr_next_state_calls(OpName,Nr),
677 get_nr_cache_results(OpName,RNr),
678 (inv_op_name(OpName) -> Results='violations' ; Results = 'results'),
679 format('Next-state-calls for ~w: ~w (~w ~w)~n',[OpName,Nr,RNr,Results]),
680 operation_guard_read_info(OpKey,RelVars,_),
681 findall(1,op_guard_fails(_,OpName,_),Fails), length(Fails,NrFails),
682 format(' projected-failures (on ~w): ~w~n',[RelVars,NrFails]),
683 fail.
684 print_op_cache_profile :-
685 get_total_number_of_next_state_calls(Nr,InvNr),
686 format('Total Number of Next-state-calls for Operations: ~w~n',[Nr]),
687 get_counter(op_cached_failures,FailCalls),
688 format(' - Reused guard failures: ~w~n',[FailCalls]),
689 get_counter(op_cached_successes,SuccCalls),
690 format(' - Reused successful operation call results: ~w~n',[SuccCalls]),
691 format('Total Number of Invariant-check-calls: ~w~n',[InvNr]),
692 get_counter(inv_cached_successes,SuccInvCalls),
693 format(' - Reused invariant check results: ~w~n',[SuccInvCalls]),
694 get_counter(op_cached_errors,Errs),
695 format('Errors during calls: ~w~n',[Errs]),
696 get_counter(op_cached_timeouts,Timeouts),
697 format('Timeouts during calls: ~w~n',[Timeouts]),
698 get_counter(op_cached_enum_warnings,EnumWarns),
699 format('Enumeration warnings during calls: ~w~n',[EnumWarns]),
700 fail.
701 print_op_cache_profile :- debug_mode(on), nl,
702 operation_read_projection_cache(_,OpName,Skel,_,_),
703 format('~n** Local Operation Cache Info for ~w ** (projected on ~w):~n',[OpName,Skel]),
704 operation_computed(_Hash,OpName,ConstID,PackedValList,ID),
705 (operation_cached_max_reached(ID,OpName) -> MaxR='(max reached, not all transitions computed)'
706 ; MaxR=''),
707 format('~nNode ID = ~w, Operation = ~w ~w~n',[ID,OpName,MaxR]),
708 unpack_bind_list(PackedValList,Skel,State), translate_bstate_limited(State,NodeDesc),
709 format(' projected state : (ConstID ~w) ~w~n',[ConstID,NodeDesc]),
710 operation_cached_results(ID,Operation,PackedNewState,_PathInfo),
711 translate_event_with_limit(Operation,100,OpStr),
712 unpack_values(PackedNewState,NewState), translate:translate_bstate_limited(NewState,UpdateStr),
713 format(' ~w -upd-> ~w~n',[OpStr,UpdateStr]),
714 fail.
715 print_op_cache_profile :- print_violated_invariants,fail.
716 print_op_cache_profile :- (debug_mode(on) -> analyze_hash_collisions,print('----------'),nl ; true).
717
718 get_total_number_of_next_state_calls(OpNr,InvNr) :-
719 get_counter(op_cache_id,TotNr),
720 get_counter(inv_cache_nr,InvNr),
721 OpNr is TotNr-InvNr.
722 %findall(0,b_operation_cache:operation_computed(_Hash,_Op,_,_,_ID),Ls), length(Ls,Nr).
723
724 get_op_cache_stats([next_state_calls-NrN, % actual calls to the B interpreter to compute next state
725 operations_cached-NrC, % number of operations whose calls are cached
726 invariants_cached-NrI, % number of invariants whose evaluation is cached
727 next_state_guard_failures-NrFails, % number of next-state_call failures stored (disabled operation)
728 reused_next_state_calls-SuccCalls,
729 reused_next_state_failures-FailCalls,
730 inv_check_calls-InvNr, % actual calls to check individual invariants in a state
731 reused_inv_check_calls-SuccInvCalls
732 ]) :-
733 findall(OpKey,(operation_read_projection_cache(OpKey,OpName,_,_,_),atomic(OpName)),OK1),
734 length(OK1,NrC),
735 findall(OpKey,invariant_op_key(OpKey,_),OK2),
736 length(OK2,NrI),
737 findall(OpKey,(op_guard_fails(OpKey,_,_)),OK3),
738 length(OK3,NrFails),
739 get_total_number_of_next_state_calls(NrN,InvNr),
740 get_counter(op_cached_failures,FailCalls),
741 get_counter(op_cached_successes,SuccCalls),
742 get_counter(inv_cached_successes,SuccInvCalls).
743
744 % ----------------------
745
746 :- use_module(probsrc(tools_strings),[ajoin/2]).
747 tcltk_op_cache_stats(list([list(['Operation','#Next-State', '#Results',
748 '# Proj.Vars','Proj.Vars', 'ReadCsts', 'OnlyWritten'])|SEntries])) :-
749 %b_get_machine_variables(Var),length(Var,VLen),
750 findall(list([OP,NrCalls,RNr,NrProjVars,ProjVars,ReadConstants,AdditionalOutVars]),
751 (operation_read_projection_cache(OpKey,OpName,ProjVars,_,AdditionalOutVars),
752 (OpName = check_invariant_violated(Nr) -> ajoin(['Invariant',Nr],OP) ; OP=OpName),
753 length(ProjVars,NrProjVars),
754 operation_read_constants(OpKey,ReadConstants),
755 get_nr_next_state_calls(OpName,NrCalls),
756 get_nr_cache_results(OpName,RNr)
757 ), Entries), sort(Entries,SEntries).
758
759 % ----------------------
760 % DOT RENDERING (not yet finished)
761
762 %op_cache_node(ID,OpName,NodeDesc,Shape,Style,Color) :- Shape=box, Style=solid, Color=blue,
763 % operation_computed(_Hash,OpName,_,PackedState,ID),
764 % unpack_values(PackedState,State), translate_bstate_limited(State,NodeDesc).
765 %:- use_module(probsrc(dotsrc(dot_graph_generator)),[gen_dot_graph/3]).
766 % Predicates for creating a dependency graph
767 %tcltk_operation_cache_graph(File) :- gen_dot_graph(File,op_cache_node,cbc_dependence_trans_predicate).
768