Major optimization, rewrite to avoid deep recursion if possible.
[SXSI/xpathcomp.git] / ata.ml
diff --git a/ata.ml b/ata.ml
index 99f5c97..5288b78 100644 (file)
--- a/ata.ml
+++ b/ata.ml
@@ -1,6 +1,6 @@
 INCLUDE "debug.ml"
 INCLUDE "utils.ml"
-
+open Camlp4.Struct
 type jump_kind = [ `TAG of Tag.t | `CONTAINS of string | `NOTHING ]
 
 (* Todo : move elsewhere *)
@@ -14,8 +14,9 @@ end =
 struct
   type t = int
   let make = 
-    let id = ref (-1) in
-      fun () -> incr id;!id
+    let id = ref ~-1 in
+    fun () -> incr id; !id
+
   let compare = (-)
   let equal = (==)
   external hash : t -> int =  "%identity"
@@ -25,8 +26,25 @@ struct
     if x < 0 then failwith (Printf.sprintf "State: Assertion %i < 0 failed" x)
 end
 
-module StateSet = Ptset.Int
-  
+module StateSet = 
+struct
+  include Ptset.Make ( struct type t = int 
+                             type data = t
+                             external hash : t -> int = "%identity"
+                             external uid : t -> Uid.t = "%identity"
+                             external equal : t -> t -> bool = "%eq"
+                             external make : t -> int = "%identity"
+                             external node : t -> int = "%identity"
+                             external with_id : Uid.t -> t = "%identity"
+                      end
+                    ) 
+  let print ppf s = 
+    Format.pp_print_string ppf "{ ";
+    iter (fun i -> Format.fprintf ppf "%i " i) s;
+    Format.pp_print_string ppf "}";
+    Format.pp_print_flush ppf ()
+end
+
 module Formula =
 struct
     type 'hcons expr = 
@@ -58,8 +76,8 @@ struct
       match f.pos with
        | False -> 0
        | True -> 1
-       | Or (f1,f2) -> HASHINT3(PRIME2,f1.Node.id, f2.Node.id)
-       | And (f1,f2) -> HASHINT3(PRIME3,f1.Node.id,f2.Node.id)
+       | Or (f1,f2) -> HASHINT3(PRIME2,Uid.to_int f1.Node.id, Uid.to_int f2.Node.id)
+       | And (f1,f2) -> HASHINT3(PRIME3,Uid.to_int f1.Node.id, Uid.to_int f2.Node.id)
        | Atom(d,p,s) -> HASHINT4(PRIME4,hash_const_variant d,vb p,s)       
     end
 
@@ -197,7 +215,9 @@ module Transition = struct
   type node = State.t*TagSet.t*bool*Formula.t*bool
   include Hcons.Make(struct
                       type t = node
-                      let hash (s,ts,m,f,b) = HASHINT5(s,TagSet.uid ts,Formula.uid f,vb m,vb b)
+                      let hash (s,ts,m,f,b) = HASHINT5(s,Uid.to_int (TagSet.uid ts),
+                                                       Uid.to_int (Formula.uid f),
+                                                       vb m,vb b)
                       let equal (s,ts,b,f,m) (s',ts',b',f',m') = 
                         s == s' && ts == ts' && b==b' && m==m' && f == f'
                     end)
@@ -219,8 +239,6 @@ module Transition = struct
 
 end
 
-module TransTable = Hashtbl
 module Formlist = struct 
   include Hlist.Make(Transition)
   let print ppf fl = 
@@ -236,9 +254,9 @@ end
   
 type 'a t = { 
     id : int;
-    mutable states : Ptset.Int.t;
-    init : Ptset.Int.t;
-    starstate : Ptset.Int.t option;
+    mutable states : StateSet.t;
+    init : StateSet.t;
+    starstate : StateSet.t option;
     (* Transitions of the Alternating automaton *)
     trans : (State.t,(TagSet.t*Transition.t) list) Hashtbl.t;
     query_string: string;
@@ -284,7 +302,9 @@ module FormTable = Hashtbl.Make(struct
                                  let equal (f1,s1,t1) (f2,s2,t2) =
                                    f1 == f2 && s1 == s2 && t1 == t2
                                  let hash (f,s,t) = 
-                                   HASHINT3(Formula.uid f ,StateSet.uid s,StateSet.uid t)
+                                   HASHINT3(Uid.to_int (Formula.uid f),
+                                            Uid.to_int (StateSet.uid s),
+                                            Uid.to_int (StateSet.uid t))
                                end)
 module F = Formula
 
@@ -332,12 +352,16 @@ module FTable = Hashtbl.Make(struct
                               type t = Tag.t*Formlist.t*StateSet.t*StateSet.t
                               let equal (tg1,f1,s1,t1) (tg2,f2,s2,t2) =
                                 tg1 == tg2 && f1 == f2 &&  s1 == s2 && t1 == t2;;
-                              let hash (tg,f,s,t) =  HASHINT4(tg,Formlist.uid f ,StateSet.uid s,StateSet.uid t);;
+                              let hash (tg,f,s,t) =  
+                                HASHINT4(tg, Uid.to_int (Formlist.uid f),
+                                         Uid.to_int (StateSet.uid s),
+                                         Uid.to_int (StateSet.uid t))
                             end)
 
 
 let h_f = FTable.create BIG_H_SIZE 
-
+type merge_conf = NO | ONLY1 | ONLY2 | ONLY12 | MARK | MARK1 | MARK2 | MARK12
+(* 000 001 010 011 100 101 110 111 *)
 let eval_formlist tag s1 s2 fl =
   let rec loop fl =
           try 
@@ -355,8 +379,32 @@ let eval_formlist tag s1 s2 fl =
                      else res
                      in FTable.add h_f (tag,fl,s1,s2) r;r
                  | Formlist.Nil -> StateSet.empty,(false,false,false,false)
-  in loop fl
-             
+  in 
+  let r,conf = loop fl
+  in
+  r,(match  conf with
+    | (false,_,_,_) -> NO
+    | (_,false,false,false) -> NO
+    | (_,true,false,false) -> ONLY1
+    | (_,false,true,false) -> ONLY2
+    | (_,true,true,false) -> ONLY12
+    | (_,false,false,true) -> MARK
+    | (_,true,false,true) -> MARK1
+    | (_,false,true,true) -> MARK2
+    | _ -> MARK12)
+
+let bool_of_merge conf =
+  match  conf with
+    | NO -> false,false,false,false
+    | ONLY1 -> true,true,false,false
+    | ONLY2 -> true,false,true,false 
+    | ONLY12 -> true,true,true,false 
+    | MARK -> true,false,false,true
+    | MARK1 -> true,true,false,true
+    | MARK2 -> true,false,true,true
+    | MARK12 -> true,true,true,true
+
+
 let tags_of_state a q = 
   Hashtbl.fold  
     (fun p l acc -> 
@@ -394,7 +442,7 @@ let tags_of_state a q =
       val fold : ( elt -> 'a -> 'a) -> t -> 'a -> 'a
       val map : ( elt -> elt) -> t -> t
       val length : t -> int
-      val merge : (bool*bool*bool*bool) -> elt -> t -> t -> t 
+      val merge : merge_conf -> elt -> t -> t -> t 
       val mk_quick_tag_loop : (elt -> elt -> 'a*t array) -> 'a -> int -> Tree.t -> Tag.t -> (elt -> elt -> 'a*t array)
       val mk_quick_star_loop : (elt -> elt -> 'a*t array) -> 'a -> int -> Tree.t -> (elt -> elt -> 'a*t array)
     end
@@ -403,6 +451,7 @@ let tags_of_state a q =
     struct
       type t = int
       type elt = [`Tree] Tree.node
+
       let empty = 0
       let cons _ x = x+1
       let concat x y = x + y
@@ -410,7 +459,8 @@ let tags_of_state a q =
       let fold _ _ _ = failwith "fold not implemented"
       let map _ _ = failwith "map not implemented"
       let length x = x
-      let merge (rb,rb1,rb2,mark) t res1 res2 = 
+      let merge2 conf t res1 res2 = 
+       let rb,rb1,rb2,mark = conf in
        if rb then
          let res1 = if rb1 then res1 else 0
          and res2 = if rb2 then res2 else 0
