text
stringlengths 12
786k
|
---|
let derive_glbfun_table globals_table = let glbfun_table = Hashtbl . create 7 in let rec recurse initvalue = match initvalue with | Unknown -> ( ) | Block b -> Array . iter recurse b | FuncInEnv { env ; _ } -> Array . iteri ( fun func_offset env_val -> match env_val with | Function { label } -> Hashtbl . replace glbfun_table label ( func_offset , env ) | _ -> ( ) ) env | Function _ -> assert false in Hashtbl . iter ( fun glb initvalue -> recurse initvalue ) globals_table ; glbfun_table |
let trace_stack_max depth instr = match instr with | I . Kapply num -> if num < 4 then depth + 3 else depth | Kappterm ( num , slots ) -> max depth ( depth - slots + num ) | Kpushtrap _ -> depth + 4 | _ -> depth |
let trace_stack_instr depth instr = match instr with | I . Klabel _ -> assert false | Krestart -> depth | Kconst _ | Kacc _ | Kassign _ | Kenvacc _ | Kgetglobal _ -> depth | Kpush -> depth + 1 | Kpop num -> depth - num | ( Knegint | Kboolnot | Koffsetint _ | Koffsetref _ | Kisint | Ksetglobal _ | Kgetfield _ | Kgetfloatfield _ | Kvectlength ) -> depth | ( Kaddint | Ksubint | Kmulint | Kdivint | Kmodint | Kandint | Korint | Kxorint | Klslint | Klsrint | Kasrint | Kintcomp _ | Kisout | Ksetfield _ | Ksetfloatfield _ | Kgetvectitem | Kgetstringchar | Kgetbyteschar ) -> depth - 1 | ( Ksetvectitem | Ksetbyteschar ) -> depth - 2 | ( Kmakeblock ( size , _ ) | Kmakefloatblock size ) -> depth ( - max ( size - 1 ) 0 ) | Kccall ( _ , num ) -> depth ( - num - 1 ) | Kbranch _ | Kbranchif _ | Kbranchifnot _ | Kswitch _ -> depth | Kpush_retaddr _ -> depth + 3 | Kapply num -> depth - num - ( if num < 4 then 0 else 3 ) | Kappterm _ | Kreturn _ | Kraise _ | Kstop -> depth | Kgrab _ -> depth | Kclosure ( _ , num ) -> depth ( - max ( num - 1 ) 0 ) | Kclosurerec ( funcs , num ) -> let num_funcs = List . length funcs in depth ( - max ( num - 1 ) 0 ) + num_funcs | Koffsetclosure _ -> depth | Kpushtrap _ | Kpoptrap -> depth | Kcheck_signals -> depth | Kgetmethod -> depth | Kgetpubmet _ -> depth + 1 | Kgetdynmet -> depth | Kevent _ -> depth | Kstrictbranchif _ -> assert false | Kstrictbranchifnot _ -> assert false |
let max_stack_depth_of_instrs instrs = let len = Array . length instrs in let rec recurse mdepth depth k = if k < len then let mdep = trace_stack_max depth instrs . ( k ) in let depth ' = trace_stack_instr depth instrs . ( k ) in recurse ( max mdepth ( max mdep depth ' ) ) depth ' ( k + 1 ) else mdepth in recurse 0 0 0 |
let local_branch_labels = function | I . Kbranch l -> [ l ] | Kbranchif l -> [ l ] | Kbranchifnot l -> [ l ] | Kswitch ( la1 , la2 ) -> Array . to_list la1 @ Array . to_list la2 | _ -> [ ] |
let rec dump block indent = let open Wc_control in let open Wc_util in let istr = String . make ( 4 * indent ) ' ' in eprintf " % sBLOCK % s % s \ n " istr ( match block . loop_label with | Some l -> sprintf " loop =% d " l | None -> " " ) ( match block . break_label with | Some l -> sprintf " break =% d " l | None -> " " ) ; Array . iter ( function | Label label -> eprintf " % sLABEL % d \ n " istr label | Simple i -> eprintf " % s % s \ n " istr ( string_of_kinstruction i ) | Trap { trylabel ; catchlabel ; poplabel } -> eprintf " % sTrap try =% d catch =% d pop =% s \ n " istr trylabel catchlabel ( Option . map string_of_int poplabel |> Option . value ~ default " " ) : | TryReturn -> eprintf " % sTryReturn \ n " istr | NextMain label -> eprintf " % sNextMain % d \ n " istr label | Block inner -> dump inner ( indent + 1 ) ) block . instructions |
let max_stack_depth_of_fblock fblock = let open Wc_control in let depth_table = Hashtbl . create 7 in let update_depth_table depth labels = List . iter ( fun label -> try let d = Hashtbl . find depth_table label in if d <> depth then ( eprintf " [ DEBUG ] Bad function : % d \ n " fblock . scope . cfg_func_label ; eprintf " [ DEBUG ] Bad label : % d \ n " label ; eprintf " [ DEBUG ] d =% d depth =% d \ n " d depth ; dump fblock . block 0 ; assert false ; ) with | Not_found -> Hashtbl . add depth_table label depth ) labels in let rec recurse block = Array . fold_left ( fun ( max_depth , depth ) instr -> match instr with | Label label -> let depth = try Hashtbl . find depth_table label with Not_found -> 0 in ( max max_depth depth , depth ) | Simple i -> let labels = local_branch_labels i in update_depth_table depth labels ; let depth ' = Wc_traceinstr . trace_stack_instr depth i in ( max depth ' max_depth , depth ' ) | Trap { catchlabel ; poplabel = Some pop } -> update_depth_table depth [ catchlabel ; pop ] ; ( max_depth , depth ) | Trap { catchlabel ; poplabel = None } -> update_depth_table depth [ catchlabel ] ; ( max_depth , depth ) | TryReturn -> ( max_depth , depth ) | NextMain _ -> ( max_depth , depth ) | Block inner -> recurse inner ) ( 0 , 0 ) block . instructions in recurse fblock . block |> fst |
type state = { camlstack : store list ; camldepth : int ; accu : store ; realaccu : ISet . t ; arity : int ; } |
type lpad = { locals : ( string , repr ) Hashtbl . t ; mutable avoid_locals : bool ; mutable loops : ISet . t ; indegree : ( int , int ) Hashtbl . t ; state_table : ( int , state ) Hashtbl . t ; mutable globals_table : ( int , Wc_traceglobals . initvalue ) Hashtbl . t ; mutable environment : Wc_traceglobals . initvalue array ; mutable func_offset : int ; } |
let real_accu = RealAccu { no_function = false } |
let real_accu_no_func = RealAccu { no_function = true } |
let empty_state = { camlstack = [ ] ; camldepth = 0 ; accu = Invalid ; realaccu = ISet . empty ; arity = 1 ; } |
let empty_lpad ( ) = { locals = Hashtbl . create 7 ; avoid_locals = false ; loops = ISet . empty ; indegree = Hashtbl . create 7 ; state_table = Hashtbl . create 7 ; globals_table = Hashtbl . create 1 ; environment = [ | ] ; | func_offset = 0 ; } |
let new_local lpad repr = let k = Hashtbl . length lpad . locals in let s = sprintf " x % d " k in Hashtbl . add lpad . locals s repr ; s |
let stack_descr state = let cd = state . camldepth in let rd = ref 0 in let stack = Array . make cd false in List . iter ( fun st -> match st with | RealStack pos -> assert ( pos >= ( - cd ) ) ; if pos < 0 then ( stack . ( pos + cd ) <- true ; rd := max ! rd ( - pos ) ) | _ -> ( ) ) state . camlstack ; let uninit = ref [ ] in Array . iteri ( fun i used -> if not used && i >= cd - ! rd then uninit := ( - cd + i ) :: ! uninit ) stack ; let stack_save_accu = state . realaccu <> ISet . empty || ( match state . accu with RealAccu _ -> true | _ -> false ) in { stack_uninit = ! uninit ; stack_depth = ! rd ; stack_save_accu } |
let set_camlstack pos store state = let cd = state . camldepth in if pos >= ( - cd ) && pos <= ( - 1 ) then let camlstack = List . mapi ( fun i old_store -> if ( - cd + i ) = pos then store else old_store ) state . camlstack in camlstack else state . camlstack |
let pop_camlstack state = let cd = state . camldepth in let cpos = ( - cd ) in match state . camlstack with | RealStack pos :: tl -> { state with camlstack = tl ; camldepth = cd - 1 ; } | ( RealAccu _ ) :: tl -> { state with camlstack = tl ; camldepth = cd - 1 ; realaccu = ISet . remove cpos state . realaccu ; } | ( Const _ | Local _ | Atom _ | TracedGlobal _ | Invalid ) :: tl -> { state with camlstack = tl ; camldepth = cd - 1 } | [ ] -> assert false |
let rec popn_camlstack number state = if number = 0 then state else popn_camlstack ( number - 1 ) ( pop_camlstack state ) |
let push_camlstack store state = let cd = state . camldepth in let cpos = ( - cd - 1 ) in match store with | RealStack pos -> { state with camlstack = store :: state . camlstack ; camldepth = cd + 1 ; } | RealAccu _ -> { state with camlstack = store :: state . camlstack ; camldepth = cd + 1 ; realaccu = ISet . add cpos state . realaccu ; } | ( Const _ | Local _ | Atom _ | TracedGlobal _ ) -> { state with camlstack = store :: state . camlstack ; camldepth = cd + 1 ; } | Invalid -> assert false |
let flush_accu lpad state = let instrs_rev = ISet . fold ( fun pos instr_acc -> let instr = Wcopy { src = real_accu ; dest = RealStack pos } in instr :: instr_acc ) state . realaccu [ ] in let instrs = List . rev instrs_rev in let camlstack = List . mapi ( fun i old -> let pos = ( - state . camldepth + i ) in if ISet . mem pos state . realaccu then ( RealStack pos ) else old ) state . camlstack in let state = { state with camlstack ; realaccu = ISet . empty ; } in ( state , instrs ) |
let straighten_accu lpad state = let state , instrs_flush = flush_accu lpad state in match state . accu with | Invalid -> ( state , [ ] ) | RealAccu _ -> ( state , instrs_flush ) | store -> let instr = Wcopy { src = store ; dest = real_accu } in let state = { state with accu = real_accu } in ( state , instrs_flush @ [ instr ] ) |
let straighten_accu_when_on_stack lpad state = match state . accu with | ( RealStack _ ) -> straighten_accu lpad state | _ -> ( state , [ ] ) |
let straighten_accu_for_branch lpad state = match state . accu with | RealStack _ | Const _ | Atom _ | TracedGlobal _ -> straighten_accu lpad state | Local _ | RealAccu _ | Invalid -> ( state , [ ] ) |
let pop_real_stack lpad state num = let cd = state . camldepth in match state . accu with | ( RealStack pos ) when pos >= ( - cd ) && pos <= ( - cd + num - 1 ) -> straighten_accu lpad state | _ -> ( state , [ ] ) |
let flush_real_stack_only_accu_at lpad state pos = match state . accu with | ( RealStack p ) when p = pos -> straighten_accu lpad state | _ -> ( state , [ ] ) |
let patch camlstack depth patches = let rec recurse camlstack pos patches = match patches with | [ ] -> camlstack | next_patch :: patches ' -> if pos = next_patch then match camlstack with | _ :: tl -> RealStack pos :: ( recurse tl ( pos + 1 ) patches ' ) | [ ] -> assert false else match camlstack with | hd :: tl -> hd :: recurse tl ( pos + 1 ) patches | [ ] -> assert false in recurse camlstack ( - depth ) ( ISet . elements patches ) |
let flush_real_stack_at lpad state pos = let cd = state . camldepth in let state , instrs1 = flush_real_stack_only_accu_at lpad state pos in let _ , positions = List . fold_left ( fun ( q , acc ) store -> match store with | RealStack p when p = pos && q <> p -> assert ( p > q ) ; let acc ' = ISet . add q acc in ( q + 1 , acc ' ) | _ -> ( q + 1 , acc ) ) ( - cd , ISet . empty ) state . camlstack in let instrs2 = positions |> ISet . elements |> List . map ( fun q -> Wcopy { src = RealStack pos ; dest = RealStack q } ) in let camlstack = patch state . camlstack cd positions in let state = { state with camlstack ; } in ( state , instrs1 @ instrs2 ) let cd = state . camldepth in let state , instrs1 = flush_real_stack_only_accu_at lpad state pos in let local = new_local lpad RIntVal in let _ , positions = List . fold_left ( fun ( q , acc ) store -> match store with | RealStack p when p = pos && q <> p -> assert ( p > q ) ; let acc ' = ISet . add q acc in ( q + 1 , acc ' ) | _ -> ( q + 1 , acc ) ) ( - cd , ISet . empty ) state . camlstack in let src = RealStack pos in let instrs2 = [ Wcopy { src ; dest = Local ( RIntVal , local ) } ] in let camlstack = List . mapi ( fun i old -> let q = - cd + i in if ISet . mem q positions then Local ( RIntVal , local ) else old ) state . camlstack in let state = { state with camlstack } in ( state , instrs1 @ instrs2 ) ) * |
let straighten_stack_at lpad state pos = if pos >= 0 then ( state , [ Wcomment ( sprintf " ****** STRANGE CASE : straighten_stack_at pos =% d " ***** pos ) ] ) else let k = pos + state . camldepth in let store = List . nth state . camlstack k in match store with | RealAccu _ -> assert ( ISet . mem pos state . realaccu ) ; let state , instrs = flush_accu lpad state in ( state , instrs ) | RealStack p when p = pos -> ( state , [ ] ) | _ -> assert ( not ( List . mem ( RealStack pos ) state . camlstack ) ) ; let instrs = [ Wcopy { src = store ; dest = RealStack pos } ] in let state = { state with camlstack = set_camlstack pos ( RealStack pos ) state ; } in ( state , instrs ) |
let straighten_stack_multi lpad state pos_list = let state , rev_acc = List . fold_left ( fun ( state , rev_acc ) pos -> let ( state , instrs ) = straighten_stack_at lpad state pos in ( state , List . rev_append instrs rev_acc ) ) ( state , [ ] ) pos_list in ( state , List . rev rev_acc ) |
let accu_is_realaccu state = match state . accu with | RealAccu _ -> true | _ -> false |
let accu_is_realaccu_or_invalid state = match state . accu with | RealAccu _ | Invalid -> true | _ -> false |
let straighten_stack lpad state = let state , instrs1 = flush_accu lpad state in let cd = state . camldepth in let pos_list = state . camlstack |> List . mapi ( fun i store -> ( i , store ) ) |> List . concat_map ( fun ( i , store ) -> match store with | RealStack p when p <> - cd + i -> [ - cd + i ] | _ -> [ - cd + i ] ) in let state , instrs2 = straighten_stack_multi lpad state pos_list in ( state , instrs1 @ instrs2 ) |
let straighten_all lpad state = let state , instrs1 = straighten_accu lpad state in assert ( accu_is_realaccu_or_invalid state && state . realaccu = ISet . empty ) ; let state , instrs2 = straighten_stack lpad state in ( state , instrs1 @ instrs2 ) |
let localize_accu lpad state repr = match state . accu with | RealStack _ | RealAccu _ -> let local = new_local lpad repr in let lstore = Local ( repr , local ) in let instrs = [ Wcopy { src = state . accu ; dest = lstore } ] in let cd = state . camldepth in let positions = List . mapi ( fun i st -> if st = state . accu then i else ( - 1 ) ) state . camlstack |> List . filter ( fun i -> i >= 0 ) |> List . map ( fun i -> - cd + i ) in let state = List . fold_left ( fun state pos -> { state with camlstack = set_camlstack pos lstore state } ) state positions in let state = { state with accu = lstore } in ( state , instrs ) | _ -> ( state , [ ] ) |
let unary_operation ( ? no_function = false ) lpad state op_repr op_code = let src1 = state . accu in let op_repr = if lpad . avoid_locals then RValue else op_repr in match op_repr with | RValue -> let state , instrs_flush = flush_accu lpad state in let state = { state with accu = real_accu } in let instrs_op = [ Wunary { op = op_code ; src1 ; dest = real_accu } ] in ( state , instrs_flush @ instrs_op ) | _ -> let dest_name = new_local lpad op_repr in let dest = Local ( op_repr , dest_name ) in let state = { state with accu = dest } in let instrs_op = [ Wunary { op = op_code ; src1 ; dest } ] in ( state , instrs_op ) |
let unary_effect lpad state op_code = let src1 = state . accu in let state = { state with accu = Const 0 } in let instrs_op = [ Wunaryeffect { op = op_code ; src1 } ] in ( state , instrs_op ) |
let binary_operation ( ? no_function = false ) lpad state op_repr op_code = let src1 = state . accu in let src2 = List . hd state . camlstack in let op_repr = if lpad . avoid_locals then RValue else op_repr in match op_repr with | RValue -> let state , instrs_flush = flush_accu lpad state in let state = { state with accu = real_accu } |> pop_camlstack in let instrs_op = [ Wbinary { op = op_code ; src1 ; src2 ; dest = real_accu } ] in ( state , instrs_flush @ instrs_op ) | _ -> let dest_name = new_local lpad op_repr in let dest = Local ( op_repr , dest_name ) in let state = { state with accu = dest } |> pop_camlstack in let instrs_op = [ Wbinary { op = op_code ; src1 ; src2 ; dest } ] in ( state , instrs_op ) |
let binary_effect lpad state op_code = let src1 = state . accu in let src2 = List . hd state . camlstack in let state = { state with accu = Const 0 } |> pop_camlstack in let instrs_op = [ Wbinaryeffect { op = op_code ; src1 ; src2 } ] in ( state , instrs_op ) |
let ternary_effect lpad state op_code = let src1 = state . accu in let src2 = List . hd state . camlstack in let src3 = List . hd ( List . tl state . camlstack ) in let state = { state with accu = Const 0 } |> pop_camlstack |> pop_camlstack in let instrs_op = [ Wternaryeffect { op = op_code ; src1 ; src2 ; src3 } ] in ( state , instrs_op ) |
let global_offset ident = assert ( Ident . global ident ) ; let name = Ident . name ident in int_of_string name |
let make_label lpad label = if ISet . mem label lpad . loops then Loop label else Label label |
let validate state = let d = state . camldepth in List . iteri ( fun i st -> match st with | RealStack pos -> assert ( pos = ( - d + i ) ) | _ -> assert false ) state . camlstack ; assert ( match state . accu with | RealAccu { no_function = true } -> false | RealAccu _ | Local _ | Invalid -> true | _ -> false ) ; assert ( state . realaccu = ISet . empty ) |
let update_state_table lpad state label = try let s = Hashtbl . find lpad . state_table label in assert ( s . camldepth = state . camldepth ) with | Not_found -> Hashtbl . add lpad . state_table label state |
let norm_accu state = match state . accu with | RealAccu { no_function = true } -> { state with accu = real_accu } | _ -> state |
let branch lpad state label = let state = norm_accu state in let instr_br = Wbranch { label = make_label lpad label } in try let dest_state = Hashtbl . find lpad . state_table label in validate dest_state ; let ( state , instrs1 ) = straighten_accu_for_branch lpad state in let ( state , instrs2 ) = straighten_stack lpad state in validate state ; assert ( state . camldepth = dest_state . camldepth ) ; let instrs = if state . accu = dest_state . accu || dest_state . accu = Invalid then instrs1 @ instrs2 @ [ instr_br ] else instrs1 @ instrs2 @ [ Wcopy { src = state . accu ; dest = dest_state . accu } ; instr_br ] in ( state , instrs ) with | Not_found -> let n = try Hashtbl . find lpad . indegree label with Not_found -> 0 in if n < 0 then ( let state , instrs1 = straighten_all lpad state in let state = if n = ( - 2 ) then { state with accu = Invalid } else state in Hashtbl . add lpad . state_table label state ; ( state , instrs1 @ [ instr_br ] ) ) else if n <= 1 then ( let ( state , instrs1 ) = straighten_accu_for_branch lpad state in Hashtbl . add lpad . state_table label state ; ( state , instrs1 @ [ instr_br ] ) ) else ( let ( state , instrs1 ) = straighten_accu_for_branch lpad state in let ( state , instrs2 ) = straighten_stack lpad state in Hashtbl . add lpad . state_table label state ; ( state , instrs1 @ instrs2 @ [ instr_br ] ) ) |
let transl_instr lpad state instr = match instr with | I . Klabel _ -> assert false | Kconst ( Lambda . Const_base ( Asttypes . Const_int k ) ) -> ( { state with accu = Const k } , [ ] ) | Kconst _ -> assert false | Kacc sp -> let state = if sp < state . camldepth then { state with accu = List . nth state . camlstack sp } else { state with accu = RealStack ( - state . camldepth + sp ) } in ( state , [ ] ) | Kpush -> let state = push_camlstack state . accu state in ( state , [ Wcomment ( sprintf " ( depth =% d ) " state . camldepth ) ] ) | Kpush_retaddr lab -> let state = push_camlstack ( Const 0 ) state in let state = push_camlstack ( Const 0 ) state in let state = push_camlstack ( Const 0 ) state in ( state , [ ] ) | Kpop num -> let state , instrs = pop_real_stack lpad state num in let state = popn_camlstack num state in ( state , instrs @ [ Wcomment ( sprintf " ( depth =% d ) " state . camldepth ) ] ) | Kassign sp -> let cd = state . camldepth in let state , instrs_flush = flush_real_stack_at lpad state ( - cd + sp ) in let state = { state with camlstack = set_camlstack ( - cd + sp ) ( RealStack ( - cd + sp ) ) state } in let instrs_copy = [ Wcopy { src = state . accu ; dest = RealStack ( - cd + sp ) } ] in ( state , instrs_flush @ instrs_copy ) | Kenvacc field -> let state , instrs_flush = flush_accu lpad state in let real_field = lpad . func_offset + field in if real_field < Array . length lpad . environment && lpad . environment . ( real_field ) <> Unknown then ( let efield = lpad . environment . ( real_field ) in let state = { state with accu = TracedGlobal ( Env 0 , [ field ] , efield ) } in ( state , instrs_flush ) ) else let accu = real_accu in let state = { state with accu } in let instrs_op = [ Wenv { field } ] in ( state , instrs_flush @ instrs_op ) | Kgetglobal ident -> let offset = global_offset ident in assert ( offset >= 0 ) ; let state , instrs_flush = flush_accu lpad state in ( match Hashtbl . find lpad . globals_table offset with | initvalue -> let accu = TracedGlobal ( Glb offset , [ ] , initvalue ) in let state = { state with accu } in ( state , instrs_flush ) | exception Not_found -> let accu = real_accu in let state = { state with accu } in let instrs_op = [ Wgetglobal { src = Global offset } ] in ( state , instrs_flush @ instrs_op ) ) | Knegint -> unary_operation lpad state RIntVal Pnegint | Kboolnot -> unary_operation lpad state RIntVal Pboolnot | Koffsetint offset -> let ( state , instrs1 ) = if lpad . avoid_locals then ( state , [ ] ) else localize_accu lpad state RIntVal in let ( state , instrs2 ) = unary_operation lpad state RIntVal ( Poffsetint offset ) in ( state , instrs1 @ instrs2 ) | Koffsetref offset -> unary_effect lpad state ( Poffsetref offset ) | Kisint -> unary_operation lpad state RInt Pisint | Ksetglobal ident -> let offset = global_offset ident in unary_effect lpad state ( Psetglobal ( Global offset ) ) | Kgetfield field -> ( match state . accu with | TracedGlobal ( glb , path , initvalue ) -> let new_path = path @ [ field ] in let new_initvalue = match initvalue with | Block b when field < Array . length b -> b . ( field ) | _ -> Unknown in let accu = TracedGlobal ( glb , new_path , new_initvalue ) in let state = { state with accu ; } in ( state , [ ] ) | _ -> unary_operation lpad state RValue ( Pgetfield field ) ) | Kvectlength -> unary_operation lpad state RIntVal Pvectlength | Kgetpubmet k -> let state = push_camlstack state . accu state in unary_operation lpad state RValue ( Pgetpubmet k ) | Kaddint -> binary_operation lpad state RIntVal Paddint | Ksubint -> binary_operation lpad state RIntVal Psubint | Kmulint -> binary_operation lpad state RIntUnclean Pmulint | Kdivint -> binary_operation lpad state RInt Pdivint | Kmodint -> binary_operation lpad state RInt Pmodint | Kandint -> binary_operation lpad state RIntVal Pandint | Korint -> binary_operation lpad state RIntVal Porint | Kxorint -> binary_operation lpad state RIntVal Pxorint | Klslint -> binary_operation lpad state RIntVal Plslint | Klsrint -> binary_operation lpad state RIntVal Plsrint | Kasrint -> binary_operation lpad state RIntVal Pasrint | Kintcomp cmp -> binary_operation lpad state RInt ( Pintcomp cmp ) | Kisout -> binary_operation lpad state RInt ( Puintcomp Clt ) | Ksetfield field -> binary_effect lpad state ( Psetfield field ) | Ksetfloatfield field -> binary_effect lpad state ( Psetfloatfield field ) | Kgetvectitem -> binary_operation lpad state RValue Pgetvectitem | Kgetstringchar -> binary_operation lpad state RInt Pgetstringchar | Kgetbyteschar -> binary_operation lpad state RInt Pgetbyteschar | Kgetmethod -> let state = push_camlstack ( List . hd state . camlstack ) state in binary_operation lpad state RValue Pgetmethod | Kgetdynmet -> let state = push_camlstack ( List . hd state . camlstack ) state in binary_operation lpad state RValue Pgetdynmet | Ksetvectitem -> ternary_effect lpad state Psetvectitem | Ksetbyteschar -> ternary_effect lpad state Psetbyteschar | Kgetfloatfield field -> let src1 = state . accu in let state , instrs_flush = flush_accu lpad state in let temp_name = new_local lpad RFloat in let temp = Local ( RFloat , temp_name ) in let descr = stack_descr state in let accu = real_accu_no_func in let instrs = instrs_flush @ [ Wunary { op = Pgetfloatfield field ; src1 ; dest = temp ; } ; Walloc { src = temp ; dest = accu ; descr } ] in let state = { state with accu } in ( state , instrs ) | Kmakeblock ( 0 , tag ) -> let state = { state with accu = Atom tag } in ( state , [ ] ) | Kmakeblock ( size , tag ) -> let state , instrs_flush = flush_accu lpad state in let src1 = state . accu in let src = src1 :: list_prefix ( size - 1 ) state . camlstack in let descr = stack_descr state in let accu = real_accu_no_func in let instrs = instrs_flush @ [ Wmakeblock { tag ; src ; descr } ] in let state = { state with accu } |> popn_camlstack ( size - 1 ) in ( state , instrs ) | Kmakefloatblock size -> assert ( size > 0 ) ; let state , instrs_flush = flush_accu lpad state in let src1 = state . accu in let src = src1 :: list_prefix ( size - 1 ) state . camlstack in let descr = stack_descr state in let instrs = instrs_flush @ [ Wmakefloatblock { src ; descr } ] in let accu = real_accu_no_func in let state = { state with accu } |> popn_camlstack ( size - 1 ) in ( state , instrs ) | Kccall ( name , num ) when num <= 5 -> let state , instrs_flush = flush_accu lpad state in let src1 = state . accu in let src = src1 :: list_prefix ( num - 1 ) state . camlstack in let descr = stack_descr state in let instrs = instrs_flush @ [ Wccall { name ; src ; descr } ] in let no_function = Hashtbl . mem Wc_prims . prims_non_func_result name in let state = { state with accu = RealAccu { no_function } } |> popn_camlstack ( num - 1 ) in ( state , instrs ) | Kccall ( name , num ) -> let state , instrs_str = straighten_all lpad state in let descr = stack_descr state in let depth = state . camldepth + 1 in let instrs = instrs_str @ [ Wcopy { src = real_accu ; dest = RealStack ( - depth ) } ; Wccall_vector { name ; numargs = num ; depth ; descr } ] in let no_function = Hashtbl . mem Wc_prims . prims_non_func_result name in let state = { state with accu = RealAccu { no_function } } |> popn_camlstack ( num - 1 ) in ( state , instrs ) | Kbranch label -> branch lpad state label | Kbranchif label -> let ( br_state , instrs ) = branch lpad state label in ( state , [ Wif { src = state . accu ; neg = false ; body = instrs } ] ) | Kbranchifnot label -> let ( br_state , instrs ) = branch lpad state label in ( state , [ Wif { src = state . accu ; neg = true ; body = instrs } ] ) | Kswitch ( labels_int , labels_blk ) -> let state = norm_accu state in let state , instrs_str = straighten_all lpad state in validate state ; Array . iter ( update_state_table lpad state ) labels_int ; Array . iter ( update_state_table lpad state ) labels_blk ; let labels_int = Array . map ( make_label lpad ) labels_int in let labels_blk = Array . map ( make_label lpad ) labels_blk in let src = state . accu in ( state , instrs_str @ [ Wswitch { labels_int ; labels_blk ; src } ] ) | Kapply num when num <= 3 -> let direct_opt = extract_directly_callable_function state . accu in let state = match direct_opt with | Some _ -> { state with accu = real_accu } | None -> state in let state , instrs_str = straighten_all lpad state in let cd = state . camldepth in let instrs_move = enum 0 num |> List . map ( fun k -> Wcopy { src = RealStack ( - cd + k ) ; dest = RealStack ( - cd + k - 3 ) } ) in let depth = cd + 3 in let instr_apply = match direct_opt with | Some ( global , path , funlabel , _ ) -> Wapply_direct { global ; path ; funlabel ; numargs = num ; depth } | None -> Wapply { numargs = num ; depth } in let instrs = instrs_str @ instrs_move @ [ Wcopy { src = Const 0 ; dest = RealStack ( - cd + num - 3 ) } ; Wcopy { src = Const 0 ; dest = RealStack ( - cd + num - 2 ) } ; Wcopy { src = Const 0 ; dest = RealStack ( - cd + num - 1 ) } ; instr_apply ] in let state = state |> popn_camlstack num in ( state , instrs ) | Kapply num -> let direct_opt = extract_directly_callable_function state . accu in let state = match direct_opt with | Some _ -> { state with accu = real_accu } | None -> state in let state , instrs_str = straighten_all lpad state in let depth = state . camldepth in let instr_apply = match direct_opt with | Some ( global , path , funlabel , _ ) -> Wapply_direct { global ; path ; funlabel ; numargs = num ; depth } | None -> Wapply { numargs = num ; depth } in let instrs = instrs_str @ [ instr_apply ] in let state = state |> popn_camlstack ( num + 3 ) in ( state , instrs ) | Kappterm ( num , slots ) -> let state , instrs_accu = straighten_accu lpad state in let state , instrs_stack = straighten_stack_multi lpad state ( enum ( - state . camldepth ) num ) in let instrs = instrs_accu @ instrs_stack @ [ Wappterm { numargs = num ; oldnumargs ( = slots - state . camldepth ) ; depth = state . camldepth } ] in ( state , instrs ) | Kreturn slots -> assert ( state . camldepth + state . arity = slots ) ; ( state , [ Wreturn { src = state . accu ; arity = state . arity } ] ) | Kgrab num -> ( { state with arity = num + 1 } , [ Wgrab { numargs = num } ] ) | Kclosure ( lab , num ) -> let state , instrs_flush = flush_accu lpad state in let src = if num = 0 then [ ] else state . accu :: list_prefix ( num - 1 ) state . camlstack in let descr = stack_descr state in let accu = real_accu in let instrs = instrs_flush @ [ Wclosurerec { src ; dest [ = accu , lab ] ; descr } ] in let state = { state with accu } |> popn_camlstack ( max ( num - 1 ) 0 ) in ( state , instrs ) | Kclosurerec ( funcs , num ) -> let state , instrs_flush = flush_accu lpad state in let descr = stack_descr state in let num_stack = max ( num - 1 ) 0 in let src = if num = 0 then [ ] else state . accu :: list_prefix num_stack state . camlstack in let state = state |> popn_camlstack num_stack in let start_dest = - state . camldepth - 1 in let dest = List . mapi ( fun i lab -> ( RealStack ( start_dest - i ) , lab ) ) funcs in let state = List . fold_left ( fun state ( store , _ ) -> push_camlstack store state ) state dest in let state = { state with accu = Const 0 } in let instrs = instrs_flush @ [ Wclosurerec { src ; dest ; descr } ] in ( state , instrs ) | Koffsetclosure offset -> let state , instrs_flush = flush_accu lpad state in let real_field = lpad . func_offset + offset in let n = Array . length lpad . environment in if n > 0 && real_field < Array . length lpad . environment && ( let _ = assert ( real_field >= 0 ) in true ) && Wc_traceglobals . is_function lpad . environment . ( real_field ) then ( let efield = Wc_traceglobals . FuncInEnv { func_offset = real_field ; env = lpad . environment } in let state = { state with accu = TracedGlobal ( Env offset , [ ] , efield ) } in ( state , instrs_flush ) ) else let accu = real_accu in let state = { state with accu } in let instrs = instrs_flush @ [ Wcopyenv { offset } ] in ( state , instrs ) | Krestart -> ( state , [ ] ) | Kpushtrap _ | Kpoptrap -> ( state , [ ] ) | Kraise kind -> ( state , [ Wraise { src = state . accu ; kind } ] ) | Kstop -> ( state , [ Wstop ] ) | Kcheck_signals | Kevent _ -> ( state , [ ] ) | Kstrictbranchif _ -> assert false | Kstrictbranchifnot _ -> assert false |
let local_branch_labels = function | I . Kbranch l -> [ l ] | Kbranchif l -> [ l ] | Kbranchifnot l -> [ l ] | Kswitch ( la1 , la2 ) -> Array . to_list la1 @ Array . to_list la2 | _ -> [ ] |
let transl_fblock lpad fblock = let open Wc_control in let indegree = Hashtbl . create 7 in let state_table = Hashtbl . create 7 in let lpad = { lpad with indegree ; state_table } in let incr_indegree lab = let n = try Hashtbl . find indegree lab with Not_found -> 0 in if n >= 0 then Hashtbl . replace indegree lab ( n + 1 ) in let disable_indegree lab = Hashtbl . replace indegree lab ( - 1 ) in let loop_indegree lab = Hashtbl . replace indegree lab ( - 2 ) in let rec count_indegree block = ( match block . loop_label with | Some lab -> loop_indegree lab | None -> ( ) ) ; Array . iter ( function | Block b -> count_indegree b | Trap { catchlabel } -> incr_indegree catchlabel | Simple i -> ( match i with | ( I . Kbranch lab | Kbranchif lab | Kbranchifnot lab ) -> incr_indegree lab | Kswitch ( la1 , la2 ) -> Array . iter disable_indegree la1 ; Array . iter disable_indegree la2 ; | _ -> ( ) ) | Label _ | TryReturn | NextMain _ -> ( ) ) block . instructions in let get_state label = try Hashtbl . find state_table label with Not_found -> empty_state in let rec transl_block block loops = let state = empty_state in let upd_loops = match block . loop_label with | Some lab -> ISet . add lab loops | _ -> loops in let state , instrs_rev = Array . fold_left ( fun ( state , acc ) instr -> match instr with | Label label -> let state = get_state label in let comment = Wcomment ( sprintf " Label % d ( depth =% d ) " label state . camldepth ) in ( state , comment :: acc ) | Simple i -> lpad . loops <- upd_loops ; let next_state , instrs = transl_instr lpad state i in let comment = Wcomment ( " " *** ^ Wc_util . string_of_kinstruction i ) in ( next_state , List . rev_append ( comment :: instrs ) acc ) | Trap { trylabel ; catchlabel ; poplabel } -> let state , instrs_str = straighten_all lpad state in let accu = real_accu in let state = { state with accu } in let instrs = [ Wcomment ( sprintf " *** Trap ( try =% d , catch =% d ) " trylabel catchlabel ) ] @ instrs_str @ [ Wtrap { trylabel ; catchlabel ; depth = state . camldepth } ; ( match poplabel with | None -> Wunreachable | Some pop -> Wbranch { label = Label pop } ) ] in update_state_table lpad state catchlabel ; Option . iter ( update_state_table lpad state ) poplabel ; ( state , List . rev_append instrs acc ) | TryReturn -> let instrs = [ Wcomment " *** TryReturn " ; Wtryreturn { src = state . accu } ] in ( state , List . rev_append instrs acc ) | Block inner -> let instrs = transl_block inner upd_loops in ( state , List . rev_append instrs acc ) | NextMain label -> let instrs = [ Wnextmain { label } ] in ( state , List . rev_append instrs acc ) ) ( state , [ ] ) block . instructions in let instrs = List . rev instrs_rev in match block . loop_label , block . break_label with | Some _ , Some _ -> assert false | Some label , None -> [ Wblock { label = Loop label ; body = instrs } ] | None , Some label -> [ Wblock { label = Label label ; body = instrs } ] | None , None -> instrs in count_indegree fblock . block ; transl_block fblock . block ISet . empty |
let string_of_raise_kind = function | Lambda . Raise_regular -> " regular " | Raise_reraise -> " reraise " | Raise_notrace -> " notrace " |
let string_of_int_comparison = function | Lambda . Ceq -> " eq " | Cne -> " ne " | Clt -> " lt " | Cgt -> " gt " | Cle -> " le " | Cge -> " ge " |
let string_of_kinstruction = function | I . Klabel label -> sprintf " Klabel ( label % d ) " label | Kacc k -> sprintf " Kacc ( % d ) " k | Kenvacc k -> sprintf " Kenvacc ( % d ) " k | Kpush -> " Kpush " | Kpop k -> sprintf " Kpop ( % d ) " k | Kassign k -> sprintf " Kassign ( % d ) " k | Kpush_retaddr label -> sprintf " Kpush_retaddr ( label % d ) " label | Kapply k -> sprintf " Kapply ( % d ) " k | Kappterm ( k1 , k2 ) -> sprintf " Kappterm ( % d , % d ) " k1 k2 | Kreturn k -> sprintf " Kreturn ( % d ) " k | Krestart -> " Krestart " | Kgrab k -> sprintf " Kgrab ( % d ) " k | Kclosure ( label , k ) -> sprintf " Kclosure ( label % d , % d ) " label k | Kclosurerec ( labels , k ) -> let s = List . map ( sprintf " label % d " ) labels |> String . concat " , " in sprintf " Kclosurerec ( % s ; % d ) " s k | Koffsetclosure k -> sprintf " Koffsetclosure ( % d ) " k | Kgetglobal id -> sprintf " Kgetglobal ( % s ) " ( Ident . name id ) | Ksetglobal id -> sprintf " Ksetglobal ( % s ) " ( Ident . name id ) | Kconst ( Lambda . Const_base ( Asttypes . Const_int k ) ) -> sprintf " Kconst ( % d ) " k | Kconst _ -> " Kconst ( undecodable ) " | Kmakeblock ( k1 , k2 ) -> sprintf " Kmakeblock ( % d , % d ) " k1 k2 | Kmakefloatblock k -> sprintf " Kmakefloatblock ( % d ) " k | Kgetfield k -> sprintf " Kgetfield ( % d ) " k | Ksetfield k -> sprintf " Ksetfield ( % d ) " k | Kgetfloatfield k -> sprintf " Kgetfloatfield ( % d ) " k | Ksetfloatfield k -> sprintf " Ksetfloatfield ( % d ) " k | Kvectlength -> " Kvectlength " | Kgetvectitem -> " Kgetvectitem " | Ksetvectitem -> " Ksetvectitem " | Kgetstringchar -> " Kgetstringchar " | Kgetbyteschar -> " Kgetbyteschar " | Ksetbyteschar -> " Ksetbyteschar " | Kbranch label -> sprintf " Kbranch ( label % d ) " label | Kbranchif label -> sprintf " Kbranchif ( label % d ) " label | Kbranchifnot label -> sprintf " Kbranchifnot ( label % d ) " label | Kstrictbranchif _ -> assert false | Kstrictbranchifnot _ -> assert false | Kswitch ( labels1 , labels2 ) -> let s1 = Array . to_list labels1 |> List . map ( sprintf " label % d " ) |> String . concat " , " in let s2 = Array . to_list labels2 |> List . map ( sprintf " label % d " ) |> String . concat " , " in sprintf " Kswitch ( % s ; % s ) " s1 s2 | Kboolnot -> " Kboolnot " | Kpushtrap label -> sprintf " Kpushtrap ( label % d ) " label | Kpoptrap -> " Kpoptrap " | Kraise kind -> sprintf " Kraise ( % s ) " ( string_of_raise_kind kind ) | Kcheck_signals -> " Kcheck_signals " | Kccall ( name , k ) -> sprintf " Kccall ( % s , % d ) " name k | Knegint -> " Knegint " | Kaddint -> " Kaddint " | Ksubint -> " Ksubint " | Kmulint -> " Kmulint " | Kdivint -> " Kdivint " | Kmodint -> " Kmodint " | Kandint -> " Kandint " | Korint -> " Korint " | Kxorint -> " Kxorint " | Klslint -> " Klslint " | Klsrint -> " Klsrint " | Kasrint -> " Kasrint " | Kintcomp cmp -> sprintf " Kintcomp ( % s ) " ( string_of_int_comparison cmp ) | Koffsetint k -> sprintf " Koffsetint ( % d ) " k | Koffsetref k -> sprintf " Koffsetref ( % d ) " k | Kisint -> " Kistin " | Kisout -> " Kisout " | Kgetmethod -> " Kgetmethod " | Kgetpubmet k -> sprintf " Kgetpubmet ( % d ) " k | Kgetdynmet -> " Kgetdynmet " | Kevent _ -> " Kevent " | Kstop -> " Kstop " |
let hexdigits = [ | ' 0 ' ; ' 1 ' ; ' 2 ' ; ' 3 ' ; ' 4 ' ; ' 5 ' ; ' 6 ' ; ' 7 ' ; ' 8 ' ; ' 9 ' ; ' a ' ; ' b ' ; ' c ' ; ' d ' ; ' e ' ; ' f ' ] | |
let rec enum k n = if n > 0 then k :: enum ( k + 1 ) ( n - 1 ) else [ ] |
let rec list_prefix n l = if n = 0 then [ ] else match l with | x :: l ' -> x :: ( list_prefix ( n - 1 ) l ' ) | [ ] -> assert false |
let create l = if not ( 0 <= l && l <= Obj . Ephemeron . max_ephe_length ) then invalid_arg ( " Weak . create " ) ; create l |
let length x = Obj . size ( Obj . repr x ) - additional_values |
let raise_if_invalid_offset e o msg = if not ( 0 <= o && o < length e ) then invalid_arg ( msg ) |
let set e o x = raise_if_invalid_offset e o " Weak . set " ; match x with | None -> unset e o | Some x -> set ' e o x |
let get e o = raise_if_invalid_offset e o " Weak . get " ; get e o |
let get_copy e o = raise_if_invalid_offset e o " Weak . get_copy " ; get_copy e o |
let check e o = raise_if_invalid_offset e o " Weak . check " ; check e o |
let blit e1 o1 e2 o2 l = if l < 0 || o1 < 0 || o1 > length e1 - l || o2 < 0 || o2 > length e2 - l then invalid_arg " Weak . blit " else if l <> 0 then blit e1 o1 e2 o2 l |
let fill ar ofs len x = if ofs < 0 || len < 0 || ofs > length ar - len then raise ( Invalid_argument " Weak . fill " ) else begin for i = ofs to ( ofs + len - 1 ) do set ar i x done end |
module type S = sig type data type t val create : int -> t val clear : t -> unit val merge : t -> data -> data val add : t -> data -> unit val remove : t -> data -> unit val find : t -> data -> data val find_opt : t -> data -> data option val find_all : t -> data -> data list val mem : t -> data -> bool val iter : ( data -> unit ) -> t -> unit val fold : ( data -> ' a -> ' a ) -> t -> ' a -> ' a val count : t -> int val stats : t -> int * int * int * int * int * int end |
module Make ( H : Hashtbl . HashedType ) : ( S with type data = H . t ) = struct type ' a weak_t = ' a t let weak_create = create let emptybucket = weak_create 0 type data = H . t type t = { mutable table : data weak_t array ; mutable hashes : int array array ; mutable limit : int ; mutable oversize : int ; mutable rover : int ; } let get_index t h = ( h land max_int ) mod ( Array . length t . table ) let limit = 7 let over_limit = 2 let create sz = let sz = if sz < 7 then 7 else sz in let sz = if sz > Sys . max_array_length then Sys . max_array_length else sz in { table = Array . make sz emptybucket ; hashes = Array . make sz [ | ] ; | limit = limit ; oversize = 0 ; rover = 0 ; } let clear t = for i = 0 to Array . length t . table - 1 do t . table . ( i ) <- emptybucket ; t . hashes . ( i ) <- [ | ] ; | done ; t . limit <- limit ; t . oversize <- 0 let fold f t init = let rec fold_bucket i b accu = if i >= length b then accu else match get b i with | Some v -> fold_bucket ( i + 1 ) b ( f v accu ) | None -> fold_bucket ( i + 1 ) b accu in Array . fold_right ( fold_bucket 0 ) t . table init let iter f t = let rec iter_bucket i b = if i >= length b then ( ) else match get b i with | Some v -> f v ; iter_bucket ( i + 1 ) b | None -> iter_bucket ( i + 1 ) b in Array . iter ( iter_bucket 0 ) t . table let iter_weak f t = let rec iter_bucket i j b = if i >= length b then ( ) else match check b i with | true -> f b t . hashes . ( j ) i ; iter_bucket ( i + 1 ) j b | false -> iter_bucket ( i + 1 ) j b in Array . iteri ( iter_bucket 0 ) t . table let rec count_bucket i b accu = if i >= length b then accu else count_bucket ( i + 1 ) b ( accu + ( if check b i then 1 else 0 ) ) let count t = Array . fold_right ( count_bucket 0 ) t . table 0 let next_sz n = min ( 3 * n / 2 + 3 ) Sys . max_array_length let prev_sz n = ( ( n - 3 ) * 2 + 2 ) / 3 let test_shrink_bucket t = let bucket = t . table . ( t . rover ) in let hbucket = t . hashes . ( t . rover ) in let len = length bucket in let prev_len = prev_sz len in let live = count_bucket 0 bucket 0 in if live <= prev_len then begin let rec loop i j = if j >= prev_len then begin if check bucket i then loop ( i + 1 ) j else if check bucket j then begin blit bucket j bucket i 1 ; hbucket . ( i ) <- hbucket . ( j ) ; loop ( i + 1 ) ( j - 1 ) ; end else loop i ( j - 1 ) ; end ; in loop 0 ( length bucket - 1 ) ; if prev_len = 0 then begin t . table . ( t . rover ) <- emptybucket ; t . hashes . ( t . rover ) <- [ | ] ; | end else begin let newbucket = weak_create prev_len in blit bucket 0 newbucket 0 prev_len ; t . table . ( t . rover ) <- newbucket ; t . hashes . ( t . rover ) <- Array . sub hbucket 0 prev_len end ; if len > t . limit && prev_len <= t . limit then t . oversize <- t . oversize - 1 ; end ; t . rover <- ( t . rover + 1 ) mod ( Array . length t . table ) let rec resize t = let oldlen = Array . length t . table in let newlen = next_sz oldlen in if newlen > oldlen then begin let newt = create newlen in let add_weak ob oh oi = let setter nb ni _ = blit ob oi nb ni 1 in let h = oh . ( oi ) in add_aux newt setter None h ( get_index newt h ) ; in iter_weak add_weak t ; t . table <- newt . table ; t . hashes <- newt . hashes ; t . limit <- newt . limit ; t . oversize <- newt . oversize ; t . rover <- t . rover mod Array . length newt . table ; end else begin t . limit <- max_int ; t . oversize <- 0 ; end and add_aux t setter d h index = let bucket = t . table . ( index ) in let hashes = t . hashes . ( index ) in let sz = length bucket in let rec loop i = if i >= sz then begin let newsz = min ( 3 * sz / 2 + 3 ) ( Sys . max_array_length - additional_values ) in if newsz <= sz then failwith " Weak . Make : hash bucket cannot grow more " ; let newbucket = weak_create newsz in let newhashes = Array . make newsz 0 in blit bucket 0 newbucket 0 sz ; Array . blit hashes 0 newhashes 0 sz ; setter newbucket sz d ; newhashes . ( sz ) <- h ; t . table . ( index ) <- newbucket ; t . hashes . ( index ) <- newhashes ; if sz <= t . limit && newsz > t . limit then begin t . oversize <- t . oversize + 1 ; for _i = 0 to over_limit do test_shrink_bucket t done ; end ; if t . oversize > Array . length t . table / over_limit then resize t ; end else if check bucket i then begin loop ( i + 1 ) end else begin setter bucket i d ; hashes . ( i ) <- h ; end ; in loop 0 let add t d = let h = H . hash d in add_aux t set ( Some d ) h ( get_index t h ) let find_or t d ifnotfound = let h = H . hash d in let index = get_index t h in let bucket = t . table . ( index ) in let hashes = t . hashes . ( index ) in let sz = length bucket in let rec loop i = if i >= sz then ifnotfound h index else if h = hashes . ( i ) then begin match get_copy bucket i with | Some v when H . equal v d -> begin match get bucket i with | Some v -> v | None -> loop ( i + 1 ) end | _ -> loop ( i + 1 ) end else loop ( i + 1 ) in loop 0 let merge t d = find_or t d ( fun h index -> add_aux t set ( Some d ) h index ; d ) let find t d = find_or t d ( fun _h _index -> raise Not_found ) let find_opt t d = let h = H . hash d in let index = get_index t h in let bucket = t . table . ( index ) in let hashes = t . hashes . ( index ) in let sz = length bucket in let rec loop i = if i >= sz then None else if h = hashes . ( i ) then begin match get_copy bucket i with | Some v when H . equal v d -> begin match get bucket i with | Some _ as v -> v | None -> loop ( i + 1 ) end | _ -> loop ( i + 1 ) end else loop ( i + 1 ) in loop 0 let find_shadow t d iffound ifnotfound = let h = H . hash d in let index = get_index t h in let bucket = t . table . ( index ) in let hashes = t . hashes . ( index ) in let sz = length bucket in let rec loop i = if i >= sz then ifnotfound else if h = hashes . ( i ) then begin match get_copy bucket i with | Some v when H . equal v d -> iffound bucket i | _ -> loop ( i + 1 ) end else loop ( i + 1 ) in loop 0 let remove t d = find_shadow t d ( fun w i -> set w i None ) ( ) let mem t d = find_shadow t d ( fun _w _i -> true ) false let find_all t d = let h = H . hash d in let index = get_index t h in let bucket = t . table . ( index ) in let hashes = t . hashes . ( index ) in let sz = length bucket in let rec loop i accu = if i >= sz then accu else if h = hashes . ( i ) then begin match get_copy bucket i with | Some v when H . equal v d -> begin match get bucket i with | Some v -> loop ( i + 1 ) ( v :: accu ) | None -> loop ( i + 1 ) accu end | _ -> loop ( i + 1 ) accu end else loop ( i + 1 ) accu in loop 0 [ ] let stats t = let len = Array . length t . table in let lens = Array . map length t . table in Array . sort compare lens ; let totlen = Array . fold_left ( + ) 0 lens in ( len , count t , totlen , lens . ( 0 ) , lens . ( len / 2 ) , lens . ( len - 1 ) ) end |
type ' a t = { mutable size : int ; mutable array : ' a Weak . t ; } |
let create n = { size = 0 ; array = Weak . create ( max 1 n ) } |
let clear xs = let threshold = Weak . length xs . array * 2 / 3 in if xs . size < threshold then Obj . truncate ( Obj . repr xs . array ) ( 1 + threshold ) ; xs . size <- 0 |
let exists xs x = let rec loop i = if i < xs . size then match Weak . get xs . array i with | Some y when x == y -> true | _ -> loop ( i + 1 ) else false in loop 0 |
let add xs x = if not ( exists xs x ) then ( if Weak . length xs . array = xs . size then begin let array = Weak . create ( xs . size * 3 / 2 + 1 ) in let j = ref 0 in for i = 0 to xs . size - 1 do match Weak . get xs . array i with | Some _ as x ' opt -> Weak . set array ! j x ' opt ; incr j | None -> ( ) done ; xs . size <- ! j ; xs . array <- array end ; Weak . set xs . array xs . size ( Some x ) ; xs . size <- xs . size + 1 ) |
let fold fn xs acc = let acc = ref acc in let j = ref 0 in for i = 0 to xs . size - 1 do match Weak . get xs . array i with | Some x as x ' opt -> acc := fn x ! acc ; if ! j < i then Weak . set xs . array ! j x ' opt ; incr j | None -> ( ) done ; xs . size <- ! j ; ! acc |
type typed_dictionary_mismatch = | MissingRequiredField of { field_name : Identifier . t ; class_name : Identifier . t ; } | FieldTypeMismatch of { field_name : Identifier . t ; expected_type : Type . t ; actual_type : Type . t ; class_name : Identifier . t ; } | UndefinedField of { field_name : Identifier . t ; class_name : Identifier . t ; } |
type weakened_type = { resolved : Type . t ; typed_dictionary_errors : typed_dictionary_mismatch Node . t list ; } |
let typed_dictionary_errors { typed_dictionary_errors ; _ } = typed_dictionary_errors |
let resolved_type { resolved ; _ } = resolved |
let make_weakened_type ( ? typed_dictionary_errors = [ ] ) resolved = { resolved ; typed_dictionary_errors } |
let combine_weakened_types weakened_types = { resolved = Type . union ( List . map weakened_types ~ f : resolved_type ) ; typed_dictionary_errors = List . concat_map weakened_types ~ f : typed_dictionary_errors ; } |
let undefined_field_mismatches ~ location ~ expected_typed_dictionary : { Type . Record . TypedDictionary . fields = expected_fields ; name = class_name } ~ resolved_typed_dictionary { : Type . Record . TypedDictionary . fields = resolved_fields ; _ } = let make_undefined_field_mismatch { Type . Record . TypedDictionary . name ; annotation = _ ; _ } = UndefinedField { field_name = name ; class_name } |> Node . create ~ location in let is_undefined_field field = not ( List . exists expected_fields ~ f ( : Type . TypedDictionary . same_name field ) ) in List . filter resolved_fields ~ f : is_undefined_field |> List . map ~ f : make_undefined_field_mismatch |
let distribute_union_over_parametric ~ parametric_name ~ number_of_parameters annotation = match annotation with | Type . Union parameters -> let extract_matching_parameters = function | Type . Parametric { name ; parameters } when Identifier . equal name parametric_name && List . length parameters = number_of_parameters -> Type . Parameter . all_singles parameters | _ -> None in let combine_parameters parameters_list = match number_of_parameters with | 1 -> Some [ Type . Parameter . Single ( Type . union ( List . concat parameters_list ) ) ] | 2 -> Some [ Type . Parameter . Single ( Type . union ( List . map ~ f : List . hd_exn parameters_list ) ) ; Type . Parameter . Single ( Type . union ( List . map ~ f : List . last_exn parameters_list ) ) ; ] | _ -> None in List . map parameters ~ f : extract_matching_parameters |> Option . all >>= combine_parameters >>| fun parametric_types -> Type . parametric parametric_name parametric_types | _ -> None |
let rec weaken_mutable_literals resolve ~ resolve_items_individually ~ get_typed_dictionary ~ expression ~ resolved ~ expected ~ comparator = let comparator_without_override = comparator in let comparator = comparator ~ get_typed_dictionary_override ( : fun _ -> None ) in let open Expression in match expression , resolved , expected with | _ , _ , Type . Union expected_types -> ( let weakened_types = List . map ~ f ( : fun expected_type -> weaken_mutable_literals ~ get_typed_dictionary resolve ~ expression ~ resolved ~ expected : expected_type ~ resolve_items_individually ~ comparator : comparator_without_override ) expected_types in match List . exists2 ~ f ( : fun { resolved = left ; _ } right -> comparator ~ left ~ right ) weakened_types expected_types with | Ok true -> make_weakened_type expected | Ok false -> make_weakened_type ~ typed_dictionary_errors ( : List . concat_map weakened_types ~ f : typed_dictionary_errors ) resolved | Unequal_lengths -> make_weakened_type resolved ) | ( Some { Node . value = Expression . List items ; _ } , Type . Parametric { name = " list " as container_name ; parameters = [ Single actual_item_type ] } , Type . Parametric { name = " list " ; parameters = [ Single expected_item_type ] } ) | ( Some { Node . value = Expression . Set items ; _ } , Type . Parametric { name = " set " as container_name ; parameters = [ Single actual_item_type ] } , Type . Parametric { name = " set " ; parameters = [ Single expected_item_type ] } ) -> let weakened_item_types = List . map ~ f ( : fun item -> let resolved_item_type = resolve item in let resolved = if resolve_items_individually && not ( Type . is_top resolved_item_type ) then resolved_item_type else actual_item_type in weaken_mutable_literals ~ get_typed_dictionary resolve ~ expression ( : Some item ) ~ resolved ~ expected : expected_item_type ~ resolve_items_individually ~ comparator : comparator_without_override ) items in let { resolved = weakened_item_type ; typed_dictionary_errors } = combine_weakened_types weakened_item_types in make_weakened_type ~ typed_dictionary_errors ( if comparator ~ left : weakened_item_type ~ right : expected_item_type then expected else Type . parametric container_name [ Single weakened_item_type ] ) | ( Some { Node . value = Expression . ListComprehension _ ; _ } , Type . Parametric { name = " list " ; parameters = [ Single actual ] } , Type . Parametric { name = " list " ; parameters = [ Single expected_parameter ] } ) when comparator ~ left : actual ~ right : expected_parameter -> make_weakened_type expected | ( Some { Node . value = Expression . SetComprehension _ ; _ } , Type . Parametric { name = " set " ; parameters = [ Single actual ] } , Type . Parametric { name = " set " ; parameters = [ Single expected_parameter ] } ) when comparator ~ left : actual ~ right : expected_parameter -> make_weakened_type expected | ( Some { Node . value = Expression . Tuple items ; _ } , Type . Tuple ( Concrete actual_item_types ) , Type . Tuple ( Concrete expected_item_types ) ) when List . length actual_item_types = List . length expected_item_types -> ( let weakened_item_types = List . map3 ~ f ( : fun item actual_item_type expected_item_type -> weaken_mutable_literals ~ get_typed_dictionary resolve ~ expression ( : Some item ) ~ resolved : actual_item_type ~ expected : expected_item_type ~ resolve_items_individually ~ comparator : comparator_without_override ) items actual_item_types expected_item_types in match weakened_item_types with | Ok weakened_item_types -> let resolved_types = List . map weakened_item_types ~ f : resolved_type in let weakened_type = Type . Tuple ( Concrete resolved_types ) in make_weakened_type ~ typed_dictionary_errors : ( List . concat_map weakened_item_types ~ f : typed_dictionary_errors ) ( if comparator ~ left : weakened_type ~ right : expected then expected else weakened_type ) | Unequal_lengths -> make_weakened_type resolved ) | ( Some { Node . value = Expression . Tuple items ; _ } , Type . Tuple ( Concrete actual_item_types ) , Type . Tuple ( Concatenation concatenation ) ) -> let weakened_tuple expected_item_type = let weakened_item_types = List . map2 ~ f ( : fun item actual_item_type -> weaken_mutable_literals ~ get_typed_dictionary resolve ~ expression ( : Some item ) ~ resolved : actual_item_type ~ expected : expected_item_type ~ resolve_items_individually ~ comparator : comparator_without_override ) items actual_item_types in match weakened_item_types with | Ok weakened_item_types -> let { resolved = weakened_item_type ; typed_dictionary_errors } = combine_weakened_types weakened_item_types in Some ( make_weakened_type ~ typed_dictionary_errors ( if comparator ~ left : weakened_item_type ~ right : expected_item_type then expected else resolved ) ) | Unequal_lengths -> None in Type . OrderedTypes . Concatenation . extract_sole_unbounded_annotation concatenation >>= weakened_tuple |> Option . value ~ default ( : make_weakened_type resolved ) | ( Some { Node . value = Expression . Dictionary { entries ; keywords = [ ] } ; location } , _ , Type . Primitive _ ) -> ( let open Type . Record . TypedDictionary in match get_typed_dictionary expected with | Some ( { fields = expected_fields ; name = expected_class_name } as expected_typed_dictionary ) -> let find_matching_field ~ name = let matching_name ( { name = expected_name ; _ } : Type . t typed_dictionary_field ) = String . equal name expected_name in List . find ~ f : matching_name in let resolve_entry { Dictionary . Entry . key ; value } = let key = resolve key in match key with | Type . Literal ( Type . String ( Type . LiteralValue name ) ) -> let annotation , required = let resolved = resolve value in let relax { annotation ; _ } = if Type . is_dictionary resolved || Option . is_some ( get_typed_dictionary resolved ) then weaken_mutable_literals resolve ~ expression ( : Some value ) ~ resolved ~ expected : annotation ~ comparator : comparator_without_override ~ resolve_items_individually ~ get_typed_dictionary else if comparator ~ left : resolved ~ right : annotation then make_weakened_type annotation else make_weakened_type resolved in find_matching_field expected_fields ~ name >>| ( fun field -> relax field , field . required ) |> Option . value ~ default ( : make_weakened_type resolved , true ) in Some { name ; annotation ; required } | _ -> None in let add_missing_fields_if_all_non_required sofar = let is_missing ( { name ; _ } : Type . t typed_dictionary_field ) = Option . is_none ( find_matching_field sofar ~ name ) in let missing_fields = List . filter expected_fields ~ f : is_missing in if List . for_all missing_fields ~ f ( : fun { required ; _ } -> not required ) then sofar @ missing_fields else sofar in let fresh_class_name = " $ fresh_class_name " in let get_typed_dictionary_override ~ typed_dictionary annotation = match annotation with | Type . Primitive name when String . equal name fresh_class_name -> Some typed_dictionary | _ -> None in let weaken_valid_fields fields = let ( { fields = actual_fields ; _ } as resolved_typed_dictionary ) = add_missing_fields_if_all_non_required fields |> Type . TypedDictionary . anonymous in let less_than_expected = comparator_without_override ~ get_typed_dictionary_override : ( get_typed_dictionary_override ~ typed_dictionary : resolved_typed_dictionary ) ~ left ( : Type . Primitive fresh_class_name ) ~ right : expected in if less_than_expected then make_weakened_type ~ typed_dictionary_errors : ( undefined_field_mismatches ~ location ~ resolved_typed_dictionary ~ expected_typed_dictionary ) expected else let type_mismatches = let make_type_mismatch { Type . Record . TypedDictionary . name = expected_field_name ; annotation = expected_type ; _ ; } { Type . Record . TypedDictionary . annotation = actual_type ; required = _ ; _ } = FieldTypeMismatch { field_name = expected_field_name ; expected_type ; actual_type ; class_name = expected_class_name ; } |> Node . create ~ location in let find_type_mismatch expected_field = List . find actual_fields ~ f ( : Type . TypedDictionary . same_name_different_annotation expected_field ) >>| make_type_mismatch expected_field in List . filter_map expected_fields ~ f : find_type_mismatch in let missing_field_mismatches = let is_missing expected_field = not ( List . exists actual_fields ~ f ( : Type . TypedDictionary . same_name expected_field ) ) in let make_missing_field_mismatch { Type . Record . TypedDictionary . name = field_name ; required ; _ } = MissingRequiredField { field_name ; class_name = expected_class_name } |> Node . create ~ location |> Option . some_if required in List . filter expected_fields ~ f : is_missing |> List . filter_map ~ f : make_missing_field_mismatch in make_weakened_type ~ typed_dictionary_errors ( : type_mismatches @ missing_field_mismatches ) resolved in let valid_field_or_typed_dictionary_error { name ; required ; annotation = { resolved ; typed_dictionary_errors } as weakened_type ; } = match typed_dictionary_errors with | [ ] -> Ok { name ; required ; annotation = resolved } | _ -> Error weakened_type in List . map entries ~ f : resolve_entry |> Option . all >>| List . map ~ f : valid_field_or_typed_dictionary_error >>| Result . combine_errors >>| ( function | Ok fields -> weaken_valid_fields fields | Error erroneous_weakened_types -> make_weakened_type ~ typed_dictionary_errors : ( List . concat_map erroneous_weakened_types ~ f : typed_dictionary_errors ) resolved ) |> Option . value ~ default ( : make_weakened_type resolved ) | None -> make_weakened_type resolved ) | ( Some { Node . value = Expression . Dictionary _ ; _ } , _ , Type . Parametric { name = " typing . Mapping " as generic_name ; parameters } ) | ( Some { Node . value = Expression . List _ ; _ } , _ , Type . Parametric { name = ( " typing . Sequence " | " typing . Iterable " ) as generic_name ; parameters } ) | ( Some { Node . value = Expression . Set _ ; _ } , _ , Type . Parametric { name = " typing . AbstractSet " as generic_name ; parameters } ) -> let mutable_generic_name = match generic_name with | " typing . Mapping " -> " dict " | " typing . Sequence " | " typing . Iterable " -> " list " | " typing . AbstractSet " -> " set " | _ -> failwith " Unexpected generic name " in let { resolved = weakened_fallback_type ; typed_dictionary_errors } = weaken_mutable_literals ~ get_typed_dictionary resolve ~ resolved ~ expected ( : Type . parametric mutable_generic_name parameters ) ~ comparator : comparator_without_override ~ expression ~ resolve_items_individually in let resolved = match weakened_fallback_type with | Type . Parametric { name ; parameters } when Identifier . equal name mutable_generic_name -> Type . parametric generic_name parameters | _ -> weakened_fallback_type in make_weakened_type ~ typed_dictionary_errors resolved | ( Some { Node . value = Expression . Dictionary { entries ; _ } ; _ } , Type . Parametric { name = " dict " ; parameters = [ Single actual_key_type ; Single actual_value_type ] } , Type . Parametric { name = " dict " ; parameters = [ Single expected_key_type ; Single expected_value_type ] } ) -> weaken_dictionary_entries ~ get_typed_dictionary resolve ~ expected ~ comparator : comparator_without_override ~ entries ~ actual_key_type ~ actual_value_type ~ expected_key_type ~ expected_value_type ~ resolve_items_individually | ( Some { Node . value = Expression . DictionaryComprehension _ ; _ } , Type . Parametric { name = " dict " ; parameters = [ Single actual_key ; Single actual_value ] } , Type . Parametric { name = " dict " ; parameters = [ Single expected_key ; Single expected_value ] } ) when comparator ~ left : actual_key ~ right : expected_key && comparator ~ left : actual_value ~ right : expected_value -> make_weakened_type expected | ( Some { Node . value = Expression . Constant ( Constant . String { StringLiteral . kind = StringLiteral . String ; value = _ } ) as expression ; _ ; } , Type . Primitive " str " , Type . Literal ( Type . String _ ) ) | ( Some { Node . value = Expression . Constant ( Constant . Integer _ ) as expression ; _ } , Type . Primitive " int " , Type . Literal ( Type . Integer _ ) ) | ( Some { Node . value = Expression . Constant Constant . ( True | False ) as expression ; _ } , Type . Primitive " bool " , Type . Literal ( Type . Boolean _ ) ) | ( Some { Node . value = Expression . Name ( Attribute _ ) as expression ; _ } , Type . Primitive _ , Type . Literal ( Type . EnumerationMember _ ) ) -> ( match Type . create_literal expression with | Some ( Type . Literal _ as actual_literal ) -> if Type . equal actual_literal expected then make_weakened_type expected else make_weakened_type actual_literal | _ -> make_weakened_type resolved ) | _ , _ , Type . RecursiveType recursive_type -> let ( { resolved = weakened_fallback_type ; _ } as weakened_type ) = weaken_mutable_literals ~ get_typed_dictionary resolve ~ expression ~ resolved ~ expected ( : Type . RecursiveType . unfold_recursive_type recursive_type ) ~ comparator : comparator_without_override ~ resolve_items_individually : true in let resolved = if comparator ~ left : weakened_fallback_type ~ right : expected then expected else weakened_fallback_type in { weakened_type with resolved } | _ -> weaken_by_distributing_union ~ get_typed_dictionary resolve ~ expected ~ resolved ~ comparator : comparator_without_override ~ expression ~ resolve_items_individually ~ get_typed_dictionary resolve ~ expected ~ comparator ~ entries ~ actual_key_type ~ actual_value_type ~ expected_key_type ~ expected_value_type ~ resolve_items_individually = let comparator_without_override = comparator in let comparator = comparator ~ get_typed_dictionary_override ( : fun _ -> None ) in let { resolved = weakened_key_type ; typed_dictionary_errors = key_errors } = List . map ~ f ( : fun { key ; _ } -> weaken_mutable_literals ~ get_typed_dictionary resolve ~ expression ( : Some key ) ~ resolved : actual_key_type ~ expected : expected_key_type ~ resolve_items_individually ~ comparator : comparator_without_override ) entries |> combine_weakened_types in let { resolved = weakened_value_type ; typed_dictionary_errors = value_errors } = List . map ~ f ( : fun { value ; _ } -> weaken_mutable_literals ~ get_typed_dictionary resolve ~ expression ( : Some value ) ~ resolved ( : if resolve_items_individually then resolve value else actual_value_type ) ~ expected : expected_value_type ~ resolve_items_individually ~ comparator : comparator_without_override ) entries |> combine_weakened_types in make_weakened_type ~ typed_dictionary_errors ( : key_errors @ value_errors ) ( if comparator ~ left : weakened_key_type ~ right : expected_key_type && comparator ~ left : weakened_value_type ~ right : expected_value_type then expected else Type . dictionary ~ key : weakened_key_type ~ value : weakened_value_type ) ~ get_typed_dictionary resolve ~ expected ~ resolved ~ comparator ~ expression ~ resolve_items_individually = let open Expression in let comparator_without_override = comparator in match expression , resolved , expected with | ( Some { Node . value = Expression . List _ | Expression . Set _ ; _ } , Type . Union _ , Type . Parametric { name = ( " list " | " set " ) as parametric_name ; parameters = [ Single ( Type . Union _ ) ] as parameters ; } ) | ( Some { Node . value = Expression . Dictionary _ ; _ } , Type . Union _ , Type . Parametric { name = " dict " as parametric_name ; parameters = ( [ Single ( Type . Union _ ) ; _ ] | [ _ ; Single ( Type . Union _ ) ] ) as parameters ; } ) -> ( match distribute_union_over_parametric ~ parametric_name ~ number_of_parameters ( : List . length parameters ) resolved with | Some resolved -> weaken_mutable_literals ~ get_typed_dictionary resolve ~ expression ~ resolved ~ expected ~ resolve_items_individually ~ comparator : comparator_without_override | None -> make_weakened_type resolved ) | _ -> make_weakened_type resolved |
let weaken_mutable_literals = weaken_mutable_literals ~ resolve_items_individually : false |
type block = int array ; ; |
type objdata = | Present of block | Absent of int ; ; |
type bunch = { objs : objdata array ; wp : block Weak . t ; } ; ; |
let data = Array . init size ( fun i -> let n = 1 + Random . int size in { objs = Array . make n ( Absent 0 ) ; wp = Weak . create n ; } ) ; ; |
let gccount ( ) = ( Gc . quick_stat ( ) ) . Gc . major_collections ; ; |
let check_and_change i j = let gc1 = gccount ( ) in match data . ( i ) . objs . ( j ) , Weak . check data . ( i ) . wp j with | Present x , false -> assert false | Absent n , true -> assert ( gc1 <= n + 1 ) | Absent _ , false -> let x = Array . make ( 1 + Random . int 10 ) 42 in data . ( i ) . objs . ( j ) <- Present x ; Weak . set data . ( i ) . wp j ( Some x ) ; | Present _ , true -> if Random . int 10 = 0 then begin data . ( i ) . objs . ( j ) <- Absent gc1 ; let gc2 = gccount ( ) in if gc1 <> gc2 then data . ( i ) . objs . ( j ) <- Absent gc2 ; end ; ; |
let dummy = ref [ ] ; ; || dummy := Array . make ( Random . int 300 ) 0 ; let i = Random . int size in let j = Random . int ( Array . length data . ( i ) . objs ) in check_and_change i j ; done |
let alive = ref ( Array . init n ( fun _ -> Array . make 10 0 ) ) |
let create_weaks ( ) = Array . init n ( fun i -> let w = Weak . create 1 in Weak . set w 0 ( Some ( ! alive . ( i ) ) ) ; w ) |
let weak1 = create_weaks ( ) |
let weak2 = create_weaks ( ) |
let weak3 = create_weaks ( ) |
let ( ) = let dummy = ref [ ] || in for l = 0 to 10 do dummy := Array . make 300 0 done |
let gccount ( ) = ( Gc . quick_stat ( ) ) . Gc . major_collections ; ; |
let ( ) = for _l = 1 to loop do let bad = ref 0 in for i = 0 to n - 1 do for _j = 0 to n * 10 do ignore ( Weak . get weak2 . ( i ) 0 ) ; done ; if Weak . check weak2 . ( i ) 0 && not ( Weak . check weak1 . ( i ) 0 ) && Weak . check weak2 . ( i ) 0 then incr bad ; if Weak . check weak2 . ( i ) 0 && not ( Weak . check weak3 . ( i ) 0 ) && Weak . check weak2 . ( i ) 0 then incr bad ; ! alive . ( i ) <- Array . make 10 0 ; done ; if ! bad > 0 then Printf . printf " failing \ n " %! else Printf . printf " success \ n " %! done |
let random_state = Domain . DLS . new_key Random . State . make_self_init |
let random_int = Random . State . int ( Domain . DLS . get random_state ) |
type block = int array ; ; |
type objdata = | Present of block | Absent of int ; ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.