Something went wrong. Try again.
forked from certirocq/certirocq
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961(**********************************************************************)(* CertiRocq *)(* Copyright (c) 2017 *)(**********************************************************************)
open Printeropen Metarocq_template_plugin.Ast_quoteropen AstCommonopen Plugin_utilsopen Caml_natopen Certirocq_options
type command_args = Certirocq_options.command_argstype prim = Certirocq_options.primtype inductive_mapping = Certirocq_options.inductive_mappingtype inductives_mapping = Certirocq_options.inductives_mappingtype extract_inductive = Certirocq_options.extract_inductivetype extract_inductives = Certirocq_options.extract_inductivestype options = Certirocq_options.options
let get_stringopt_option key = let open Goptions in match get_option_value key with | Some get -> fun () -> begin match get () with | StringOptValue b -> b | _ -> assert false end | None -> (declare_stringopt_option_and_ref ~key ~value:None ()).get
let get_build_dir_opt = get_stringopt_option ["CertiRocq"; "Build"; "Directory"]
let get_ocamlfind = get_stringopt_option ["CertiRocq"; "ocamlfind"]
let get_c_compiler = get_stringopt_option ["CertiRocq"; "CC"]
(* Taken from Coq's increment_subscript, but works on strings rather than idents *)let increment_subscript id = let len = String.length id in let rec add carrypos = let c = id.[carrypos] in if Util.is_digit c then if Int.equal (Char.code c) (Char.code '9') then begin assert (carrypos>0); add (carrypos-1) end else begin let newid = Stdlib.Bytes.of_string id in Stdlib.Bytes.fill newid (carrypos+1) (len-1-carrypos) '0'; Stdlib.Bytes.set newid carrypos (Char.chr (Char.code c + 1)); newid end else begin let newid = Stdlib.Bytes.of_string (id^"0") in if carrypos < len-1 then begin Stdlib.Bytes.fill newid (carrypos+1) (len-1-carrypos) '0'; Stdlib.Bytes.set newid (carrypos+1) '1' end; newid end in String.of_bytes (add (len-1))
let debug_reify = CDebug.create ~name:"certirocq-reify" ()
external get_unboxed_ordinal : Obj.t -> int = "get_unboxed_ordinal" [@@noalloc]
external get_boxed_ordinal : Obj.t -> (int [@untagged]) = "get_boxed_ordinal" "get_boxed_ordinal" [@@noalloc]
(** Various Utils *)
let pr_string s = Pp.str (Caml_bytestring.caml_string_of_bytestring s)
(* remove duplicates but preserve order, keep the leftmost element *)let nub (xs : 'a list) : 'a list = List.fold_right (fun x xs -> if List.mem x xs then xs else x :: xs) xs []
let debug_msg (flag : bool) (s : string) = if flag then Feedback.msg_debug (Pp.str s) else ()
(* Separate registration of primitive extraction *)
let global_registers = Summary.ref (([], []) : prim list * import list) ~name:"CertiRocq Registration"
let global_registers_name = "certirocq-registration"
let cache_registers (prims, imports) = let (prims', imports') = !global_registers in global_registers := (prims @ prims', imports @ imports')let global_registers_input = let open Libobject in declare_object (global_object_nodischarge global_registers_name ~cache:(fun r -> cache_registers r) ~subst:None) (*(fun (msub, r) -> r)) *)
let register (prims : prim list) (imports : import list) : unit = let curlib = Sys.getcwd () in let newr = (prims, List.map (fun i -> match i with | FromAbsolutePath s -> FromRelativePath (Filename.concat curlib s) | _ -> i) imports) in (* Feedback.msg_debug Pp.(str"Prims: " ++ prlist_with_sep spc (fun ((x, y), wt) -> str (string_of_bytestring y)) (fst newr)); *) Lib.add_leaf (global_registers_input newr)
let get_global_prims () = fst !global_registerslet get_global_includes () = snd !global_registers
(* Extract Inductive *)
let global_inductive_registers = Summary.ref ([] : inductives_mapping) ~name:"CertiRocq Extract Inductive Registration"
let global_inductive_registers_name = "certirocq-extract-inductive-registration"
let cache_inductive_registers inds = let inds' = !global_inductive_registers in global_inductive_registers := inds @ inds'
let global_inductive_registers_input = let open Libobject in declare_object (global_object_nodischarge global_inductive_registers_name ~cache:(fun r -> cache_inductive_registers r) ~subst:None)
let register_inductives (inds : inductives_mapping) : unit = Lib.add_leaf (global_inductive_registers_input inds)
let get_global_inductives_mapping () = !global_inductive_registers
(* Extract Inline *)
let global_inlining_registers = Summary.ref ~name:"CertiRocq Extraction Inlining Registration" Kernames.KernameSet.empty
let global_inlining_registers_name = "certirocq-inlining-registration"
let cache_inlining_registers csts = let csts' = !global_inlining_registers in global_inlining_registers := Kernames.KernameSet.union csts csts'
let global_inlining_registers_input = let open Libobject in declare_object (global_object_nodischarge global_inlining_registers_name ~cache:(fun r -> cache_inlining_registers r) ~subst:None)
let register_inlines (csts : Kernames.kername list) : unit = Lib.add_leaf (global_inlining_registers_input (Obj.magic (Metarocq_template_plugin.Kernames.KernameSetProp.of_list (Obj.magic csts))))
let get_global_inlinings_mapping () = !global_inlining_registers
(* Extract Inductive to Constants *)
let global_inductive_constant_registers = Summary.ref ([] : extract_inductives) ~name:"CertiRocq Inductive to Constants Registration"
let global_inductive_constant_registers_name = "certirocq-inductive-constants-registration"
let cache_inductive_constant_registers inds = let inds' = !global_inductive_constant_registers in global_inductive_constant_registers := inds @ inds'
let global_inductive_constant_registers_input = let open Libobject in declare_object (global_object_nodischarge global_inductive_constant_registers_name ~cache:(fun r -> cache_inductive_constant_registers r) ~subst:None)
let register_constant_inductives (extr : extract_inductives) : unit = Lib.add_leaf (global_inductive_constant_registers_input extr)
let get_global_inductives_constant_mapping () = !global_inductive_constant_registers
(* Support for dynamically-linked certirocq-compiled programs *)type certirocq_run_function = unit -> Obj.t
let certirocq_run_functions = Summary.ref ~local:true ~name:"CertiRocq Run Functions Table" (CString.Map.empty : certirocq_run_function CString.Map.t)
let certirocq_run_functions_name = "certirocq-run-functions-registration"
let all_run_functions = ref CString.Set.empty
let cache_certirocq_run_function (s, s', fn) = let fns = !certirocq_run_functions in all_run_functions := CString.Set.add s (CString.Set.add s' !all_run_functions); certirocq_run_functions := CString.Map.add s fn fns
let certirocq_run_function_input = let open Libobject in declare_object (local_object_nodischarge certirocq_run_functions_name ~cache:(fun r -> cache_certirocq_run_function r))
let register_certirocq_run s s' fn = (* Feedback.msg_debug Pp.(str"Registering function " ++ str s ++ str " in certirocq_run"); *) Lib.add_leaf (certirocq_run_function_input (s, s', fn))
let exists_certirocq_run s = (* Feedback.msg_debug Pp.(str"Looking up " ++ str s ++ str " in certirocq_run_functions"); *) let res = CString.Map.find_opt s !certirocq_run_functions in (* if Option.is_empty res then Feedback.msg_debug Pp.(str"Not found"); *) res
let run_certirocq_run s = try CString.Map.find s !certirocq_run_functions with Not_found -> CErrors.user_err Pp.(str"Could not find certirocq run function associated to " ++ str s)
(** Coq FFI: message channels and raising user errors. *)
let rocq_msg_info s = let s = Caml_bytestring.caml_string_of_bytestring s in Feedback.msg_info (Pp.str s)
let _ = Callback.register "rocq_msg_info" rocq_msg_info
let rocq_msg_debug s = Feedback.msg_debug Pp.(str (Caml_bytestring.caml_string_of_bytestring s))
let _ = Callback.register "rocq_msg_debug" rocq_msg_debug
let rocq_msg_notice s = Feedback.msg_notice Pp.(str (Caml_bytestring.caml_string_of_bytestring s))
let _ = Callback.register "rocq_msg_notice" rocq_msg_notice
let rocq_user_error s = CErrors.user_err Pp.(str (Caml_bytestring.caml_string_of_bytestring s))
let _ = Callback.register "rocq_user_error" rocq_user_error
(** Compilation Command Arguments *)
let default_build_dir () = match get_build_dir_opt () with None -> "." | Some s -> s
let default_options () : options = Certirocq_options.default_options ~build_dir:(default_build_dir ()) ~inductives_mapping:(get_global_inductives_mapping ()) ~extracted_inductives:(get_global_inductives_constant_mapping ()) ()
let make_options (l : command_args list) (pr : prim list) (fname : string) : options = Certirocq_options.make_options ~build_dir:(default_build_dir ()) ~inductives_mapping:(get_global_inductives_mapping ()) ~extracted_inductives:(get_global_inductives_constant_mapping ()) l pr fname
let make_unsafe_passes b = let open Erasure0 in { cofix_to_lazy = b; unboxing = b; betared = b; inductives_extraction = b }
let all_unsafe_passes = make_unsafe_passes truelet no_unsafe_passes = make_unsafe_passes false
let quote_inductives_mapping l = List.map (fun (hd, (na, cstrs)) -> (hd, (bytestring_of_string na, List.map (fun i -> nat_of_caml_int i) cstrs))) l
let quote_prims l = let open Pipeline_utils in List.map (fun ((x, y), ar, b) -> { prim_name = x; prim_target = y; prim_arity = nat_of_caml_int ar; prim_alloc = b}) l
let make_pipeline_options (opts : options) = let erasure_config = Erasure0.({ enable_typed_erasure = opts.typed_erasure; enable_unsafe = if opts.unsafe_erasure then all_unsafe_passes else no_unsafe_passes; inlining = not (opts.no_inlining); dearging_config = default_dearging_config; inlined_constants = get_global_inlinings_mapping (); extracted_inductives = Obj.magic opts.extracted_inductives; (* kername and list representation are the same *) }) in let cps = opts.cps in let args = nat_of_caml_int opts.args in let olevel = nat_of_caml_int opts.olevel in let timing = opts.time in let timing_anf = opts.time_anf in let debug = opts.debug in let anf_variant = nat_of_caml_int opts.anf_variant in let toplevel_name = bytestring_of_string opts.toplevel_name in let prims = get_global_prims () @ opts.prims in let prims = quote_prims prims in let inductives_mapping = quote_inductives_mapping opts.inductives_mapping in (* Feedback.msg_debug Pp.(str"Prims: " ++ prlist_with_sep spc (fun ((x, y), wt) -> str (string_of_bytestring y)) prims); *) Pipeline.make_opts erasure_config inductives_mapping cps args anf_variant olevel timing timing_anf debug toplevel_name prims
(** Main Compilation Functions *)
(* Get fully qualified name of a constant *)let get_name (gr : Names.GlobRef.t) : string = match gr with | Names.GlobRef.ConstRef c -> Names.KerName.to_string (Names.Constant.canonical c) | _ -> CErrors.user_err Pp.(Printer.pr_global gr ++ str " is not a constant definition")
(* Quote Coq term *)let quote_term ~opaque_access opts env sigma c = let debug = opts.debug in let bypass = opts.bypass_qed in debug_msg debug "Quoting"; let time = Unix.gettimeofday() in let term = Metarocq_template_plugin.Ast_quoter.quote_term_rec ~bypass ~opaque_access env sigma (EConstr.to_constr sigma c) in let time = (Unix.gettimeofday() -. time) in debug_msg debug (Printf.sprintf "Finished quoting in %f s.. compiling to L7." time); term
let quote ~opaque_access opts gr = let env = Global.env () in let sigma = Evd.from_env env in let sigma, c = Evd.fresh_global env sigma gr in quote_term ~opaque_access opts env sigma c
(* Compile Quoted term with CertiRocq *)
module type CompilerInterface = sig type name_env val compile : Pipeline_utils.coq_Options -> Ast0.Env.program -> ((name_env * Clight.program) * Clight.program) CompM.error * Bytestring.String.t val printProg : Clight.program -> name_env -> string -> import list -> unit
val generate_glue : Pipeline_utils.coq_Options -> Ast0.Env.global_declarations -> (((name_env * Clight.program) * Clight.program) * Bytestring.String.t list) CompM.error
end
module MLCompiler : CompilerInterface with type name_env = BasicAst.name Term0.M.t = struct type name_env = BasicAst.name Term0.M.t let compile = Pipeline.compile let printProg prog names (dest : string) (imports : import list) = let imports' = List.filter_map (fun i -> match i with | FromRelativePath s -> Some ("#include \"" ^ s ^ "\"") | FromLibrary (s, _) -> Some ("#include <" ^ s ^ ">") | LibraryPath _ -> None | Link _ -> None | FromAbsolutePath s -> failwith "Import with absolute path should have been filled") imports in PrintClight.print_dest_names_imports prog (Term0.M.elements names) dest imports' let generate_glue = Glue.generate_glueend
module CompileFunctor (CI : CompilerInterface) = struct
let make_fname opts str = Filename.concat opts.build_dir str
type line = | EOF | Info of string | Error of string
let read_line stdout stderr = try Info (input_line stdout) with End_of_file -> try Error (input_line stderr) with End_of_file -> EOF
let push_line buf line = Buffer.add_string buf line; Buffer.add_string buf "\n"
let string_of_buffer buf = Stdlib.Bytes.to_string (Buffer.to_bytes buf)
let execute cmd = debug Pp.(fun () -> str "Executing: " ++ str cmd ++ str " in environemt: " ++ prlist_with_sep spc str (Array.to_list (Unix.environment ()))); let (stdout, stdin, stderr) = Unix.open_process_full cmd (Unix.environment ()) in let continue = ref true in let outbuf, errbuf = Buffer.create 100, Buffer.create 100 in let push_info = push_line outbuf in let push_error = push_line errbuf in while !continue do match read_line stdout stderr with | EOF -> debug Pp.(fun () -> str "Program terminated"); continue := false | Info s -> push_info s | Error s -> push_error s done; let status = Unix.close_process_full (stdout, stdin, stderr) in status, string_of_buffer outbuf, string_of_buffer errbuf
let execute ?loc cmd = let status, out, err = execute cmd in match status with | Unix.WEXITED 0 -> out, err | Unix.WEXITED n -> CErrors.user_err ?loc Pp.(str"Command" ++ spc () ++ str cmd ++ spc () ++ str"exited with code " ++ int n ++ str "." ++ fnl () ++ str"stdout: " ++ spc () ++ str out ++ fnl () ++ str "stderr: " ++ str err) | Unix.WSIGNALED n | Unix.WSTOPPED n -> CErrors.user_err ?loc Pp.(str"Command" ++ spc () ++ str cmd ++ spc () ++ str"was signaled with code " ++ int n ++ str"." ++ fnl () ++ str"stdout: " ++ spc () ++ str out ++ fnl () ++ str "stderr: " ++ str err)
let compile opts term imports = let debug = opts.debug in let options = make_pipeline_options opts in let runtime_imports = [FromLibrary ("gc_stack.h", None)] in let curlib = Sys.getcwd () in let imports = List.map (fun i -> match i with | FromAbsolutePath s -> FromRelativePath (Filename.concat curlib s) | _ -> i) imports in let imports = runtime_imports @ get_global_includes () @ imports in let p = CI.compile options term in match p with | (CompM.Ret ((nenv, header), prg), dbg) -> debug_msg debug "Finished compiling, printing to file."; let time = Unix.gettimeofday() in let fname = opts.filename in let suff = opts.ext in let cstr = fname ^ suff ^ ".c" in let hstr = fname ^ suff ^ ".h" in let cstr' = make_fname opts cstr in let hstr' = make_fname opts hstr in CI.printProg prg nenv cstr' (imports @ [FromRelativePath hstr]); CI.printProg header nenv hstr' (runtime_imports);
(* let cstr = Metarocq_template_plugin.Tm_util.string_to_list (Names.KerName.to_string (Names.Constant.canonical const) ^ suff ^ ".c") in * let hstr = Metarocq_template_plugin.Tm_util.string_to_list (Names.KerName.to_string (Names.Constant.canonical const) ^ suff ^ ".h") in * Pipeline.printProg (nenv,prg) cstr; * Pipeline.printProg (nenv,header) hstr; *) let time = (Unix.gettimeofday() -. time) in debug_msg debug (Printf.sprintf "Printed to file %s in %f s.." cstr' time); debug_msg debug "Pipeline debug:"; debug_msg debug (string_of_bytestring dbg) | (CompM.Err s, dbg) -> debug_msg debug "Pipeline debug:"; debug_msg debug (string_of_bytestring dbg); CErrors.user_err Pp.(str "Could not compile: " ++ (pr_string s) ++ str "\n")
(* Generate glue code for the compiled program *) let generate_glue (standalone : bool) opts globs = if standalone && opts.filename = "" then CErrors.user_err Pp.(str "You need to provide an output name with the --output option.") else let debug = opts.debug in let options = make_pipeline_options opts in let runtime_imports = [ FromLibrary ("gc_stack.h", None); FromLibrary ("stdio.h", None) ] in let time = Unix.gettimeofday() in (match CI.generate_glue options globs with | CompM.Ret (((nenv, header), prg), logs) -> let time = (Unix.gettimeofday() -. time) in debug_msg debug (Printf.sprintf "Generated glue code in %f s.." time); (match logs with [] -> () | _ -> debug_msg debug (Printf.sprintf "Logs:\n%s" (String.concat "\n" (List.map string_of_bytestring logs)))); let time = Unix.gettimeofday() in let suff = opts.ext in let fname = opts.filename in let cstr = if standalone then fname ^ ".c" else "glue." ^ fname ^ suff ^ ".c" in let hstr = if standalone then fname ^ ".h" else "glue." ^ fname ^ suff ^ ".h" in let cstr' = make_fname opts cstr in let hstr' = make_fname opts hstr in CI.printProg prg nenv cstr' (runtime_imports @ [FromRelativePath hstr]); CI.printProg header nenv hstr' runtime_imports;
let time = (Unix.gettimeofday() -. time) in debug_msg debug (Printf.sprintf "Printed glue code to file %s in %f s.." cstr time) | CompM.Err s -> CErrors.user_err Pp.(str "Could not generate glue code: " ++ pr_string s))
let compile_only ~opaque_access (opts : options) (gr : Names.GlobRef.t) (imports : import list) : unit = let term = quote ~opaque_access opts gr in compile opts (Obj.magic term) imports
let generate_glue_only ~opaque_access opts gr = let term = quote ~opaque_access opts gr in generate_glue true opts (Ast0.Env.declarations (fst (Obj.magic term)))
let find_executable debug cmd = let whichcmd = Unix.open_process_in cmd in let result = try Stdlib.input_line whichcmd with End_of_file -> "" in let status = Unix.close_process_in whichcmd in match status with | Unix.WEXITED 0 -> if debug then Feedback.msg_debug Pp.(str "Compiler is " ++ str result); result | _ -> failwith "Compiler not found"
let compiler_executable debug = match get_c_compiler () with | None -> find_executable debug "which gcc || which clang-11" | Some s -> s
let ocamlfind_executable debug = match get_ocamlfind () with | None -> find_executable debug "which ocamlfind" | Some s -> s
let read_line stdout stderr = try Info (input_line stdout) with End_of_file -> try Error (input_line stderr) with End_of_file -> EOF
let run_program debug prog = let (stdout, stdin, stderr) = Unix.open_process_full ("./" ^ prog) (Unix.environment ()) in let continue = ref true in while !continue do match read_line stdout stderr with | EOF -> debug_msg debug ("Program terminated"); continue := false | Info s -> Feedback.msg_notice Pp.(str prog ++ str": " ++ str s) | Error s -> Feedback.msg_warning Pp.(str prog ++ str": " ++ str s) done; ignore (Unix.close_process_full (stdout, stdin, stderr))
let runtime_dir () = let open Boot in let env = Env.init_with ~coqlib:None in Path.relative (Path.relative (Path.relative (Env.user_contrib env) "CertiRocq") "Plugin") "runtime"
let make_rt_file na = Boot.Env.Path.(to_string (relative (runtime_dir ()) na))
let compile_C ~opaque_access opts gr imports = let () = compile_only ~opaque_access opts gr imports in let imports = get_global_includes () @ imports in let debug = opts.debug in let fname = opts.filename in let suff = opts.ext in let name = make_fname opts (fname ^ suff) in let compiler = compiler_executable debug in let rt_dir = runtime_dir () in let cmd = Printf.sprintf "%s -fPIC -Wno-everything -O2 -fomit-frame-pointer -g -I %s -I %s -c -o %s %s" compiler opts.build_dir (Boot.Env.Path.to_string rt_dir) (name ^ ".o") (name ^ ".c") in let importso = let oname s = assert (CString.is_suffix ".h" s); String.sub s 0 (String.length s - 2) ^ ".o" in let imports' = List.concat (List.map (fun i -> match i with | FromAbsolutePath s -> [oname s] | FromRelativePath s -> [oname s] | LibraryPath s -> ["-L"; s] | Link s -> ["-l" ^ s] | FromLibrary (s, _) -> [make_rt_file (oname s)]) imports) in let l = make_rt_file "certirocq_run_main.o" :: imports' in String.concat " " l in let gc_stack_o = make_rt_file "gc_stack.o" in debug_msg debug (Printf.sprintf "Executing command: %s" cmd); match Unix.system cmd with | Unix.WEXITED 0 -> let linkcmd = Printf.sprintf "%s -fPIC -Wno-everything -g -L %s -L %s -o %s %s %s %s" compiler opts.build_dir (Boot.Env.Path.to_string rt_dir) name gc_stack_o (name ^ ".o") importso in debug_msg debug (Printf.sprintf "Executing command: %s" linkcmd); (match Unix.system linkcmd with | Unix.WEXITED 0 -> debug_msg debug (Printf.sprintf "Compilation ran fine, running %s" name); run_program debug name | Unix.WEXITED n -> CErrors.user_err Pp.(str"Compiler exited with code " ++ int n ++ str" while running " ++ str linkcmd) | Unix.WSIGNALED n | Unix.WSTOPPED n -> CErrors.user_err Pp.(str"Compiler was signaled with code " ++ int n)) | Unix.WEXITED n -> CErrors.user_err Pp.(str"Compiler exited with code " ++ int n ++ str" while running " ++ str cmd) | Unix.WSIGNALED n | Unix.WSTOPPED n -> CErrors.user_err Pp.(str"Compiler was signaled with code " ++ int n ++ str" while running " ++ str cmd)
type reifyable_type = | IsInductive of Names.inductive * UVars.Instance.t * Constr.t list | IsPrimitive of Names.Constant.t * UVars.Instance.t * Constr.t list
let type_of_reifyable_type = function | IsInductive (hd, u, args) -> Term.applistc (Constr.mkIndU ((hd, u))) args | IsPrimitive (c, u, args) -> Term.applistc (Constr.mkConstU ((c, u))) args
let pr_reifyable_type env sigma ty = Printer.pr_constr_env env sigma (type_of_reifyable_type ty)
let find_nth_constant n ar = let open Inductiveops in let rec aux i const = if Array.length ar <= i then raise Not_found else if CList.is_empty ar.(i).cs_args then (* FIXME lets in constructors *) if const = n then i else aux (i + 1) (const + 1) else aux (i + 1) const in aux 0 0
let find_nth_non_constant n ar = let open Inductiveops in let rec aux i nconst = if Array.length ar <= i then raise Not_found else if not (CList.is_empty ar.(i).cs_args) then if nconst = n then i else aux (i + 1) (nconst + 1) else aux (i + 1) nconst in aux 0 0
let check_reifyable env sigma ty = (* We might have bound universes though. It's fine! *) try let (hd, u), args = Inductiveops.find_inductive env sigma ty in IsInductive (hd, EConstr.EInstance.kind sigma u, List.map (EConstr.to_constr sigma) args) with Not_found -> let hnf = Reductionops.whd_all env sigma ty in let hd, args = EConstr.decompose_app sigma hnf in match EConstr.kind sigma hd with | Const (c, u) when Environ.is_primitive_type env c -> IsPrimitive (c, EConstr.EInstance.kind sigma u, CArray.map_to_list EConstr.Unsafe.to_constr args) | _ -> CErrors.user_err Pp.(str"Cannot reify values of non-inductive or non-primitive type: " ++ Printer.pr_econstr_env env sigma ty)
let ill_formed env sigma ty = match ty with | IsInductive _ -> CErrors.anomaly ~label:"certirocq-reify-ill-formed" Pp.(str "Ill-formed inductive value representation in CertiRocq's reification for type " ++ pr_reifyable_type env sigma ty) | IsPrimitive _ -> CErrors.anomaly ~label:"certirocq-reify-ill-formed" Pp.(str "Ill-formed primitive value representation in CertiRocq's reification for type " ++ pr_reifyable_type env sigma ty)
(* let ocaml_get_boxed_ordinal v = (* tag is the header of the object *) let tag = Array.unsafe_get (Obj.magic v : Obj.t array) (-1) in (* We turn it into an ocaml int usable for arithmetic operations *) let tag_int = (Stdlib.Int.shift_left (Obj.magic (Obj.repr tag)) 1) + 1 in Feedback.msg_debug (Pp.str (Printf.sprintf "Ocaml tag: %i" (Obj.tag tag))); Feedback.msg_debug (Pp.str (Printf.sprintf "Ocaml get_boxed_ordinal int: %u" tag_int)); Feedback.msg_debug (Pp.str (Printf.sprintf "Ocaml get_boxed_ordinal ordinal: %u" (tag_int land 255))); tag_int land 255 *)
let time ~(msg:Pp.t) f = let start = Unix.gettimeofday() in let res = f () in let time = Unix.gettimeofday () -. start in Feedback.msg_notice Pp.(msg ++ str (Printf.sprintf " executed in %f sec" time)); res
let apply_reordering hd m cstrs = try let find_ind_ord (ind, (na, tags)) = if Kernames.eq_inductive_def ind hd then Some (Array.of_list (List.map (fun i -> cstrs.(i)) tags)) else None in CList.find_map_exn find_ind_ord m with Not_found -> cstrs
let find_reverse_mapping hd m cstr = try let find_ind_ord (ind, (na, tags)) = if Kernames.eq_inductive_def ind hd then Some (CList.index0 Int.equal cstr tags) else None in CList.find_map_exn find_ind_ord m with Not_found -> cstr
let reify im env sigma ty v : Constr.t = let open Declarations in let debug s = debug_reify Pp.(fun () -> str s) in let rec aux ty v = Control.check_for_interrupt (); let () = debug_reify Pp.(fun () -> str "Reifying value of type " ++ pr_reifyable_type env sigma ty) in match ty with | IsInductive (hd, u, args) -> let open Inductive in let open Inductiveops in let qhd = match Metarocq_template_plugin.Ast_quoter.quote_global_reference (IndRef hd) with Metarocq_template_plugin.Kernames.IndRef i -> (Obj.magic i : Kernames.inductive) | _ -> assert false in let spec = lookup_mind_specif env hd in let npars = inductive_params spec in let params, _indices = CList.chop npars args in let indfam = make_ind_family ((hd, EConstr.EInstance.make u), List.map (EConstr.of_constr) params) in let cstrs = get_constructors env indfam in let cstrs = apply_reordering qhd im cstrs in if Obj.is_block v then let ord = get_boxed_ordinal v in let () = debug (Printf.sprintf "Reifying constructor block of tag %i" ord) in let coqidx = try find_nth_non_constant ord cstrs with Not_found -> ill_formed env sigma ty in let cstr = cstrs.(coqidx) in let coqidx = find_reverse_mapping qhd im coqidx in let ctx = Vars.smash_rel_context (EConstr.to_rel_context sigma cstr.cs_args) in let vargs = List.init (List.length ctx) (Obj.field v) in let args' = List.map2 (fun decl v -> let argty = check_reifyable env sigma (EConstr.of_constr (Context.Rel.Declaration.get_type decl)) in aux argty v) (List.rev ctx) vargs in Term.applistc (Constr.mkConstructU ((hd, coqidx + 1), u)) (params @ args') else (* Constant constructor *) let ord = (Obj.magic v : int) in let () = debug (Printf.sprintf "Reifying constant constructor: %i" ord) in let coqidx = try find_nth_constant ord cstrs with Not_found -> ill_formed env sigma ty in let coqidx = find_reverse_mapping qhd im coqidx in let () = debug (Printf.sprintf "Reifying constant constructor: %i is %i in Coq" ord coqidx) in Term.applistc (Constr.mkConstructU ((hd, coqidx + 1), u)) params | IsPrimitive (c, u, _args) -> if Environ.is_array_type env c then CErrors.user_err Pp.(str "Primitive arrays are not supported yet in CertiRocq reification") else if Environ.is_float64_type env c then Constr.mkFloat (Obj.magic v) else if Environ.is_int63_type env c then Constr.mkInt (Obj.magic v) else if Environ.is_string_type env c then Constr.mkString (Obj.magic v) else CErrors.user_err Pp.(str "Unsupported primitive type in CertiRocq reification") in aux ty v
let reify opts env sigma tyinfo result = if opts.time then time ~msg:(Pp.str "Reification") (fun () -> reify opts.inductives_mapping env sigma tyinfo result) else reify opts.inductives_mapping env sigma tyinfo result
let template name = Printf.sprintf "\nvalue %s ()\n { struct thread_info* tinfo = make_tinfo(); return %s_body(tinfo); }\n" name name let template_header name = Printf.sprintf "#include <gc_stack.h>\nextern value %s ();\n" name
let write_c_driver opts name = let fname = make_fname opts (opts.filename ^ ".c") in let fhname = make_fname opts (opts.filename ^ ".h") in let fd = Unix.(openfile fname [O_CREAT; O_APPEND; O_WRONLY] 0o640) in let chan = Unix.out_channel_of_descr fd in output_string chan (template name); flush chan; close_out chan; let chan = open_out fhname in output_string chan (template_header name); flush chan; close_out chan; fname
let template_ocaml id filename name = Printf.sprintf "external %s : unit -> Obj.t = \"%s\"\nlet _ = Certirocq_plugin.Certirocq.register_certirocq_run \"%s\" \"%s\" (Obj.magic %s)" name name id filename name
let write_ocaml_driver id opts name = let fname = make_fname opts (opts.filename ^ "_wrapper.ml") in let chan = open_out fname in output_string chan (template_ocaml id opts.filename name); flush chan; close_out chan; fname
let c_flags = "-O2 -fomit-frame-pointer -g"
let certirocq_eval_named ~opaque_access opts env sigma c global_id imports = let prog = quote_term ~opaque_access opts env sigma c in let tyinfo = let ty = Retyping.get_type_of env sigma c in (* assert (Evd.is_empty sigma); *) check_reifyable env sigma ty in let id = opts.toplevel_name in let () = compile { opts with toplevel_name = id ^ "_body" } (Obj.magic prog) imports in (* Write wrapping code *) let c_driver = write_c_driver opts id in let ocaml_driver = write_ocaml_driver global_id opts id in let imports = get_global_includes () @ imports in let debug = opts.debug in let suff = opts.ext in let compiler = compiler_executable debug in let ocamlfind = ocamlfind_executable debug in let rt_dir = runtime_dir () in let cmd = Printf.sprintf "%s -fPIC -Wno-everything %s -I %s -I %s -c -o %s %s" compiler c_flags opts.build_dir (Boot.Env.Path.to_string rt_dir) (Filename.remove_extension c_driver ^ ".o") c_driver in let importso = let oname s = assert (CString.is_suffix ".h" s); String.sub s 0 (String.length s - 2) ^ ".o" in let imports' = List.concat (List.map (fun i -> match i with | FromAbsolutePath s -> [oname s] | FromRelativePath s -> [oname s] | Link s -> ["-cclib"; "-l" ^ s] | LibraryPath s -> ["-cclib"; "-L"; "-cclib"; s] | FromLibrary (_, Some s) -> [make_rt_file (oname s)] | FromLibrary (s, None) -> [make_rt_file (oname s)]) imports) in let l = imports' in String.concat " " l in let gc_stack_o = make_rt_file "gc_stack.o" in debug_msg debug (Printf.sprintf "Executing command: %s" cmd); let packages = ["rocq-runtime"; "rocq-runtime.plugins.ltac"; "rocq-metarocq-template-ocaml"; "rocq-runtime.interp"; "rocq-runtime.kernel"; "rocq-runtime.library"; "rocq-certirocq.plugin"] in let pkgs = String.concat "," packages in let dontlink = "str,unix,dynlink,threads,zarith,rocq-runtime,rocq-runtime.plugins.ltac,rocq-runtime.interp,rocq-certirocq.plugin" in let () = ignore (execute cmd) in let shared_lib = make_fname opts opts.filename ^ suff ^ ".cmxs" in let linkcmd = Printf.sprintf "%s ocamlopt -shared -linkpkg -dontlink %s -thread -rectypes -package %s \ -I %s -package rocq-certirocq -o %s %s %s %s %s" ocamlfind dontlink pkgs opts.build_dir shared_lib ocaml_driver gc_stack_o (make_fname opts opts.filename ^ ".o") importso in debug_msg debug (Printf.sprintf "Executing command: %s" linkcmd); let _out, _err = execute linkcmd in Dynlink.loadfile_private shared_lib; debug_msg debug (Printf.sprintf "Dynamic linking succeeded, retrieving function %s" global_id); let result = if opts.time then time ~msg:(Pp.str id) (run_certirocq_run global_id) else run_certirocq_run global_id () in debug_msg debug (Printf.sprintf "Running the dynamic linked program succeeded, reifying result"); reify opts env sigma tyinfo result
let next_string_away_from s bad = let rec name_rec s = if bad s then name_rec (increment_subscript s) else s in name_rec s
let find_fresh s map = next_string_away_from s (fun s -> CString.Set.mem s map)
let toplevel_name_of_filename s = let comps = CString.split_on_char '.' s in CString.uncapitalize_ascii (CString.concat "_" comps)
let certirocq_eval ~opaque_access opts env sigma c imports = let global_id = opts.filename in let fresh_name = find_fresh global_id !all_run_functions in let opts = { opts with toplevel_name = toplevel_name_of_filename fresh_name; filename = fresh_name } in certirocq_eval_named ~opaque_access opts env sigma c global_id imports
let run_existing opts env sigma c id run = let tyinfo = let ty = Retyping.get_type_of env sigma c in check_reifyable env sigma ty in let result = if opts.time then time ~msg:Pp.(str"Running " ++ id) run else run () in debug_msg opts.debug (Printf.sprintf "Running the dynamic linked program succeeded, reifying result"); reify opts env sigma tyinfo result
let eval ~opaque_access opts env sigma c imports = match exists_certirocq_run opts.filename with | None -> certirocq_eval ~opaque_access opts env sigma c imports | Some run -> debug_msg opts.debug (Printf.sprintf "Retrieved earlier compiled code for %s" opts.filename); run_existing opts env sigma c (Pp.str opts.filename) run
let eval_gr ~opaque_access opts gr imports = let env = Global.env () in let sigma = Evd.from_env env in let sigma, c = Evd.fresh_global env sigma gr in let filename = get_name gr in let name = toplevel_name_of_filename filename in let opts = { opts with toplevel_name = name; filename = filename } in eval ~opaque_access opts env sigma c imports
let print_to_file (s : string) (file : string) = let f = open_out file in Printf.fprintf f "%s\n" s; close_out f
let show_ir ~opaque_access opts gr = let term = quote ~opaque_access opts gr in let debug = opts.debug in let options = make_pipeline_options opts in let p = Pipeline.show_IR options (Obj.magic term) in match p with | (CompM.Ret prg, dbg) -> debug_msg debug "Finished compiling, printing to file."; let time = Unix.gettimeofday() in let suff = opts.ext in let fname = make_fname opts opts.filename in let file = fname ^ suff ^ ".ir" in print_to_file (string_of_bytestring prg) file; let time = (Unix.gettimeofday() -. time) in debug_msg debug (Printf.sprintf "Printed to file %s in %f s.." file time); debug_msg debug "Pipeline debug:"; debug_msg debug (string_of_bytestring dbg) | (CompM.Err s, dbg) -> debug_msg debug "Pipeline debug:"; debug_msg debug (string_of_bytestring dbg); CErrors.user_err Pp.(str "Could not compile: " ++ (pr_string s) ++ str "\n")
let print_to_file_no_nl (s : string) (file : string) = let f = open_out file in Printf.fprintf f "%s" s; close_out f
let compile_wasm ~opaque_access opts gr = let term = quote ~opaque_access opts gr in let debug = opts.debug in let options = make_pipeline_options opts in let p = Pipeline.compile_Wasm options (Obj.magic term) in match p with | (CompM.Ret prg, dbg) -> debug_msg debug "Finished compiling, printing to file."; let time = Unix.gettimeofday() in let suff = opts.ext in let fname = opts.filename in let file = fname ^ suff ^ ".wasm" in print_to_file_no_nl (string_of_bytestring prg) file; let time = (Unix.gettimeofday() -. time) in debug_msg debug (Printf.sprintf "Printed to file %s in %f s.." file time); debug_msg debug "Pipeline debug:"; debug_msg debug (string_of_bytestring dbg) | (CompM.Err s, dbg) -> debug_msg debug "Pipeline debug:"; debug_msg debug (string_of_bytestring dbg); CErrors.user_err Pp.(str "compile_wasm" ++ (str "Could not compile: " ++ (pr_string s) ++ str "\n"))
(* Quote Coq inductive type *) let quote_ind ~opaque_access opts gr : Metarocq_template_plugin.Ast_quoter.quoted_program * string = let debug = opts.debug in let env = Global.env () in let sigma = Evd.from_env env in let sigma, c = Evd.fresh_global env sigma gr in let name = match gr with | Names.GlobRef.IndRef i -> let (mut, _) = i in Names.KerName.to_string (Names.MutInd.canonical mut) | _ -> CErrors.user_err Pp.(Printer.pr_global gr ++ str " is not an inductive type") in debug_msg debug "Quoting"; let time = Unix.gettimeofday() in let term = quote_term_rec ~bypass:true ~opaque_access env sigma (EConstr.to_constr sigma c) in let time = (Unix.gettimeofday() -. time) in debug_msg debug (Printf.sprintf "Finished quoting in %f s.." time); (term, name)
let glue_command ~opaque_access opts grs = let terms = grs |> List.rev |> List.map (fun gr -> Metarocq_template_plugin.Ast0.Env.declarations (fst (quote ~opaque_access opts gr))) |> List.concat |> nub in generate_glue true opts (Obj.magic terms)
end
module MLCompile = CompileFunctor (MLCompiler)include MLCompile