@@ -418,6 +468,21 @@ let tags_of_state a q =
            if mark then 1+res1+res2
            else res1+res2
        else 0
+      let merge conf t res1 res2 = 
+       match conf with
+         | NO -> 0                         
+         | ONLY1 -> res1                
+         | ONLY2 -> res2           
+         | ONLY12 -> res1+res2     
+         | MARK -> 1
+         | MARK1 -> res1+1         
+         | MARK2 -> res2+1         
+         | MARK12 -> res1+res2+1   
+      let merge conf _ res1 res2 =
+       let conf = Obj.magic conf in 
+       (conf lsr 2) + ((conf land 0b10) lsr 1)*res2 + (conf land 0b1)*res1
+
+
       let mk_quick_tag_loop _ sl ss tree tag = ();
        fun t ctx ->
          (sl, Array.make ss (Tree.subtree_tags tree tag t))
@@ -427,7 +492,7 @@ let tags_of_state a q =
          
     end
 
-    module IdSet : ResultSet 
+    module IdSet : ResultSet= 
     struct
       type elt = [`Tree] Tree.node
       type node = Nil 
@@ -469,28 +534,34 @@ let tags_of_state a q =
        in
          { l with node = loop l.node }
            
-      let merge (rb,rb1,rb2,mark) t res1 res2 = 
-       if rb then
-         let res1 = if rb1 then res1 else empty
-         and res2 = if rb2 then res2 else empty
-         in
-           if mark then { node = Cons(t,(Concat(res1.node,res2.node)));
-                          length = res1.length + res2.length + 1;}
-           else
-             { node = (Concat(res1.node,res2.node));
-               length = res1.length + res2.length ;}
-       else empty 
+      let merge conf t res1 res2 = 
+       match conf with
+          NO -> empty
+         | MARK -> cons t empty
+         | ONLY1 -> res1
+         | ONLY2 -> res2
+         | ONLY12 -> { node = (Concat(res1.node,res2.node));
+                       length = res1.length + res2.length ;}
+         | MARK12 -> { node = Cons(t,(Concat(res1.node,res2.node)));
+                       length = res1.length + res2.length + 1;}
+         | MARK1 -> { node = Cons(t,res1.node);
+                       length = res1.length + 1;}
+         | MARK2 -> { node = Cons(t,res2.node);
+                      length = res2.length + 1;}
+
       let mk_quick_tag_loop f _ _ _ _ = f
       let mk_quick_star_loop f _ _ _ = f
     end
     module GResult(Doc : sig val doc : Tree.t end) = struct
       type bits
       type elt = [` Tree] Tree.node
-      external create_empty : int -> bits = "caml_result_set_create"
-      external set : bits -> int -> unit = "caml_result_set_set"
-      external next : bits -> int -> int = "caml_result_set_next"
-      external clear : bits -> elt -> elt -> unit = "caml_result_set_clear"
-
+      external create_empty : int -> bits = "caml_result_set_create" "noalloc"
+      external set : bits -> int -> unit = "caml_result_set_set" "noalloc"
+      external next : bits -> int -> int = "caml_result_set_next" "noalloc"
+      external count : bits -> int  = "caml_result_set_count" "noalloc"
+      external clear : bits -> elt -> elt -> unit = "caml_result_set_clear" "noalloc"
+        
+      external set_tag_bits : bits -> Tag.t -> Tree.t -> elt -> elt = "caml_set_tag_bits" "noalloc"
       type t = 
         { segments : elt list;
           bits : bits;
@@ -540,44 +611,96 @@ let tags_of_state a q =
          else (f ((Obj.magic i):elt);loop (next t.bits i))
        in loop (next t.bits 0)
          
-      let fold _ _ _ = failwith "noop"
+      let fold f t acc = 
+       let rec loop i acc = 
+         if i == -1 then acc
+         else loop (next t.bits i) (f ((Obj.magic i):elt) acc)
+       in loop (next t.bits 0) acc
+
       let map _ _ = failwith "noop"
-      let length t = let cpt = ref 0 in
-      iter (fun _ -> incr cpt) t; !cpt
+      (*let length t = let cpt = ref 0 in
+      iter (fun _ -> incr cpt) t; !cpt *)
+      let length t = count t.bits 
       
+      let clear_bits t = 
+       let rec loop l = match l with
+          [] -> ()
+         | idx::ll ->
+             clear t.bits idx (Tree.closing Doc.doc idx); loop ll
+       in
+       loop t.segments;empty
+
       let merge (rb,rb1,rb2,mark) elt t1 t2 =
        if rb then
 (*     let _ = Printf.eprintf "Lenght before merging is %i %i\n"
          (List.length t1.segments) (List.length t2.segments)
-       in      *)
+       in *)
        match t1.segments,t2.segments with
           [],[] -> if mark then cons elt empty else empty
-         | [p],[] when rb1 -> if mark then cons elt t1 else t1
-         | [], [p] when rb2 -> if mark then cons elt t2 else t2
-         | [x],[y] when rb1 && rb2 -> if mark then cons elt empty else
+         | [_],[] when rb1 -> if mark then cons elt t1 else t1
+         | [], [_] when rb2 -> if mark then cons elt t2 else t2
+         | [_],[_] when rb1 && rb2 -> if mark then cons elt empty else
            concat t1 t2
-         | _,_ -> 
-       let t1 = if rb1 then t1 else 
-       (List.iter (fun idx -> clear t1.bits idx (Tree.closing Doc.doc idx)) t1.segments;empty)
-       and t2 = if rb2 then t2 else 
-       (List.iter (fun idx -> clear t2.bits idx (Tree.closing Doc.doc idx)) t2.segments;empty)
+         | _ -> 
+       let t1 = if rb1 then t1 else clear_bits t1
+       and t2 = if rb2 then t2 else clear_bits t2
        in
        (if mark then cons elt (concat t1 t2)
         else concat t1 t2)
        else
-       let _ = 
-         List.iter (fun idx -> clear t1.bits idx (Tree.closing Doc.doc idx)) t1.segments;
-         List.iter (fun idx -> clear t2.bits idx (Tree.closing Doc.doc idx)) t2.segments
-       in
-       empty     
-      let mk_quick_tag_loop f _ _ _ _ = f
+       let _ = clear_bits t1 in
+       clear_bits t2
+
+      let merge conf t t1 t2 = 
+       match t1.segments,t2.segments,conf with
+         | _,_,NO -> let _ = clear_bits t1 in clear_bits t2
+         | [],[],(MARK1|MARK2|MARK12|MARK) -> cons t empty
+         | [],[],_ -> empty
+         | [_],[],(ONLY1|ONLY12) -> t1
+         | [_],[],(MARK1|MARK12) -> cons t t1
+         | [],[_],(ONLY2|ONLY12) -> t2
+         | [],[_],(MARK2|MARK12) -> cons t t2
+         | [_],[_],ONLY12 -> concat t1 t2
+         | [_],[_],MARK12 -> cons t empty
+         | _,_,MARK -> let _ = clear_bits t2 in cons t (clear_bits t1)     
+         | _,_,ONLY1 -> let _ = clear_bits t2 in t1
+         | _,_,ONLY2 -> let _ = clear_bits t1 in t2
+         | _,_,ONLY12 -> concat t1 t2
+         | _,_,MARK1 -> let _ = clear_bits t2 in cons t t1
+         | _,_,MARK2 -> let _ = clear_bits t1 in cons t t2
+         | _,_,MARK12 ->  cons t (concat t1 t2)
+
+      let mk_quick_tag_loop _ sl ss tree tag = ();
+       fun t _ ->        
+         let res = empty in
+         let first = set_tag_bits empty.bits tag tree t in
+         let res = 
+           if first == Tree.nil then res else 
+           cons first res 
+         in
+         (sl, Array.make ss res)
+
       let mk_quick_star_loop f _ _ _ = f
     end
     module Run (RS : ResultSet) =
     struct
 
