package frama-c-rpp

  1. Overview
  2. Docs

Source file rpp_generator.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
(**************************************************************************)
(*                                                                        *)
(*  SPDX-License-Identifier LGPL-2.1                                      *)
(*  Copyright (C)                                                         *)
(*  CEA (Commissariat à l'énergie atomique et aux énergies alternatives)  *)
(*                                                                        *)
(**************************************************************************)

open Cil_types
open Cil
open Rpp_types

let get_typ_in_current_project t self loc=
  let rec aux t = let tnode = aux_node t.tnode in { t with tnode }
  and aux_node = function
    | (TVoid | TInt(_) | TFloat _ | TBuiltin_va_list) as t -> t
    | TPtr t ->
      let new_t = aux t in TPtr new_t
    | TArray(t,e) ->
      let new_t = aux t in TArray(new_t,e)
    | TFun(_) ->
      Rpp_options.Self.abort ~source:(fst loc)
        "Error in predicate: Function types are not supported yet"
    | TNamed t -> let new_t = Visitor_behavior.Get.typeinfo self t in TNamed new_t
    | TComp c ->let new_c = Visitor_behavior.Get.compinfo self c in TComp new_c
    | TEnum e -> let new_e = Visitor_behavior.Get.enuminfo self e in TEnum new_e
  in
  aux t

(**
   Visitor for coping function bodies
*)
class aux_visitor vis_beh var_ret = object(self)
  inherit Visitor.generic_frama_c_visitor(vis_beh)

  val stmt_hashtb = Hashtbl.create 3

  (*Return statement are replaced by an affectation to the local variable
    ("var_ret") used in the proof of the relational property*)
  method! vstmt_aux s =
    (*Set the statement to origine status to avoid the visitor to lose
      the binding with the statement annotation: it is not the best
      solution but it work => find better solution for the future*)
    let s =  Visitor_behavior.Get_orig.stmt self#behavior s in
    match (s.skind, s.labels) with
    | Return (Some e,l),[] ->
      let var_ret = match var_ret with
        |None -> let (loc,_) = l in
          Rpp_options.Self.fatal ~source:loc
            "Function is supposed to return something, \
             but no return variable has been created"
        | Some x -> x
      in
      let return_lval =
        (Var(var_ret),NoOffset)
      in
      let newt = Cil.typeOfLval return_lval in
      let oldt =
        Visitor.visitFramacType self#frama_c_plain_copy (Cil.typeOf e)
      in
      let e = Cil.mkCastT ~oldt ~newt e in
      let instr = Instr (Set(return_lval, e, l)) in
      let new_stmt = Cil.mkStmt ~valid_sid:true instr in
      ChangeDoChildrenPost(new_stmt, fun x -> x)

    | Return (None,l), [] ->
      let _var_ret = match var_ret with
        | None -> None
        | Some _ -> let (loc,_) = l in
          Rpp_options.Self.fatal ~source:loc
            "Function is supposed to return nothing, \
             but a return variable has been created"
      in
      let new_stmt =
        Cil.mkEmptyStmt ~valid_sid:true ()
      in
      ChangeDoChildrenPost(new_stmt, fun x -> x)


    | Return (None,_), h::[] ->
      (match h with
       | Label(name,l,b) ->
         begin
           let new_stmt = (try (Hashtbl.find stmt_hashtb name) with
               | Not_found ->
                 let new_name =
                   String.concat "_" [name;"label";
                                      string_of_int (Rpp_options.Counting_label.next ())]
                 in
                 let _var_ret = match var_ret with
                   | None -> None
                   | Some _ -> let (loc,_) = l in
                     Rpp_options.Self.fatal ~source:loc
                       "Function is supposed to return nothing, but a \
                        return variable have been created"
                 in
                 let new_stmt =
                   Cil.mkEmptyStmt ~valid_sid:true ()
                 in
                 new_stmt.labels <-[Label(new_name,l,b)];
                 Hashtbl.add stmt_hashtb name new_stmt;
                 new_stmt)
           in
           ChangeDoChildrenPost(new_stmt, fun x -> x)
         end

       | _ -> Rpp_options.Self.abort "Juste Label in Goto are supported yet")

    | Goto(target,_), [] ->
      (match (!target.skind,!target.labels) with
       | Return (Some e,_),h::[] ->
         (match h with
          | Label(name,l,b) ->
            let new_stmt = (try (Hashtbl.find stmt_hashtb name ) with
                | Not_found ->
                  (let new_name =
                     String.concat "_" [name;"label";
                                        string_of_int (Rpp_options.Counting_label.next ())]
                   in
                   let var_ret = match var_ret with
                     |None -> let (loc,_) = l in
                       Rpp_options.Self.fatal ~source:loc
                         "Function is supposed to return something, but no return \
                          variable have been created"
                     | Some x -> x
                   in
                   let return_lval =
                     (Var(var_ret),NoOffset)
                   in
                   let e = Cil.mkCast ~newt:(Cil.typeOfLval return_lval) e in
                   let instr = Instr (Set(return_lval, e, l)) in
                   let new_stmt = Cil.mkStmt ~valid_sid:true instr in
                   new_stmt.labels <-[Label(new_name,l,b)];
                   Hashtbl.add stmt_hashtb name new_stmt;
                   new_stmt))
            in
            let goto_stmt = Cil.mkStmt ~valid_sid:true (Goto((ref new_stmt),l)) in
            ChangeTo goto_stmt

          | _ -> Rpp_options.Self.abort "Juste Label in Goto are supported yet")

       | Return (None,_), h::[] ->
         (match h with
          | Label(name,l,b) ->
            begin
              let new_stmt = (try (Hashtbl.find stmt_hashtb name) with
                  | Not_found ->
                    let new_name =
                      String.concat "_" [name;"label";
                                         string_of_int (Rpp_options.Counting_label.next ())]
                    in
                    let _var_ret = match var_ret with
                      | None -> None
                      | Some _ -> let (loc,_) = l in
                        Rpp_options.Self.fatal ~source:loc
                          "Function is supposed to return nothing, but a \
                           return variable have been created"
                    in
                    let new_stmt =
                      Cil.mkEmptyStmt ~valid_sid:true ()
                    in
                    new_stmt.labels <-[Label(new_name,l,b)];
                    Hashtbl.add stmt_hashtb name new_stmt;
                    new_stmt)
              in
              let goto_stmt = Cil.mkStmt ~valid_sid:true (Goto((ref new_stmt),l)) in
              ChangeTo goto_stmt
            end
          | _ -> Rpp_options.Self.abort "Juste Label in Goto are supported yet")

       | _, h::[] ->
         (match h with
          | Label(name,l,b) ->
            let new_stmt = (try (Hashtbl.find stmt_hashtb name ) with
                | Not_found ->
                  (let new_name =
                     String.concat "_" [name;"label";
                                        string_of_int (Rpp_options.Counting_label.next ())]
                   in
                   let new_stmt =
                     Cil.mkStmt ~valid_sid:true (!target.skind)
                   in
                   new_stmt.labels <-[Label(new_name,l,b)];
                   Hashtbl.add stmt_hashtb name new_stmt;
                   new_stmt))
            in

            let goto_stmt = Cil.mkStmt ~valid_sid:true (Goto((ref new_stmt),l)) in
            ChangeTo goto_stmt

          | _ -> Rpp_options.Self.abort "Juste Label in Goto are supported yet")
       | _ -> Rpp_options.Self.abort "Juste one Label in Goto are supported")

    (* UnspecifiedSequence are not really in the scope of relational property verification,
       so they are replaced by block. *)
    | UnspecifiedSequence l,[] ->
      let b = Cil.block_from_unspecified_sequence l in
      ChangeDoChildrenPost (Cil.mkStmt ~valid_sid:true (Block b), fun x-> x)

    | _,[] ->
      ChangeDoChildrenPost(Cil.mkStmt ~valid_sid:true s.skind, fun x -> x)

    | kind, h::[] ->
      (match (kind,h) with
       | Goto(_,_),Label(_,l_label,_) -> let (loc,_) = l_label in
         Rpp_options.Self.abort ~source:loc " Label on goto are not supported yet"
       | Return (Some e,l),Label(name,_,b) ->
         let new_stmt = (try (Hashtbl.find stmt_hashtb name) with
             | Not_found ->
               (let new_name =
                  String.concat "_" [name;"label";
                                     string_of_int (Rpp_options.Counting_label.next ())]
                in
                let var_ret = match var_ret with
                  |None -> let (loc,_) = l in
                    Rpp_options.Self.fatal ~source:loc
                      "Function is supposed to return something, but no \
                       return variable have been created"
                  | Some x -> x
                in
                let return_lval = (Var(var_ret),NoOffset) in
                let newt = Cil.typeOfLval return_lval in
                let oldt =
                  Visitor.visitFramacType self#frama_c_plain_copy (Cil.typeOf e)
                in
                let e = Cil.mkCastT ~oldt ~newt e in
                let instr = Instr (Set(return_lval, e, l)) in
                let new_stmt = Cil.mkStmt ~valid_sid:true instr in
                new_stmt.labels <-[Label(new_name,l,b)];
                Hashtbl.add stmt_hashtb name new_stmt;
                new_stmt))
         in
         ChangeDoChildrenPost(new_stmt, fun x -> x)
       | Return (None,l), Label(name,_,b) ->
         let new_stmt = (try (Hashtbl.find stmt_hashtb name) with
             | Not_found ->
               let new_name =
                 String.concat "_" [name;"label";
                                    string_of_int (Rpp_options.Counting_label.next ())]
               in
               let _var_ret = match var_ret with
                 | None -> None
                 | Some _ -> let (loc,_) = l in
                   Rpp_options.Self.fatal ~source:loc
                     "Function is supposed to return nothing, but a \
                      return variable have been created"
               in
               let new_stmt =
                 Cil.mkEmptyStmt ~valid_sid:true ()
               in
               new_stmt.labels <-[Label(new_name,l,b)];
               Hashtbl.add stmt_hashtb name new_stmt;
               new_stmt)
         in
         ChangeDoChildrenPost(new_stmt, fun x -> x)

       | _, Label(name,l,b) ->
         let new_stmt = (try (Hashtbl.find stmt_hashtb name) with
             | Not_found ->
               (let new_name =
                  String.concat "_" [name;"label";
                                     string_of_int (Rpp_options.Counting_label.next ())]
                in
                let new_stmt =
                  Cil.mkStmt ~valid_sid:true kind
                in
                new_stmt.labels <-[Label(new_name,l,b)];
                Hashtbl.add stmt_hashtb name new_stmt;
                new_stmt))
         in
         ChangeDoChildrenPost(new_stmt, fun x ->x )

       | _ -> Rpp_options.Self.abort "Juste Label are supported yet")

    | _ ,_::_ -> Rpp_options.Self.abort "Multiple labels on a stmt are no supported yet"

end

(**
   Visitor for coping \requires clauses
*)
class aux_visitor_2 vis_beh = object(_)
  inherit Visitor.generic_frama_c_visitor(vis_beh)

  method! vbehavior b =
    match b.b_requires with
    | [] -> ChangeDoChildrenPost(Cil.mk_behavior ~name:b.b_name (), fun x -> x)
    | _ ->
      let new_funbehavior =
        Cil.mk_behavior ~name:b.b_name ~assumes: b.b_assumes ~requires: b.b_requires ()
      in
      ChangeDoChildrenPost(new_funbehavior, fun x -> x)
end

exception Unknown_term of Cil_types.logic_var
exception Local_return

(**
   Visitor for transforming require predicate into predicate juste with the formals of the function
*)
class aux_visitor_3 vis_beh l_v_list ?(quan=[]) ?(pre=[]) formal_map = object(_)
  inherit Visitor.generic_frama_c_visitor(vis_beh)

  val quant = ref quan
  val pred = ref pre

  method! vpredicate_node p =
    match p with
    | Pforall(q,_) ->
      let inter = !quant in
      quant := q @ !quant;
      DoChildrenPost(fun x -> quant := inter; x)

    | Papp(l,_,_) ->
      let inter = !pred in
      pred := l.l_var_info :: !pred;
      DoChildrenPost(fun x -> pred := inter; x)

    | Pand(a,b) ->
      let vis =
        new aux_visitor_3 vis_beh l_v_list formal_map ~quan:!quant
      in
      let new_a =
        try Visitor.visitFramacPredicate vis a with
          Local_return -> {a with pred_content = Ptrue}
      in
      let new_b =
        try Visitor.visitFramacPredicate vis b with
          Local_return -> {a with pred_content = Ptrue}
      in
      begin
        match new_a.pred_content,new_b.pred_content with
        | Ptrue,Ptrue -> Cil.ChangeTo Ptrue
        | _,Ptrue -> Cil.ChangeTo new_a.pred_content
        | Ptrue,_ -> Cil.ChangeTo new_b.pred_content
        | _, _ -> Cil.ChangeTo (Pand(new_a,new_b))
      end

    | Prel _ | Pseparated _ | Pvalid _
    | Pvalid_read _ | Pnot _ | Pimplies _ | Por _ -> DoChildren

    | _ -> Rpp_options.Self.abort
             "Unsupported predicate in requires clause:@. @[%a@] @."
             Printer.pp_predicate_node p

  method! vterm t =
    let rec aux lv data =
      match data with
      | Some(_,v,new_t)::_ when (Cil.cvar_to_lvar v).lv_id == lv.lv_id  ->
        ChangeDoChildrenPost(new_t,fun x -> x)
      | _::q  -> aux lv q
      | [] -> DoChildren
    in
    match t.term_node with
    | TLval(TVar(l_v),_) -> aux l_v formal_map
    | _ -> DoChildren

  method! vlogic_var_use l =
    let rec aux3 lv data =
      match data with
      | h::_ when h.lv_id ==  lv.lv_id -> DoChildren
      | _::q  -> aux3 lv q
      | [] -> raise (Unknown_term lv)
    in
    let rec aux2 lv data =
      match data with
      | h::_ when h.lv_id == (Visitor_behavior.Get_orig.logic_var vis_beh lv).lv_id ->
        DoChildren
      | _::q  -> aux2 lv q
      | [] -> aux3 lv !pred
    in
    let rec aux lv data =
      match data with
      | h::_ when (Cil.cvar_to_lvar h).lv_id == lv.lv_id  ->
        DoChildren
      | _::q  -> aux lv q
      | [] -> aux2 lv !quant
    in
    match Str.bounded_split (Str.regexp "_") (l.lv_name) 4 with
    | "local" :: "variable" :: "relational" :: _ -> raise Local_return
    | _ ->  aux l l_v_list
end

let do_one_require_vis self new_funct globals formal_map kf requires =
  let formals =
    (Kernel_function.get_formals (Globals.Functions.get new_funct.svar))
    @ globals
  in
  let vis =
    new aux_visitor_3 self#behavior formals formal_map
  in
  List.fold_right (fun x acc ->
      match  Visitor.visitFramacIdPredicate vis x with
      | exception Unknown_term lv ->
        Rpp_options.Self.abort ~source:(fst x.ip_content.tp_statement.pred_loc)
          "Function %s is supposed no to depend on %a"
          (Kernel_function.get_name kf)
          Printer.pp_logic_var lv
      | exception Local_return -> acc
      | pred -> pred :: acc
    ) requires []

class aux_visitor_5 vis_behavior = object
  inherit Visitor.generic_frama_c_visitor(vis_behavior)

  method! vbehavior g =
    let rec aux g  =
      match g with
      | [] -> []
      | { ext_name = "relational"; ext_kind = Ext_preds(_)} :: q -> aux q
      | h :: q -> h :: aux q
    in
    let b_extended = aux g.b_extended
    in ChangeDoChildrenPost ({g with b_extended},fun x -> x)
end

class aux_visitor_6 vis_beh = object(_)
  inherit Visitor.generic_frama_c_visitor(vis_beh)

  method! vterm t =
    match t.term_node with
    | TLval(TMem(t_aux),TNoOffset) ->
      ChangeDoChildrenPost(t_aux, fun x -> x)
    | TLval(TMem(_),_) ->
      let (l,_) = t.term_loc in
      Rpp_options.Self.abort ~source:l
        "Unsupported term in separate generation:@. @[%a@] @."
        Printer.pp_term t

    | _ -> DoChildren
end

class aux_visitor_7 vis_beh formals_map = object(self)
  inherit Visitor.generic_frama_c_visitor(vis_beh)

  method! vterm t =
    match t.term_node with
    | TLval(TMem(t_aux),TNoOffset) ->
      self#vterm t_aux
    | TLval(TMem(_),_) ->
      let (l,_) = t.term_loc in
      Rpp_options.Self.abort ~source:l
        "Unsupported term in separate generation:@. @[%a@] @."
        Printer.pp_term t

    (* Use "\let in" in the future if more support is require*)

    | TLval(TVar(log),TNoOffset) ->
      begin
        match Cil_datatype.Logic_var.Map.find log formals_map with
        | exception Not_found -> ChangeDoChildrenPost(t, fun x -> x)
        | term ->
          ChangeDoChildrenPost(term, fun x -> x)
      end
    | TLval(TVar(log),off) ->
      begin
        match Cil_datatype.Logic_var.Map.find log formals_map with
        | exception Not_found -> ChangeDoChildrenPost(t, fun x -> x)
        | {term_node = TLval(a,off_sub)} as term ->
          let new_offset = Logic_const.addTermOffset off off_sub in
          let new_term =
            {term with term_node = TLval(a,new_offset)}
          in
          ChangeDoChildrenPost(new_term, fun x -> x)
        | term ->
          let (l,_) = term.term_loc in
          Rpp_options.Self.abort ~source:l
            "Unsupported term in separate generation.\
             Term to replace:@. @[%a@] @.\
             by @. @[%a@] @."
            Printer.pp_term t Printer.pp_term term
      end
    | _ -> ChangeDoChildrenPost(t, fun x -> x)
end

let global_binder_aux map self log_map log_map_orig =
  Cil_datatype.Varinfo.Map.iter
    (fun vo data ->
       begin
         match Cil_datatype.Logic_var.Map.find (Cil.cvar_to_lvar vo) !log_map with
         | exception Not_found ->
           log_map := Cil_datatype.Logic_var.Map.add
               (Cil.cvar_to_lvar vo)
               (Cil.cvar_to_lvar (Visitor_behavior.Get.varinfo self#behavior vo)) !log_map;
         | _ -> ()
       end;
       Visitor_behavior.Unset.logic_var self#behavior (Cil.cvar_to_lvar vo);
       Visitor_behavior.Set.logic_var self#behavior
         (Cil.cvar_to_lvar vo) data;

       begin
         match Cil_datatype.Logic_var.Map.find (Cil.cvar_to_lvar vo) !log_map_orig with
         | exception Not_found ->
           log_map_orig := Cil_datatype.Logic_var.Map.add
               (Cil.cvar_to_lvar vo)
               (Cil.cvar_to_lvar (Visitor_behavior.Get_orig.varinfo self#behavior vo))
               !log_map_orig;
         | _ -> ()
       end;
       Visitor_behavior.Unset_orig.logic_var self#behavior (Cil.cvar_to_lvar vo);
       Visitor_behavior.Set_orig.logic_var self#behavior
         data (Cil.cvar_to_lvar vo)) map

let binder_aux f apply id self global_map =
  let log_map = ref Cil_datatype.Logic_var.Map.empty in
  let log_map_orig = ref Cil_datatype.Logic_var.Map.empty in

  (*Make the binding for the globale variable*)
  begin
    match id with
    | None ->  ()
    | Some _ ->
      begin
        let (from_map,assert_map,from_p_map,assert_p_map) =
          global_map
        in
        global_binder_aux assert_map self log_map log_map_orig;
        global_binder_aux from_map self log_map log_map_orig;
        global_binder_aux from_p_map self log_map log_map_orig;
        global_binder_aux assert_p_map self log_map log_map_orig;
      end
  end;

  let data = f apply in

  Cil_datatype.Logic_var.Map.iter (fun a b ->
      Visitor_behavior.Unset.logic_var self#behavior a;
      Visitor_behavior.Set.logic_var self#behavior
        a b) !log_map;

  Cil_datatype.Logic_var.Map.iter (fun a b ->
      Visitor_behavior.Unset_orig.logic_var self#behavior a;
      Visitor_behavior.Set_orig.logic_var self#behavior
        a b) !log_map_orig;

  data

let global_binder map self var_map var_map_orig log_map log_map_orig =
  Cil_datatype.Varinfo.Map.iter
    (fun vo data ->
       match  data with
       | {lv_origin = Some(var)} ->
         begin
           match Cil_datatype.Varinfo.Map.find vo !var_map with
           | exception Not_found ->
             var_map := Cil_datatype.Varinfo.Map.add vo
                 (Visitor_behavior.Get.varinfo self#behavior vo)
                 !var_map;
           | _ -> ()
         end;
         Visitor_behavior.Unset.varinfo self#behavior vo;
         Visitor_behavior.Set.varinfo self#behavior vo var;

         begin
           match Cil_datatype.Varinfo.Map.find vo !var_map_orig with
           | exception Not_found ->
             var_map_orig := Cil_datatype.Varinfo.Map.add vo
                 (Visitor_behavior.Get_orig.varinfo self#behavior vo)
                 !var_map_orig;
           | _ -> ()
         end;
         Visitor_behavior.Unset_orig.varinfo self#behavior vo;
         Visitor_behavior.Set_orig.varinfo self#behavior var vo;

         begin
           match Cil_datatype.Logic_var.Map.find (Cil.cvar_to_lvar vo) !log_map with
           | exception Not_found ->
             log_map := Cil_datatype.Logic_var.Map.add
                 (Cil.cvar_to_lvar vo)
                 (Cil.cvar_to_lvar (Visitor_behavior.Get.varinfo self#behavior vo)) !log_map;
           | _ -> ()
         end;
         Visitor_behavior.Unset.logic_var self#behavior (Cil.cvar_to_lvar vo);
         Visitor_behavior.Set.logic_var self#behavior
           (Cil.cvar_to_lvar vo) (Cil.cvar_to_lvar var);

         begin
           match Cil_datatype.Logic_var.Map.find (Cil.cvar_to_lvar vo) !log_map_orig with
           | exception Not_found ->
             log_map_orig := Cil_datatype.Logic_var.Map.add
                 (Cil.cvar_to_lvar vo)
                 (Cil.cvar_to_lvar (Visitor_behavior.Get_orig.varinfo self#behavior vo))
                 !log_map_orig;
           | _ -> ()
         end;
         Visitor_behavior.Unset_orig.logic_var self#behavior (Cil.cvar_to_lvar vo);
         Visitor_behavior.Set_orig.logic_var self#behavior
           (Cil.cvar_to_lvar var) (Cil.cvar_to_lvar vo);

       | _ -> assert false) map

let binder_no_local_logic f apply id self formalsinit formalsi global_map =
  let log_map = ref Cil_datatype.Logic_var.Map.empty in
  let log_map_orig = ref Cil_datatype.Logic_var.Map.empty in

  (*Make the binding for the formals*)
  assert (List.length formalsinit = List.length formalsi);
  List.iter2
    (fun a b ->
       log_map := Cil_datatype.Logic_var.Map.add
           (Cil.cvar_to_lvar a)
           (Cil.cvar_to_lvar (Visitor_behavior.Get.varinfo self#behavior a)) !log_map;
       Visitor_behavior.Unset.logic_var self#behavior (Cil.cvar_to_lvar a);
       Visitor_behavior.Set.logic_var self#behavior
         (Cil.cvar_to_lvar a) b)
    formalsinit formalsi;

  List.iter2
    (fun a b ->
       log_map_orig := Cil_datatype.Logic_var.Map.add
           (Cil.cvar_to_lvar b)
           (Cil.cvar_to_lvar (Visitor_behavior.Get_orig.varinfo self#behavior b))
           !log_map_orig;
       Visitor_behavior.Unset_orig.logic_var self#behavior a;
       Visitor_behavior.Set_orig.logic_var self#behavior
         a (Cil.cvar_to_lvar b))
    formalsi formalsinit;

  (*Make the binding for the globale variable*)
  begin
    match id with
    | None ->  ()
    | Some _ ->
      begin
        let (from_map,assert_map,from_p_map,assert_p_map) =
          global_map
        in
        global_binder_aux assert_map self log_map log_map_orig;
        global_binder_aux from_map self log_map log_map_orig;
        global_binder_aux from_p_map self log_map log_map_orig;
        global_binder_aux assert_p_map self log_map log_map_orig;
      end
  end;

  let data = f apply in

  Cil_datatype.Logic_var.Map.iter (fun a b ->
      Visitor_behavior.Unset.logic_var self#behavior a;
      Visitor_behavior.Set.logic_var self#behavior
        a b) !log_map;

  Cil_datatype.Logic_var.Map.iter (fun a b ->
      Visitor_behavior.Unset_orig.logic_var self#behavior a;
      Visitor_behavior.Set_orig.logic_var self#behavior
        a b) !log_map_orig;
  data

let binder_sub f apply id self formalsinit formalsi global_map =
  let var_map = ref Cil_datatype.Varinfo.Map.empty in
  let log_map = ref Cil_datatype.Logic_var.Map.empty in
  let var_map_orig = ref Cil_datatype.Varinfo.Map.empty in
  let log_map_orig = ref Cil_datatype.Logic_var.Map.empty in

  (*Make the binding for the formals*)
  assert (List.length formalsinit = List.length formalsi);
  List.iter2 (fun x y ->
      var_map := Cil_datatype.Varinfo.Map.add x
          (Visitor_behavior.Get.varinfo self#behavior x) !var_map;
      Visitor_behavior.Unset.varinfo self#behavior x;
      Visitor_behavior.Set.varinfo self#behavior x y ) formalsinit formalsi;

  List.iter2 (fun x y ->
      var_map_orig := Cil_datatype.Varinfo.Map.add y
          (Visitor_behavior.Get_orig.varinfo self#behavior y)
          !var_map_orig;
      Visitor_behavior.Unset_orig.varinfo self#behavior x;
      Visitor_behavior.Set_orig.varinfo self#behavior x y) formalsi formalsinit;

  List.iter2
    (fun a b ->
       log_map := Cil_datatype.Logic_var.Map.add
           (Cil.cvar_to_lvar a)
           (Cil.cvar_to_lvar (Visitor_behavior.Get.varinfo self#behavior a)) !log_map;
       Visitor_behavior.Unset.logic_var self#behavior (Cil.cvar_to_lvar a);
       Visitor_behavior.Set.logic_var self#behavior
         (Cil.cvar_to_lvar a) (Cil.cvar_to_lvar b))
    formalsinit formalsi;

  List.iter2
    (fun a b ->
       log_map_orig := Cil_datatype.Logic_var.Map.add
           (Cil.cvar_to_lvar b)
           (Cil.cvar_to_lvar (Visitor_behavior.Get_orig.varinfo self#behavior b))
           !log_map_orig;
       Visitor_behavior.Unset_orig.logic_var self#behavior (Cil.cvar_to_lvar a);
       Visitor_behavior.Set_orig.logic_var self#behavior
         (Cil.cvar_to_lvar a) (Cil.cvar_to_lvar b))
    formalsi formalsinit;

  (*Make the binding for the globale variable*)
  begin
    match id with
    | None ->  ()
    | Some _ ->
      begin
        let (from_map,assert_map,from_p_map,assert_p_map) =
          global_map
        in
        global_binder assert_map self var_map var_map_orig log_map log_map_orig;
        global_binder from_map self var_map var_map_orig log_map log_map_orig;
        global_binder from_p_map self var_map var_map_orig log_map log_map_orig;
        global_binder assert_p_map self var_map var_map_orig log_map log_map_orig;
      end
  end;

  let data = f apply in

  Cil_datatype.Varinfo.Map.iter ( fun x y ->
      Visitor_behavior.Unset.varinfo self#behavior x;
      Visitor_behavior.Set.varinfo self#behavior
        x y) !var_map;

  Cil_datatype.Logic_var.Map.iter (fun a b ->
      Visitor_behavior.Unset.logic_var self#behavior a;
      Visitor_behavior.Set.logic_var self#behavior
        a b) !log_map;

  Cil_datatype.Varinfo.Map.iter ( fun x y ->
      Visitor_behavior.Unset_orig.varinfo self#behavior x;
      Visitor_behavior.Set_orig.varinfo self#behavior
        x y) !var_map_orig;

  Cil_datatype.Logic_var.Map.iter (fun a b ->
      Visitor_behavior.Unset_orig.logic_var self#behavior a;
      Visitor_behavior.Set_orig.logic_var self#behavior
        a b) !log_map_orig;
  data


let binder f apply funct id self locals formalsi global_map =

  let var_map = ref Cil_datatype.Varinfo.Map.empty in
  let log_map = ref Cil_datatype.Logic_var.Map.empty in
  let var_map_orig = ref Cil_datatype.Varinfo.Map.empty in
  let log_map_orig = ref Cil_datatype.Logic_var.Map.empty in

  (*Make the binding for the formals*)
  assert (List.length funct.sformals = List.length formalsi);
  List.iter2 (fun x y ->
      var_map := Cil_datatype.Varinfo.Map.add x
          (Visitor_behavior.Get.varinfo self#behavior x) !var_map;
      Visitor_behavior.Unset.varinfo self#behavior x;
      Visitor_behavior.Set.varinfo self#behavior x y ) funct.sformals formalsi;

  List.iter2 (fun x y ->
      var_map_orig := Cil_datatype.Varinfo.Map.add y
          (Visitor_behavior.Get_orig.varinfo self#behavior y)
          !var_map_orig;
      Visitor_behavior.Unset_orig.varinfo self#behavior x;
      Visitor_behavior.Set_orig.varinfo self#behavior x y) formalsi funct.sformals;

  List.iter2
    (fun a b ->
       log_map := Cil_datatype.Logic_var.Map.add
           (Cil.cvar_to_lvar a)
           (Cil.cvar_to_lvar (Visitor_behavior.Get.varinfo self#behavior a)) !log_map;
       Visitor_behavior.Unset.logic_var self#behavior (Cil.cvar_to_lvar a);
       Visitor_behavior.Set.logic_var self#behavior
         (Cil.cvar_to_lvar a) (Cil.cvar_to_lvar b))
    funct.sformals formalsi;

  List.iter2
    (fun a b ->
       log_map_orig := Cil_datatype.Logic_var.Map.add
           (Cil.cvar_to_lvar b)
           (Cil.cvar_to_lvar (Visitor_behavior.Get_orig.varinfo self#behavior b))
           !log_map_orig;
       Visitor_behavior.Unset_orig.logic_var self#behavior (Cil.cvar_to_lvar a);
       Visitor_behavior.Set_orig.logic_var self#behavior
         (Cil.cvar_to_lvar a) (Cil.cvar_to_lvar b))
    formalsi funct.sformals;

  (*Make the binding for the locals*)
  assert (List.length funct.slocals = List.length locals);
  List.iter2 (fun x y ->
      var_map := Cil_datatype.Varinfo.Map.add x
          (Visitor_behavior.Get.varinfo self#behavior x) !var_map;
      Visitor_behavior.Unset.varinfo self#behavior x;
      Visitor_behavior.Set.varinfo self#behavior x y ) funct.slocals locals;

  List.iter2 (
    fun x y ->
      var_map_orig := Cil_datatype.Varinfo.Map.add y
          (Visitor_behavior.Get_orig.varinfo self#behavior y)
          !var_map_orig;
      Visitor_behavior.Unset_orig.varinfo self#behavior x;
      Visitor_behavior.Set_orig.varinfo self#behavior x y) locals funct.slocals;

  List.iter2
    (fun a b ->
       log_map := Cil_datatype.Logic_var.Map.add
           (Cil.cvar_to_lvar a)
           (Cil.cvar_to_lvar (Visitor_behavior.Get.varinfo self#behavior a)) !log_map;
       Visitor_behavior.Unset.logic_var self#behavior (Cil.cvar_to_lvar a);
       Visitor_behavior.Set.logic_var self#behavior
         (Cil.cvar_to_lvar a) (Cil.cvar_to_lvar b))
    funct.slocals locals;

  List.iter2
    (fun a b ->
       log_map_orig := Cil_datatype.Logic_var.Map.add
           (Cil.cvar_to_lvar b)
           (Cil.cvar_to_lvar (Visitor_behavior.Get_orig.varinfo self#behavior b))
           !log_map_orig;
       Visitor_behavior.Unset_orig.logic_var self#behavior (Cil.cvar_to_lvar a);
       Visitor_behavior.Set_orig.logic_var self#behavior
         (Cil.cvar_to_lvar a) (Cil.cvar_to_lvar b))
    locals funct.slocals;

  (*Make the binding for the globale variable*)
  begin
    match id with
    | None ->  ()
    | Some _ ->
      begin
        let (from_map,assert_map,from_p_map,assert_p_map) =
          global_map
        in
        global_binder assert_map self var_map var_map_orig log_map log_map_orig;
        global_binder from_map self var_map var_map_orig log_map log_map_orig;
        global_binder from_p_map self var_map var_map_orig log_map log_map_orig;
        global_binder assert_p_map self var_map var_map_orig log_map log_map_orig;
      end
  end;

  let data = f apply in

  Cil_datatype.Varinfo.Map.iter ( fun x y ->
      Visitor_behavior.Unset.varinfo self#behavior x;
      Visitor_behavior.Set.varinfo self#behavior
        x y) !var_map;

  Cil_datatype.Logic_var.Map.iter (fun a b ->
      Visitor_behavior.Unset.logic_var self#behavior a;
      Visitor_behavior.Set.logic_var self#behavior
        a b) !log_map;

  Cil_datatype.Varinfo.Map.iter ( fun x y ->
      Visitor_behavior.Unset_orig.varinfo self#behavior x;
      Visitor_behavior.Set_orig.varinfo self#behavior
        x y) !var_map_orig;

  Cil_datatype.Logic_var.Map.iter (fun a b ->
      Visitor_behavior.Unset_orig.logic_var self#behavior a;
      Visitor_behavior.Set_orig.logic_var self#behavior
        a b) !log_map_orig;
  data

(**
   Function for making substitution in behavior
*)
let do_one_behavior_vis kf formalsi id global_map self annot =
  let f p =
    let vis = new aux_visitor_5 self#behavior in
    Visitor.visitFramacBehaviors vis p
  in
  let formalsinit = Kernel_function.get_formals kf in
  let terms =
    binder_sub f annot id self formalsinit formalsi global_map
  in
  terms

class aux_visitor_4 vis current add_global id global_map proj annot_data loc num =
  object(self)
    inherit Visitor.generic_frama_c_visitor (vis#behavior)

    method private add_new_func vi decl =
      let spec = Cil.empty_funspec () in
      Globals.Functions.replace_by_declaration spec vi decl;
      add_global (GFunDecl(spec,vi,decl))

    method private add_rela_func rename new_kf current_kf =
      List.iter (fun (pred,log,log_pure) ->
          if not(num = pred) || rename then
            begin
              Rpp_axiomatic_generator.generat_behavior_for_kf
                loc self log (new_kf,Visitor_behavior.Get.kernel_function vis#behavior current_kf)
                global_map;
              Rpp_axiomatic_generator.generat_behavior_pure_for_kf
                loc self log_pure (new_kf,Visitor_behavior.Get.kernel_function vis#behavior current_kf)
            end
          else ();
        ) annot_data;

    method private add_rela_pure_func v rename new_kf current_kf =
      List.iter (fun (pred,log,log_pure) ->
          if not(num = pred) || rename then
            begin
              Rpp_axiomatic_generator.generat_behavior_pure_for_kf
                loc self log_pure (new_kf,Visitor_behavior.Get.kernel_function vis#behavior current_kf);
              Rpp_axiomatic_generator.generat_behavior_for_kf
                loc self log (new_kf,Visitor_behavior.Get.kernel_function vis#behavior current_kf)
                global_map;
            end
          else ();
        )annot_data;
      let log_pure =
        List.fold_left (fun acc (pred,_,x) ->
            if not(num = pred) || rename then
              x.predicate_info_pure :: acc
            else
              acc
          ) [] annot_data
      in
      let exists = List.exists(fun x ->
          let find = ref false in
          Hashtbl.iter(fun _ (_,kf) ->
              find := !find || (String.equal (Kernel_function.get_name kf) v.vname);
            ) x;
          !find;
        ) log_pure
      in
      begin
        match exists with
        | true -> Rpp_axiomatic_generator.generat_help_behavior_pure_for_kf
                    loc log_pure (new_kf,Visitor_behavior.Get.kernel_function vis#behavior current_kf);
        | _ -> ()
      end;

    method private replace_func id v rename expl return l s name =
      let aux vari =
        try Globals.Functions.get vari with
        | Not_found ->  Rpp_options.Self.fatal
                          "Can not found the kernel function  %a"
                          Printer.pp_varinfo vari
        | _ -> assert false
      in
      match  Globals.Functions.find_by_name name with
      | exception Not_found ->
        let new_vi =
          Cil.makeVarinfo
            ~source:false ~temp:false true false name (v.vtype)
        in
        self#add_new_func new_vi v.vdecl;
        let new_kf= try Globals.Functions.get new_vi with
          | Not_found ->  Rpp_options.Self.fatal
                            "Can not found the new kernel function  %a"
                            Printer.pp_varinfo new_vi
          | _ -> assert false
        in
        let annot,current_kf =
          Project.on proj (
            fun x -> let x = aux x in (Annotations.behaviors x, x)
          ) (Visitor_behavior.Get_orig.varinfo vis#behavior v)
        in
        let formalsi = Kernel_function.get_formals new_kf in
        let annot =
          do_one_behavior_vis current_kf formalsi id global_map self annot
        in
        Annotations.add_behaviors
          ~register_children:true (Rpp_options.emitter) new_kf annot;
        begin
          match id with
          | Some _ ->
            self#add_rela_func rename new_kf current_kf
          | None ->
            self#add_rela_pure_func v rename new_kf current_kf;
        end;
        let new_exp = Var(new_vi) in
        s.skind <- Instr(Call(return,new_exp,expl,l));
        s

      | kf ->
        let current_kf =
          Project.on proj (
            fun x ->
              aux x
          ) (Visitor_behavior.Get_orig.varinfo vis#behavior v)
        in
        begin
          match id with
          | Some _ ->
            self#add_rela_func rename kf current_kf
          | None ->
            self#add_rela_pure_func v rename kf current_kf;
        end;
        let new_exp = Var(Globals.Functions.get_vi kf) in
        s.skind <- Instr(Call(return,new_exp,expl,l));
        s

    method private is_inlined v =
      match current with
      | None -> false
      | Some fonct ->
        begin
          let funct =
            Kernel_function.get_definition fonct
          in
          let vo = Visitor_behavior.Get.varinfo self#behavior funct.svar in
          Cil_datatype.Varinfo.equal v vo
        end

    method! vstmt_aux s =
      match s.skind with
      | Instr(Call(return,exp1,expl,l)) ->
        begin
          match exp1 with
          | Var v ->
            begin
              let rename =
                self#is_inlined v
              in
              match id with
              | Some id ->
                let name =
                  String.concat "_" [v.vname;id]
                in
                let new_s =
                  self#replace_func (Some id) v rename expl return l s name
                in
                Cil.ChangeDoChildrenPost(new_s, fun x->x)

              | None ->
                let name =
                  String.concat "_"
                    [v.vname;"aux";string_of_int num]
                in
                let new_s =
                  self#replace_func None v rename expl return l s name
                in
                Cil.ChangeDoChildrenPost(new_s, fun x->x)
            end
          | _ ->
            let (l,_) = loc in
            Rpp_options.Self.abort ~source:l
              "Function pointers are not supported: %a @."
              Printer.pp_stmt s
        end
      | _ -> Cil.ChangeDoChildrenPost(s,fun x->x)
  end

(**
   Function for making substitution in term
*)
let do_one_terms_vis_axiom id global_map formal_map self terms =
  let global_map =
    let data =
      List.find (fun x -> String.equal (x.id) id)
        global_map
    in
    (data.from_map_logic,data.assigns_map_logic,data.from_map_p_logic,data.assigns_map_p_logic)
  in
  let f p =
    let vis = new aux_visitor_7 self#behavior formal_map in
    Visitor.visitFramacTerm vis p
  in
  let terms =
    binder_aux f terms (Some id) self global_map
  in
  terms

(**
   Function for making substitution in term
*)
let do_one_simpl_term_vis kf formalsi id global_map self term =
  let f t =
    let vis = new Visitor.generic_frama_c_visitor(self#behavior) in
    Visitor.visitFramacTerm vis t
  in
  let formalsinit = Kernel_function.get_formals kf in
  let terms =
    binder_no_local_logic f term id self formalsinit formalsi global_map
  in
  terms

(**
   Function for making substitution in term
*)
let do_one_terms_vis kf formalsi locals id global_map self terms=
  let global_map =
    match id with
    | None ->
      let map =
        Cil_datatype.Varinfo.Map.empty
      in
      (map,map,map,map)
    | Some id ->
      let data =
        List.find (fun x -> String.equal (x.id_call) id)
          global_map
      in
      (data.froms_map,data.assigns_map,data.froms_map_p,data.assigns_map_p)
  in
  match kf.fundec with
  | Declaration (_,_,param,_) ->
    begin
      let f p =
        let vis = new aux_visitor_6 self#behavior in
        vis#set_current_kf kf;
        Visitor.visitFramacTerm vis p
      in
      let formalsinit = match param with
        | None | Some [] -> []
        | Some formalsinit -> formalsinit
      in
      binder_sub f terms id self formalsinit formalsi global_map
    end

  | Definition (funct,_) ->
    let f p =
      let vis = new aux_visitor_6 self#behavior in
      vis#set_current_func funct;
      vis#set_current_kf kf;
      Visitor.visitFramacTerm vis p
    in
    binder f terms funct id self locals formalsi global_map

(**
   Function for making one copy of terms
*)
let do_one_require_copy kf formalsi id global_map self proj=
  let f p =
    let vis = new aux_visitor_2 self#behavior in
    let beh =
      Project.on proj (Visitor.visitFramacBehaviors vis) p
    in
    beh
  in
  match kf.fundec with
  | Declaration (_,_,param,_) ->
    begin
      let formalsinit = match param with
        | None | Some [] -> []
        | Some formalsinit -> formalsinit
      in
      binder_sub
        f ((Annotations.behaviors kf)) id self formalsinit formalsi global_map
    end
  | Definition (funct,_) ->
    begin
      binder_sub
        f ((Annotations.behaviors kf)) id self funct.sformals formalsi global_map
    end

(**
   Function making a copie of the local variable of copie funct for new_funct
*)
let make_local new_funct copie_funct i self loc =
  let rec aux locals i acc =
    match locals with
    | [] -> acc
    | h :: q ->
      let name =
        String.concat "_" [h.vname; string_of_int i ]
      in
      let old_blk_vi = new_funct.sbody.blocals in
      let varinfo =
        Cil.makeLocalVar new_funct name
          (get_typ_in_current_project h.vtype self loc)
      in
      varinfo.vdefined <- h.vdefined;
      new_funct.sbody.blocals <- old_blk_vi;
      aux q i (varinfo:: acc)
  in
  List.rev(aux copie_funct.slocals i [])

(**
   Function for sorting the require clause from the copy of behaviors
*)
let sort_funbehavior funbehavior =
  let rec aux funbe acc =
    match funbe with
    | [] -> acc
    | h :: q -> if Cil.is_default_behavior h then aux q (h.b_requires @ acc)
      else (
        if List.length h.b_requires == 0 then aux q acc else
          Rpp_options.Self.abort
            "Require clauses are only supported in default behaviour\
             (Require clause exist in %s)" h.b_name
      )
  in aux funbehavior []

(**
   Function detecting if a function is variadic
*)
let is_variadic_function vi = Ast_types.is_variadic vi.vtype

(**
   Function detecting the function to be inlined and call the inline function
*)
let inliner self proj funct id global_map = object (_)
  inherit Visitor.frama_c_inplace

  method !vstmt_aux stmt =
    match stmt.skind with
    | Instr(Call(return, Var vi, args, loc)) ->
      begin
        if is_variadic_function vi then
          begin
            Rpp_options.Self.warning ~current:true ~once:true
              "Variadic function call are not\
               supported:@ @[%a@] @." Printer.pp_stmt stmt;
            Cil.DoChildrenPost(fun _-> stmt)
          end
        else
          begin
            let aux vari =
              try Globals.Functions.get vari with
              | Not_found ->  Rpp_options.Self.fatal
                                "Can not found the kernel function:@ @[%a@] @."
                                Printer.pp_varinfo vari
              | _ -> assert false
            in
            let kf =
              Project.on proj (
                fun x ->
                  aux x
              ) (Visitor_behavior.Get_orig.varinfo self#behavior vi)
            in
            let inline_funct =
              match Kernel_function.get_definition kf with
              | exception _ -> Rpp_options.Self.fatal
                                 "Can not found the definition of function:@ @[%a@] @."
                                 Printer.pp_varinfo vi
              | x -> x
            in
            let locals =
              make_local
                (funct) inline_funct
                (Rpp_options.Counting_local_variable_copies.next()) self#behavior loc
            in

            let formals, initializers =
              (* Formals become locals of the new block. They are initialized to the
                 corresponding argument. *)
              try
                List.fold_left2
                  (fun (vars, inits) h exp ->
                     let name =
                       String.concat "_"
                         ["aux_local_variable";
                          string_of_int (Rpp_options.Counting_aux_local_variable.next())]
                     in
                     let old_blk_vi = funct.sbody.blocals in
                     let vi' =
                       Cil.makeLocalVar
                         funct name (get_typ_in_current_project h.vtype self#behavior loc)
                     in
                     funct.sbody.blocals <- old_blk_vi;
                     let init =
                       Cil.mkStmtOneInstr ~valid_sid:true
                         (Set ((Var vi', NoOffset), exp, exp.eloc))
                     in
                     vi' :: vars, init :: inits)
                  ([], []) inline_funct.sformals
                  args
              with Invalid_argument _ ->
                Rpp_options.Self.fatal "inliner: undetected variadic function call:@ @[%a@] @."
                  Printer.pp_varinfo vi
            in
            let resi =
              match return with
              | Some ((Var(v),NoOffset)) -> Some v
              | Some (x) ->
                Rpp_options.Self.fatal "Unsupported return variable in inlier:@ @[%a@] @."
                  Printer.pp_lval x
              | None -> None
            in
            let f p =
              (*Save the current new kf and make a binding with the wrapper
                function for code annotation generation*)
              let buffer_kf = Visitor_behavior.Get.kernel_function self#behavior kf in
              Visitor_behavior.Set.kernel_function self#behavior
                kf
                (Globals.Functions.get (funct.svar));
              let vis = new aux_visitor self#behavior resi in
              vis#set_current_func inline_funct;
              vis#set_current_kf kf;
              let bodys = funct.sbody in
              let locals = funct.slocals in
              let formals = funct.sformals in
              let body =
                Project.on proj (Visitor.visitFramacBlock vis) p
              in
              funct.sbody <- bodys;
              funct.slocals <- locals;
              funct.sformals <- formals;
              (*Make binding for reversing the last binding with the kf*)
              Visitor_behavior.Set.kernel_function self#behavior
                kf
                buffer_kf;
              body
            in
            let body =
              binder f (inline_funct.sbody) inline_funct id self locals formals global_map
            in
            let inline_body = Cil.mkBlock [(Cil.mkStmt ~valid_sid:true (Block body))] in
            let first_stmt = List.hd (inline_body.bstmts) in
            inline_body.blocals <- formals;
            inline_body.bstmts <- initializers @ inline_body.bstmts;

            (*The body include some assert clauses corresponding to requires clauses*)
            (*Copy of require clauses and transformation to assert clause*)
            let behaviours =
              do_one_require_copy
                kf formals id global_map self proj
            in
            let requires =
              sort_funbehavior behaviours
            in
            List.iter(fun data ->
                let top_pred =
                  Logic_const.(toplevel_predicate (pred_of_id_pred data))
                in
                let the_code_annotation =
                  Logic_const.new_code_annotation (AAssert ([],top_pred))
                in
                Annotations.add_code_annot
                  Rpp_options.emitter ~kf:(Globals.Functions.get (funct.svar))
                  first_stmt
                  the_code_annotation
              )requires;
            Cil.DoChildrenPost(fun _ -> Cil.mkStmt ~valid_sid:true (Block inline_body))
          end
      end
    | Instr(Call(_)) ->
      Rpp_options.Self.warning ~current:true
        "Function pointer are not\
         supported:@ @[%a@] @." Printer.pp_stmt stmt;
      Cil.DoChildren

    | _ -> Cil.DoChildren
end

let no_inline resi self kf l formalsi proof id global_map proj annot_data num =
  let return_lval = match resi with
    | None -> None
    | Some x -> Some(Var(x),NoOffset)
  in
  let current_kf = Visitor_behavior.Get.kernel_function self#behavior kf in
  let var_funct = match current_kf.fundec with
    | Definition (f,_) -> f.svar
    | Declaration (_,v,_,_) -> v
  in
  let func = Var var_funct in
  let params =
    List.map (fun x -> Cil.new_exp ~loc:l (Lval(Var(x),NoOffset)))
      formalsi
  in
  let k = Instr(Call(return_lval, func, params, l))
  in
  let s = Cil.mkStmt ~valid_sid:true k
  in
  let b = {battrs = [];
           bscoping = true;
           blocals = [];
           bstatics = [];
           bstmts = [s]}
  in
  if not proof then
    begin
      let funct_vis = new aux_visitor_4
        self None self#add_new_global
        id global_map proj annot_data l num
      in
      Visitor.visitFramacBlock funct_vis b
    end
  else
    b

let do_inline self kf new_funct resi funct proj locals formalsi global_map id proof n l num annot_data =
  let f p =
    (*Save the current new kf and make a binding with the wrapper
      function for code annotation generation*)
    let buffer_kf = Visitor_behavior.Get.kernel_function self#behavior kf in

    Visitor_behavior.Set.kernel_function self#behavior
      kf
      (Globals.Functions.get (new_funct.svar));

    let vis = new aux_visitor (self#behavior) resi in
    vis#set_current_func funct;
    vis#set_current_kf kf;
    let bodys = new_funct.sbody in
    let locals = new_funct.slocals in
    let formals = new_funct.sformals in
    let body =
      Project.on proj (Visitor.visitFramacBlock vis) p
    in
    new_funct.sbody <- bodys;
    new_funct.slocals <- locals;
    new_funct.sformals <- formals;
    (*Make binding for reversing the last binding with the kf*)
    Visitor_behavior.Set.kernel_function self#behavior
      kf
      buffer_kf;
    body
  in
  let body =
    binder f (funct.sbody) funct id self locals formalsi global_map
  in
  (* Inlining all function  *)
  let rec aux b i =
    match i with
    | 0 -> b
    | k ->
      let vis =
        inliner self proj new_funct id global_map
      in
      let block =
        Visitor.visitFramacBlock vis b
      in
      aux block (k - 1)
  in
  let new_body = aux body (n - 1) in
  if not proof then
    begin
      let funct_vis = new aux_visitor_4
        self (Some kf)
        self#add_new_global
        id global_map proj annot_data l num
      in
      funct_vis#set_current_func new_funct;
      funct_vis#set_current_kf (Globals.Functions.get (new_funct.svar));
      let new_body = Visitor.visitFramacBlock funct_vis new_body in
      new_body
    end
  else new_body


(**
   Function for making one copy of the body of kf
*)
let do_one_copy ?(proof=false) kf formalsi resi locals id global_map inline new_funct self proj l annot_data num =
  match Kernel_function.get_definition kf with
  | exception _ -> no_inline resi self kf l formalsi proof id global_map proj annot_data num
  | funct ->
    begin
      match inline with
      | 0 ->
        no_inline resi self kf l formalsi proof id global_map proj annot_data num
      | n ->
        do_inline self kf new_funct resi funct proj locals
          formalsi global_map id proof n l num annot_data
    end