1 % (c) 2009-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(enabling_analysis,[reset_enabling_analysis/0,
6 tcltk_cbc_cfg_analysis/1, tcltk_dot_cfg_analysis/1,
7 tcltk_cbc_enabling_analysis/1, tcltk_cbc_enabling_analysis/2,
8 tcltk_cbc_enabling_relations_for_operation/3,
9 tcltk_cbc_enabling_relations_after_operation/3, compute_cbc_enable_rel/4,
10 tcltk_cbc_simultaneous_enabling_analysis/1,
11 tcltk_cbc_dependence_analysis/1, print_enable_table/1,
12 eop_node_predicate/6,init_or_op/1,
13 enabling_dot_graph_attrs/2, enabling_dot_node/4, enabling_dot_edge_attrs/4,
14 feasible_operation/2, feasible_operation_with_timeout/3,
15 check_if_feasible_operation/5,
16 feasible_operation_cache/2,infeasible_operation/1, infeasible_operation_cache/1,
17 cbc_enable_analysis/4,
18 is_timeout_enabling_result/1,
19 translate_enable_res/6,
20 operation_sequence_possible/3, operation_can_be_enabled_by/4,
21 partition_predicate/4,
22 cbc_enable_analysis_cache/4 % for prologTasks
23 ]).
24
25 :- use_module(probsrc(module_information),[module_info/2]).
26 :- module_info(group,cbc).
27 :- module_info(description,'This module computes enabling relations for B operations.').
28 % --------------
29
30 :- use_module(probporsrc(static_analysis), [action_dependent_to_itself/4, get_conj_inv_predicate/3, is_timeout/1]).
31 :- use_module(probsrc(bmachine), [b_top_level_operation/1]).
32 :- use_module(probsrc(b_state_model_check),[get_negated_guard/3,get_negated_guard/4]).
33 :- use_module(library(lists)).
34 :- use_module(probsrc(error_manager)).
35 :- use_module(probsrc(debug)).
36 :- use_module(probsrc(bsyntaxtree), [conjunct_predicates/2]).
37 :- use_module(probsrc(translate), [translate_bexpression/2, translate_bexpression_with_limit/3]).
38 :- use_module(probsrc(b_read_write_info),
39 [b_get_read_write/3,b_get_read_write_vars/5, b_get_operation_read_guard_vars/4]).
40 :- use_module(probsrc(static_enabling_analysis),[static_cannot_enable/2, vars_ord_intersect/2]).
41 :- use_module(cbcsrc(cbc_path_solver), [testcase_path_timeout_catch/9]).
42 :- use_module(probsrc(tools),[ajoin/2,start_ms_timer/1,stop_ms_timer_with_debug_msg/2]).
43
44 % -------------------- BINARY STATIC ANALYSIS -------------------------
45
46 % certain static analyses used by CBC Test case generation
47
48 % return Res=impossible if from Invariant we can never execute OpName1 followed by OpName2
49 % is used by sap:check_operation_sequence_possible
50 operation_sequence_possible(OpName1,OpName2,Res) :-
51 static_cannot_enable(OpName1,OpName2), %\+ static_activation_dependent(OpName1,OpName2),
52 !,
53 Res = activation_independent.
54 operation_sequence_possible(OpName1,OpName2,Res) :-
55 % we assume OpName2 is feasible on its own
56 get_negated_guard(OpName2,PosGuard2,_NegGuard2),
57 Timeout1 = 200,
58 % print('Guard: '),translate:print_bexpr(PosGuard2),nl,
59 (testcase_path_timeout_catch(invariant,Timeout1,[OpName1],PosGuard2,_Csts,_Ops,_TestS,_TI,Res)
60 -> true
61 ; Res = impossible
62 ).
63
64
65 % return whether OpName1 can enable a previously disabled OpName2
66 operation_can_be_enabled_by(OpName1,OpName2,TIMEOUT,Res) :-
67 b_top_level_operation(OpName1),
68 b_get_read_write(OpName1,_Reads1,Writes1),
69 b_top_level_operation(OpName2),
70 formatsilent("~nCHECKING if ~w (~w) can enable ~w~n",[OpName1,Writes1,OpName2]),
71 \+ static_cannot_enable(OpName1,OpName2),
72 get_negated_guard(OpName2,PosGuard2,_NegGuard2),
73 filter_predicate(PosGuard2,Writes1,FilteredPosGuard2),
74 create_negation(FilteredPosGuard2,FilteredNegGuard2),
75 % TIMEOUT used to be hardwired to 500
76 % print('Before: '), translate:print_bexpr(FilteredNegGuard2),nl,print('After: '), translate:print_bexpr(PosGuard2),nl,
77 testcase_path_timeout_catch(pred(FilteredNegGuard2),TIMEOUT,[OpName1],PosGuard2,_,_,_,_,Res),
78 println_silent(can_be_enabled_result(Res)).
79
80
81
82 % -------------------- CFG ANALYSIS -------------------------
83 :- use_module(dotsrc(dot_graph_generator), [gen_dot_graph/6, use_new_dot_attr_pred/7, dot_no_same_rank/1, dot_no_subgraph/3]).
84 tcltk_dot_cfg_analysis(File) :-
85 enabling_dot_graph_attrs('control flow graph',GraphAttrs),
86 gen_dot_graph(File,GraphAttrs,
87 use_new_dot_attr_pred(enabling_analysis:enabling_dot_node(with_init)),
88 use_new_dot_attr_pred(enabling_analysis:cfg_dot_edge),
89 dot_no_same_rank,dot_no_subgraph).
90
91 :- public cfg_dot_edge/3.
92 cfg_dot_edge(NodeID,SuccID,Attrs) :-
93 cbc_quick_cfg_analysis(NodeID,SuccID,Res),
94 cfg_res_kind(Res,NodeID,SuccID,Kind),
95 enabling_dot_edge_kind_attrs(Kind,Attrs).
96
97 cfg_res_kind(cannot_enable,_,_,_) :- !, fail.
98 cfg_res_kind(syntactic_independent,X,Y,independent) :- !,X=Y. % only show if source & dest identical
99 cfg_res_kind(race_dependent,X,Y,race_independent) :- !,X=Y. % only show if source & dest identical
100 cfg_res_kind(possible,_,_,can_enable) :- !.
101 cfg_res_kind(timeout_possible,_,_,timeout(can_enable)) :- !.
102 cfg_res_kind(X,_,_,unknown(X)).
103
104 :- use_module(probsrc(preferences),[get_preference/2]).
105 op_node_predicate(NodeID,SubGraph,NodeDesc,Shape,Style,Color) :-
106 get_preference(dot_enabling_show_readwrites,false), !,
107 SubGraph=none, Shape=box, Style=none,
108 b_top_level_operation(Op), NodeID = Op, NodeDesc=Op, Color=blue.
109 op_node_predicate(NodeID,SubGraph,NodeDesc,Shape,Style,Color) :- SubGraph=none,
110 Shape=record, Style=none,
111 b_top_level_operation(Op), NodeID = Op,
112 %NodeDesc = NodeID,
113 b_get_read_write(Op,Reads2,Writes1),
114 b_get_operation_read_guard_vars(Op,false,ReadsGrd,_Precise),
115 insert_commas(ReadsGrd,0,R1), insert_commas(Reads2,0,R2), insert_commas(Writes1,0,W1),
116 append(W1,['}|'],W2),
117 append(R1,['\\n|reads: '|R2],Reads),
118 append(Reads,['\\n|writes: '|W2],As),
119 ajoin(['|{',Op,'\\n|reads (guard): '|As],NodeDesc),
120 Color=blue.
121
122 insert_commas('$all',_,['ALL']).
123 insert_commas([],_,[]).
124 insert_commas([H],_,R) :- !, R=[H].
125 insert_commas([H|T],N,[H,Sep|IT]) :-
126 (N>5 -> N1=0, Sep=',\\n' ; N1 is N+1, Sep=', '),
127 insert_commas(T,N1,IT).
128
129 % compute a Control Flow Graph very quickly
130 % ideal when we have program counter style variables
131 tcltk_cbc_cfg_analysis(list([list(['Origin'|SOps])|Result])) :-
132 findall(Op, b_top_level_operation(Op), Ops), sort(Ops,SOps),
133 findall(list([OpName1|EnableList]),
134 (b_get_sorted_op(OpName1),
135 findall(Possible,cbc_quick_cfg_analysis(OpName1,_OpName2,Possible),EnableList)),
136 Result),
137 print_enable_table([list(['Origin'|Ops])|Result]).
138
139 /* TO DO: complete into a determinacy analysis ?
140 cbc_quick_det_analysis(OpName1,OpName2,Res) :-
141 b_top_level_operation(OpName1), % top_level
142 ((b_get_sorted_op(OpName2), OpName2 \= OpName1,
143 % get_negated_guard(OpName1,PosGuard1,NegGuard1),
144 get_negated_guard(OpName2,PosGuard2,NegGuard2),
145 testcase_path_timeout(pred(PosGuard2),1200,[OpName1],b(truth,pred,[]),_,_,_,_,Res))
146 -> format(user_output,'Operation ~w can be simultaneously enabled with ~w (~w).~n',[OpName1,OpName2,Res])
147 ; format(user_output,'Operation ~w cannot be simultanously enabled with another operation.~n',[OpName1]), Res=det
148 ).
149 */
150
151 cbc_quick_cfg_analysis(OpName1,OpName2,Res) :-
152 OpName1='INITIALISATION',
153 b_top_level_operation(OpName2),
154 b_get_read_write(OpName2,Reads2,Writes2),
155 formatsilent(user_output,"COMPUTING CFG: INITIALISATION --> ~w r:~w / w:~w~n~n",
156 [OpName2,Reads2,Writes2]),
157 ( testcase_path_timeout_catch(init,250,[OpName2],b(truth,pred,[]),_Constants,_Ops,_TestS,_TI,R1)
158 -> formatsilent(user_output," ~w can be enabled by ~w (~w)!~n",[OpName2,OpName1,R1]),
159 (is_timeout(R1) -> Res=timeout_possible; Res = possible)
160 ; formatsilent(user_output," ~w cannot be enabled by ~w!~n",[OpName2,OpName1]),
161 Res = cannot_enable
162 ).
163 cbc_quick_cfg_analysis(OpName1,OpName2,Res) :-
164 b_top_level_operation(OpName1), % top_level
165 b_get_read_write(OpName1,Reads1,Writes1),
166 %get_negated_guard(OpName1,PosGuard1,NegGuard1),
167 b_get_sorted_op(OpName2),
168 (b_get_read_write(OpName2,Reads2,Writes2),
169 formatsilent(user_output,"COMPUTING CFG: ~w r:~w / w:~w --> ~w r:~w / w:~w~n~n",
170 [OpName1,Reads1,Writes1,OpName2,Reads2,Writes2]),
171 (\+ vars_ord_intersect(Writes1,Reads2)
172 -> (vars_ord_intersect(Writes1,Writes2)
173 -> Res = race_dependent, formatsilent(user_output," ~w cannot be enabled/disabled by ~w!~n",[OpName2,OpName1])
174 ; Res = syntactic_independent, formatsilent(user_output," ~w cannot be enabled/disabled/modified by ~w!~n",[OpName2,OpName1])
175 )
176 ; get_negated_guard(OpName2,PosGuard2,NegGuard2),
177 garbage_collect,
178 print('Guard: '), translate:print_bexpr(PosGuard2),nl,
179 ((testcase_path_timeout_catch(typing(NegGuard2),60,[OpName1],PosGuard2,_,_,_,_,_R0), % quick check without invariants & properties
180 % TO DO: project constants, variables onto the ones really needed
181 testcase_path_timeout_catch(pred(NegGuard2),250,[OpName1],PosGuard2,_Constants,_Ops,_TestS,_TI,R1))
182 -> formatsilent(user_output," ~w can be enabled by ~w (~w)!~n",[OpName2,OpName1,R1]),
183 (is_timeout(R1) -> Res=timeout_possible; Res = possible)
184 ; formatsilent(user_output," ~w cannot be enabled by ~w!~n",[OpName2,OpName1]),
185 Res = cannot_enable)
186 )
187 ).
188
189 %use_module(enabling_analysis),enabling_analysis:cbc_quick_cfg_analysis('SEQUENCER2','SEQUENCER3',Res).
190 %use_module(cbcsrc(sap)),use_module(enabling_analysis),enabling_analysis:cbc_quick_cfg_analysis('COMPUTE_SDDBs_points','prop_COMPUTE_0',Res).
191 %use_module(cbcsrc(sap)),use_module(enabling_analysis),enabling_analysis:cbc_quick_cfg_analysis('COMPUTE_SDDBs_points','COMPUTE_SDDBs_length',Res).
192
193 % -------------------- DEPENDENCE ANALYSIS ----------------------
194 /*
195
196 Independency between two actions in a B/Event-B model can be expressed also by means of LTL-formulas:
197 1. Two actions a and b are independent if the following LTL-formula is satisfied by the model:
198 "G ((e(b) & [a] => X e(b)) & (e(a) & [b] => X e(a)))" (ind)
199 2. If (ind) is violated by the model then a and b are dependent actions.
200
201 Note: The race_dependent condition cannot be covered by the above LTL-formula. If two actions are race dependent, but never simultaniously enabled in a state
202 from the state space, then (ind) will be satisfied.
203
204 */
205
206 tcltk_cbc_dependence_analysis(list([list(['Origin'|SOps])|Result])) :-
207 %findall(Op, b_get_machine_operation(Op,_,_,_), Ops), sort(Ops,SOps),
208 findall(Op, b_top_level_operation(Op), Ops), sort(Ops,SOps),
209 findall(list([OpName1|EnableList]),
210 (b_get_sorted_op(OpName1),
211 findall(Enable,cbc_dependence_analysis(OpName1,_OpName2,Enable),EnableList)),
212 Result).
213 %,print_enable_table([list(['Origin'|Ops])|Result]).
214
215 b_get_sorted_op(Op) :- findall(Op, b_top_level_operation(Op), Ops),
216 sort(Ops,SOps), member(Op,SOps).
217
218 cbc_dependence_analysis(OpName1,OpName2,Res) :-
219 b_top_level_operation(OpName1),
220 b_get_read_write_vars(OpName1,GReads1,AReads1,Reads1,Writes1),
221 b_get_sorted_op(OpName2),
222 (OpName1=OpName2 -> action_dependent_to_itself(OpName1,GReads1,Writes1,Res) % TO DO: check if it is possible that for two different parameter values of the same event there is dependence
223 ; OpName2 @< OpName1 -> Res = '-' % our checking is symmetric; only check one pair
224 ;
225 b_get_read_write_vars(OpName2,GReads2,AReads2,Reads2,Writes2),
226 formatsilent("CHECKING DEPENDENCE: ~w gr:~w / ar:~w / w:~w <--> ~w gr:~w / ar:~w / w:~w~n",[OpName1,GReads1,AReads1,Writes1,OpName2,GReads2,AReads2,Writes2]),
227 ( syntactical_independence(Reads1,Writes1,Reads2,Writes2) -> Res = syntactic_independent
228 ; vars_ord_intersect(Writes1,Writes2) -> Res = race_dependent
229 ; (vars_ord_intersect(AReads1,Writes2);vars_ord_intersect(AReads2,Writes1)) -> Res = race_dependent
230 % TO DO: in this case check if there is indeed a race dependence (e.g. in scheduler new and ready_active are actually independent !)
231 % Set up [OpName1,OpName2], [OpName2,OpName1] and see if for ord_intersect(Writes1,Writes2) we can find different values
232 ;
233 % get constraints for G_{Op_1} \leadsto{Op_2} not(G_{Op_1})
234 get_negated_guard(OpName1,PosGuard1,NegGuard1),
235 get_conj_inv_predicate([NegGuard1],1,NegGuard1_Inv),
236 % get constraints for G_{Op_2} \leadsto{Op_1} not(G_{Op_2})
237 get_negated_guard(OpName2,PosGuard2,NegGuard2),
238 get_conj_inv_predicate([NegGuard2],1,NegGuard2_Inv),
239 conjunct_predicates([PosGuard1,PosGuard2],GuardsConj),
240 (vars_ord_intersect(GReads1,Writes2),
241 testcase_path_timeout_catch(pred(GuardsConj),500,[OpName2],NegGuard1_Inv,_Constants,_Ops,_TestS,_TI,R1)
242 -> formatsilent(" ~w may disable ~w (~w)!~n",[OpName2,OpName1,R1]),
243 (is_timeout(R1) -> Res=timeout_dependent; Res = dependent)
244 ; (vars_ord_intersect(GReads2,Writes1),
245 testcase_path_timeout_catch(pred(GuardsConj),500,[OpName1],NegGuard2_Inv,_,_,_,_,R2))
246 -> formatsilent(" ~w may disable ~w (~w)!~n",[OpName1,OpName2,R2]),
247 (is_timeout(R2) -> Res=timeout_dependent; Res = dependent)
248 ; Res = independent))).
249
250 syntactical_independence(Reads1,Writes1,Reads2,Writes2) :-
251 \+ vars_ord_intersect(Writes1,Reads2), % op1 does not modify guard/effect of op2
252 \+ vars_ord_intersect(Writes2,Reads1), % op2 does not modify guard/effect of op1
253 \+ vars_ord_intersect(Writes1,Writes2). % no race condition
254
255 % -------------- ENABLING ANALYSIS --------------
256
257 :- dynamic cbc_enable_analysis_cache/4.
258
259 % check which operations can be enabled after executing another operation
260 % to do: move maybe to another module; provide proper CSV export using Sebastian's modules
261 cbc_enable_analysis(OpName1,OpName2,Enable,ExtraTimeout) :-
262 init_or_op(OpName1),
263 if(cbc_enable_analysis_cache(OpName1,OpName2,Result,ExtraTimeout),
264 Result = Enable, % already computed
265 (% now compute all enablings form OpName1
266 cbc_enable_analysis_calc(OpName1,Op2,R,ExtraTimeout),
267 assertz(cbc_enable_analysis_cache(OpName1,Op2,R,ExtraTimeout)),
268 fail
269 ;
270 % now look up:
271 cbc_enable_analysis_cache(OpName1,OpName2,Enable,ExtraTimeout)
272 )).
273
274
275 cbc_enable_analysis_calc(OpName1,OpName2,Enable,ExtraTimeout) :-
276 OpName1='INITIALISATION',printsilent('CHECKING ENABLING AFTER INITIALISATION'),nls,
277 b_top_level_operation(OpName2),
278 printsilent('INITIALISATION'), printsilent(' ---> '), printsilent(OpName2), printsilent(' :: '),
279 add_to_time_out(ExtraTimeout,200,Timeout),
280 ( testcase_path_timeout_catch(init,Timeout,[OpName2],b(truth,pred,[]),_Constants,_Ops,_TestS,_TI,R)
281 -> printsilent(R), printsilent(' : '),
282 get_negated_guard(OpName2,_,NegGuard),
283 (testcase_path_timeout_catch(init,Timeout,[],NegGuard,_Constants2,_Ops2,_TestS2,_TI2,R2)
284 -> printsilent(R2), printsilent(' : '),Enable=possible
285 ; Enable=guaranteed)
286 ; Enable=impossible),
287 printsilent(Enable),nls.
288 cbc_enable_analysis_calc(OpName1,OpName2,Enable,ExtraTimeout) :-
289 b_top_level_operation(OpName1),
290 b_get_read_write(OpName1,Reads1,Writes1),
291 %b_get_operation_read_guard_vars(OpName1,true,Reads1,_Precise),
292 %get_negated_guard(OpName1,PosGuard1,_NegGuard1),
293 formatsilent("CHECKING ENABLING AFTER: ~w r:~w / w:~w~n",[OpName1,Reads1,Writes1]),
294 b_top_level_operation(OpName2),
295 formatsilent('~w ---> ~w :: ',[OpName1,OpName2]),
296 cbc_enable_calc_aux(OpName1,Writes1,OpName2,Enable,ExtraTimeout),
297 formatsilent('Enable=~w~n',[Enable]).
298
299 :- use_module(probporsrc(static_analysis),[syntactic_independence/3]).
300 cbc_enable_calc_aux(OpName1,_Writes1,_OpName2,Enable,ExtraTimeout) :-
301 (ExtraTimeout>500 -> infeasible_operation(OpName1)
302 ; infeasible_operation_cache(OpName1)), % only check cached version
303 !,
304 Enable=infeasible.
305 cbc_enable_calc_aux(_OpName1,_Writes1,OpName2,Enable,ExtraTimeout) :-
306 (ExtraTimeout>500 -> infeasible_operation(OpName2)
307 ; infeasible_operation_cache(OpName2)), % only check cached version
308 !,
309 Enable=impossible_infeasible.
310 cbc_enable_calc_aux(OpName1,_Writes1,OpName2,Enable,_) :-
311 % first check if we can syntactically determine independence
312 syntactic_independence(OpName1,OpName2,Res),
313 !,
314 Enable=Res.
315 cbc_enable_calc_aux(OpName1,Writes1,OpName2,Enable,ExtraTimeout) :-
316 % now we do the semantic checks
317 add_to_time_out(ExtraTimeout,200,Timeout1),
318 add_to_time_out(ExtraTimeout,300,Timeout2),
319
320 get_negated_guard(OpName2,PosGuard2,NegGuard2),
321 filter_predicate(PosGuard2,Writes1,FilteredPosGuard2),
322 create_negation(FilteredPosGuard2,FilteredNegGuard2),
323 cbc_enable_calc_aux2(OpName1,OpName2,Enable,Timeout1,Timeout2,PosGuard2,NegGuard2,FilteredNegGuard2).
324 % TO DO: return timeout results and compute timeout info here
325
326
327 cbc_enable_calc_aux2(OpName1,OpName2,Enable,Timeout1,Timeout2,PosGuard2,NegGuard2,FilteredNegGuard2) :-
328 %format('Check if ~w can be enabled after ~w ~n',[OpName2,OpName1]),
329 %print(' Pos Guard: '),translate:print_bexpr(PosGuard2),nl,
330 %((OpName1=winc,OpName2=winc) -> trace ; true),
331 testcase_path_timeout_catch(invariant,Timeout1,[OpName1],PosGuard2,_Csts,_Ops,_TestS,_TI,R), % advantage over version with [OpName1,OpName2] : one less state to setup and enumerate; but inner guards may not be checked
332 !,
333 printsilent(can_be_enabled_after(R)), printsilent(' : '),
334 % print('Neg Guard: '),translate:print_bexpr(NegGuard2),nl,
335 % TO DO: first check whether OpName2 can be disabled given Invariant ?
336 (testcase_path_timeout_catch(invariant,Timeout1,[OpName1],NegGuard2,_Csts2,_Ops2,_TestS2,_TI2,R2)
337 -> printsilent(can_be_disabled_after(R2)), printsilent(' : '),
338 % TO DO: test if NegGuard2 holds initially it is possible to execute [OpName1,OpName2]; if not: OpName1 cannot enable OpName2, only keep it -> Enable=keep_possible
339 % then we could check if OpName1 can disable OpName2: PosGuard2,[OpName1],NegGuard2
340 (OpName1\=OpName2, % otherwise OpName2 must be enabled if [OpName1] can be executed
341 %testcase_path_timeout_catch(pred(NegGuard2),Timeout2,[OpName1,OpName2],b(truth,pred,[]),_,_,_,_,R3)
342 testcase_path_timeout_catch(pred(NegGuard2),Timeout2,[OpName1],PosGuard2,_,_,_,_,R3)
343 -> printsilent(can_enable(R3)), printsilent(' : '),
344 %nl, translate:print_bexpr(PosGuard2),nl,print(OpName1),nl,translate:print_bexpr(NegGuard2),nl,
345 %print('FILTERED: '), translate:print_bexpr(FilteredNegGuard2),nl,
346 (testcase_path_timeout_catch(pred(PosGuard2),Timeout2,[OpName1],FilteredNegGuard2,_,_,_,_,R4)
347 -> printsilent(can_disable(R4)), printsilent(' : '),
348 (contains_timeout([R,R2,R3,R4]) -> Enable=timeout_possible ; Enable=possible)
349 ; printsilent('cannot_disable : '),
350 (contains_timeout([R,R2,R3]) -> Enable=timeout_possible_enable ; Enable=possible_enable) /* Opname cannot disable OpName2; only enable it */
351 )
352 ; /* OpName1 cannot enable OpName2; only preserve it */
353 printsilent('cannot_enable : '),
354 (testcase_path_timeout_catch(pred(PosGuard2),Timeout2,[OpName1],FilteredNegGuard2,_,_,_,_,R4)
355 -> printsilent(can_disable(R4)), printsilent(' : '),
356 (contains_timeout([R,R2,R4]) -> Enable=timeout_possible_disable; Enable=possible_disable)
357 ; (contains_timeout([R,R2]) -> Enable=timeout_keep; Enable=keep) /* Opname cannot enable or disable */
358 )
359 )
360 ; (is_timeout(R) -> Enable=timeout_guaranteed; Enable=guaranteed)
361 ).
362 cbc_enable_calc_aux2(OpName1,_OpName2,Enable,_Timeout1,Timeout2,PosGuard2,_NegGuard2,FilteredNegGuard2) :-
363 % OpName2 can never be enabled after OpName1; check whether it can be enabled before
364 % Note: we could replace FilteredNegGuard2 by truth
365 testcase_path_timeout_catch(pred(PosGuard2),Timeout2,[OpName1],FilteredNegGuard2,_,_,_,_,R4),
366 !,
367 printsilent(can_disable(R4)), printsilent(' : '),
368 (is_timeout(R4) -> Enable=timeout_impossible; Enable=impossible).
369 cbc_enable_calc_aux2(_OpName1,_OpName2,Enable,_,_,_PosGuard2,_NegGuard2,_FilteredNegGuard2) :-
370 % OpName2 can never ben enabled after nor before
371 Enable=impossible_keep.
372
373
374 % check if contains timeout or similar result
375 contains_timeout(List) :- (member(timeout,List) -> true ; member(clpfd_overflow,List) -> true).
376
377
378 :- use_module(probsrc(bsyntaxtree),[conjunction_to_list/2,some_id_occurs_in_expr/2,create_negation/2]).
379 % remove all predicates which are not modified
380 filter_predicate(Pred,ModifiedVars,FilteredPred) :- partition_predicate(Pred,ModifiedVars,FilteredPred,_).
381
382 % partition all predicates into those which are not modified and those that can be
383 partition_predicate(Pred,Var,FilteredPred,Rest) :- var(Var),!,
384 add_internal_error('Missing write variables:',partition_predicate(Pred,Var,FilteredPred,Rest)),
385 partition_predicate(Pred,'$all',FilteredPred,Rest).
386 partition_predicate(Pred,'$all',FilteredPred,Rest) :- !, FilteredPred=Pred, Rest=b(truth,pred,[]).
387 partition_predicate(Pred,ModifiedVars,FilteredPred,Rest) :-
388 conjunction_to_list(Pred,List),
389 partition(can_be_modified(ModifiedVars),List,FilteredList,[],UnFilteredList),
390 conjunct_predicates(FilteredList,FilteredPred),
391 conjunct_predicates(UnFilteredList,Rest).
392
393 can_be_modified(ModifiedVars,Pred,Res) :-
394 some_id_occurs_in_expr(ModifiedVars,Pred),!, Res='<'.
395 can_be_modified(_,_,'>').
396
397 %predicate_modified_by_write_vars(_Pred,'$all') :- !.
398 %predicate_modified_by_write_vars(Pred,SortedWriteVars) :- some_id_occurs_in_expr(SortedWriteVars,Pred).
399
400
401 :- use_module(probsrc(preferences),[get_time_out_preference_with_factor/2, add_time_outs/3]).
402
403 add_to_time_out(Extra,OriginalTimeout,New) :-
404 (OriginalTimeout < 300 % default for timeout_cbc_analysis is 300
405 -> E is (Extra * OriginalTimeout) // 300
406 ; E is Extra
407 ),
408 add_time_outs(OriginalTimeout,E,New).
409
410 tcltk_cbc_enabling_analysis(L) :-
411 get_time_out_preference_with_factor(0.1,TOF),
412 (TOF > 250 -> ExtraTO is TOF-250 ; ExtraTO = 0),
413 tcltk_cbc_enabling_analysis(ExtraTO,L).
414 tcltk_cbc_enabling_analysis(ExtraTimeout,list([list(['Origin'|Ops])|Result])) :-
415 findall(Op, b_top_level_operation(Op), Ops),
416 %statistics(walltime,[WT1,_]),
417 findall(list([OpName1|EnableList]),
418 (init_or_op(OpName1),
419 findall(Enable,cbc_enable_analysis(OpName1,_OpName2,Enable,ExtraTimeout),EnableList)),
420 Result).
421 %statistics(walltime,[WT2,_]), Time is WT2-WT1,
422 %format('Runtime for enabling analysis: ~w ms~n',[Time])
423 %,print_enable_table([list(['Origin'|Ops])|Result]).
424
425 % -----------------
426 % compute the four edges of the enable relation for a particular operation
427 tcltk_cbc_enabling_relations_for_operation(OpName2,ExtraTimeout,
428 list([list(['Event','Enable','KeepEnabled','Disable','KeepDisabled'])|Results])) :-
429 findall(list([OpName1|ResOp2]),
430 compute_cbc_enable_rel(OpName1,OpName2,ExtraTimeout,ResOp2), Results).
431 tcltk_cbc_enabling_relations_after_operation(OpName1,ExtraTimeout,
432 list([list(['Event','Enable','KeepEnabled','Disable','KeepDisabled'])|Results])) :-
433 findall(list([OpName2|ResOp2]),
434 compute_cbc_enable_rel(OpName1,OpName2,ExtraTimeout,ResOp2), Results).
435
436 % compute the four edges of the enable relation for a pair of events:
437 compute_cbc_enable_rel(OpName1,OpName2,ExtraTimeout,[Enable,KeepEnabled,Disable,KeepDisabled]) :-
438 b_top_level_operation(OpName1),
439 b_get_read_write(OpName1,_,Writes1),
440 b_get_operation_read_guard_vars(OpName1,true,Reads1,_Precise),
441 formatsilent("CHECKING ENABLING RELATION AFTER: ~w r:~w / w:~w~n",[OpName1,Reads1,Writes1]),
442 b_top_level_operation(OpName2),
443 get_negated_guard(OpName2,PosGuard2,_NegGuard2),
444 partition_predicate(PosGuard2,Writes1,FilteredPosGuard2,StaticPosGuard2),
445 create_negation(FilteredPosGuard2,FilteredNegGuard2),
446 Timeout1 is 300+ExtraTimeout,
447 formatsilent('~w ---> ~w :: ',[OpName1,OpName2]),
448 %print(' FPOS: '),translate:print_bexpr(FilteredPosGuard2),nl,
449 %print('Neg Guard: '),translate:print_bexpr(NegGuard2),nl,
450 %print(' Filtered: '),translate:print_bexpr(FilteredNegGuard2),nl,
451 % TO DO: use syntactic conditions
452 my_testcase_path_timeout(pred(PosGuard2),Timeout1,[OpName1],FilteredPosGuard2,KeepEnabled),
453 my_testcase_path_timeout(pred(PosGuard2),Timeout1,[OpName1],FilteredNegGuard2,Disable),
454 (OpName1==OpName2 -> KeepDisabled=false, Enable=false
455 ; conjunct_predicates([StaticPosGuard2,FilteredNegGuard2],NegEnableGuard2), % as StaticPosGuard2 must be same before after: it must be true before to be true after
456 my_testcase_path_timeout(pred(NegEnableGuard2),Timeout1,[OpName1],FilteredPosGuard2,Enable),
457 % this is the unoptimised call:
458 %my_testcase_path_timeout(pred(NegGuard2),Timeout1,[OpName1],NegGuard2,KeepDisabled),
459 % we do two calls for KeepDisabled: pred(NegStaticGuard2) true after, or StaticGuard2 & NegFiltered -> NegFiltered
460 create_negation(StaticPosGuard2,StaticNegGuard2),
461 my_testcase_path_timeout(pred(StaticNegGuard2),Timeout1,[OpName1],b(truth,pred,[]),KeepDisabled1),
462 (KeepDisabled1 = ok -> KeepDisabled=ok
463 ; my_testcase_path_timeout(pred(NegEnableGuard2),Timeout1,[OpName1],FilteredNegGuard2,KeepDisabled)
464 ),
465 formatsilent(' KeepEnabled=~w, Disable=~w, Enable=~w, KeepDisabled=~w~n',
466 [KeepEnabled,Disable,Enable,KeepDisabled])
467 ).
468
469 my_testcase_path_timeout(Before,Timeout,Path,After,Result) :-
470 (testcase_path_timeout_catch(Before,Timeout,Path,After,_,_,_,_,Result) -> true
471 ; Result = false).
472
473 % ----------------------------------------------
474
475
476 init_or_op('INITIALISATION').
477 init_or_op(OpName1) :- b_top_level_operation(OpName1). %b_get_machine_operation(OpName1,_,_,_).
478
479 % print table in CSV format
480 print_enable_table(R) :- print_enable_table_list(R).
481 print_enable_table_list([]) :- nl,nl.
482 print_enable_table_list([list(L)|T]) :-
483 print_csv_list(L), print_enable_table_list(T).
484 print_csv_list([]) :- !,nl.
485 print_csv_list([H]) :- !,print(H),nl.
486 print_csv_list([H|T]) :- !,print(H), print(','), print_csv_list2(T).
487 print_csv_list(X) :- print(illegal_list(X)),nl, add_internal_error('Illegal list: ', print_csv_list(X)).
488
489 print_csv_list2([H]) :- !,print_enable_info(H),nl.
490 print_csv_list2([H|T]) :- !,print_enable_info(H), print(','), print_csv_list2(T).
491 print_csv_list2(X) :- print(illegal_list(X)),nl, add_internal_error('Illegal list: ', print_csv_list(X)).
492
493 print_enable_info(I) :- (translate_enable_info(I,TI) -> print(TI) ; print_for_csv(I)).
494 % simplify result further for output to CSV; reason: also testing (e.g., test 1360 which sometimes causes overflow on Mac, and time_out on Linux)
495 translate_enable_info(timeout,unknown).
496 translate_enable_info(time_out,unknown).
497 translate_enable_info(overflow,unknown).
498 translate_enable_info(virtual_time_out,unknown).
499
500 print_for_csv([]) :- !, print('{}').
501 print_for_csv([H|T]) :- !, % print list without commas ,
502 format('{~w',[H]), maplist(print_csv_el,T), print('}').
503 print_for_csv(Term) :- print(Term).
504 print_csv_el(H) :- format(' ~w',[H]).
505
506
507 % ---------- create enable graph ------------------
508
509 eop_node_predicate(NodeID,SubGraph,NodeDesc,Shape,Style,black) :-
510 op_node_predicate(NodeID,SubGraph,NodeDesc,Shape,Style,_Color).
511 eop_node_predicate('INITIALISATION',SubGraph,'INITIALISATION',Shape,Style,Color) :- SubGraph=none,
512 Shape=hexagon, Style=none, Color=olivedrab2.
513
514 translate_enable_res(Rel,_,_,'impossible',red,_) :- impossible(Rel),!, fail.
515 translate_enable_res(guaranteed,_,_,'guaranteed',olivedrab2,solid) :- !.
516 translate_enable_res(Rel,X,Y,TransRel,TCol,bold) :- independent(Rel,Col),
517 !,X=Y, % only show if source & dest identical
518 TransRel=Rel,TCol=Col.
519 translate_enable_res(possible,_,_,'possible',black,solid) :- !.
520 translate_enable_res(keep,_,_,'keep',lightgray,solid) :- !.
521 translate_enable_res(possible_enable,_,_,'(enable)',black,solid) :- !.
522 translate_enable_res(possible_disable,_,_,'(disable)',lightblue,solid) :- !.
523 translate_enable_res(timeout_keep,_,_,'keep?',tomato,dashed) :- !.
524 translate_enable_res(timeout_possible,_,_,'possible?',tomato,dashed) :- !.
525 translate_enable_res(timeout_possible_disable,_,_,'(disable?)',tomato,dashed) :- !.
526 translate_enable_res(timeout_possible_enable,_,_,'(enable?)',tomato,dashed) :- !.
527 translate_enable_res(pred(Expr),_,_,String,black,dashed) :- !,
528 translate_bexpression(Expr,String).
529 translate_enable_res(predicate(Expr),_,_,String,black,dashed) :- !,
530 translate_bexpression(Expr,String).
531 translate_enable_res(dependent,_,_,dependent,green,solid) :- !.
532 translate_enable_res(race_dependent,_,_,race_dependent,green,solid) :- !.
533 translate_enable_res(guard_dependent,_,_,guard_dependent,olive,dashed) :- !.
534 translate_enable_res(action_dependent,_,_,action_dependent,green,dashed) :- !.
535 translate_enable_res(X,_,_,'independent',lightgray,solid) :-
536 memberchk(X,[independent,syntactic_independent,syntactic_fully_independent,syntactic_unchanged]),!.
537 translate_enable_res(X,_,_,X,red,solid).
538
539
540 impossible(impossible).
541 impossible(impossible_keep).
542 impossible(impossible_disable).
543 impossible(impossible_infeasible).
544 impossible(infeasible).
545
546 independent(independent,yellow).
547 independent(syntactic_keep,lightgray).
548 independent(syntactic_independent,lightgray).
549 independent(syntactic_fully_independent,lightgray).
550 independent(syntactic_unchanged,lightgray).
551 independent(activation_indepdendent,lightgray).
552
553 % ---------- new style dot graph support for enabling/dependence/CFG graphs ------------------
554 % shared by dot_graphs_static_analysis, enable_graph and the CFG analysis above
555
556 :- use_module(probsrc(tools),[html_escape/2]).
557 :- use_module(probsrc(tools_strings),[ajoin_with_sep/3]).
558
559 % graph attributes for gen_dot_graph/6; Kind is used in the title
560 enabling_dot_graph_attrs(Kind,[graph_name/enabling_graph, no_page_size, fontname/'Helvetica',
561 nodesep/0.5, ranksep/0.6,
562 node_defaults/[fontname/'Helvetica', shape/box, style/'rounded,filled', margin/'0.1,0.05'],
563 edge_defaults/[fontname/'Helvetica', fontsize/9, arrowsize/0.8]
564 | TitleAttrs]) :-
565 (get_preference(dot_print_graph_title,true), bmachine:b_machine_name(Main)
566 -> ajoin([Main,' - ',Kind],Title),
567 get_preference(dot_title_font_size,TFS), TitleAttrs = [label/Title, labelloc/t, fontsize/TFS]
568 ; TitleAttrs = []).
569
570 % enabling_dot_node(InitOpt,NodeID,SubGraph,Attrs): one node per operation (+ INITIALISATION if InitOpt=with_init)
571 :- public enabling_dot_node/4.
572 enabling_dot_node(_,Op,none,[label/htmllabel(Label), tooltip/Tooltip, fillcolor/'#E3EDF7', color/'#1F5F99']) :-
573 b_top_level_operation(Op),
574 (get_preference(dot_enabling_show_readwrites,false)
575 -> html_escape(Op,EOp), ajoin(['<<b>',EOp,'</b>>'],Label), Tooltip=Op
576 ; b_get_read_write(Op,Reads,Writes),
577 b_get_operation_read_guard_vars(Op,false,ReadsGrd,_Precise),
578 html_escape(Op,EOp),
579 maplist(rw_row,['guard reads','reads','writes'],[ReadsGrd,Reads,Writes],Rows),
580 ajoin(['<<table border="0" cellborder="0" cellspacing="0" cellpadding="1">',
581 '<tr><td colspan="2"><b>',EOp,'</b></td></tr><hr/>'|Rows],L0),
582 ajoin([L0,'</table>>'],Label),
583 maplist(rw_text,[ReadsGrd,Reads,Writes],[TG,TR,TW]),
584 ajoin([Op,'\nguard reads: ',TG,'\nreads: ',TR,'\nwrites: ',TW],Tooltip)
585 ).
586 enabling_dot_node(with_init,'INITIALISATION',none,
587 [label/htmllabel('<<b>INITIALISATION</b>>'), tooltip/'INITIALISATION',
588 fillcolor/'#E4F2E5', color/'#2E7D32', shape/box, style/'filled,bold']).
589
590 rw_text('$all','ALL') :- !.
591 rw_text([],'-') :- !.
592 rw_text(L,T) :- ajoin_with_sep(L,', ',T).
593
594 rw_row(Title,Ids,Row) :-
595 rw_html(Ids,Html),
596 ajoin(['<tr><td align="right" valign="top"><font point-size="9" color="#707070">',Title,' ',
597 '</font></td><td align="left" balign="left"><font point-size="10">',Html,'</font></td></tr>'],Row).
598
599 rw_html('$all','<i>ALL</i>') :- !.
600 rw_html([],'<font color="#A0A0A0">–</font>') :- !.
601 rw_html(Ids,Html) :- maplist(html_escape,Ids,EIds), wrap_ids(EIds,0,Parts), ajoin(Parts,Html).
602
603 % insert line breaks after about 30 characters
604 wrap_ids([],_,[]).
605 wrap_ids([H],_,[H]) :- !.
606 wrap_ids([H|T],Len,[H,Sep|R]) :-
607 atom_length(H,HL), Len1 is Len+HL+2,
608 (Len1 > 30 -> Sep=',<br/>', Len2=0 ; Sep=', ', Len2=Len1),
609 wrap_ids(T,Len2,R).
610
611 % translate an enabling result (as computed by cbc_enable_analysis, enable_analysis, ...) into dot edge attributes
612 % fails if no edge should be drawn
613 enabling_dot_edge_attrs(Res,X,Y,Attrs) :-
614 enable_res_kind(Res,X,Y,Kind),
615 enabling_dot_edge_kind_attrs(Kind,Attrs).
616
617 enable_res_kind(Rel,_,_,_) :- impossible(Rel),!, fail.
618 enable_res_kind(guaranteed,_,_,guaranteed) :- !.
619 enable_res_kind(Rel,X,Y,independent) :- independent(Rel,_), !, X=Y. % only show if source & dest identical
620 enable_res_kind(possible,_,_,possible) :- !.
621 enable_res_kind(keep,_,_,keep) :- !.
622 enable_res_kind(possible_enable,_,_,possible_enable) :- !.
623 enable_res_kind(possible_disable,_,_,possible_disable) :- !.
624 enable_res_kind(timeout_keep,_,_,timeout(keep)) :- !.
625 enable_res_kind(timeout_possible,_,_,timeout(possible)) :- !.
626 enable_res_kind(timeout_possible_disable,_,_,timeout(possible_disable)) :- !.
627 enable_res_kind(timeout_possible_enable,_,_,timeout(possible_enable)) :- !.
628 enable_res_kind(timeout,_,_,timeout(possible)) :- !.
629 enable_res_kind(pred(Expr),_,_,predicate(Expr)) :- !.
630 enable_res_kind(predicate(Expr),_,_,predicate(Expr)) :- !.
631 enable_res_kind(Dep,_,_,Dep) :- memberchk(Dep,[dependent,race_dependent,guard_dependent,action_dependent]), !.
632 enable_res_kind(X,_,_,unknown(X)).
633
634 % enabling_dot_edge_kind_attrs(Kind,Attrs)
635 enabling_dot_edge_kind_attrs(Kind,Attrs) :-
636 edge_kind(Kind,Label,Col,Style,PW,LText,Order), !,
637 (get_preference(dot_print_legend,true), LText \= ''
638 -> Attrs0 = [legend/LText, legend_order/Order], ShowLabel=false
639 ; Attrs0 = [], ShowLabel=true),
640 edge_label_attrs(Kind,Label,ShowLabel,Col,LAttrs),
641 (PW=1 -> PAttrs=[] ; PAttrs=[penwidth/PW]),
642 append([[color/Col, style/Style],PAttrs,LAttrs,Attrs0],Attrs).
643
644 % labels of edges with a condition or a timeout are always shown; the others only if there is no legend
645 edge_label_attrs(predicate(Expr),_,_,Col,[label/htmllabel(HL), fontcolor/Col, tooltip/Tooltip]) :- !,
646 translate_bexpression_with_limit(Expr,250,S),
647 html_escape(S,ES),
648 atom_codes(ES,Codes), split_conj_codes(Codes,Parts),
649 ajoin_with_sep(Parts,' &<br/>',Body),
650 ajoin(['<',Body,'>'],HL),
651 ajoin(['enabled if: ',S],Tooltip).
652 edge_label_attrs(timeout(_),Label,_,Col,[label/Label, fontcolor/Col, tooltip/Label]) :- !.
653 edge_label_attrs(unknown(_),Label,_,Col,[label/Label, fontcolor/Col, tooltip/Label]) :- !.
654 edge_label_attrs(_,Label,true,Col,[label/Label, fontcolor/Col, tooltip/Label]) :- !.
655 edge_label_attrs(_,Label,_,_,[tooltip/Label]).
656
657 split_conj_codes(Codes,[P|Rest]) :- % split at conjunctions (also nested ones; good enough for display)
658 append(Prefix,Tail,Codes), append(PC," & ",Prefix), !,
659 atom_codes(P,PC), split_conj_codes(Tail,Rest).
660 split_conj_codes(Codes,[P]) :- atom_codes(P,Codes).
661
662 % edge_kind(Kind,Label,Colour,Style,PenWidth,LegendText,LegendOrder)
663 edge_kind(guaranteed,guaranteed,'#2E7D32',solid,2,'guaranteed to enable',10).
664 edge_kind(possible,possible,'#1F5F99',solid,1,'can enable',20).
665 edge_kind(possible_enable,enable,'#1F5F99',solid,1,'can enable',20).
666 edge_kind(can_enable,'','#1F5F99',solid,1,'can enable (control flow)',20).
667 edge_kind(predicate(_),condition,'#6A1B9A',dashed,1,'enables under condition',30).
668 edge_kind(keep,keep,gray60,solid,1,'keeps enabled',40).
669 edge_kind(possible_disable,disable,'#C62828',solid,1,'can disable',50).
670 edge_kind(dependent,dependent,'#C06040',solid,1,'dependent',60).
671 edge_kind(race_dependent,race,'#C62828',solid,1,'race dependent',61).
672 edge_kind(action_dependent,action,'#1F5F99',dashed,1,'action dependent',62).
673 edge_kind(guard_dependent,guard,'#8A6D1E',dashed,1,'guard dependent',63).
674 edge_kind(independent,independent,gray70,dotted,1,'independent of itself',70).
675 edge_kind(race_independent,'race independent',gray70,dotted,1,'race independent of itself',71).
676 edge_kind(timeout(K),Label,'#E65100',dashed,1,'unknown (timeout)',80) :-
677 (edge_kind(K,KL,_,_,_,_,_), KL \= '' -> true ; KL = enable),
678 ajoin([KL,'?'],Label).
679 edge_kind(unknown(X),X,red,solid,1,'',90).
680
681 is_timeout_enabling_result(timeout_keep).
682 is_timeout_enabling_result(timeout_possible).
683 is_timeout_enabling_result(timeout_possible_disable).
684 is_timeout_enabling_result(timeout_possible_enable).
685 is_timeout_enabling_result(timeout).
686 is_timeout_enabling_result(timeout_dependent).
687 is_timeout_enabling_result(timeout_guaranteed).
688 is_timeout_enabling_result(timeout_impossible).
689
690 % Simultaneous Enabling Analysis
691 % Find events which cannot be enabled simultaneously
692 % Usage:
693 % a) if one event is known to be enabled we do not need to check the impossible ones
694 % b) if one event is known to be disabled we do not need check events which guarantee it
695
696 % use_module(enabling_analysis), tcltk_cbc_simultaneous_enabling_analysis(R).
697
698 tcltk_cbc_simultaneous_enabling_analysis(list([list(['Origin'|SOps])|Result])) :-
699 findall(Op, b_top_level_operation(Op), Ops),
700 sort(Ops,SOps), % sort operations to ensure nice triangular display
701 statistics(walltime,[WT1,_]),
702 findall(list([OpName1|EnableList]),
703 (member(OpName1,SOps),
704 findall(SimulRes,tcltk_simult(OpName1,SOps,SimulRes),EnableList)),
705 Result),
706 statistics(walltime,[WT2,_]), Time is WT2-WT1,
707 formatsilent('Runtime for simultaneous enabling analysis: ~w ms~n',[Time])
708 . %,print_enable_table([list(['Origin'|Ops])|Result]).
709
710 tcltk_simult(Op1,SOps,Res) :- member(Op2,SOps),tcltk_simult2(Op1,Op2,Res).
711 tcltk_simult2(Op1,Op2,Res) :-
712 Op1 = Op2, % Op2 @=< Op1, % the simultaneous impossible analysis is symmetric: TO DO: do not compute/display info twice
713 !,
714 Res = '-'.
715 tcltk_simult2(Op1,Op2,TRes) :-
716 simult_enable_analysis(Op1,Op2,1,fixed_time_out(150),TRes).
717
718 simult_enable_analysis(OpName1,OpName2,UseInvariant,TimeoutFactor,Res) :-
719 b_top_level_operation(OpName1),
720 b_top_level_operation(OpName2),
721 %OpName2 @>OpName1,
722 get_negated_guard(OpName1,PosGuard1,_NegGuard1),
723 get_negated_guard(OpName2,PosGuard2,NegGuard2),
724 get_conj_inv_predicate([PosGuard1,PosGuard2],UseInvariant,Pred),
725 %print(checking_simultaneous(OpName1,OpName2)),nl,
726 (solve_predicate_with_chr(Pred,_State,TimeoutFactor,[],RR)
727 -> %print(state(_State)),nl, print(result(RR)),nl,
728 ((RR = contradiction_found ; RR = no_solution_found(unfixed_deferred_sets))
729 -> Res = impossible % we do not compute PosGuard1,NegGuard2 in this case: otherwise this would mean that Operation 1 can never fire !
730 ; get_conj_inv_predicate([PosGuard1,NegGuard2],UseInvariant,Pred2),
731 solve_predicate_with_chr(Pred2,_State2,TimeoutFactor,[],RR2),
732 combine_simult_result(RR,RR2,Res))
733 ; print('********* ERROR ***********'),nl,fail).
734
735 combine_simult_result(solution(_),solution(_),R) :- !,R=possible.
736 combine_simult_result(solution(_),B,R) :-
737 (B = contradiction_found ; B = no_solution_found(unfixed_deferred_sets)), !,
738 R=guaranteed.
739 combine_simult_result(A,B,Res) :- functor(A,FA,_), functor(B,FB,_),
740 ajoin([FA,'_',FB],Res).
741
742 % ---------------------------------------------------
743
744 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
745 :- register_event_listener(specification_initialised,reset_enabling_analysis,
746 'Initialise module enabling analysis.').
747
748 :- dynamic feasible_operation_cache/2.
749 reset_enabling_analysis :-
750 %retractall(disable_graph(_)),
751 retractall(feasible_operation_cache(_,_)),
752 retractall(cbc_enable_analysis_cache(_,_,_,_)).
753
754 % in principle you should only call this for Op with operation_name_not_yet_covered(Op)
755 feasible_operation(Op,Res) :- feasible_operation_cache(Op,CR),!,Res=CR.
756 feasible_operation(Op,Res) :- UseInvariant=1,
757 check_if_feasible_operation(Op,UseInvariant,fixed_time_out(500),CR,_),
758 assertz(feasible_operation_cache(Op,CR)),
759 Res=CR.
760
761 feasible_operation_with_timeout(Op,TimeOut,Res) :- feasible_operation_cache(Op,CR),
762 (CR \= unknown ; TimeOut =< 500), !, Res=CR.
763 feasible_operation_with_timeout(Op,TimeOut,Res) :- check_if_feasible_operation(Op,1,fixed_time_out(TimeOut),CR,_),
764 retractall(feasible_operation_cache(Op,_)), % must be unknown if it was asserted before
765 assertz(feasible_operation_cache(Op,CR)),
766 Res=CR.
767
768
769 :- use_module(probsrc(state_space),[operation_not_yet_covered/1]).
770 infeasible_operation(Op) :- feasible_operation_cache(Op,CR),!, CR=impossible.
771 infeasible_operation(Op) :- operation_not_yet_covered(Op),
772 feasible_operation(Op,impossible). % will also assert feasible_operation_cache
773
774 infeasible_operation_cache(Op) :- feasible_operation_cache(Op,impossible).
775
776 :- use_module(probsrc(solver_interface), [solve_predicate/5]).
777 solve_predicate_with_chr(Pred,State,TimeoutFactor,Options,RR) :-
778 solve_predicate(Pred,State,TimeoutFactor,['CHR','CLPFD','SMT'|Options],RR).
779
780 :- use_module(probsrc(debug), [debug_mode/1]).
781 :- use_module(probsrc(store),[normalise_store/2]).
782 % check if an operation is feasible
783 % UseInvariant = 1 : assume invariant
784 check_if_feasible_operation(OpName1,UseInvariant,TimeoutFactor,Res,NormalisedResultState) :-
785 b_top_level_operation(OpName1),
786 (debug_mode(on)
787 -> print(checking_feasibility(OpName1)),nl,tools:start_ms_timer(TIMER) ; true),
788 if(check_if_feasible_operation2(OpName1,UseInvariant,TimeoutFactor,Res,State),true,
789 (add_internal_error('Failed:',check_if_feasible_operation2(OpName1,UseInvariant,TimeoutFactor,Res,State)),fail)),
790 % TO DO: add missing variables and put into order
791 normalise_enabling_store(State,NormalisedResultState),
792 %b_interpreter:sort_variable_binding(NormalisedResultState,SortedStore),
793 stop_ms_timer_with_debug_msg(TIMER,feasible(OpName1)).
794
795 normalise_enabling_store('$UNKNOWN_STATE',R) :- !, R='$UNKNOWN_STATE'.
796 normalise_enabling_store(CState,State) :- normalise_store(CState,State).
797
798 :- use_module(probsrc(tools_timeout),[get_time_out_with_factor/2]).
799 check_if_feasible_operation2(OpName1,UseInvariant,TimeoutFactor,Res,ResultState) :-
800 get_negated_guard(OpName1,PosGuard1,_NegGuard1,Precise),
801 % format('Guard is ~w for ~w~n',[Precise,OpName1]),
802 Precise = precise,
803 !,
804 % Warning: guard is under approximation for sequential composition, while loops, ...
805 get_conj_inv_predicate([PosGuard1],UseInvariant,Pred),
806 (debug_mode(on) -> translate:nested_print_bexpr(Pred),nl ; true),
807 % visualize_graph:print_predicate_dependency_as_graph_for_dot(Pred,'~/Desktop/out.dot'),
808 (solve_predicate_with_chr(Pred,State,TimeoutFactor,[full_machine_state],RR)
809 -> %print(state(_State)),nl, print(result(RR)),nl,
810 ((RR=no_solution_found(unfixed_deferred_sets) ; RR = contradiction_found)
811 -> Res = impossible, ResultState = '$UNKNOWN_STATE'
812 %,format('Computing unsat core for infeasible ~w~n',[OpName1]),unsat_cores:unsat_core(Pred,no_solution_found,Core),print('CORE: '),nl,translate:nested_print_bexpr_as_classicalb(Core),nl
813 ; RR=solution(_) -> Res = possible,
814 (debug_mode(on) -> print('SOLUTION: '),translate:print_bstate(State),nl ; true),
815 ResultState = State
816 ; simplify_for_output(RR,Res), ResultState = '$UNKNOWN_STATE' )
817 ; add_internal_error('Failed to compute feasibility for: ',OpName1),
818 translate:print_bexpr(Pred),nl,
819 Res = internal_error, ResultState = '$UNKNOWN_STATE').
820 check_if_feasible_operation2(OpName1,UseInvariant,TimeoutFactor,Res,ResultState) :-
821 formatsilent('Guard computation is imprecise for ~w. Not using predicate solver (but B interpreter).~n',[OpName1]),
822 % this version uses sap:testcase_path: this works for things like sequential composition and WHILE loops better
823 get_time_out_with_factor(TimeoutFactor,TO),
824 (UseInvariant=1 -> INV=invariant ; INV=typing),
825 (testcase_path_timeout_catch(INV,TO,[OpName1],b(truth,pred,[]),_Constants,Ops,StateSequence,_TI,R1)
826 -> (is_timeout(R1) -> Res=timeout ; Res = possible),
827 (nonvar(StateSequence),StateSequence=[ResultState|_] -> true ; ResultState = '$UNKNOWN_STATE'),
828 (debug_level_inactive_for(19) -> true
829 ; print(feasibility_result(OpName1,R1,Ops)),nl,
830 (ResultState = '$UNKNOWN_STATE' -> true
831 ; print('SOLUTION: '),translate:print_bstate(ResultState),nl)
832 )
833 ; Res=impossible,ResultState = '$UNKNOWN_STATE').
834
835
836 simplify_for_output(no_solution_found(enumeration_warning(_,_,_,_,_)),virtual_time_out).
837 simplify_for_output(no_solution_found(clpfd_overflow),overflow).
838 simplify_for_output(time_out,time_out).
839