-      module SList = Hlist.Make (StateSet)
-
+      module SList = struct 
+       include Hlist.Make (StateSet)
+       let print ppf l = 
+         Format.fprintf ppf "[ ";
+         begin
+           match l.Node.node with
+             | Nil -> ()
+             | Cons(s,ll) -> 
+                 StateSet.print ppf s;
+                 iter (fun s -> Format.fprintf ppf "; ";
+                       StateSet.print ppf s) ll
+         end;
+         Format.fprintf ppf "]%!"
+               
+           
+      end
 
 
 IFDEF DEBUG
@@ -586,11 +709,31 @@ THEN
 INCLUDE "html_trace.ml"
              
 END            
-      let mk_fun f s = D_IGNORE_(register_funname f s,f)
-      let mk_app_fun f arg s = let g = f arg in 
-       D_IGNORE_(register_funname g ((get_funname f) ^ " " ^ s), g) 
-      let mk_app_fun2 f arg1 arg2 s = let g = f arg1 arg2 in 
-       D_IGNORE_(register_funname g ((get_funname f) ^ " " ^ s), g) 
+      module Trace =
+      struct
+       module HFname = Hashtbl.Make (struct
+                                       type t = Obj.t
+                                       let hash = Hashtbl.hash
+                                       let equal = (==)
+                                     end)
+         
+       let h_fname = HFname.create 401
+         
+       let register_funname f s = 
+         HFname.add h_fname (Obj.repr  f) s
+       let get_funname f = try HFname.find h_fname  (Obj.repr f) with _ -> "[anon_fun]"
+
+
+
+       let mk_fun f s = register_funname f s;f
+       let mk_app_fun f arg s = 
+         let g = f arg in 
+         register_funname g ((get_funname f) ^ " " ^ s); g
+       let mk_app_fun2 f arg1 arg2 s = 
+         let g = f arg1 arg2 in 
+         register_funname g ((get_funname f) ^ " " ^ s); g 
+
+      end
 
       let string_of_ts tags = (Ptset.Int.fold (fun t a -> a ^ " " ^ (Tag.to_string t) ) tags "{")^ " }"
 
@@ -696,323 +839,648 @@ END
              if Ptset.Int.is_empty cl then
              if Ptset.Int.is_singleton ll then
              let tag = Ptset.Int.choose ll in 
-             (`TAG(tag),mk_app_fun f_tn tag (Tag.to_string tag))
+             (`TAG(tag),Trace.mk_app_fun f_tn tag (Tag.to_string tag))
              else
-             (`MANY(ll),mk_app_fun f_sn ll (string_of_ts ll))
+             (`MANY(ll),Trace.mk_app_fun f_sn ll (string_of_ts ll))
              else if Ptset.Int.is_empty ll then
              if Ptset.Int.is_singleton cl then
              let tag = Ptset.Int.choose cl in 
-             (`TAG(tag),mk_app_fun f_t1 tag (Tag.to_string tag))
+             (`TAG(tag),Trace.mk_app_fun f_t1 tag (Tag.to_string tag))
              else
-             (`MANY(cl),mk_app_fun f_s1 cl (string_of_ts cl))
+             (`MANY(cl),Trace.mk_app_fun f_s1 cl (string_of_ts cl))
              else
-             (`ANY,mk_app_fun2 f_s1n cl ll ((string_of_ts cl) ^ " " ^ (string_of_ts ll)))
+             (`ANY,Trace.mk_app_fun2 f_s1n cl ll ((string_of_ts cl) ^ " " ^ (string_of_ts ll)))
 
          | _ -> assert false
          
       let choose_jump_down tree d =
        choose_jump d
-         (mk_fun (fun _ -> Tree.nil) "Tree.mk_nil")
-         (mk_fun (Tree.tagged_child tree) "Tree.tagged_child") 
-         (mk_fun (Tree.select_child tree) "Tree.select_child")
-         (mk_fun (Tree.tagged_desc tree) "Tree.tagged_desc")
-         (mk_fun (Tree.select_desc tree) "Tree.select_desc") 
-         (mk_fun (fun _ _ -> Tree.first_child tree) "[FIRSTCHILD]Tree.select_child_desc")
-         (mk_fun (Tree.first_element tree) "Tree.first_element")
-         (mk_fun (Tree.first_child tree) "Tree.first_child") 
+         (Trace.mk_fun (fun _ -> Tree.nil) "Tree.mk_nil")
+         (Trace.mk_fun (Tree.tagged_child tree) "Tree.tagged_child") 
+         (Trace.mk_fun (Tree.select_child tree) "Tree.select_child")
+         (Trace.mk_fun (Tree.tagged_descendant tree) "Tree.tagged_desc")
+         (Trace.mk_fun (Tree.select_descendant tree) "Tree.select_desc") 
+         (Trace.mk_fun (fun _ _ -> Tree.first_child tree) "[FIRSTCHILD]Tree.select_child_desc")
+         (Trace.mk_fun (Tree.first_element tree) "Tree.first_element")
+         (Trace.mk_fun (Tree.first_child tree) "Tree.first_child") 
 
       let choose_jump_next tree d = 
        choose_jump d
