text
stringlengths
12
786k
let cpu_compute xc yc zc ( ) = let sum = ref { re = 0 . ; im = 0 . } in for row = 0 to n - 1 do for col = 0 to n - 1 do sum := { re = 0 . ; im = 0 . } ; for i = 0 to n - 1 do let l = { xre = xc . ( row * n + i ) . re ; xim = xc . ( row * n + i ) . im ; yre = yc . ( i * n + col ) . re ; yim = yc . ( i * n + col ) . im ; } in sum := { re = ! sum . re . + ( l . xre . * l . yre . - l . xim . * l . yim ) ; im = ! sum . im . + ( l . xim . * l . yre . + l . xre . * l . yim ) } done ; zc . ( row * n + col ) <- ! sum done done
let _ = let devs = Devices . init ( ) in let dev = devs . ( devid ) in let block_size = 4 in Printf . printf " Dev is % s \ n " devs . ( devid ) . Devices . general_info . Devices . name ; let x = Vector . create ( Vector . Custom customComplex ) ( n * n ) and y = Vector . create ( Vector . Custom customComplex ) ( n * n ) and z = Vector . create ( Vector . Custom customComplex ) ( n * n ) and xc = Array . create ( n * n ) { re = 0 . ; im = 0 . } and yc = Array . create ( n * n ) { re = 0 . ; im = 0 . } and zc = Array . create ( n * n ) { re = 0 . ; im = 0 . } and blocsA = Array . init block_size ( fun x -> Array . init block_size ( fun _ -> Vector . create ( Vector . Custom customComplex ) ( n / block_size * n / block_size ) ) ) and blocsB = Array . init block_size ( fun x -> Array . init block_size ( fun _ -> Vector . create ( Vector . Custom customComplex ) ( n / block_size * n / block_size ) ) ) and blocsC = Array . init block_size ( fun x -> Array . init block_size ( fun _ -> Vector . create ( Vector . Custom customComplex ) ( n / block_size * n / block_size ) ) ) in for i = 0 to n * n - 1 do let a = { re = ( Random . float 3 . ) . * 5 . ; im = ( Random . float 3 . ) . * 5 . } and b = { re = ( Random . float 3 . ) . * 5 . ; im = ( Random . float 3 . ) . * 5 . } in Mem . set x i a ; Mem . set y i b ; xc . ( i ) <- a ; yc . ( i ) <- b ; done ; for i = 0 to block_size - 1 do for j = 0 to block_size - 1 do for n = 0 to n / block_size * n / block_size - 1 do let a = { re = ( Random . float 3 . ) . * 5 . ; im = ( Random . float 3 . ) . * 5 . } and b = { re = ( Random . float 3 . ) . * 5 . ; im = ( Random . float 3 . ) . * 5 . } in Mem . set blocsA . ( i ) . ( j ) n a ; Mem . set blocsB . ( i ) . ( j ) n b ; done ; done ; done ; let threadsPerBlock dev = match dev . Devices . specific_info with | Devices . OpenCLInfo clI -> ( match clI . Devices . device_type with | Devices . CL_DEVICE_TYPE_CPU -> 1 | _ -> 16 ) | _ -> 16 in let blocksPerGrid dev = ( n + ( threadsPerBlock dev ) - 1 ) / ( threadsPerBlock dev ) in let block dev = { Spoc . Kernel . blockX = threadsPerBlock dev ; Spoc . Kernel . blockY = threadsPerBlock dev ; Spoc . Kernel . blockZ = 1 ; } in let grid dev = { Spoc . Kernel . gridX = blocksPerGrid dev ; Spoc . Kernel . gridY = blocksPerGrid dev ; Spoc . Kernel . gridZ = 1 ; } in Kirc . gen matmult_complex ; let name = dev . Spoc . Devices . general_info . Spoc . Devices . name in measure_time ( fun ( ) -> Kirc . run matmult_complex ( x , y , z , n ) ( block dev , grid dev ) 0 dev ; Mem . to_cpu z ( ) ; Devices . flush dev ( ) ; ) ( " GPU " ^ name ) ; let blocksPerGrid dev = ( n / block_size + ( threadsPerBlock dev ) - 1 ) / ( threadsPerBlock dev ) in let block dev = { Spoc . Kernel . blockX = threadsPerBlock dev ; Spoc . Kernel . blockY = threadsPerBlock dev ; Spoc . Kernel . blockZ = 1 ; } in let grid dev = { Spoc . Kernel . gridX = blocksPerGrid dev ; Spoc . Kernel . gridY = blocksPerGrid dev ; Spoc . Kernel . gridZ = 1 ; } in let tasks = ref [ ] in let taskM = Mutex . create ( ) in let multicompute ( ) = for i = 0 to block_size - 1 do for j = 0 to block_size - 1 do tasks := ( fun ( block , grid ) -> for k = 0 to block_size - 1 do Kirc . run matmult_complex ( Mem . sub_vector blocsA . ( i ) . ( k ) 0 ( n * n / block_size / block_size ) , Mem . sub_vector blocsB . ( k ) . ( j ) 0 ( n * n / block_size / block_size ) , blocsC . ( i ) . ( j ) , ( n / block_size ) ) ( block , grid ) 0 dev ; done ; ) :: ! tasks done ; done ; in let rec worker i dev = Mutex . lock taskM ; match ! tasks with | t :: q -> tasks := q ; Mutex . unlock taskM ; t ( block dev , grid dev ) ; Devices . flush dev ( ) ; worker ( i + 1 ) dev | [ ] -> Mutex . unlock taskM in multicompute ( ) ; measure_time ( fun ( ) -> let t1 = Thread . create ( fun ( ) -> worker 0 devs . ( 0 ) ) ( ) in Thread . join t1 ; ) " 1 x 680 " ; for i = 0 to block_size - 1 do for j = 0 to block_size - 1 do for n = 0 to n / block_size * n / block_size - 1 do let a = { re = ( Random . float 3 . ) . * 5 . ; im = ( Random . float 3 . ) . * 5 . } and b = { re = ( Random . float 3 . ) . * 5 . ; im = ( Random . float 3 . ) . * 5 . } in Mem . set blocsA . ( i ) . ( j ) n a ; Mem . set blocsB . ( i ) . ( j ) n b ; done ; done ; done ; multicompute ( ) ; measure_time ( fun ( ) -> let t1 = Thread . create ( fun ( ) -> worker 0 devs . ( 0 ) ) ( ) and t2 = Thread . create ( fun ( ) -> worker 0 devs . ( 1 ) ) ( ) in Thread . join t1 ; Thread . join t2 ; ) " 2x 680 " ; for i = 0 to block_size - 1 do for j = 0 to block_size - 1 do for n = 0 to n / block_size * n / block_size - 1 do let a = { re = ( Random . float 3 . ) . * 5 . ; im = ( Random . float 3 . ) . * 5 . } and b = { re = ( Random . float 3 . ) . * 5 . ; im = ( Random . float 3 . ) . * 5 . } in Mem . set blocsA . ( i ) . ( j ) n a ; Mem . set blocsB . ( i ) . ( j ) n b ; done ; done ; done ; multicompute ( ) ; measure_time ( fun ( ) -> let t1 = Thread . create ( fun ( ) -> worker 0 devs . ( 0 ) ) ( ) and t2 = Thread . create ( fun ( ) -> worker 0 devs . ( 1 ) ) ( ) and t3 = Thread . create ( fun ( ) -> worker 0 devs . ( 2 ) ) ( ) in Thread . join t1 ; Thread . join t2 ; Thread . join t3 ; ) " 2x 680 + i7 " ; measure_time ( cpu_compute xc yc zc ) " CPU "
let input_bigstring ic buf off len = let tmp = Bytes . create len in let res = input ic tmp 0 len in Bigstringaf . blit_from_bytes tmp ~ src_off : 0 buf ~ dst_off : off ~ len : res ; res
let output_bigstring oc buf off len = let res = Bigstringaf . substring buf ~ off ~ len in output_string oc res
module N : sig type encoder type dst = [ ` Channel of out_channel | ` Buffer of Buffer . t | ` Manual ] type ret = [ ` Flush of encoder | ` End ] val dst_rem : encoder -> int val dst : encoder -> Zl . bigstring -> int -> int -> encoder val encode : encoder -> ret val encoder : i : Zl . bigstring -> q : De . Queue . t -> w : De . Lz77 . window -> source : int -> H . bigstring -> dst -> Duff . hunk list -> encoder type dst = [ ` Channel of out_channel | ` Buffer of Buffer . t | ` Manual ] type encoder = { dst : dst ; src : Bigstringaf . t ; o : H . bigstring ; o_pos : int ; o_max : int ; h : H . N . encoder ; z : Zl . Def . encoder ; t : Zl . bigstring ; d : [ ` Copy of int * int | ` Insert of string | ` End | ` Await ] list ; } type ret = [ ` Flush of encoder | ` End ] let flush k e = match e . dst with | ` Manual -> ` Flush e | ` Channel oc -> output_bigstring oc e . o 0 e . o_pos ; k { e with o_pos = 0 } | ` Buffer b -> for i = 0 to e . o_pos - 1 do Buffer . add_char b ( Bigstringaf . get e . o i ) done ; k { e with o_pos = 0 } let rec encode_z e = match Zl . Def . encode e . z with | ` End z -> let len = Bigstringaf . length e . o - Zl . Def . dst_rem z in let z = Zl . Def . dst z De . bigstring_empty 0 0 in if len > 0 then flush encode_z { e with z ; o_pos = len } else ` End | ` Flush z -> let len = Bigstringaf . length e . o - Zl . Def . dst_rem z in flush encode_z { e with z ; o_pos = len } | ` Await z -> ( match e . d with | [ ] -> let z = Zl . Def . src z De . bigstring_empty 0 0 in encode_z { e with z } | d -> H . N . dst e . h e . t 0 ( De . bigstring_length e . t ) ; encode_h e d ) and encode_h e d = let v , d = match d with v :: d -> v , d | [ ] -> ` End , [ ] in match H . N . encode e . h v , d with | ` Ok , [ ] -> let len = Bigstringaf . length e . t - H . N . dst_rem e . h in let z = Zl . Def . src e . z e . t 0 len in encode_z { e with d ; z } | ` Ok , d -> encode_h { e with d } d | ` Partial , d -> let len = Bigstringaf . length e . t - H . N . dst_rem e . h in let z = Zl . Def . src e . z e . t 0 len in encode_z { e with d = ` Await :: d ; z } let encode e = encode_z e let encoder ~ i ~ q ~ w ~ source src dst hunks = let o , o_pos , o_max = match dst with | ` Manual -> De . bigstring_empty , 1 , 0 | ` Buffer _ | ` Channel _ -> De . bigstring_create H . io_buffer_size , 0 , H . io_buffer_size - 1 in let z = Zl . Def . encoder ` Manual ` Manual ~ q ~ w ~ level : 0 in let z = Zl . Def . dst z De . bigstring_empty 0 0 in { dst ; src ; o ; o_pos ; o_max ; t = i ; d = List . map ( function | Duff . Copy ( off , len ) -> ` Copy ( off , len ) | Duff . Insert ( off , len ) -> ` Insert ( Bigstringaf . substring src ~ off ~ len ) ) hunks ; z ; h = H . N . encoder ` Manual ~ dst_len ( : Bigstringaf . length src ) ~ src_len : source ; } let dst_rem e = e . o_max - e . o_pos + 1 let dst e s j l = let z = Zl . Def . dst e . z s j l in { e with z ; o = s ; o_pos = j ; o_max = j + l - 1 } end
module M : sig type decoder type src = [ ` Channel of in_channel | ` String of string | ` Manual ] type decode = [ ` Await of decoder | ` Header of int * int * decoder | ` End of decoder | ` Malformed of string ] val src_len : decoder -> int val dst_len : decoder -> int val src_rem : decoder -> int val dst_rem : decoder -> int val src : decoder -> Zl . bigstring -> int -> int -> decoder val dst : decoder -> H . bigstring -> int -> int -> decoder val source : decoder -> H . bigstring -> decoder val decode : decoder -> decode val decoder : ? source : H . bigstring -> o : Zl . bigstring -> allocate ( : int -> Zl . window ) -> src -> decoder type src = [ ` Channel of in_channel | ` String of string | ` Manual ] type decoder = { src : src ; dst : H . bigstring ; dst_len : int ; src_len : int ; i : Zl . bigstring ; i_pos : int ; i_len : int ; o : Zl . bigstring ; z : Zl . Inf . decoder ; h : H . M . decoder ; k : decoder -> decode ; } and decode = [ ` Await of decoder | ` Header of int * int * decoder | ` End of decoder | ` Malformed of string ] let refill k d = match d . src with | ` String _ -> let z = Zl . Inf . src d . z De . bigstring_empty 0 0 in k { d with z } | ` Channel ic -> let res = input_bigstring ic d . i 0 ( De . bigstring_length d . i ) in let z = Zl . Inf . src d . z d . i 0 res in k { d with z } | ` Manual -> ` Await { d with k } let rec decode d = match H . M . decode d . h with | ` Header ( src_len , dst_len ) -> ` Header ( src_len , dst_len , { d with src_len ; dst_len ; k = decode } ) | ` End -> ` End { d with k = decode } | ` Malformed err -> ` Malformed err | ` Await -> inflate { d with z = Zl . Inf . flush d . z } and inflate d = match Zl . Inf . decode d . z with | ` Await z -> let dst_len = De . bigstring_length d . o - Zl . Inf . dst_rem z in H . M . src d . h d . o 0 dst_len ; refill inflate { d with z } | ` End z -> let dst_len = De . bigstring_length d . o - Zl . Inf . dst_rem z in H . M . src d . h d . o 0 dst_len ; decode { d with z } | ` Flush z -> let dst_len = De . bigstring_length d . o - Zl . Inf . dst_rem z in H . M . src d . h d . o 0 dst_len ; decode { d with z } | ` Malformed err -> ` Malformed err let src d s j l = let z = Zl . Inf . src d . z s j l in { d with z } let dst d s j l = H . M . dst d . h s j l ; d let source d src = H . M . source d . h src ; d let dst_len d = let dst_len = H . M . dst_len d . h in assert ( d . dst_len = dst_len ) ; dst_len let src_len d = let src_len = H . M . src_len d . h in assert ( d . src_len = src_len ) ; src_len let dst_rem d = H . M . dst_rem d . h let src_rem d = Zl . Inf . src_rem d . z let decoder ? source ~ o ~ allocate src = let decoder_z = Zl . Inf . decoder ` Manual ~ o ~ allocate in let decoder_h = H . M . decoder ` Manual ? source in let i , i_pos , i_len = match src with | ` Manual -> De . bigstring_empty , 1 , 0 | ` String x -> ( Bigstringaf . of_string x ~ off : 0 ~ len ( : String . length x ) , 0 , String . length x - 1 ) | ` Channel _ -> Bigstringaf . create De . io_buffer_size , 1 , 0 in { src ; dst = De . bigstring_empty ; dst_len = 0 ; src_len = 0 ; i ; i_pos ; i_len ; o ; z = decoder_z ; h = decoder_h ; k = decode ; } let decode d = d . k d end
type chIP_sample = [ | ` ChIP_Pho4_noPi | ` ChIP_Pho4_highPi | ` ChIP_Cbf1_noPi | ` ChIP_Mock_noPi ]
type input_sample = [ | ` Input_Pho4_noPi | ` Input_Pho4_highPi | ` Input_Cbf1_noPi | ` Input_Mock_noPi ]
type sample = [ | chIP_sample | input_sample ]
type factor = [ | ` Pho4 | ` Cbf1 | ` Mock ]
type condition = [ | ` noPi | ` highPi ]
let factor = function | ` ChIP_Pho4_highPi | ` ChIP_Pho4_noPi -> ` Pho4 | ` ChIP_Cbf1_highPi | ` ChIP_Cbf1_noPi -> ` Cbf1 | ` ChIP_Mock_highPi | ` ChIP_Mock_noPi -> ` Mock
let condition = function | ` ChIP_Mock_highPi | ` ChIP_Pho4_highPi | ` ChIP_Cbf1_highPi -> ` highPi | ` ChIP_Pho4_noPi | ` ChIP_Cbf1_noPi | ` ChIP_Mock_noPi -> ` noPi
let control_sample = function | ` ChIP_Cbf1_noPi -> ` Input_Cbf1_noPi | ` ChIP_Pho4_noPi -> ` Input_Pho4_noPi | ` ChIP_Pho4_highPi -> ` Input_Pho4_highPi | ` ChIP_Mock_noPi -> ` Input_Mock_noPi
let genome = Ucsc_gb . genome_sequence ` sacCer2
let genome_2bit = Ucsc_gb . genome_2bit_sequence ` sacCer2
let srr_id = function | ` ChIP_Pho4_noPi -> [ " SRR217304 " ; " SRR217305 " ] | ` ChIP_Pho4_highPi -> [ " SRR217306 " ] | ` ChIP_Cbf1_noPi -> [ " SRR217310 " ] | ` ChIP_Mock_noPi -> [ " SRR217312 " ] | ` Input_WT_noPi -> [ " SRR217324 " ] | ` Input_Pho4_noPi -> [ " SRR217319 " ] | ` Input_Pho4_highPi -> [ " SRR217320 " ] | ` Input_Cbf1_noPi -> [ " SRR217323 " ] | ` Input_Mock_noPi -> [ " SRR217324 " ]
let fastq x = srr_id x |> List1 . of_list_exn |> List1 . map ~ f ( : fun id -> Sra_toolkit . ( fastq_dump fastq_gz ) ( ` id id ) |> Fastq_sample . compressed_se )
let ecoli_genome : fasta file = Bistro_unix . wget " ftp :// ftp . ncbi . nlm . nih . gov / genomes / all / GCF / 000 / 005 / 845 / GCF_000005845 . 2_ASM584v2 / GCF_000005845 . 2_ASM584v2_genomic . fna . gz " |> Bistro_unix . gunzip
let fastq_screen x = Fastq_screen . fastq_screen ( List1 . hd ( fastq x ) ) [ " E_coli " , ecoli_genome ]
let bowtie_index = Bowtie . bowtie_build genome
let mapped_reads x = let Cons ( fq , additional_samples ) = fastq x in Bowtie . bowtie ~ v : 1 bowtie_index ~ additional_samples fq
let mapped_reads_bam x = Samtools . indexed_bam_of_sam ( mapped_reads x )
let tf_peaks ? qvalue treatment_sample = let control_sample = control_sample treatment_sample in let treatment = mapped_reads treatment_sample in let control = mapped_reads control_sample in Macs2 . callpeak ~ mfold ( : 1 , 100 ) ? qvalue Macs2 . sam ~ control [ : control ] [ treatment ]
let centered_tf_peaks ? qvalue ~ radius treatment_sample = let summits = Macs2 . peak_summits ( tf_peaks ? qvalue treatment_sample ) in let chrom_sizes = Ucsc_gb . fetchChromSizes ` sacCer2 in Bedtools . ( slop ~ mode ( ` : both radius ) bed summits chrom_sizes )
let best_macs_summits ? qvalue ~ n sample = let summits = Macs2 . peak_summits ( tf_peaks ? qvalue sample ) in let open Bistro . Shell_dsl in Bistro . Workflow . shell ~ descr " : best_macs_summits " [ pipe [ cmd " sort " [ string " - r - g - k 5 " ; dep summits ; ] ; cmd " head " ~ stdout : dest [ opt " - n " int n ; ] ] ]
let best_peak_sequences ( ? nseqs = Int . max_value ) ? qvalue ~ radius treatment_sample = let summits = best_macs_summits ? qvalue ~ n : nseqs treatment_sample in let chrom_sizes = Ucsc_gb . fetchChromSizes ` sacCer2 in let regions = Bedtools . ( slop ~ mode ( ` : both radius ) bed summits chrom_sizes ) in Ucsc_gb . twoBitToFa genome_2bit ( Bed . keep4 regions )
let meme ( ? nseqs = 500 ) treatment_sample = best_peak_sequences ~ nseqs ~ qvalue : 1e - 10 ~ radius : 50 treatment_sample |> Meme_suite . meme ~ nmotifs : 3 ~ minw : 5 ~ maxw : 8 ~ revcomp : true ~ alphabet ` : dna ~ maxsize : 1_000_000
let meme_motifs treatment_sample = Bistro . Workflow . select ( meme treatment_sample ) [ " meme . txt " ]
let meme_chip treatment_sample = best_peak_sequences ~ qvalue : 1e - 10 ~ radius : 50 treatment_sample |> Meme_suite . meme_chip ~ meme_nmotifs : 3 ~ meme_minw : 5 ~ meme_maxw : 8
let chipqc = let samples = List . map all_of_chIP_sample ~ f ( : fun x -> { ChIPQC . id = show_chIP_sample x ; tissue = " yeast " ; factor = show_factor ( factor x ) ; replicate = " 1 " ; bam = mapped_reads_bam x ; peaks = Macs2 . narrow_peaks ( tf_peaks x ) ; } ) in ChIPQC . run samples
let occdist_vs_peak_score treatment_sample : svg file = let open Bistro . Shell_dsl in let peaks = centered_tf_peaks ~ radius : 500 treatment_sample in let sequences = Ucsc_gb . twoBitToFa genome_2bit ( Bed . keep4 peaks ) in let occ = dep @@ Meme_suite . fimo ( meme_motifs treatment_sample ) sequences in let peaks = dep peaks in let script = [ % script { | closest_occ <- sapply ( peaks $ id , function ( p ) { o <- occ [ occ $ X . pattern . name == m & occ $ sequence . name == as . character ( p ) , ] pos <- c ( 1000 , ( o $ start + o $ start + 1 ) / 2 ) pos [ which . min ( abs ( pos - 500 ) ) ] } ) plot ( peaks $ score , closest_occ , main = sprintf ( " motif % d " , m ) , xlab " = Peak score " , ylab " = Closest occ " ) close_occ <- abs ( closest_occ - 500 ) < 100 print ( summary ( close_occ ) ) df <- data . frame ( score = peaks $ score , close_occ = close_occ ) g <- glm ( close_occ ~ score , df , family " = binomial " ) plot ( peaks $ score , close_occ , xlab " = Peak score " , ylab " = Close occ prob " ) lines ( peaks $ score , predict ( g , type " = resp " ) ) } dev . off ( ) } ] | in Bistro . Workflow . shell ~ descr " : occdist_vs_peak_rank " [ cmd " Rscript " [ file_dump script ] ]
let report = [ % include_script " lib / bio / examples / zhou2011 . md " ] |> Report . Md . to_html
let repo = Repo . [ item [ " report . html " ] report ; ]
let run ( ) = Repo . build_main ~ np ~ mem ( ` : GB 4 ) ~ outdir " : res " ~ loggers [ : Console_logger . create ( ) ] repo
module Dataset = struct type t = [ ` SongD1 ] let to_string = function | ` SongD1 -> " SongD1 " let alignments d = Bistro_unix . wget " https :// ndownloader . figshare . com / files / 9473962 " |> Bistro_unix . tar_xfj |> Fn . flip Workflow . select [ " single - gene_alignments " ; to_string d ] |> Workflow . glob ~ pattern " " :* let best_trees d = Bistro_unix . wget " https :// ndownloader . figshare . com / files / 9473953 " |> Bistro_unix . tar_xfj |> Fn . flip Workflow . select [ " single - gene_trees " ; to_string d ; " Best_observed " ] |> Workflow . glob ~ pattern " " :* end
module Raxml = struct let img = [ docker_image ~ account " : pveber " ~ name " : raxml " ~ tag " : 8 . 2 . 9 " ( ) ] let hpc alignment = Workflow . shell ~ descr " : raxmlhpc " ~ np : 4 [ within_container img ( and_list [ cd tmp ; cmd " raxmlHPC " [ opt " - T " ident np ; string " - p 1 - m GTRGAMMA -- no - bfgs " ; opt " - s " dep alignment ; string " - n NAME " ; ] ; ] ) ; mv ( tmp // " RAxML_bestTree . NAME " ) dest ; ] end
module Fasttree = struct let img = [ docker_image ~ account " : pveber " ~ name " : fasttree " ~ tag " : 2 . 1 . 10 " ( ) ] let fasttree fa = Workflow . shell ~ descr " : fasttree " [ cmd ~ img " / usr / local / bin / FastTree " ~ stdout : dest [ string " - nt - gtr - gamma - spr 4 - mlacc 2 - slownni " ; dep fa ; ] ] end
module IQTree = struct let img = [ docker_image ~ account " : pveber " ~ name " : iqtree " ~ tag " : 1 . 4 . 2 " ( ) ] let iqtree fa = let tmp_ali_fn = " data . fa " in let tmp_ali = tmp // tmp_ali_fn in Workflow . shell ~ descr " : iqtree " [ within_container img ( and_list [ cmd " ln " [ string " - s " ; dep fa ; tmp_ali ] ; cmd " / usr / local / bin / iqtree " [ string " - m GTR + G4 " ; opt " - s " ident tmp_ali ; string " - seed 1 " ; opt " - nt " ident np ; ] ; mv ( tmp // ( tmp_ali_fn ^ " . treefile " ) ) dest ; ] ) ] end
module PhyML = struct let img = [ docker_image ~ account " : pveber " ~ name " : phyml " ~ tag " : 3 . 3 . 20180129 " ( ) ] let phyml alignment = let tmp_ali_fn = " alignment " in let tmp_ali = tmp // tmp_ali_fn in Workflow . shell ~ descr " : phyml " [ within_container img ( and_list [ cd tmp ; cmd " ln " [ string " - s " ; dep alignment ; tmp_ali ] ; cmd " / usr / local / bin / phyml " [ opt " - i " ident tmp_ali ; string " -- r_seed 1 - d nt - b 0 - m GTR - f e - c 4 - a e - s SPR -- n_rand_starts 1 - o tlr - p -- run_id ID " ; ] ; mv ( tmp // ( tmp_ali_fn ^ " * _phyml_tree_ID . txt " ) ) dest ; ] ) ] end
module Goalign = struct let img = [ docker_image ~ account " : pveber " ~ name " : goalign " ~ tag " : 0 . 2 . 9 " ( ) ] let phylip_of_fasta fa = Workflow . shell ~ descr " : goalign . reformat " [ cmd " goalign " ~ img [ string " reformat phylip " ; opt " - i " dep fa ; opt " - o " ident dest ; ] ] end
module Gotree = struct let img = [ docker_image ~ account " : pveber " ~ name " : gotree " ~ tag " : 0 . 2 . 10 " ( ) ] let compare_trees ~ input ~ reference = Workflow . shell ~ descr " : gotree . compare " [ cmd " / usr / local / bin / gotree " ~ stdout : dest ~ img [ string " compare trees -- binary " ; opt " - i " dep input ; opt " - c " dep reference ; ] ] end
let tree_inference meth fa = match meth with | ` Fasttree -> Fasttree . fasttree fa | ` RAXML -> Raxml . hpc fa | ` IQTree -> IQTree . iqtree fa | ` PhyML -> PhyML . phyml ( Goalign . phylip_of_fasta fa )
let inferred_trees d meth = Workflow . spawn ( Dataset . alignments d ) ~ f ( : tree_inference meth )
let comparisons d meth = Workflow . spawn2 ( inferred_trees d meth ) ( Dataset . best_trees d ) ~ f ( : fun input reference -> Gotree . compare_trees ~ input ~ reference ) List . map [ % eval Workflow . ( spawn results ~ f : eval_path ) ] ~ f ( : fun fn -> In_channel . read_lines fn |> Fn . flip List . nth_exn 1 ) |> Out_channel . write_lines [ % dest ]
let repo = Repo . [ item [ " concatenated_comps_fasttree " ] ( concat ( comparisons ` SongD1 ` Fasttree ) ) ; items [ " comps_fasttree " ] ~ prefix " : tree " ( comparisons ` SongD1 ` Fasttree ) ; ]
let ( ) = Repo . build_main ~ loggers [ : Console_logger . create ( ) ] ~ np : 4 ~ mem ( ` : GB 4 ) ~ outdir " : res " repo
type t = { num : int ; source : string ; } { arrnm : string ; index : t ; }
let compare id1 id2 = compare id1 . num id2 . num
let name id = id . source ^ " _ " ^ ( string_of_int id . num )
let source id = id . source
let num = ref 0
let fresh s = num := ! num + 1 ; { num = ! num ; source = s }
let fprint_t ff id = Format . fprintf ff " % s " ( name id )
module M = struct type t = t_alias let compare = compare let fprint = fprint_t end
module Env = struct include ( Map . Make ( M ) ) let singleton i tentry = add i tentry empty let fprint_t fprint_v ff s = Format . fprintf ff " [ @< hov { >@ " ; iter ( fun k v -> Format . fprintf ff " [ @% a : % a ] " @ M . fprint k fprint_v v ) s ; Format . fprintf ff " } ] " @ let fprint_3ident ff s = let fprint_v ff ( id1 , id2 , id3 ) = Format . fprintf ff " [ @% a ] " @ ( Pp_tools . print_list_r M . fprint " ( " " , " " ) " ) [ id1 ; id2 ; id3 ] in fprint_t fprint_v ff s let append env0 env = fold ( fun x v acc -> update x ( function _ -> Some ( v ) ) acc ) env0 env end
module S = struct include ( Set . Make ( M ) ) let fprint_t ff s = Format . fprintf ff " [ @< hov { >@ " ; iter ( fun e -> Format . fprintf ff " % a @ " M . fprint e ) s ; Format . fprintf ff " } ] " @ let fresh s ss = let add_fresh id m = Env . add id ( fresh s ) m in fold add_fresh ss Env . empty let domain acc env = Env . fold ( fun k _ set -> add k set ) env acc let range acc env = Env . fold ( fun _ v set -> add v set ) env acc let map f s = fold ( fun e rs -> add ( f e ) rs ) s empty end
let bpw = dbits / 8
let asft = Int . ceil_log2 bpw
let reg_spec = Reg_spec . create ( ) ~ clock ~ clear
module Memory = struct module I = struct type ' a t = { memory_data_in : ' a [ @ bits dbits ] ; memory_ready : ' a } [ @@ deriving sexp_of , hardcaml ] end module O = struct type ' a t = { memory_request : ' a ; memory_read_write : ' a ; memory_address : ' a [ @ bits dbits ] ; memory_data_out : ' a [ @ bits dbits ] } [ @@ deriving sexp_of , hardcaml ] end end
let memory_if ~ e ~ stack_o ~ bc_o ~ mem_o ~ ext_i = let open Memory . I in let open Memory . O in let open Always in let ( -- ) s n = s -- ( " memory_if_ " ^ n ) in let module States = struct type t = | Request | Ready [ @@ deriving enumerate , compare , sexp_of ] end in let { State_machine . is ; switch = sm ; set_next = next ; _ } = State_machine . create ( module States ) ~ enable : e reg_spec in let m = [ stack_o ; bc_o ; mem_o ] in let req = concat_lsb ( List . map m ~ f ( : fun ( x : Always . Variable . t Memory . O . t ) -> x . memory_request . value ) ) in let gnt = let e = e &: is Request -- " arbiter_en " in let prefix f l = List . fold l ~ init [ ] : ~ f ( : fun acc x -> match acc with | [ ] -> [ x ] | h :: t -> f x h :: h :: t ) |> List . rev in Arbiter . arbiter ~ prefix ~ enable : e ~ req in let gntb = onehot_to_binary gnt in let sel f = mux gntb ( List . map m ~ f ) in let ext_o = { memory_data_out = sel ( fun x -> x . memory_data_out . value ) ; memory_read_write = sel ( fun x -> x . memory_read_write . value ) ; memory_address = sel ( fun x -> x . memory_address . value ) ; memory_request = sel ( fun x -> x . memory_request . value ) } in Always . ( compile [ sm [ Request , [ when_ ( req . <>: 0 ) [ next Ready ] ] ; Ready , [ when_ ext_i . memory_ready [ next Request ] ] ] ] ) ; let stack_i , bc_i , mem_i = let mk i = { memory_data_in = ext_i . memory_data_in ; memory_ready = bit gnt i &: ext_i . memory_ready } in mk 0 , mk 1 , mk 2 in ext_o , stack_i , bc_i , mem_i ; ;
module Decode = struct type ' a t = { acc : ' a ; acc_op : ' a ; push : ' a ; pushacc : ' a ; push_op : ' a ; pop : ' a ; assign : ' a ; envacc : ' a ; envacc_op : ' a ; pushenvacc : ' a ; pushenvacc_op : ' a ; push_retaddr : ' a ; apply : ' a ; apply_op : ' a ; appterm : ' a ; appterm_op : ' a ; closure : ' a ; closurerec : ' a ; return : ' a ; restart : ' a ; grab : ' a ; offsetclosure : ' a ; offsetclosure_op : ' a ; pushoffsetclosure : ' a ; pushoffsetclosure_op : ' a ; pushgetglobal : ' a ; getglobal : ' a ; pushgetglobalfield : ' a ; getglobalfield : ' a ; setglobal : ' a ; atom : ' a ; atom_op : ' a ; pushatom : ' a ; pushatom_op : ' a ; makeblock : ' a ; makeblock_op : ' a ; getfield : ' a ; getfield_op : ' a ; setfield : ' a ; setfield_op : ' a ; vectlength : ' a ; getvectitem : ' a ; setvectitem : ' a ; getstringchar : ' a ; setstringchar : ' a ; branch : ' a ; branch_op : ' a ; boolnot : ' a ; pushtrap : ' a ; poptrap : ' a ; raise_ : ' a ; check_signals : ' a ; c_call : ' a ; c_call_op : ' a ; const : ' a ; const_op : ' a ; pushconst : ' a ; pushconst_op : ' a ; alu : ' a ; alu_op : ' a ; comp : ' a ; comp_op : ' a ; offsetint : ' a ; offsetref : ' a ; isint : ' a ; getmethod : ' a ; bcomp : ' a ; bcomp_op : ' a ; ucomp : ' a ; ucomp_op : ' a ; bucomp : ' a ; bucomp_op : ' a ; getpubmet : ' a ; getdynmet : ' a ; stop : ' a ; event : ' a ; break : ' a ; reraise : ' a ; raise_notrace : ' a } [ @@ deriving sexp_of , hardcaml ] end
module I = struct type ' a t = { start : ' a ; bytecode_start_address : ' a [ @ bits dbits ] ; atom_table_address : ' a [ @ bits dbits ] ; globals_start_address : ' a [ @ bits dbits ] ; heap_start_address : ' a [ @ bits dbits ] ; stack_start_address : ' a [ @ bits dbits ] ; memory_i : ' a Memory . I . t ; c_call_ready : ' a ; c_call_result : ' a [ @ bits dbits ] } [ @@ deriving sexp_of , hardcaml ] end
module O = struct type ' a t = { state : ' a ; pc : ' a [ @ bits dbits ] ; sp : ' a [ @ bits dbits ] ; accu : ' a [ @ bits dbits ] ; env : ' a [ @ bits dbits ] ; extra_args : ' a [ @ bits dbits ] ; instruction : ' a [ @ bits 8 ] ; error : ' a ; memory_o : ' a Memory . O . t ; decode : ' a Decode . t ; c_call_request : ' a ; c_call_prim : ' a [ @ bits dbits ] } [ @@ deriving sexp_of , hardcaml ] end
type decinstr = { lte : t ; gte : t ; eq : t ; range : t }
let decode instr = let constins i = consti ~ width : 8 ( Opcode . to_int i ) in let ins = Opcode . all in let sel = let sel = Array . of_list @@ List . map ins ~ f ( : fun i -> let i = constins i in { lte = instr <=: i ; gte = instr >=: i ; eq = instr ==: i ; range = instr -: i } ) in fun i -> sel . ( Opcode . to_int i ) in let acc = ( sel ACC ) . lte in let acc_op = ( sel ACC0 ) . range . [ : 3 , 0 ] in let push = ( sel PUSH ) . eq |: ( sel PUSHACC0 ) . eq in let pushacc = ( sel PUSH ) . gte &: ( sel PUSHACC ) . lte in let push_op = ( sel PUSHACC0 ) . range . [ : 3 , 0 ] in let pop = ( sel POP ) . eq in let assign = ( sel ASSIGN ) . eq in let envacc = ( sel ENVACC1 ) . gte &: ( sel ENVACC ) . lte in let envacc_op = ( sel ENVACC1 ) . range . [ : 2 , 0 ] in let pushenvacc = ( sel PUSHENVACC1 ) . gte &: ( sel PUSHENVACC ) . lte in let pushenvacc_op = ( sel PUSHENVACC1 ) . range . [ : 2 , 0 ] in let push_retaddr = ( sel PUSH_RETADDR ) . eq in let apply = ( sel APPLY ) . gte &: ( sel APPLY3 ) . lte in let apply_op = ( sel APPLY ) . range . [ : 1 , 0 ] in let appterm = ( sel APPTERM ) . gte &: ( sel APPTERM3 ) . lte in let appterm_op = ( sel APPTERM ) . range . [ : 1 , 0 ] in let closure = ( sel CLOSURE ) . eq in let closurerec = ( sel CLOSUREREC ) . eq in let return = ( sel RETURN ) . eq in let restart = ( sel RESTART ) . eq in let grab = ( sel GRAB ) . eq in let pushgetglobal = ( sel PUSHGETGLOBAL ) . eq in let getglobal = ( sel GETGLOBAL ) . eq in let pushgetglobalfield = ( sel PUSHGETGLOBALFIELD ) . eq in let getglobalfield = ( sel GETGLOBALFIELD ) . eq in let setglobal = ( sel SETGLOBAL ) . eq in let offsetclosure = ( sel OFFSETCLOSUREM2 ) . gte &: ( sel OFFSETCLOSURE ) . lte in let offsetclosure_op = ( sel OFFSETCLOSUREM2 ) . range . [ : 1 , 0 ] in let pushoffsetclosure = ( sel PUSHOFFSETCLOSUREM2 ) . gte &: ( sel PUSHOFFSETCLOSURE ) . lte in let pushoffsetclosure_op = ( sel PUSHOFFSETCLOSUREM2 ) . range . [ : 1 , 0 ] in let atom = ( sel ATOM0 ) . gte &: ( sel ATOM ) . lte in let atom_op = ( sel ATOM0 ) . range . [ : 0 , 0 ] in let pushatom = ( sel PUSHATOM0 ) . gte &: ( sel PUSHATOM ) . lte in let pushatom_op = ( sel PUSHATOM0 ) . range . [ : 0 , 0 ] in let makeblock = ( sel MAKEBLOCK ) . gte &: ( sel MAKEFLOATBLOCK ) . lte in let makeblock_op = ( sel MAKEBLOCK ) . range . [ : 2 , 0 ] in let getfield = ( sel GETFIELD ) . gte &: ( sel GETFLOATFIELD ) . lte in let getfield_op = ( sel GETFIELD ) . range . [ : 2 , 0 ] in let setfield = ( sel SETFIELD ) . gte &: ( sel SETFLOATFIELD ) . lte in let setfield_op = ( sel SETFIELD ) . range . [ : 2 , 0 ] in let vectlength = ( sel VECTLENGTH ) . eq in let getvectitem = ( sel GETVECTITEM ) . eq in let setvectitem = ( sel SETVECTITEM ) . eq in let getstringchar = ( sel GETSTRINGCHAR ) . eq in let setstringchar = ( sel SETSTRINGCHAR ) . eq in let branch = ( sel BRANCH ) . gte &: ( sel SWITCH ) . lte in let branch_op = ( sel BRANCH ) . range . [ : 1 , 0 ] in let boolnot = ( sel BOOLNOT ) . eq in let pushtrap = ( sel PUSHTRAP ) . eq in let poptrap = ( sel POPTRAP ) . eq in let raise_ = ( sel RAISE ) . eq in let check_signals = ( sel CHECK_SIGNALS ) . eq in let c_call = ( sel C_CALL1 ) . gte &: ( sel C_CALLN ) . lte in let c_call_op = ( sel C_CALL1 ) . range . [ : 2 , 0 ] in let const = ( sel CONST0 ) . gte &: ( sel CONSTINT ) . lte in let const_op = ( sel CONST0 ) . range . [ : 2 , 0 ] in let pushconst = ( sel PUSHCONST0 ) . gte &: ( sel PUSHCONSTINT ) . lte in let pushconst_op = ( sel PUSHCONST0 ) . range . [ : 2 , 0 ] in let alu = ( sel NEGINT ) . gte &: ( sel ASRINT ) . lte in let alu_op = ( sel NEGINT ) . range . [ : 3 , 0 ] in let comp = ( sel EQ ) . gte &: ( sel GEINT ) . lte in let comp_op = ( sel EQ ) . range . [ : 2 , 0 ] in let offsetint = ( sel OFFSETINT ) . eq in let offsetref = ( sel OFFSETREF ) . eq in let isint = ( sel ISINT ) . eq in let getmethod = ( sel GETMETHOD ) . eq in let bcomp = ( sel BEQ ) . gte &: ( sel BGEINT ) . lte in let bcomp_op = ( sel BGEINT ) . range . [ : 2 , 0 ] in let ucomp = ( sel ULTINT ) . gte &: ( sel UGEINT ) . lte in let ucomp_op = ( sel ULTINT ) . range . [ : 0 , 0 ] in let bucomp = ( sel BULTINT ) . gte &: ( sel BUGEINT ) . lte in let bucomp_op = ( sel BULTINT ) . range . [ : 0 , 0 ] in let getpubmet = ( sel GETPUBMET ) . eq in let getdynmet = ( sel GETDYNMET ) . eq in let stop = ( sel STOP ) . eq in let event = ( sel EVENT ) . eq in let break = ( sel BREAK ) . eq in let reraise = ( sel RERAISE ) . eq in let raise_notrace = ( sel RAISE_NOTRACE ) . eq in Decode . { acc ; acc_op ; push ; pushacc ; push_op ; pop ; assign ; envacc ; envacc_op ; pushenvacc ; pushenvacc_op ; push_retaddr ; apply ; apply_op ; appterm ; appterm_op ; closure ; closurerec ; return ; restart ; grab ; offsetclosure ; offsetclosure_op ; pushoffsetclosure ; pushoffsetclosure_op ; pushgetglobal ; getglobal ; pushgetglobalfield ; getglobalfield ; setglobal ; atom ; atom_op ; pushatom ; pushatom_op ; makeblock ; makeblock_op ; getfield ; getfield_op ; setfield ; setfield_op ; vectlength ; getvectitem ; setvectitem ; getstringchar ; setstringchar ; branch ; branch_op ; boolnot ; pushtrap ; poptrap ; raise_ ; check_signals ; c_call ; c_call_op ; const ; const_op ; pushconst ; pushconst_op ; alu ; alu_op ; comp ; comp_op ; offsetref ; isint ; getmethod ; offsetint ; bcomp ; bcomp_op ; ucomp ; ucomp_op ; bucomp ; bucomp_op ; getpubmet ; getdynmet ; stop ; event ; break ; reraise ; raise_notrace } ; ;
let alu_int op a b = let a , b , z = msbs a , msbs b , zero ( dbits - 1 ) in mux op [ z ; a +: b ; a -: b ; ( a *+ b ) . [ : dbits - 2 , 0 ] ; z ; z ; a &: b ; a |: b ; a ^: b ; log_shift sll a b . [ : 5 , 0 ] ; log_shift srl a b . [ : 5 , 0 ] ; log_shift sra a b . [ : 5 , 0 ] ] @: vdd ; ;
let comp_int op a b = let a , b = msbs a , msbs b in zero ( dbits - 2 ) @: mux op [ a ==: b ; a <>: b ; a <+ b ; a <=+ b ; a >+ b ; a >=+ b ] @: vdd ; ;
let ucomp_int op a b = let a , b = msbs a , msbs b in zero ( dbits - 2 ) @: mux op [ a <: b ; a >: b ] @: vdd ; ;
module States = struct type t = [ ` init | ` fetch | ` decode | ` acc_set | ` acc_offset | ` pushacc | ` envacc | ` pop | ` constint | ` branch | ` c_call0 | ` c_call1 | ` c_call2 | ` c_call3 | ` alu | ` comp | ` ucomp | ` bcomp | ` bucomp | ` bcomp_setpc | ` closure_nfuncs | ` closure_nvars | ` closure_alloc | ` closure_var_start | ` closure_var_read | ` closure_var_write | ` closure_func_start | ` closure_func_hdr | ` closure_func_pc | ` closure_func_wpc | ` closure_func_stack | ` closure_accu_pc0 | ` closure_accu_pc1 | ` closure_accu_pc2 | ` setglobal | ` getglobal_data | ` getglobal | ` getglobalfield_data | ` getglobalfield | ` makeblock | ` makeblock_alloc | ` makeblock_accu | ` makeblock_read | ` makeblock_write | ` offsetint | ` offsetref0 | ` offsetref1 | ` offsetref2 | ` atom | ` apply_pop_stack | ` apply_push_stack_env | ` apply_push_stack_pc | ` apply_push_stack_args | ` apply_eargs | ` apply | ` appterm0 | ` appterm1 | ` appterm2 | ` appterm3 | ` appterm4 | ` grab | ` push_retaddr0 | ` push_retaddr1 | ` push_retaddr2 | ` push_retaddr3 | ` vectlength | ` getvectitem0 | ` getvectitem1 | ` setvectitem0 | ` setvectitem1 | ` setvectitem2 | ` getstringchar0 | ` getstringchar1 | ` setstringchar0 | ` setstringchar1 | ` setstringchar2 | ` setstringchar3 | ` not_implemented | ` invalid_instruction ] [ @@ deriving sexp_of , compare , enumerate ] end
let state_str = List . map States . all ~ f ( : fun s -> Sexp . to_string_hum ( States . sexp_of_t s ) )
module M = Mlvalues . Make ( struct include Signal let ( /: ) _ _ = failwith " " /: let ( %: ) _ _ = failwith " " %: let const = consti ~ width : dbits let zero = const 0 let one = const 1 let log_shift f a b = if Signal . is_const b then f a ( to_int b ) else log_shift f a b let sll a b = log_shift sll a b . [ : 5 , 0 ] let srl a b = log_shift srl a b . [ : 5 , 0 ] let sra a b = log_shift sra a b . [ : 5 , 0 ] end )
let zinc i = let open Memory . O in let open Memory . I in let open Decode in let open I in let open O in let open Always in let e = vdd in let ures x = uresize x dbits in let sres x = sresize x dbits in let val_int x = uresize x ( dbits - 1 ) @: vdd in let val_unit = val_int ( zero dbits ) in let int_val x = sra x 1 in let stack_o = Memory . O . ( map t ~ f ( : fun ( _ , b ) -> Variable . reg ~ enable : e reg_spec ~ width : b ) ) in let mem_o = Memory . O . ( map t ~ f ( : fun ( _ , b ) -> Variable . reg ~ enable : e reg_spec ~ width : b ) ) in let bc_o = Memory . O . ( map t ~ f ( : fun ( _ , b ) -> Variable . reg ~ enable : e reg_spec ~ width : b ) ) in let memory_o , stack_i , bc_i , mem_i = memory_if ~ e ~ stack_o ~ bc_o ~ mem_o ~ ext_i : i . memory_i in let bc_sel = Variable . reg reg_spec ~ enable : e ~ width : 1 in let bc_i = { bc_i with memory_data_in = sres @@ mux2 bc_sel . value bc_i . memory_data_in . [ : 63 , 32 ] bc_i . memory_data_in . [ : 31 , 0 ] } in let pc = Variable . reg reg_spec ~ enable : e ~ width : dbits in let pc_next = pc . value . +: 4 in let sp = Variable . reg reg_spec ~ enable : e ~ width : dbits in let accu = Variable . reg reg_spec ~ enable : e ~ width : dbits in let env = Variable . reg reg_spec ~ enable : e ~ width : dbits in let extra_args = Variable . reg reg_spec ~ enable : e ~ width : dbits in let error = Variable . reg reg_spec ~ enable : e ~ width : 1 in let state = State_machine . create ( module States ) reg_spec ~ enable : e in let n_temps = 3 in let temp = Array . init n_temps ~ f ( : fun i -> let g = Variable . reg reg_spec ~ enable : e ~ width : dbits in ignore ( g . value -- ( " temp_ " ^ Int . to_string i ) : Signal . t ) ; g ) in let clear_temps = proc ( Array . to_list @@ Array . map temp ~ f ( : fun t -> t . <-- 0 ) ) in let shift_temp_up din = proc ( Array . to_list @@ Array . init n_temps ~ f ( : fun i -> temp . ( i ) <-- if i = 0 then din else temp . ( i - 1 ) . value ) ) in let shift_temp_down din = proc ( Array . to_list @@ Array . init n_temps ~ f ( : fun i -> temp . ( i ) <-- if i = n_temps - 1 then din else temp . ( i + 1 ) . value ) ) in let count = let r = Variable . reg reg_spec ~ enable : e ~ width : dbits in ignore ( r . value -- " count " : Signal . t ) ; r in let count_next = count . value . +: 1 -- " count_next " in let alloc_base = Variable . reg reg_spec ~ enable : e ~ width : dbits in let alloc_pointer = Variable . reg reg_spec ~ enable : e ~ width : dbits in let instruction = bc_i . memory_data_in . [ : 7 , 0 ] in let decode = decode instruction in let decode ' = let e = e &: state . is ` decode in Decode . map decode ~ f ( : reg reg_spec ~ enable : e ) in let c_call_request = Variable . reg reg_spec ~ enable : e ~ width : 1 in let c_call_prim = Variable . reg reg_spec ~ enable : e ~ width : dbits in let access_memif mem_i mem_o = let read addr nstate = proc [ mem_o . memory_address <-- addr ; mem_o . memory_request . <-- 1 ; mem_o . memory_read_write . <-- 0 ; state . set_next nstate ] in let write addr data nstate = proc [ mem_o . memory_address <-- addr ; mem_o . memory_data_out <-- data ; mem_o . memory_request . <-- 1 ; mem_o . memory_read_write . <-- 1 ; state . set_next nstate ] in let ready = let ready = ( ~: mem_o . memory_request . value ) |: mem_i . memory_ready in fun f -> when_ ready [ mem_o . memory_request . <-- 0 ; proc ( f mem_i . memory_data_in ) ] in read , write , ready in let read_bytecode , when_bytecode_ready = let read , _ , ready = access_memif bc_i bc_o in let pcaddr = pc . value . [ : dbits - 1 , asft ] @: zero asft in let pcsel = pc . value . [ : 2 , 2 ] in let read nstate = proc [ bc_sel <-- pcsel ; read pcaddr nstate ; pc <-- pc_next ] in read , ready in let read_mem , write_mem , when_mem_ready = access_memif mem_i mem_o in let alloc_block col tag words rstate = proc [ write_mem alloc_base . value ( M . make_header words col tag ) rstate ; alloc_base <-- alloc_base . value +: sll ( words . +: 1 ) asft ; alloc_pointer <-- alloc_base . value . +: bpw ] in let alloc_pointer_next = alloc_pointer . value . +: bpw in let read_stack , write_stack , when_stack_ready = access_memif stack_i stack_o in let push_stack = let sp_next = sp . value . -: bpw in fun data nstate -> proc [ write_stack sp_next data nstate ; sp <-- sp_next ] in let pop_stack = let sp_next = sp . value . +: bpw in fun nstate -> proc [ read_stack sp . value nstate ; sp <-- sp_next ] in let push_stack_accu = push_stack accu . value in let closure_nfuncs = temp . ( 0 ) in let closure_nvars = temp . ( 1 ) in let closure_base_pc = temp . ( 2 ) in let closure_nfuncs_offs = mux2 decode ' . closure ( one dbits ) ( sll ( closure_nfuncs . value -- " nfuncs " ) 1 . -: 1 ) in let closure_blksize = closure_nfuncs_offs +: closure_nvars . value in let makeblock_wosize = temp . ( 0 ) in let makeblock_accu_base = temp . ( 1 ) in let alu_int = alu_int decode ' . alu_op accu . value stack_i . memory_data_in in let bcomp_int = ( comp_int decode ' . bcomp_op bc_i . memory_data_in accu . value ) . [ : 1 , 1 ] in let bucomp_int = ( ucomp_int decode ' . bucomp_op bc_i . memory_data_in accu . value ) . [ : 1 , 1 ] in let comp_int = comp_int decode ' . comp_op accu . value stack_i . memory_data_in in let ucomp_int = ucomp_int decode ' . ucomp_op accu . value stack_i . memory_data_in in let atom_ptr tag = i . atom_table_address +: sll tag asft in let aofs v = sll ( uresize v dbits ) 3 in let bcofs v = sll ( uresize v dbits ) 2 in let hdrp v = v +: aofs ( consti ~ width : dbits ( - 1 ) ) in let get_byte s d = let f n = d . [ ( : 8 * n ) + 7 , 8 * n ] in mux s @@ Array . to_list @@ Array . init 8 ~ f in let set_byte s d b = let f n = insert ~ into : d b ~ at_offset ( : n * 8 ) in mux s @@ Array . to_list @@ Array . init 8 ~ f in compile [ mem_o . memory_read_write . <-- 0 ; mem_o . memory_data_out . <-- 0 ; mem_o . memory_request . <-- 0 ; mem_o . memory_address . <-- 0 ; bc_o . memory_read_write . <-- 0 ; bc_o . memory_data_out . <-- 0 ; state . switch [ ( ` init , [ accu <-- val_unit ; sp <-- i . stack_start_address ; pc <-- i . bytecode_start_address ; alloc_base <-- i . heap_start_address ; env <-- atom_ptr ( zero dbits ) ; extra_args . <-- 0 ; when_ i . start [ state . set_next ` fetch ] ] ) ; ( ` fetch , [ read_bytecode ` decode ; count . <-- 0 ; clear_temps ] ) ; ( ` decode , [ when_bytecode_ready ( fun _ -> [ if_ ( reduce ~ f ( : |: ) [ decode . return ; decode . restart ; decode . offsetclosure ; decode . pushoffsetclosure ; decode . pushtrap ; decode . poptrap ; decode . raise_ ; decode . check_signals ; decode . getmethod ; decode . getpubmet ; decode . getdynmet ; decode . event ; decode . break ; decode . reraise ; decode . raise_notrace ; decode . alu &: ( decode . alu_op . ==: 4 ) ; decode . alu &: ( decode . alu_op . ==: 5 ) ; decode . c_call &: ( decode . c_call_op . ==: 5 ) ; decode . branch &: ( decode . branch_op . ==: 3 ) ; decode . apply &: ( decode . apply_op . ==: 0 ) ; decode . appterm &: ( decode . appterm_op . ==: 0 ) ; decode . makeblock &: ( decode . makeblock_op . ==: 4 ) ] ) [ state . set_next ` not_implemented ] @@ elif decode . acc [ if_ ( msb decode . acc_op ) [ read_bytecode ` acc_offset ] [ read_stack ( sp . value +: aofs decode . acc_op ) ` acc_set ] ] @@ elif ( decode . pushacc |: decode . pushconst |: decode . pushgetglobal |: decode . pushgetglobalfield |: decode . pushatom |: decode . pushenvacc ) [ push_stack_accu ` pushacc ] @@ elif decode . envacc [ read_mem ( env . value +: aofs ( decode . envacc_op . +: 1 ) ) ` envacc ] @@ elif decode . const [ if_ ( msb decode . const_op ) [ read_bytecode ` constint ] [ accu <-- val_int decode . const_op ; state . set_next ` fetch ] ] @@ elif decode . branch [ read_bytecode ` branch ] @@ elif decode . pop [ read_bytecode ` pop ] @@ elif decode . alu [ if_ ( decode . alu_op . ==: 0 ) [ accu <-- val_int ( negate ( msbs accu . value ) ) ; state . set_next ` fetch ] [ pop_stack ` alu ; when_ ( decode . alu_op . ==: 4 ) [ state . set_next ` invalid_instruction ] ; when_ ( decode . alu_op . ==: 5 ) [ state . set_next ` invalid_instruction ] ] ] @@ elif decode . comp [ pop_stack ` comp ] @@ elif decode . ucomp [ pop_stack ` ucomp ] @@ elif decode . bcomp [ read_bytecode ` bcomp ] @@ elif decode . bucomp [ read_bytecode ` bucomp ] @@ elif decode . offsetint [ read_bytecode ` offsetint ] @@ elif decode . offsetref [ read_bytecode ` offsetref0 ] @@ elif decode . isint [ accu <-- ures accu . value . [ : 0 , 0 ] ; state . set_next ` fetch ] @@ elif decode . closure [ read_bytecode ` closure_nvars ] @@ elif decode . closurerec [ read_bytecode ` closure_nfuncs ] @@ elif decode . setglobal [ read_bytecode ` setglobal ] @@ elif ( decode . getglobal |: decode . getglobalfield ) [ read_bytecode ` getglobal_data ] @@ elif decode . makeblock [ if_ ( decode . makeblock_op . ==: 0 ) [ read_bytecode ` makeblock ] [ makeblock_wosize <-- ures decode . makeblock_op ; read_bytecode ` makeblock_alloc ] ] @@ elif decode . c_call [ push_stack env . value ` c_call0 ] @@ elif decode . atom [ if_ decode . atom_op [ read_bytecode ` atom ] [ state . set_next ` atom ] ] @@ elif decode . apply [ if_ decode . apply_op [ state . set_next ` apply_pop_stack ] [ read_bytecode ` apply_eargs ] ] @@ elif decode . appterm [ if_ decode . appterm_op [ temp . ( 0 ) <-- ures decode . appterm_op ; read_bytecode ` appterm1 ] [ read_bytecode ` appterm0 ] ] @@ elif decode . grab [ read_bytecode ` grab ] @@ elif decode . stop [ state . set_next ` invalid_instruction ] @@ elif decode . push_retaddr [ read_bytecode ` push_retaddr0 ] @@ elif decode . vectlength [ read_mem ( hdrp accu . value ) ` vectlength ] @@ elif decode . getvectitem [ pop_stack ` getvectitem0 ] @@ elif decode . setvectitem [ pop_stack ` setvectitem0 ] @@ elif decode . getstringchar [ pop_stack ` getstringchar0 ] @@ elif decode . setstringchar [ pop_stack ` setstringchar0 ] @@ elif decode . boolnot [ accu <-- val_int ( ~: accu . value . [ : 1 , 1 ] ) ; state . set_next ` fetch ] [ state . set_next ` invalid_instruction ] ] ) ] ) ; ( ` acc_offset , [ when_bytecode_ready ( fun offset -> [ read_stack ( sp . value +: aofs offset ) ` acc_set ] ) ] ) ; ( ` acc_set , [ when_stack_ready ( fun data -> [ accu <-- data ; state . set_next ` fetch ] ) ] ) ; ( ` pushacc , [ when_stack_ready ( fun _ -> [ if_ decode ' . pushconst [ if_ ( msb decode ' . pushconst_op ) [ read_bytecode ` constint ] [ accu <-- val_int decode ' . pushconst_op ; state . set_next ` fetch ] ] @@ elif decode ' . push [ state . set_next ` fetch ] @@ elif decode ' . pushenvacc [ read_mem ( env . value +: aofs ( decode ' . pushenvacc_op . +: 1 ) ) ` envacc ] @@ elif ( decode ' . pushgetglobal |: decode ' . pushgetglobalfield ) [ read_bytecode ` getglobal_data ] @@ elif decode ' . pushatom [ if_ decode ' . pushatom_op [ read_bytecode ` atom ] [ state . set_next ` atom ] ] [ if_ ( msb decode ' . push_op ) [ read_bytecode ` acc_offset ] [ read_stack ( sp . value +: aofs decode ' . push_op ) ` acc_set ] ] ] ) ] ) ; ( ` envacc , [ when_mem_ready ( fun data -> [ accu <-- data ; state . set_next ` fetch ; when_ ( decode ' . envacc &: ( decode ' . envacc_op . ==: 4 ) |: ( decode ' . pushenvacc &: ( decode ' . pushenvacc_op . ==: 4 ) ) ) [ state . set_next ` invalid_instruction ] ] ) ] ) ; ( ` pop , [ when_bytecode_ready ( fun offset -> [ sp <-- sp . value +: aofs offset ; state . set_next ` fetch ] ) ] ) ; ( ` constint , [ when_bytecode_ready ( fun data -> [ accu <-- val_int data ; state . set_next ` fetch ] ) ] ) ; ( ` branch , [ when_bytecode_ready ( fun data -> [ pc <-- pc . value +: bcofs ( data . -: 1 ) ; state . set_next ` fetch ] ) ] ) ; ( ` alu , [ when_stack_ready ( fun _ -> [ accu <-- alu_int ; state . set_next ` fetch ] ) ] ) ; ( ` comp , [ when_stack_ready ( fun _ -> [ accu <-- comp_int ; state . set_next ` fetch ] ) ] ) ; ( ` ucomp , [ when_stack_ready ( fun _ -> [ accu <-- ucomp_int ; state . set_next ` fetch ] ) ] ) ; ( ` bcomp , [ when_bytecode_ready ( fun _ -> [ if_ bcomp_int [ read_bytecode ` bcomp_setpc ] [ pc <-- pc_next ; state . set_next ` fetch ] ] ) ] ) ; ( ` bucomp , [ when_bytecode_ready ( fun _ -> [ if_ bucomp_int [ read_bytecode ` bcomp_setpc ] [ pc <-- pc_next ; state . set_next ` fetch ] ] ) ] ) ; ( ` bcomp_setpc , [ when_bytecode_ready ( fun data -> [ pc <-- pc . value +: bcofs ( data . -: 1 ) ; state . set_next ` fetch ] ) ] ) ; ( ` makeblock , [ when_bytecode_ready ( fun wosize -> [ makeblock_wosize <-- wosize ; read_bytecode ` makeblock_alloc ] ) ] ) ; ( ` makeblock_alloc , [ when_bytecode_ready ( fun tag -> [ alloc_block M . black ( ures tag . [ : 7 , 0 ] ) makeblock_wosize . value ` makeblock_accu ] ) ] ) ; ( ` makeblock_accu , [ when_mem_ready ( fun _ -> [ makeblock_accu_base <-- alloc_pointer . value ; count <-- count_next ; alloc_pointer <-- alloc_pointer_next ; write_mem alloc_pointer . value accu . value ` makeblock_read ] ) ] ) ; ( ` makeblock_read , [ when_mem_ready ( fun _ -> [ if_ ( count . value ==: makeblock_wosize . value ) [ accu <-- makeblock_accu_base . value ; state . set_next ` fetch ] [ pop_stack ` makeblock_write ] ] ) ] ) ; ( ` makeblock_write , [ when_stack_ready ( fun data -> [ count <-- count_next ; alloc_pointer <-- alloc_pointer_next ; write_mem alloc_pointer . value ( mux2 ( count . value . ==: 0 ) accu . value data ) ` makeblock_read ] ) ] ) ; ( ` closure_nfuncs , [ when_bytecode_ready ( fun data -> [ closure_nfuncs <-- data ; read_bytecode ` closure_nvars ] ) ] ) ; ( ` closure_nvars , [ when_bytecode_ready ( fun data -> [ closure_nvars <-- data ; if_ ( data . >: 0 ) [ push_stack_accu ` closure_alloc ] [ state . set_next ` closure_alloc ] ] ) ] ) ; ( ` closure_alloc , [ when_stack_ready ( fun _ -> [ alloc_block M . black M . closure_tag closure_blksize ` closure_var_start ] ) ] ) ; ( ` closure_var_start , [ accu <-- alloc_pointer . value ; when_mem_ready ( fun _ -> [ count . <-- 0 ; if_ ( closure_nvars . value . <>: 0 ) [ state . set_next ` closure_var_read ] @@ elif decode ' . closure [ read_bytecode ` closure_accu_pc1 ] [ state . set_next ` closure_func_start ] ] ) ] ) ; ( ` closure_var_read , [ when_mem_ready ( fun _ -> [ pop_stack ` closure_var_write ] ) ] ) ; ( ` closure_var_write , [ when_stack_ready ( fun data -> let addr = alloc_pointer . value +: aofs ( count . value +: closure_nfuncs_offs ) in [ write_mem addr data ` closure_var_read ; count <-- count_next ; when_ ( count_next ==: closure_nvars . value ) [ if_ decode ' . closure [ state . set_next ` closure_accu_pc0 ] [ state . set_next ` closure_func_start ] ] ] ) ] ) ; ( ` closure_func_start , [ count . <-- 0 ; closure_base_pc <-- pc . value ; when_mem_ready ( fun _ -> [ read_bytecode ` closure_func_wpc ] ) ] ) ; ( ` closure_func_hdr , let data = M . make_header ( sll count . value 1 ) M . white M . infix_tag in [ when_stack_ready ( fun _ -> [ alloc_pointer <-- alloc_pointer_next ; if_ ( count . value ==: closure_nfuncs . value ) [ state . set_next ` fetch ] [ write_mem alloc_pointer . value data ` closure_func_pc ] ] ) ] ) ; ( ` closure_func_pc , [ when_mem_ready ( fun _ -> [ read_bytecode ` closure_func_wpc ] ) ] ) ; ( ` closure_func_wpc , [ when_bytecode_ready ( fun data -> [ alloc_pointer <-- alloc_pointer_next ; write_mem alloc_pointer . value ( closure_base_pc . value +: bcofs data ) ` closure_func_stack ] ) ] ) ; ( ` closure_func_stack , let data = mux2 ( count . value . ==: 0 ) accu . value ( alloc_pointer . value +: ( aofs ( sll count . value 1 ) . +: 1 ) ) in [ when_mem_ready ( fun _ -> [ count <-- count_next ; push_stack data ` closure_func_hdr ] ) ] ) ; ( ` closure_accu_pc0 , [ when_mem_ready ( fun _ -> [ read_bytecode ` closure_accu_pc1 ] ) ] ) ; ( ` closure_accu_pc1 , [ when_bytecode_ready ( fun ofs -> [ write_mem accu . value ( pc . value +: bcofs ( ofs . -: 1 ) ) ` closure_accu_pc2 ] ) ] ) ; ` closure_accu_pc2 , [ when_mem_ready ( fun _ -> [ state . set_next ` fetch ] ) ] ; ( ` setglobal , [ when_bytecode_ready ( fun ofs -> [ write_mem ( i . globals_start_address +: aofs ofs ) accu . value ` fetch ; accu <-- val_unit ] ) ] ) ; ( ` getglobal_data , [ when_bytecode_ready ( fun ofs -> [ read_mem ( i . globals_start_address +: aofs ofs ) ` getglobal ] ) ] ) ; ( ` getglobal , [ when_mem_ready ( fun data -> [ accu <-- data ; if_ ( decode ' . getglobalfield |: decode ' . pushgetglobalfield ) [ read_bytecode ` getglobalfield_data ] [ state . set_next ` fetch ] ] ) ] ) ; ( ` getglobalfield_data , [ when_bytecode_ready ( fun ofs -> [ read_mem ( accu . value +: aofs ofs ) ` getglobalfield ] ) ] ) ; ( ` getglobalfield , [ when_mem_ready ( fun data -> [ accu <-- data ; state . set_next ` fetch ] ) ] ) ; ` c_call0 , [ when_stack_ready ( fun _ -> [ read_bytecode ` c_call1 ] ) ] ; ( ` c_call1 , [ when_bytecode_ready ( fun prim -> [ c_call_prim <-- prim ; if_ ( decode ' . c_call_op . ==: 5 ) [ state . set_next ` invalid_instruction ] [ c_call_request . <-- 1 ; state . set_next ` c_call2 ] ] ) ] ) ; ( ` c_call2 , [ when_ i . c_call_ready [ c_call_request . <-- 0 ; accu <-- i . c_call_result ; pop_stack ` c_call3 ] ] ) ; ( ` c_call3 , [ when_stack_ready ( fun _ -> [ sp <-- sp . value +: aofs decode ' . c_call_op ; state . set_next ` fetch ] ) ] ) ; ( ` offsetint , [ when_bytecode_ready ( fun data -> [ accu <-- accu . value +: sll data 1 ; state . set_next ` fetch ] ) ] ) ; ( ` offsetref0 , [ when_bytecode_ready ( fun data -> [ temp . ( 0 ) <-- data ; read_mem accu . value ` offsetref1 ] ) ] ) ; ( ` offsetref1 , [ when_mem_ready ( fun data -> [ write_mem accu . value ( data +: sll temp . ( 0 ) . value 1 ) ` offsetref2 ] ) ] ) ; ( ` offsetref2 , [ when_mem_ready ( fun _ -> [ accu <-- val_unit ; state . set_next ` fetch ] ) ] ) ; ( ` atom , let get_tag ofs = mux2 ( decode ' . atom &: decode ' . atom_op |: ( decode ' . pushatom &: decode ' . pushatom_op ) ) ofs ( zero dbits ) in [ when_bytecode_ready ( fun ofs -> [ accu <-- atom_ptr ( get_tag ofs ) ; state . set_next ` fetch ] ) ] ) ; ( ` apply_pop_stack , [ when_stack_ready ( fun d -> [ shift_temp_up d ; count <-- count_next ; if_ ( count . value ==: ures decode ' . apply_op ) [ count . <-- 0 ; push_stack ( val_int extra_args . value ) ` apply_push_stack_env ; extra_args <-- ures ( decode ' . apply_op . -: 1 ) ] [ pop_stack ` apply_pop_stack ] ] ) ] ) ; ( ` apply_push_stack_env , [ when_stack_ready ( fun _ -> [ push_stack env . value ` apply_push_stack_pc ] ) ] ) ; ( ` apply_push_stack_pc , [ when_stack_ready ( fun _ -> [ push_stack pc . value ` apply_push_stack_args ] ) ] ) ; ( ` apply_push_stack_args , [ when_stack_ready ( fun _ -> [ shift_temp_down ( zero dbits ) ; count <-- count_next ; if_ ( count . value ==: ures decode ' . apply_op ) [ read_mem accu . value ` apply ] [ push_stack temp . ( 0 ) . value ` apply_push_stack_args ] ] ) ] ) ; ( ` apply_eargs , [ when_bytecode_ready ( fun earg -> [ extra_args <-- mux2 ( decode ' . apply_op . ==: 0 ) ( earg . -: 1 ) ( zero dbits ) ; pc <-- accu . value ; state . set_next ` fetch ] ) ] ) ; ( ` apply , [ when_mem_ready ( fun pc ' -> [ pc <-- pc ' ; env <-- accu . value ; state . set_next ` fetch ] ) ] ) ; ( ` appterm0 , [ when_bytecode_ready ( fun nargs -> [ temp . ( 0 ) <-- nargs ; read_bytecode ` appterm1 ] ) ] ) ; ( ` appterm1 , [ when_bytecode_ready ( fun slotsize -> [ temp . ( 1 ) <-- sp . value +: aofs ( slotsize -: temp . ( 0 ) . value ) ; count <-- temp . ( 0 ) . value . -: 1 ; state . set_next ` appterm2 ] ) ] ) ; ( ` appterm2 , [ when_stack_ready ( fun _ -> [ if_ ( count . value . ==: - 1 ) [ read_mem accu . value ` appterm4 ] [ read_stack ( sp . value +: aofs count . value ) ` appterm3 ] ] ) ] ) ; ( ` appterm3 , [ when_stack_ready ( fun d -> [ write_stack ( temp . ( 1 ) . value +: aofs count . value ) d ` appterm2 ; count <-- count . value . -: 1 ] ) ] ) ; ( ` appterm4 , [ when_mem_ready ( fun pcn -> [ sp <-- temp . ( 1 ) . value ; pc <-- pcn ; env <-- accu . value ; extra_args <-- extra_args . value +: temp . ( 0 ) . value . -: 1 ; state . set_next ` fetch ] ) ] ) ; ( ` grab , [ when_bytecode_ready ( fun reqd -> [ if_ ( extra_args . value >=: reqd ) [ extra_args <-- extra_args . value -: reqd ; state . set_next ` fetch ] [ state . set_next ` invalid_instruction ] ] ) ] ) ; ( ` push_retaddr0 , [ when_bytecode_ready ( fun ofs -> [ push_stack ( pc . value +: aofs ofs ) ` push_retaddr1 ] ) ] ) ; ( ` push_retaddr1 , [ when_stack_ready ( fun _ -> [ push_stack env . value ` push_retaddr2 ] ) ] ) ; ( ` push_retaddr2 , [ when_stack_ready ( fun _ -> [ push_stack ( val_int extra_args . value ) ` push_retaddr3 ] ) ] ) ; ` push_retaddr3 , [ when_stack_ready ( fun _ -> [ state . set_next ` fetch ] ) ] ; ( ` vectlength , [ when_mem_ready ( fun d -> [ accu <-- val_int ( srl d 10 ) ] ) ] ) ; ( ` getvectitem0 , [ when_stack_ready ( fun ofs -> [ read_mem ( accu . value +: aofs ofs ) ` getvectitem1 ] ) ] ) ; ( ` getvectitem1 , [ when_mem_ready ( fun data -> [ accu <-- data ; state . set_next ` fetch ] ) ] ) ; ( ` setvectitem0 , [ when_stack_ready ( fun d -> [ temp . ( 0 ) <-- d ; pop_stack ` setvectitem1 ] ) ] ) ; ( ` setvectitem1 , [ when_stack_ready ( fun d -> [ write_mem ( accu . value +: aofs ( int_val temp . ( 0 ) . value ) ) d ` fetch ] ) ] ) ; ( ` setvectitem2 , [ when_mem_ready ( fun _ -> [ accu <-- val_unit ; state . set_next ` fetch ] ) ] ) ; ( ` getstringchar0 , [ when_stack_ready ( fun d -> [ temp . ( 0 ) <-- d ; read_mem accu . value ` getstringchar1 ] ) ] ) ; ( ` getstringchar0 , [ when_stack_ready ( fun d -> [ accu <-- val_int @@ get_byte temp . ( 0 ) . value . [ : 3 , 1 ] d ; state . set_next ` fetch ] ) ] ) ; ( ` setstringchar0 , [ when_stack_ready ( fun d -> [ temp . ( 0 ) <-- d ; pop_stack ` setstringchar1 ] ) ] ) ; ( ` setstringchar1 , [ when_stack_ready ( fun d -> [ temp . ( 1 ) <-- d ; read_mem accu . value ` setstringchar2 ] ) ] ) ; ( ` setstringchar2 , [ when_mem_ready ( fun d -> [ write_mem accu . value ( set_byte temp . ( 1 ) . value . [ : 3 , 1 ] d temp . ( 0 ) . value . [ : 8 , 1 ] ) ` setstringchar3 ] ) ] ) ; ` setstringchar3 , [ when_mem_ready ( fun _ -> [ state . set_next ` fetch ] ) ] ; ` not_implemented , [ error . <-- 1 ] ; ` invalid_instruction , [ error . <-- 1 ] ] ] ; { state = state . current ; pc = pc . value ; sp = sp . value ; accu = accu . value ; env = env . value ; extra_args = extra_args . value ; instruction = mux2 ( state . is ` decode &: bc_i . memory_ready ) instruction ( consti ~ width : 8 255 ) ; error = error . value ; memory_o ; decode = decode ' ; c_call_request = c_call_request . value ; c_call_prim = c_call_prim . value } ; ;
module Z = Cyclesim . With_interface ( Zinc . I ) ( Zinc . O )
type cfg = { waves : bool ; instr_trace : bool ; state_trace : bool ; mem_trace : bool }
let make cfg exe = let mem_size_words = 1024 * 1024 in let _show_instr = let ins = Base . List . map Opcode . all ~ f : Opcode . to_string |> Base . Array . of_list in fun x -> let i = Bits . to_int x in try ins . ( i ) with | _ -> " " in let sim = Z . create Zinc . zinc in let waves , sim = if cfg . waves then ( let waves , sim = Waveform . create sim in Some waves , sim ) else None , sim in let open Zinc . Memory . I in let open Zinc . Memory . O in let open Zinc . I in let open Zinc . O in let i = Zinc . I . map ( Cyclesim . inputs sim ) ~ f ( : fun i d -> i := Bits . consti ~ width ( : Bits . width ! i ) d ) in let i64 = Zinc . I . map ( Cyclesim . inputs sim ) ~ f ( : fun i d -> i := Bits . consti64 ~ width ( : Bits . width ! i ) d ) in let o = Zinc . O . map ( Cyclesim . outputs sim ) ~ f ( : fun o ( ) -> Bits . to_int ! o ) in let n = Zinc . O . map ( Cyclesim . outputs ~ clock_edge : After sim ) ~ f ( : fun o ( ) -> Bits . to_int ! o ) in let n64 = Zinc . O . map ( Cyclesim . outputs ~ clock_edge : After sim ) ~ f ( : fun o ( ) -> Bits . to_int64 ! o ) in let o64 = Zinc . O . map ( Cyclesim . outputs sim ) ~ f ( : fun o ( ) -> Bits . to_int ! o |> Int64 . of_int ) in let mapping , memory = init_memory exe mem_size_words in let trace ( ) = Trace . machine { Machine . empty with memory ; mapping ; env = o64 . env ( ) ; sp = o64 . sp ( ) ; accu = o64 . sp ( ) } in Cyclesim . reset sim ; i . bytecode_start_address mapping . code_address ; i . atom_table_address ( mapping . atoms_address + 8 ) ; i . globals_start_address ( mapping . globals_address + 8 ) ; i . heap_start_address mapping . heap_address ; i . stack_start_address mapping . stack_address ; i . start 1 ; let log_mem_access cycle rw addr data sp = if cfg . mem_trace then ( let offs , typ = if addr < mapping . atoms_address then ( addr - 0 ) * 2 , " BYTE " else if addr < mapping . globals_address then addr - mapping . atoms_address , " ATOM " else if addr < mapping . heap_address then addr - mapping . globals_address , " GLBL " else if addr >= sp - 8 then mapping . stack_address - addr - 1 , " STCK " else addr - mapping . heap_address , " HEAP " in printf " [ %- 8i ] % s % s [ . @% 8x | . % 8x ] = . % 16Lx [ sp =% i ] \ n " cycle ( if rw = 0 then " R " else " W " ) typ addr offs data sp ) in let run ( ) = let cycle = ref 0 in let stop = ref false in let instr_no = ref 1 in while ( not ! stop ) && o . error ( ) <> 1 do if o . state ( ) = 2 then ( try if cfg . state_trace then printf " \ n ##% i \ n " ! instr_no ; incr instr_no ; if cfg . instr_trace then printf " % 6i % s \ n " %! ( ( o . pc ( ) / 4 ) - 1 ) ( o . instruction ( ) |> Opcode . of_int |> Opcode . to_string ) ; if cfg . state_trace then trace ( ) with | _ -> stop := true ; printf " INVALID \ n " ) ; %! Cyclesim . cycle sim ; i . memory_i . memory_ready 0 ; if n . memory_o . memory_request ( ) <> 0 then ( let addr = n . memory_o . memory_address ( ) in let rw = n . memory_o . memory_read_write ( ) in let sp = o . sp ( ) in if rw = 0 then ( let data = memory . { addr lsr 3 } in log_mem_access ! cycle rw addr data sp ; i64 . memory_i . memory_data_in data ) else ( let data = n64 . memory_o . memory_data_out ( ) in log_mem_access ! cycle rw addr data sp ; memory . { addr lsr 3 } <- data ) ; i . memory_i . memory_ready 1 ) ; i . c_call_ready 0 ; if n . c_call_request ( ) = 1 then ( let prim = n . c_call_prim ( ) in if cfg . instr_trace then Printf . printf " c_call_request : [ % i ] % s \ n " prim exe . Load . prim . ( prim ) ; let value = match C_runtime . run exe prim { Machine . empty with Machine . env = o64 . env ( ) ; accu = o64 . accu ( ) ; sp = o64 . sp ( ) ; memory } with | ` ok v -> v | ` exn _ -> failwith " c - call exn not implemented " in i64 . c_call_result value ; i . c_call_ready 1 ) ; i . start 0 ; incr cycle done in let ( ) = try run ( ) with | Failure x -> printf " \ n \ nEXN : % s \ n \ n " %! x | _ -> printf " \ n \ nEXN % s \ n \ n " %! ( Printexc . get_backtrace ( ) ) in match waves with | None -> ( ) | Some waves -> Hardcaml_waveterm_interactive . run waves ; ;
let read2 ic = let lb = read1 ic in let hb = read1 ic in lb lor ( hb lsl 8 ) 8
let read4 ic = let lw = read2 ic in let hw = read2 ic in Int32 . logor ( Int32 . of_int lw ) lw ( Int32 . shift_left ( Int32 . of_int hw ) hw 16 ) 16
let read4_int ic = let lw = read2 ic in let hw = read2 ic in if hw > max_int lsr 16 then raise ( Error ( Error " " , " " , " 32 - bit data too large ) ) " ; lw lor ( hw lsl 16 ) 16
let readstring ic n = let s = Bytes . create n in really_input ic s 0 n ; Bytes . to_string s
let write2 oc n = write1 oc n ; write1 oc ( n lsr 8 ) 8
let write4 oc n = write2 oc ( Int32 . to_int n ) n ; write2 oc ( Int32 . to_int ( Int32 . shift_right_logical n 16 ) 16 ) 16
let write4_int oc n = write2 oc n ; write2 oc ( n lsr 16 ) 16
let writestring oc s = output oc ( Bytes . of_string s ) s 0 ( String . length s ) s
let writebytes oc s = output oc s 0 ( Bytes . length s ) s
type compression_method = Stored | Deflated
type entry = { filename : string ; extra : string ; comment : string ; methd : compression_method ; mtime : float ; crc : int32 ; uncompressed_size : int ; compressed_size : int ; is_directory : bool ; file_offset : int64 }
type in_file = { if_filename : string ; if_channel : Pervasives . in_channel ; if_entries : entry list ; if_directory : ( string , entry ) entry Hashtbl . t ; if_comment : string }
let entries ifile = ifile . if_entries
let comment ifile = ifile . if_comment
type out_file = { of_filename : string ; of_channel : Pervasives . out_channel ; mutable of_entries : entry list ; of_comment : string }
let strrstr pattern buf ofs len = let rec search i j = if i < ofs then - 1 else if j >= String . length pattern then i else if pattern [ . j ] j = buf [ . i + j ] j then search i ( j + 1 ) 1 else search ( i - 1 ) 1 0 in search ( ofs + len - String . length pattern ) pattern 0
let filename_is_directory name = String . length name > 0 && name [ . String . length name - 1 ] 1 = ' / '
let unixtime_of_dostime time date = fst ( fstUnix . mktime { Unix . tm_sec = ( time lsl 1 ) 1 land 0x3e ; Unix . tm_min = ( time lsr 5 ) 5 land 0x3f ; Unix . tm_hour = ( time lsr 11 ) 11 land 0x1f ; Unix . tm_mday = date land 0x1f ; Unix . tm_mon = ( ( date lsr 5 ) 5 land 0xf ) 0xf - 1 ; Unix . tm_year = ( ( date lsr 9 ) 9 land 0x7f ) 0x7f + 80 ; Unix . tm_wday = 0 ; Unix . tm_yday = 0 ; Unix . tm_isdst = false } )
let dostime_of_unixtime t = let tm = Unix . localtime t in ( tm . Unix . tm_sec lsr 1 + ( tm . Unix . tm_min lsl 5 ) 5 + ( tm . Unix . tm_hour lsl 11 ) 11 , tm . Unix . tm_mday + ( tm . Unix . tm_mon + 1 ) 1 lsl 5 + ( tm . Unix . tm_year - 80 ) 80 lsl 9 ) 9
let read_ecd filename ic = let buf = Bytes . create 256 in let filelen = in_channel_length ic in let rec find_ecd pos len = if pos <= 0 || filelen - pos >= 0x10000 then raise ( Error ( Errorfilename , " " , " end of central directory not found , not a ZIP file ) ) " ; let toread = min pos 128 in Bytes . blit buf 0 buf toread ( 256 - toread ) toread ; let newpos = pos - toread in seek_in ic newpos ; really_input ic buf 0 toread ; let newlen = min ( toread + len ) len 256 in let ofs = strrstr " PK \ 005 \ 006 " ( Bytes . to_string buf ) buf 0 newlen in if ofs < 0 || newlen < 22 || ( let comment_len = Char . code ( Bytes . get buf ( ofs + 20 ) 20 ) 20 lor ( Char . code ( Bytes . get buf ( ofs + 21 ) 21 ) 21 lsl 8 ) 8 in newpos + ofs + 22 + comment_len <> filelen ) filelen then find_ecd newpos newlen else newpos + ofs in seek_in ic ( find_ecd filelen 0 ) 0 ; let magic = read4 ic in let disk_no = read2 ic in let cd_disk_no = read2 ic in let _disk_entries = read2 ic in let cd_entries = read2 ic in let cd_size = read4 ic in let cd_offset = read4 ic in let comment_len = read2 ic in let comment = readstring ic comment_len in assert ( magic = Int32 . of_int 0x06054b50 ) 0x06054b50 ; if disk_no <> 0 || cd_disk_no <> 0 then raise ( Error ( Errorfilename , " " , " multi - disk ZIP files not supported ) ) " ; ( cd_entries , cd_size , cd_offset , comment ) comment
let read_cd filename ic cd_entries cd_offset cd_bound = let cd_bound = Int64 . of_int32 cd_bound in try LargeFile . seek_in ic ( Int64 . of_int32 cd_offset ) cd_offset ; let e = ref [ ] in let entrycnt = ref 0 in while ( LargeFile . pos_in ic < cd_bound ) cd_bound do incr entrycnt ; let magic = read4 ic in let _version_made_by = read2 ic in let _version_needed = read2 ic in let flags = read2 ic in let methd = read2 ic in let lastmod_time = read2 ic in let lastmod_date = read2 ic in let crc = read4 ic in let compr_size = read4_int ic in let uncompr_size = read4_int ic in let name_len = read2 ic in let extra_len = read2 ic in let comment_len = read2 ic in let _disk_number = read2 ic in let _internal_attr = read2 ic in let _external_attr = read4 ic in let header_offset = Int64 . of_int32 ( of_int32read4 ic ) ic in let name = readstring ic name_len in let extra = readstring ic extra_len in let comment = readstring ic comment_len in if magic <> Int32 . of_int 0x02014b50 then raise ( Error ( Errorfilename , name , " wrong file header in central directory ) ) " ; if flags land 1 <> 0 then raise ( Error ( Errorfilename , name , " encrypted entries not supported ) ) " ; e := { filename = name ; extra = extra ; comment = comment ; methd = ( match methd with 0 -> Stored | 8 -> Deflated | _ -> raise ( Error ( Errorfilename , name , " unknown compression method ) ) ) " ; mtime = unixtime_of_dostime lastmod_time lastmod_date ; crc = crc ; uncompressed_size = uncompr_size ; compressed_size = compr_size ; is_directory = filename_is_directory name ; file_offset = header_offset } :: ! e done ; assert ( assert ( assertcd_bound = ( LargeFile . pos_in ic ) ic ) ic && ( cd_entries = 65535 || ! entrycnt = cd_entries ) cd_entries ) cd_entries ; List . rev ! e with End_of_file -> raise ( Error ( Errorfilename , " " , " end - of - file while reading central directory ) ) "
let open_in filename = let ic = Pervasives . open_in_bin filename in let ( cd_entries , cd_size , cd_offset , cd_comment ) cd_comment = read_ecd filename ic in let entries = read_cd filename ic cd_entries cd_offset ( Int32 . add cd_offset cd_size ) cd_size in let dir = Hashtbl . create ( cd_entries / 3 ) 3 in List . iter ( fun e -> Hashtbl . add dir e . filename e ) e entries ; { if_filename = filename ; if_channel = ic ; if_entries = entries ; if_directory = dir ; if_comment = cd_comment }
let close_in ifile = Pervasives . close_in ifile . if_channel