-         (mk_fun (fun _ _ -> Tree.nil) "Tree.mk_nil2")
-         (mk_fun (Tree.tagged_sibling_ctx tree) "Tree.tagged_sibling_ctx")
-         (mk_fun (Tree.select_sibling_ctx tree) "Tree.select_sibling_ctx")
-         (mk_fun (Tree.tagged_foll_ctx tree) "Tree.tagged_foll_ctx")
-         (mk_fun (Tree.select_foll_ctx tree) "Tree.select_foll_ctx")
-         (mk_fun (fun _ _ -> Tree.next_sibling_ctx tree) "[NEXTSIBLING]Tree.select_sibling_foll_ctx")
-         (mk_fun (Tree.next_element_ctx tree) "Tree.next_element_ctx")   
-         (mk_fun (Tree.next_sibling_ctx tree) "Tree.node_sibling_ctx")   
+         (Trace.mk_fun (fun _ _ -> Tree.nil) "Tree.mk_nil2")
+         (Trace.mk_fun (Tree.tagged_following_sibling_below tree) "Tree.tagged_sibling_ctx")
+         (Trace.mk_fun (Tree.select_following_sibling_below tree) "Tree.select_sibling_ctx")
+         (Trace.mk_fun (Tree.tagged_following_below tree) "Tree.tagged_foll_ctx")
+         (Trace.mk_fun (Tree.select_following_below tree) "Tree.select_foll_ctx")
+         (Trace.mk_fun (fun _ _ -> Tree.next_sibling_below tree) "[NEXTSIBLING]Tree.select_sibling_foll_ctx")
+         (Trace.mk_fun (Tree.next_element_below tree) "Tree.next_element_ctx")   
+         (Trace.mk_fun (Tree.next_sibling_below tree) "Tree.node_sibling_ctx")   
                          
          
-      module SListTable = Hashtbl.Make(struct type t = SList.t
-                                             let equal = (==)
-                                             let hash t = t.SList.Node.id 
-                                      end)
-      module TransCache = 
-      struct
-       type 'a t = Obj.t array SListTable.t
-       let create n = SListTable.create n
-       let dummy = Obj.repr (fun _ -> assert false)
-       let find (h :'a t) tag slist : 'a =
-         let tab = 
-           try
-             SListTable.find h slist
-           with
-              Not_found -> 
-                SListTable.add h slist (Array.create 10000 dummy);
-                raise Not_found
-         in
-         let res = tab.(tag) in
-         if res == dummy then raise Not_found else (Obj.magic res)
 
-       let add (h : 'a t) tag slist (data : 'a) =
-         let tab = 
-           try
-             SListTable.find h slist
-           with
-              Not_found -> 
-                let arr = Array.create 10000 dummy in
-                SListTable.add h slist arr;
-                arr
+
+      module CodeCache = 
+      struct
+       let get = Array.unsafe_get
+       let set = Array.set
+
+       type fun_tree = [`Tree] Tree.node -> [`Tree] Tree.node -> SList.t ->  Tag.t -> bool -> SList.t*RS.t array
+       type t = fun_tree array array
+
+       let dummy = fun _ _ _ _ _ -> failwith "Uninitializd CodeCache"
+       let default_line = Array.create 1024 dummy (* 1024 = max_tag *)
+       let create n = Array.create n default_line 
+       let init f = 
+         for i = 0 to (Array.length default_line) - 1
+         do
+           default_line.(i) <- f
+         done
+           
+       let get_fun h slist tag =
+         get (get h (Uid.to_int slist.SList.Node.id)) tag
+
+       let set_fun (h : t) slist tag (data : fun_tree) =
+         let tab = get h (Uid.to_int slist.SList.Node.id) in
+         let line = if tab == default_line then
+           let x = Array.copy tab in
+           (set h (Uid.to_int slist.SList.Node.id) x;x)
+         else tab
          in
-         tab.(tag) <- (Obj.repr data)
-         
+         set line tag data       
 
       end
 
-      let td_trans = TransCache.create 10000 (* should be number of tags *number of states^2
-                                               in the document *)
-
       let empty_size n =
        let rec loop acc = function 0 -> acc
          | n -> loop (SList.cons StateSet.empty acc) (n-1)
        in loop SList.nil n
             
-
-      module Fold2ResOld = Hashtbl.Make(struct 
-                                      type t = Formlistlist.t*SList.t*SList.t
-                                      let hash (f,s,t) = HASHINT3(f.Formlistlist.Node.id,
-                                                                  s.SList.Node.id,
-                                                                  t.SList.Node.id)
-                                      let equal (a,b,c) (d,e,f) = a==d && b == e && c == f
-                                    end)
-
-      module FllTable = Hashtbl.Make (struct type t = Formlistlist.t
-                                            let equal = (==)
-                                            let hash t = t.Formlistlist.Node.id
-                                     end)
+     
+      module Fold2Res = struct
+       let get = Array.unsafe_get
+       let set = Array.set 
+       external field1 : Obj.t -> int = "%field1"
+       type t = Obj.t array array array array
+       let dummy_val = Obj.repr ((),2,()) 
+
+       let default_line3 = Array.create BIG_A_SIZE dummy_val
+       let default_line2 = Array.create BIG_A_SIZE default_line3
+       let default_line1 = Array.create BIG_A_SIZE default_line2
+
+       let create n = Array.create n default_line1
        
-      module Fold2Res =
-      struct
-       type 'a t = 'a SListTable.t SListTable.t FllTable.t
-       let create n = Array.init 10000 (fun _ -> FllTable.create n)
-
-       let find h tag fl s1 s2 =
-         let hf = h.(tag) in
-         let hs1 = FllTable.find hf fl in
-         let hs2 = SListTable.find hs1 s1 in
-         SListTable.find hs2 s2
+       let find h tag fl s1 s2 : SList.t*bool*(merge_conf array) = 
+         let l1 = get h tag in
+         let l2 = get l1 (Uid.to_int fl.Formlistlist.Node.id) in
+         let l3 = get l2 (Uid.to_int s1.SList.Node.id) in
+         Obj.magic (get l3 (Uid.to_int s2.SList.Node.id))
          
-       let add h tag fl s1 s2 data = 
-         let hf = h.(tag) in
-         let hs1 =
-           try FllTable.find hf fl with
-             | Not_found -> 
-                 let hs1 = SListTable.create SMALL_H_SIZE
-                 in FllTable.add hf fl hs1;hs1
-         in
-         let hs2 =
-           try SListTable.find hs1 s1
-           with
-             | Not_found ->
-                 let hs2 = SListTable.create SMALL_H_SIZE
-                 in SListTable.add hs1 s1 hs2;hs2
-         in
-         SListTable.add hs2 s2 data
+       let is_valid b = (Obj.magic b) != 2
+       let get_replace tab idx default =
+         let e = get tab idx in
+         if e == default then
+         let ne = Array.copy e in (set tab idx ne;ne)
+         else e
+         
+       let add h tag fl s1 s2 (data: SList.t*bool*(merge_conf array)) =
+         let l1 = get_replace h tag default_line1 in
+         let l2 = get_replace l1 (Uid.to_int fl.Formlistlist.Node.id) default_line2 in
+         let l3 = get_replace l2 (Uid.to_int s1.SList.Node.id) default_line3  in 
+         set l3 (Uid.to_int s2.SList.Node.id) (Obj.repr data)
       end
 
-      let h_fold2 = Fold2Res.create SMALL_H_SIZE
+            
+
       
-      let top_down ?(noright=false) a tree t slist ctx slot_size =     
+      let top_down ?(noright=false) a tree t slist ctx slot_size td_trans h_fold2=     
        let pempty = empty_size slot_size in    
        let rempty = Array.make slot_size RS.empty in
        (* evaluation starts from the right so we put sl1,res1 at the end *)
        let eval_fold2_slist fll t tag (sl2,res2) (sl1,res1) =
          let res = Array.copy rempty in
-         try
-           let r,b,btab = Fold2Res.find h_fold2 tag fll sl1 sl2  in
+         let r,b,btab = Fold2Res.find h_fold2 tag fll sl1 sl2  in
+         if Fold2Res.is_valid b then
+         begin
+           if b then for i=0 to slot_size - 1 do 
+             res.(0) <- RS.merge btab.(0) t res1.(0) res2.(0);
+           done;
+           r,res
+         end
+         else
+         begin 
+           let btab = Array.make slot_size NO in           
+           let rec fold l1 l2 fll i aq ab = 
+             match fll.Formlistlist.Node.node,
+               l1.SList.Node.node,
+               l2.SList.Node.node
+             with           
+               | Formlistlist.Cons(fl,fll),
+                SList.Cons(s1,ll1),
+                SList.Cons(s2,ll2) ->
+                   let r',conf = eval_formlist tag s1 s2 fl in
+                   let _ = btab.(i) <- conf
+                   in
+                   fold ll1 ll2 fll (i+1) (SList.cons r' aq) ((conf!=NO)||ab)
+               | _ -> aq,ab
+           in
+           let r,b = fold sl1 sl2 fll 0 SList.nil false in
+           Fold2Res.add h_fold2 tag fll sl1 sl2 (r,b,btab); 
            if b then for i=0 to slot_size - 1 do
              res.(i) <- RS.merge btab.(i) t res1.(i) res2.(i);
            done;
-           r,res
-         with
-            Not_found ->
-              let btab = Array.make slot_size (false,false,false,false) in         
-              let rec fold l1 l2 fll i aq ab = 
-                match fll.Formlistlist.Node.node,
-                  l1.SList.Node.node,
-                  l2.SList.Node.node
-                with        
-                  | Formlistlist.Cons(fl,fll),
-                   SList.Cons(s1,ll1),
-                   SList.Cons(s2,ll2) ->
-                      let r',((b,_,_,_) as flags) = eval_formlist tag s1 s2 fl in
-                      let _ = btab.(i) <- flags
-                      in
-                      fold ll1 ll2 fll (i+1) (SList.cons r' aq) (b||ab)
-                  | _ -> aq,ab
-              in
-              let r,b = fold sl1 sl2 fll 0 SList.nil false in
-              Fold2Res.add h_fold2 tag fll sl1 sl2 (r,b,btab);
-              if b then for i=0 to slot_size - 1 do
-                res.(i) <- RS.merge btab.(i) t res1.(i) res2.(i);
-              done;
-              r,res
+           r,res;
+         end
        in
 
        let null_result = (pempty,Array.copy rempty) in
-       let rec loop t slist ctx =
-         if t == Tree.nil then null_result else get_trans t slist (Tree.tag tree t) ctx
-       and loop_tag tag t slist ctx =
-         if t == Tree.nil then null_result else get_trans t slist tag ctx
-       and loop_no_right t slist ctx = 
-         if t == Tree.nil then null_result else get_trans ~noright:true t slist (Tree.tag tree t) ctx
-       and get_trans ?(noright=false) t slist tag ctx = 
-         let cont = 
-           try
-             TransCache.find td_trans tag slist
-           with        
-             | Not_found ->
-                 let fl_list,llist,rlist,ca,da,sa,fa = 
-                   SList.fold 
-                     (fun set (fll_acc,lllacc,rllacc,ca,da,sa,fa) -> (* For each set *)
-                        let fl,ll,rr,ca,da,sa,fa = 
-                          StateSet.fold
-                            (fun q acc ->                          
-                               List.fold_left 
-                                 (fun ((fl_acc,ll_acc,rl_acc,c_acc,d_acc,s_acc,f_acc) as acc) 
-                                    (ts,t)  ->
-                                      if (TagSet.mem tag ts)
-                                      then 
-                                        let _,_,_,f,_ = Transition.node t in
-                                        let (child,desc,below),(sibl,foll,after) = Formula.st f in
-                                          (Formlist.cons t fl_acc,
-                                           StateSet.union ll_acc below,
-                                           StateSet.union rl_acc after,
-                                           StateSet.union child c_acc,
-                                           StateSet.union desc d_acc,
-                                           StateSet.union sibl s_acc,
-                                           StateSet.union foll f_acc)           
-                                      else acc ) acc (
-                                   try Hashtbl.find a.trans q 
-                                   with
-                                       Not_found -> Printf.eprintf "Looking for state %i, doesn't exist!!!\n%!"
-                                         q;[]
-                                 )
-                                 
-                            ) set (Formlist.nil,StateSet.empty,StateSet.empty,ca,da,sa,fa)
-                        in (Formlistlist.cons fl fll_acc), (SList.cons ll lllacc), (SList.cons rr rllacc),ca,da,sa,fa)
-                     slist (Formlistlist.nil,SList.nil,SList.nil,StateSet.empty,StateSet.empty,StateSet.empty,StateSet.empty)
-                 in                    
-                   (* Logic to chose the first and next function *)
-                 let tags_child,tags_below,tags_siblings,tags_after = Tree.tags tree tag in
-                 let d_f = Algebra.decide a tags_child tags_below (StateSet.union ca da) true in
-                 let d_n = Algebra.decide a tags_siblings tags_after (StateSet.union sa fa) false in
-                 let f_kind,first = choose_jump_down tree d_f
-                 and n_kind,next = if noright then (`NIL, fun _ _ -> Tree.nil )
-                 else choose_jump_next tree d_n in
-                 let empty_res = null_result in
-                  let cont =
-                    match f_kind,n_kind with
-                      | `NIL,`NIL ->
-                         (fun t _ -> eval_fold2_slist fl_list t (Tree.tag tree t) empty_res empty_res)
-                     |  _,`NIL -> (
-                           match f_kind with
-                             |`TAG(tag') ->
-                               let default = fun t _ -> eval_fold2_slist fl_list t (Tree.tag tree t) empty_res
-                                  (loop_tag tag' (first t) llist t )
-                               in
-                               let cf = SList.hd llist in
-                               if (slot_size == 1) && StateSet.is_singleton cf
-                               then
-                               let s = StateSet.choose cf in
-                               if (Algebra.is_rec a s fst) && (Algebra.is_rec a s snd)
-                               && (Algebra.is_final_marking a s)
-                               then RS.mk_quick_tag_loop default llist 1 tree tag' 
-                               else default
-                               else default                            
-                            | _ ->
-                                (fun t _ -> eval_fold2_slist fl_list t (Tree.tag tree t) empty_res
-                                  (loop (first t) llist t ))
-                        )
-                      | `NIL,_ -> (
-                          match n_kind with
-                            |`TAG(tag') ->
-                              if SList.equal rlist slist && tag == tag' then
-                              let rec loop t ctx = 
-                                if t == Tree.nil then empty_res else 
-                                let res2 = loop (next t ctx) ctx in                               
-                                eval_fold2_slist fl_list t tag res2 empty_res            
-                              in loop
-                              else
-                               (fun t ctx -> eval_fold2_slist fl_list t (Tree.tag tree t)
-                                 (loop_tag tag' (next t ctx) rlist ctx ) empty_res)
-                                                                                            
-                            | _ ->
-                                (fun t ctx -> eval_fold2_slist fl_list t (Tree.tag tree t)
-                                   (loop (next t ctx) rlist ctx ) empty_res)
-                       )
+       let empty_res = null_result in
+
+       let rec loop t ctx slist _  =
+         if t == Tree.nil then null_result else
+         let tag = Tree.tag tree t in
+         (CodeCache.get_fun td_trans slist tag) t ctx slist tag false
+           (* get_trans t ctx slist tag false
+           (CodeCache.get_opcode td_trans slist tag)
+           *)
+       and loop_tag t ctx slist tag  =
+         if t == Tree.nil then null_result else 
+         (CodeCache.get_fun td_trans slist tag) t ctx slist tag false
+           (* get_trans t ctx slist tag false 
+           (CodeCache.get_opcode td_trans slist tag) *)
+         
+       and loop_no_right t ctx slist _  = 
+         if t == Tree.nil then null_result else 
+         let tag = Tree.tag tree t in
+         (CodeCache.get_fun td_trans slist tag) t ctx slist tag true
+           (* get_trans t ctx slist tag true 
+              (CodeCache.get_opcode td_trans slist tag) *)
+           (*
+       and get_trans t ctx slist tag noright opcode = 
+         match opcode with
+           | OpCode.K0 fll -> 
+               eval_fold2_slist fll t tag empty_res empty_res
+
+           | OpCode.K1 (fll,first,llist,tag1) -> 
+               eval_fold2_slist fll t tag empty_res
+                 (loop_tag (first t) t llist tag1)
+
+           | OpCode.K2 (fll,first,llist) ->
+               eval_fold2_slist fll t tag empty_res
+                 (loop (first t) t llist)
+                 
+           | OpCode.K3 (fll,next,rlist,tag2) ->
+                eval_fold2_slist fll t tag 
+                 (loop_tag (next t ctx) ctx rlist tag2)
+                 empty_res
+           | OpCode.K4 (fll,next,rlist) ->
+               eval_fold2_slist fll t tag 
+                 (loop (next t ctx) ctx rlist)           
+                 empty_res
+
+           | OpCode.K5 (fll,next,rlist,tag2,first,llist,tag1) ->
+               eval_fold2_slist fll t tag
+                 (loop_tag (next t ctx) ctx rlist tag2)                  
+                 (loop_tag (first t) t llist tag1)
+
+           | OpCode.K6 (fll,next,rlist,first,llist,tag1) ->
+               eval_fold2_slist fll t tag
+                 (loop (next t ctx) ctx rlist)           
+                 (loop_tag (first t) t llist tag1)
+
+           | OpCode.K7 (fll,next,rlist,tag2,first,llist) ->
+               eval_fold2_slist fll t tag
+                 (loop_tag (next t ctx) ctx rlist tag2)                  
+                 (loop (first t) t llist)
+
+           | OpCode.K8 (fll,next,rlist,first,llist) ->
+               eval_fold2_slist fll t tag
+                 (loop (next t ctx) ctx rlist)           
+                 (loop (first t) t llist)
+
+           | OpCode.KDefault _ -> 
+               mk_trans t ctx tag slist noright
+           *)
+       and mk_trans t ctx slist tag noright = 
+         let fl_list,llist,rlist,ca,da,sa,fa = 
+           SList.fold 
+             (fun set (fll_acc,lllacc,rllacc,ca,da,sa,fa) -> (* For each set *)
+                let fl,ll,rr,ca,da,sa,fa = 
+                  StateSet.fold
+                    (fun q acc ->                          
+                       List.fold_left 
+                         (fun ((fl_acc,ll_acc,rl_acc,c_acc,d_acc,s_acc,f_acc) as acc) 
+                          (ts,t)  ->
+                            if (TagSet.mem tag ts)
+                            then 
+                            let _,_,_,f,_ = t.Transition.node in
+                            let (child,desc,below),(sibl,foll,after) = Formula.st f in
+                            (Formlist.cons t fl_acc,
+                             StateSet.union ll_acc below,
+                             StateSet.union rl_acc after,
+                             StateSet.union child c_acc,
+                             StateSet.union desc d_acc,
+                             StateSet.union sibl s_acc,
+                             StateSet.union foll f_acc)                 
+                            else acc ) acc (
+                           try Hashtbl.find a.trans q 
+                           with
+                              Not_found -> Printf.eprintf "Looking for state %i, doesn't exist!!!\n%!"
+                                q;[]
+                         )
                          
-                      | `TAG(tag1),`TAG(tag2) ->                         
-                          (fun t ctx ->
-                            eval_fold2_slist fl_list t (Tree.tag tree t)
-                               (loop_tag tag2 (next t ctx) rlist ctx )
-                               (loop_tag tag1 (first t) llist t ))
+                    ) set (Formlist.nil,StateSet.empty,StateSet.empty,ca,da,sa,fa)
+                in (Formlistlist.cons fl fll_acc), (SList.cons ll lllacc), (SList.cons rr rllacc),ca,da,sa,fa)
+             slist (Formlistlist.nil,SList.nil,SList.nil,StateSet.empty,StateSet.empty,StateSet.empty,StateSet.empty)
+         in                    
+         (* Logic to chose the first and next function *)
+         let tags_child,tags_below,tags_siblings,tags_after = Tree.tags tree tag in
+         let d_f = Algebra.decide a tags_child tags_below (StateSet.union ca da) true in
+         let d_n = Algebra.decide a tags_siblings tags_after (StateSet.union sa fa) false in
+         let f_kind,first = choose_jump_down tree d_f
+         and n_kind,next = if noright then (`NIL, fun _ _ -> Tree.nil )
+         else choose_jump_next tree d_n in 
+         let empty_res = null_result in
+         let fll = fl_list in
+          let cont =
+            match f_kind,n_kind with
+              | `NIL,`NIL -> (*OpCode.K0(fl_list) *)
+                 fun t _ _ tag _ -> eval_fold2_slist fll t tag empty_res empty_res
+               
+             |  _,`NIL -> (
+                   match f_kind with
+                     |`TAG(tag1) -> (*OpCode.K1(fl_list,first,llist,tag1) *)
+                       fun t _ _ tag _ -> eval_fold2_slist fll t tag empty_res
+                         (loop_tag (first t) t llist tag1)
+                    | _ -> (* OpCode.K2(fl_list,first,llist) *)
+                        fun t _ _ tag _  -> eval_fold2_slist fll t tag empty_res
+                          (loop (first t) t llist tag)
+                )
+              | `NIL,_ -> (
+                  match n_kind with
+                    |`TAG(tag2) -> (*OpCode.K3(fl_list,next,rlist,tag2) *)
+                      fun t ctx _ tag _ ->
+                        eval_fold2_slist fll t tag 
+                          (loop_tag (next t ctx) ctx rlist tag2)
+                          empty_res
+
+                    | _ -> (*OpCode.K4(fl_list,next,rlist) *)
+                       fun t ctx _ tag _ ->
+                         eval_fold2_slist fll t tag 
+                           (loop (next t ctx) ctx rlist tag)
+                           empty_res
+                        
+               )
+                 
+              | `TAG(tag1),`TAG(tag2) -> (*OpCode.K5(fl_list,next,rlist,tag2,first,llist,tag1) *)
+                 fun t ctx _ tag _ -> 
+                   eval_fold2_slist fll t tag
+                     (loop_tag (next t ctx) ctx rlist tag2)              
+                     (loop_tag (first t) t llist tag1)
  
-                      | `TAG(tag'),`ANY ->
-                         (fun t ctx ->
-                           eval_fold2_slist fl_list t (Tree.tag tree t)
-                              (loop (next t ctx) rlist ctx )
-                              (loop_tag tag' (first t) llist t ))
-                                                                          
-                      | `ANY,`TAG(tag') ->
-                          (fun t ctx ->
-                            eval_fold2_slist fl_list t (Tree.tag tree t)
-                              (loop_tag tag' (next t ctx) rlist ctx )
-                              (loop (first t) llist t ))
+              | `TAG(tag1),`ANY -> (* OpCode.K6(fl_list,next,rlist,first,llist,tag1) *)
+                 fun t ctx _ tag _ -> 
+                   eval_fold2_slist fll t tag
+                     (loop (next t ctx) ctx rlist tag)
+                     (loop_tag (first t) t llist tag1)
+
+              | `ANY,`TAG(tag2) -> (* OpCode.K7(fl_list,next,rlist,tag2,first,llist) *)
+                 fun t ctx _ tag _ -> 
+                   eval_fold2_slist fll t tag
+                     (loop_tag (next t ctx) ctx rlist tag2)              
+                     (loop (first t) t llist tag)
+                         
                                                                   
-                      | `ANY,`ANY ->
-                         if SList.equal slist rlist && SList.equal slist llist
-                         then
-                         let rec loop t ctx = 
-                           if t == Tree.nil then empty_res else
-                           let r1 = loop (first t) t 
-                           and r2 = loop (next t ctx) ctx
-                           in
-                           eval_fold2_slist fl_list t (Tree.tag tree t) r2 r1
-                         in loop
-                         else 
-                          (fun t ctx ->
-                             eval_fold2_slist fl_list t (Tree.tag tree t)
-                               (loop (next t ctx) rlist ctx )
-                               (loop (first t) llist t ))
-                     | _,_ -> 
-                         (fun t ctx ->
-                             eval_fold2_slist fl_list t (Tree.tag tree t)
-                               (loop (next t ctx) rlist ctx )
-                               (loop (first t) llist t ))
-                 in
-                 let cont = D_IF_( (fun t ctx ->
-                                       let a,b = cont t ctx in
-                                       register_trace tree t (slist,a,fl_list,first,next,ctx);
-                                       (a,b)
-                                    ) ,cont)
-                  in
-                  (TransCache.add td_trans tag slist (Obj.repr cont) ;cont)
-         in (Obj.magic cont) t ctx
-              
+              | _,_ -> (*OpCode.K8(fl_list,next,rlist,first,llist) *)
+                 (*if SList.equal slist rlist && SList.equal slist llist
+                   then
+                   let rec loop t ctx = 
+                   if t == Tree.nil then empty_res else
+                   let r1 = loop (first t) t
+                   and r2 = loop (next t ctx) ctx
+                   in
+                   eval_fold2_slist fl_list t (Tree.tag tree t) r2 r1
+                   in loop
+                   else *)
+                  fun t ctx _ tag _ -> 
+                   eval_fold2_slist fll t tag
+                     (loop (next t ctx) ctx rlist tag)           
+                     (loop (first t) t llist tag)
+
+             
+
+         in
+         CodeCache.set_fun td_trans slist tag cont; 
+         cont t ctx slist tag noright
        in 
-         (if noright then loop_no_right else loop) t slist ctx
+       let _ = CodeCache.init mk_trans in
+       (if noright then loop_no_right else loop) t ctx slist Tag.dummy
 
-       let run_top_down a tree =
-         let init = SList.cons a.init SList.nil in
-         let _,res = top_down a tree Tree.root init Tree.root 1 
-         in 
-           D_IGNORE_(
-             output_trace a tree "trace.html"
-               (RS.fold (fun t a -> IntSet.add (Tree.id tree t) a) res.(0) IntSet.empty),
+
+      let run_top_down a tree =
+       let init = SList.cons a.init SList.nil in
+       let _,res = top_down a tree Tree.root init Tree.root 1 (CodeCache.create BIG_A_SIZE) (Fold2Res.create 1024)
+       in 
+       D_IGNORE_(
+         output_trace a tree "trace.html"
+           (RS.fold (fun t a -> IntSet.add (Tree.id tree t) a) res.(0) IntSet.empty),
              res.(0))
-       ;;
+      ;;
+      
+
+
+
+
+      module Code3Cache = 
+      struct
+       let get = Array.get             
+       let set = Array.set
+       let realloc a new_size default =
+         let old_size = Array.length a in
+         if old_size == new_size then a
+         else if new_size == 0 then [||]
+         else let na = Array.create new_size default in
+         Array.blit a 0 na 0 old_size;na
+
+       type fun_tree = [`Tree] Tree.node -> [`Tree] Tree.node -> StateSet.t ->  Tag.t -> StateSet.t*RS.t
+       and t = { mutable table : fun_tree array array;
+                 mutable default_elm : fun_tree;
+                 mutable default_line : fun_tree array;
+                  (* statistics *)
+                 mutable access : int;
+                 mutable miss : int;
+                }
+
+
+       let create () = 
+         { table = [||]; 
+           default_elm = (fun _ _ _ _ -> failwith "Uninitialized Code3Cache.t structure\n");
+           default_line = [||];
+           access = 0;
+           miss = 0 }
+
+       let init h f =
+         let default_line = Array.create SMALL_A_SIZE f in
+         begin
+           h.table <- Array.create SMALL_A_SIZE default_line;
+           h.default_elm <- f;
+           h.default_line <- default_line;
+           h.access <- 0;
+           h.miss <- 0
+         end
+           
+       let next_power_of_2 n = 
+         let rec loop i acc = 
+           if acc == 0 then i
+           else loop (i+1) (acc lsr 1)
+         in
+         1 lsl (loop 0 n)
+       
+       let get_fun h slist tag =
+         let _ = h.access <- h.access + 1 in
+         let idx = Uid.to_int slist.StateSet.Node.id in
+         let line = 
+           if idx >= Array.length h.table then 
+           let new_tab = realloc h.table (next_power_of_2 idx) h.default_line in
+           let _ =  h.miss <- h.miss + 1; h.table <- new_tab in h.default_line
+           else Array.unsafe_get h.table idx
+         in
+         if tag >= Array.length line then
+         let new_line = realloc line (next_power_of_2 tag) h.default_elm in
+         let _ = h.miss <- h.miss + 1; Array.unsafe_set h.table idx new_line in h.default_elm
+         else Array.unsafe_get line tag
+
+       let set_fun (h : t) slist tag (data : fun_tree) =
+         let idx = Uid.to_int slist.StateSet.Node.id in
+         let line = 
+           if idx >= Array.length h.table then 
+           let new_tab = realloc h.table (next_power_of_2 idx) h.default_line in
+           let _ =  h.table <- new_tab in h.default_line
+           else Array.unsafe_get h.table idx
+         in
+         let line = if line == h.default_line then 
+         let l = Array.copy line in Array.unsafe_set h.table idx l;l
+         else line in
+         let line = if tag >= Array.length line then
+         let new_line = realloc line (next_power_of_2 tag) h.default_elm in
+         let _ = Array.unsafe_set h.table idx new_line in new_line
+         else line
+         in
+         Array.unsafe_set line tag data
+
+
+       let dump h = Array.iteri 
+         (fun id line -> if line != h.default_line then 
+          begin
+            StateSet.print Format.err_formatter (StateSet.with_id (Uid.of_int id));
+            Format.fprintf Format.err_formatter " -> ";
+            Array.iteri (fun tag clos ->
+                           if clos != h.default_elm then
+                           Format.fprintf Format.err_formatter " (%s,%s) "
+                             (Tag.to_string tag) (Trace.get_funname clos)) line;
+            Format.fprintf Format.err_formatter "\n%!"
+          end
+         ) h.table;
+         Format.fprintf Format.err_formatter "Cache hits: %i, Cache misses: %i, ratio = %f\n%!"
+           h.access h.miss ((float_of_int h.miss)/. (float_of_int h.access));
+         Format.fprintf Format.err_formatter "Size: %i kb\n%!"
+           (((2+(Array.length h.default_line)+
+                (Array.fold_left (fun acc l ->acc + (if l == h.default_line then 0 else Array.length l))
+                (Array.length h.table) h.table)) * Sys.word_size) / 1024)
+
+      end
+
+      module StaticEnv =
+      struct
+
+       type t = { stack : Obj.t array; 
+                  mutable top : int; }
+
+       let create () = { stack = Array.create BIG_A_SIZE (Obj.repr 0); top = 0 }
+       let add t e = 
+         let _ = if t.top >= Array.length t.stack then failwith "Static Env overflow" in
+         let i = t.top in Array.unsafe_set t.stack i e; t.top <- i + 1; i
+
+       let get t i :'a = Obj.magic (Array.unsafe_get t.stack i)
+      end
+         
+      module Fold3Res = struct
+       let get = Array.unsafe_get
+       let set = Array.set 
+       external field1 : Obj.t -> int = "%field1"
+       type t = Obj.t array array array array
+       let dummy_val = Obj.repr ((),2,()) 
+
+       let default_line3 = Array.create 1024 dummy_val
+       let default_line2 = Array.create BIG_A_SIZE default_line3
+       let default_line1 = Array.create BIG_A_SIZE default_line2
+
+       let create n = Array.create n default_line1
+       
+       let find h tag fl s1 s2 : StateSet.t*bool*merge_conf = 
+         let l1 = get h (Uid.to_int fl.Formlist.Node.id) in
+         let l2 = get l1 (Uid.to_int s1.StateSet.Node.id) in
+         let l3 = get l2 (Uid.to_int s2.StateSet.Node.id) in
+         Obj.magic (get l3 tag)
+         
+       let is_valid b = b != (Obj.magic dummy_val)
+       let get_replace tab idx default =
+         let e = get tab idx in
+         if e == default then
+         let ne = Array.copy e in (set tab idx ne;ne)
+         else e
+         
+       let add h tag fl s1 s2 (data: StateSet.t*bool*merge_conf) =
+         let l1 = get_replace h (Uid.to_int fl.Formlist.Node.id) default_line1 in
+         let l2 = get_replace l1 (Uid.to_int s1.StateSet.Node.id) default_line2 in
+         let l3 = get_replace l2 (Uid.to_int s2.StateSet.Node.id) default_line3 in 
+         set l3 tag (Obj.repr data)
+      end
+
+
+      let empty_res = StateSet.empty,RS.empty
+
+      let top_down1 a tree t slist ctx td_trans h_fold2  =     
+       (* evaluation starts from the right so we put sl1,res1 at the end *)
+       let env = StaticEnv.create () in
+       let slist_reg = ref StateSet.empty in
+       let eval_fold2_slist fll t tag (sl2,res2) (sl1,res1) =   
+         let data = Fold3Res.find h_fold2 tag fll sl1 sl2  in
+         if Fold3Res.is_valid data then
+         let r,b,conf = data in
+         (r,if b then RS.merge conf t res1 res2 else RS.empty)
+         else
+         let r,conf = eval_formlist tag sl1 sl2 fll in
+         let b = conf <> NO in
+         (Fold3Res.add h_fold2 tag fll sl1 sl2 (r,b,conf);
+          (r, if b then RS.merge conf t res1 res2 else RS.empty))
+        
+       in
+       let loop t ctx slist _ =
+         if t == Tree.nil then empty_res else
+         let tag = Tree.tag tree t in
+         (Code3Cache.get_fun td_trans slist tag) t ctx slist tag
+
+       in
+       let loop_tag t ctx slist tag =
+         if t == Tree.nil then empty_res else 
+         (Code3Cache.get_fun td_trans slist tag) t ctx slist tag
+         
+       in
+       let mk_trans t ctx slist tag = 
+         let fl_list,llist,rlist,ca,da,sa,fa = 
+           StateSet.fold
+             (fun q acc ->                         
+                List.fold_left 
+                  (fun ((fl_acc,ll_acc,rl_acc,c_acc,d_acc,s_acc,f_acc) as acc) 
+                   (ts,t)  ->
+                     if (TagSet.mem tag ts)
+                     then 
+                     let _,_,_,f,_ = t.Transition.node in
+                     let (child,desc,below),(sibl,foll,after) = Formula.st f in
+                     (Formlist.cons t fl_acc,
+                      StateSet.union ll_acc below,
+                      StateSet.union rl_acc after,
+                      StateSet.union child c_acc,
+                      StateSet.union desc d_acc,
+                      StateSet.union sibl s_acc,
+                      StateSet.union foll f_acc)                
+                     else acc ) acc (
+                    try Hashtbl.find a.trans q 
+                    with
+                       Not_found -> Printf.eprintf "Looking for state %i, doesn't exist!!!\n%!"
+                         q;[]
+                  )
+                  
+             ) slist (Formlist.nil,StateSet.empty,StateSet.empty,
+                      StateSet.empty,StateSet.empty,StateSet.empty,StateSet.empty)
+
+         in                    
+         (* Logic to chose the first and next function *)
+         let tags_child,tags_below,tags_siblings,tags_after = Tree.tags tree tag in
+         let d_f = Algebra.decide a tags_child tags_below (StateSet.union ca da) true in
+         let d_n = Algebra.decide a tags_siblings tags_after (StateSet.union sa fa) false in
+         let f_kind,first = choose_jump_down tree d_f
+         and n_kind,next = choose_jump_next tree d_n in 
+
+          let cont =
+            match f_kind,n_kind with
+              | `NIL,`NIL -> 
+                 fun t _ _ tag -> eval_fold2_slist fl_list t tag empty_res empty_res
+               
+             |  _,`NIL -> (
+                   match f_kind with
+                     |`TAG(tag1) -> 
+                       (fun t _ _ tag -> eval_fold2_slist fl_list t tag empty_res
+                         (loop_tag (first t) t llist tag1))
+                    | _ ->
+                        fun t _ _ tag -> eval_fold2_slist fl_list t tag empty_res
+                          (loop (first t) t llist tag)
+                )
+              | `NIL,_ -> (
+                  match n_kind with
+                    |`TAG(tag2) -> 
+                      fun t ctx _ tag  ->
+                        eval_fold2_slist fl_list t tag 
+                          (loop_tag (next t ctx) ctx rlist tag2)
+                          empty_res
+
+                    | _ -> 
+                       fun t ctx _ tag ->
+                         eval_fold2_slist fl_list t tag 
+                           (loop (next t ctx) ctx rlist tag)
+                           empty_res
+                        
+               )
+                 
+              | `TAG(tag1),`TAG(tag2) -> 
+                 fun t ctx _ tag -> 
+                   eval_fold2_slist fl_list t tag
+                     (loop_tag (next t ctx) ctx rlist tag2)              
+                     (loop_tag (first t) t llist tag1)
+              | `TAG(tag1),`ANY -> 
+                 fun t ctx _ tag -> 
+                   eval_fold2_slist fl_list t tag
+                     (loop (next t ctx) ctx rlist tag)
+                     (loop_tag (first t) t llist tag1)
+
+              | `ANY,`TAG(tag2) -> 
+                 fun t ctx _ tag -> 
+                   eval_fold2_slist fl_list t tag
+                     (loop_tag (next t ctx) ctx rlist tag2)              
+                     (loop (first t) t llist tag)
+                         
+                                                                  
+              | _,_ -> 
+                  fun t ctx _ tag -> 
+                   eval_fold2_slist fl_list t tag
+                     (loop (next t ctx) ctx rlist tag)           
+                     (loop (first t) t llist tag)
+
+             
+
+         in
+         let _ = Trace.register_funname cont 
+           (Printf.sprintf "{first=%s, next=%s}" (Trace.get_funname first)  (Trace.get_funname next))
+         in
+         Code3Cache.set_fun td_trans slist tag cont; 
+         cont 
+       in
+       let cache_take_trans t ctx slist tag = 
+         let cont = mk_trans t ctx slist tag in
+         cont t ctx slist tag
+       in
+       Code3Cache.init td_trans (cache_take_trans);
+       loop t ctx slist Tag.dummy
+         
+      
+      let run_top_down1 a tree =
+       let code_cache = Code3Cache.create ()  in
+       let fold_cache = Fold3Res.create BIG_A_SIZE in
+       let _,res = top_down1 a tree Tree.root a.init Tree.root code_cache fold_cache
+       in 
+       (*Code3Cache.dump code_cache; *)
+       res
+
 
        module Configuration =
        struct
@@ -1030,7 +1498,7 @@ END
            if Ptss.mem s c.sets then
              { c with results = IMap.add s (RS.concat r (IMap.find s c.results)) c.results}
            else
-             { hash = HASHINT2(c.hash,Ptset.Int.uid s);
+             { hash = HASHINT2(c.hash,Uid.to_int s.StateSet.Node.id);
                sets = Ptss.add s c.sets;
                results = IMap.add s r c.results
              }
@@ -1064,7 +1532,7 @@ END
            in
            let h,s =
              Ptss.fold 
-               (fun s (ah,ass) -> (HASHINT2(ah,Ptset.Int.uid s),
+               (fun s (ah,ass) -> (HASHINT2(ah, Uid.to_int s.StateSet.Node.id ),
                                    Ptss.add s ass))
                (Ptss.union c1.sets c2.sets) (0,Ptss.empty)
            in
@@ -1082,16 +1550,17 @@ END
            match SList.node sl,fl with
              |SList.Nil,[] -> acc
              |SList.Cons(s,sll), formlist::fll ->
-                let r',(rb,rb1,rb2,mark) = 
+                let r',mcnf = 
                   let key = SList.hash sl,Formlist.hash formlist,dir in
                   try 
                     Hashtbl.find h_fold key
                   with
                      Not_found -> let res = 
-                       if dir then eval_formlist tag s Ptset.Int.empty formlist
-                       else eval_formlist tag Ptset.Int.empty s formlist 
+                       if dir then eval_formlist tag s StateSet.empty formlist
+                       else eval_formlist tag StateSet.empty s formlist 
                      in (Hashtbl.add h_fold key res;res)
                 in
+                let (rb,rb1,rb2,mark) = bool_of_merge mcnf in
                 if rb && ((dir&&rb1)|| ((not dir) && rb2))
                 then 
                 let acc = 
@@ -1110,7 +1579,7 @@ END
        let h_trans = Hashtbl.create 4096
 
        let get_up_trans slist ptag a tree =      
-         let key = (HASHINT2(SList.uid slist,ptag)) in
+         let key = (HASHINT2(Uid.to_int slist.SList.Node.id ,ptag)) in
            try
          Hashtbl.find h_trans key              
          with
@@ -1161,7 +1630,7 @@ END
          let slist = SList.rev (slist) in 
          let newconf = fold_f_conf tree parent slist fl_list conf dir in
          let accu,newconf = Configuration.IMap.fold (fun s res (ar,nc) ->
-                                                       if Ptset.Int.intersect s init then
+                                                       if StateSet.intersect s init then
                                                          ( RS.concat res ar ,nc)
                                                        else (ar,Configuration.add nc s res))
            (newconf.Configuration.results) (accu,Configuration.empty) 
@@ -1178,8 +1647,8 @@ END
              | Not_found -> 
                  let res = Hashtbl.fold (fun q l acc -> 
                                            if List.exists (fun (ts,_) -> TagSet.mem tag ts) l
-                                           then Ptset.Int.add q acc
-                                           else acc) a.trans Ptset.Int.empty
+                                           then StateSet.add q acc
+                                           else acc) a.trans StateSet.empty
                  in Hashtbl.add h_tdconf tag res;res
          in 
 (*       let _ = pr ", among ";
@@ -1187,7 +1656,7 @@ END
            pr "\n%!";
          in *)
          let r = SList.cons r SList.nil in
-         let set,res = top_down (~noright:noright) a tree t r t 1 in
+         let set,res = top_down (~noright:noright) a tree t r t 1 (CodeCache.create BIG_A_SIZE) (Fold2Res.create 1024) in
          let set = match SList.node set with
            | SList.Cons(x,_) ->x
            | _ -> assert false 
@@ -1211,7 +1680,7 @@ END
            match k with
              | `TAG (tag) -> 
                  (*Tree.tagged_lowest t tag, fun tree -> Tree.tagged_next tree tag*)
-                 (Tree.tagged_desc tree tag t, let jump = Tree.tagged_foll_ctx tree tag
+                 (Tree.tagged_descendant tree tag t, let jump = Tree.tagged_following_below tree tag
                  in fun n -> jump n t )
              | `CONTAINS(_) -> (Tree.text_below tree t,let jump = Tree.text_next tree 
                                 in fun n -> jump n t)
@@ -1236,13 +1705,16 @@ END
     end
           
     let top_down_count a t = let module RI = Run(Integer) in Integer.length (RI.run_top_down a t)
+    let top_down_count1 a t = let module RI = Run(Integer) in Integer.length (RI.run_top_down1 a t)
     let top_down a t = let module RI = Run(IdSet) in (RI.run_top_down a t)
+    let top_down1 a t = let module RI = Run(IdSet) in (RI.run_top_down1 a t)
     let bottom_up_count a t k = let module RI = Run(Integer) in Integer.length (RI.run_bottom_up a t k)
-
+    let bottom_up a t k = let module RI = Run(IdSet) in (RI.run_bottom_up a t k)
 
     module Test (Doc : sig val doc : Tree.t end) =
       struct
        module Results = GResult(Doc)
        let top_down a t = let module R = Run(Results) in (R.run_top_down a t)
+       let top_down1 a t = let module R = Run(Results) in (R.run_top_down1 a t)
       end