Debian Codegraph @

pretyping/nativenorm.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10 open CErrors
11 open Term
12 open Constr
13 open Context
14 open Vars
15 open Environ
16 open Reduction
17 open Declarations
18 open Names
19 open Inductive
20 open Util
21 open Nativecode
22 open Values
23 open Nativevalues
24 open Context.Rel.Declaration
25
26 (** This module implements normalization by evaluation to OCaml code *)
27
28 exception Find_at of int
29
30 (* timing *)
31
32 let { Goptions.get = get_timing_enabled } =
33 Goptions.declare_bool_option_and_ref
34 ~key:["NativeCompute"; "Timing"]
35 ~value:false
36 ()
37
38 (* profiling *)
39
40 let { Goptions.get = get_profiling_enabled } =
41 Goptions.declare_bool_option_and_ref
42 ~key:["NativeCompute"; "Profiling"]
43 ~value:false
44 ()
45
46 (* for supported platforms, filename for profiler results *)
47
48 let profiler_platform () =
49 match [@warning "-8"] Sys.os_type with
50 | "Unix" ->
51 let in_ch = Unix.open_process_in "uname" in
52 let uname = input_line in_ch in
53 let _ = close_in in_ch in
54 Format.sprintf "Unix (%s)" uname
55 | "Win32" -> "Windows (Win32)"
56 | "Cygwin" -> "Windows (Cygwin)"
57
58 let { Goptions.get = get_profile_filename } =
59 Goptions.declare_string_option_and_ref
60 ~key:["NativeCompute"; "Profile"; "Filename"]
61 ~value:"native_compute_profile.data"
62 ()
63
64 (* find unused profile filename *)
65 let get_available_profile_filename () =
66 let profile_filename = get_profile_filename () in
67 let dir = Filename.dirname profile_filename in
68 let base = Filename.basename profile_filename in
69 let name = Filename.remove_extension base in
70 let ext = Filename.extension base in
71 try
72 (* unlikely race: fn deleted, another process uses fn *)
73 Filename.temp_file ~temp_dir:dir (name ^ "_") ext
74 with Sys_error s ->
75 let msg = "When trying to find native_compute profile output file: " ^ s in
76 let _ = Feedback.msg_info (Pp.str msg) in
77 assert false
78
79 let invert_tag cst tag reloc_tbl =
80 try
81 for j = 0 to Array.length reloc_tbl - 1 do
82 let tagj,arity = reloc_tbl.(j) in
83 if Int.equal tag tagj && (cst && Int.equal arity 0 || not(cst || Int.equal arity 0)) then
84 raise (Find_at j)
85 else ()
86 done;raise Not_found
87 with Find_at j -> (j+1)
88
89 let decompose_prod env t =
90 let (name,dom,codom) = destProd (whd_all env t) in
91 let name = map_annot (function
92 | Anonymous -> Name (Id.of_string "x")
93 | na -> na) name
94 in
95 (name,dom,codom)
96
97 let e_whd_all = Reductionops.clos_whd_flags RedFlags.all
98
99 let app_type env sigma c =
100 let t = e_whd_all env sigma c in
101 decompose_app (EConstr.Unsafe.to_constr t)
102
103 let find_rectype_a env sigma c =
104 let (t, l) = app_type env sigma c in
105 match kind t with
106 | Ind ind -> (ind, l)
107 | _ -> raise Not_found
108
109 (* Instantiate inductives and parameters in constructor type *)
110
111 let construct_of_constr_notnative const env tag (ind,u) allargs =
112 let mib,mip = lookup_mind_specif env ind in
113 let nparams = mib.mind_nparams in
114 let params = Array.sub allargs 0 nparams in
115 let i = invert_tag const tag mip.mind_reloc_tbl in
116 let ctyp = Inductiveops.instantiate_constructor_params ((ind,i),u) (mib,mip) (Array.to_list params) in
117 let u = EConstr.Unsafe.to_instance u in
118 let params = Array.map EConstr.Unsafe.to_constr params in
119 (mkApp(mkConstructU((ind,i),u), params), EConstr.Unsafe.to_constr ctyp)
120
121 let construct_of_constr const env sigma tag typ =
122 let typ = Reductionops.clos_whd_flags RedFlags.all env sigma (EConstr.of_constr typ) in
123 let t, l = EConstr.decompose_app sigma typ in
124 match EConstr.kind sigma t with
125 | Ind indu ->
126 construct_of_constr_notnative const env tag indu l
127 | _ ->
128 assert (EConstr.eq_constr sigma t (EConstr.of_constr @@ Typeops.type_of_int env));
129 (mkInt (Uint63.of_int tag), EConstr.Unsafe.to_constr t)
130
131 let construct_of_constr_const env sigma tag typ =
132 fst (construct_of_constr true env sigma tag typ)
133
134 let construct_of_constr_block = construct_of_constr false
135
136 let get_case_annot decls =
137 Array.map_of_list (fun decl -> get_annot decl) (List.rev decls)
138
139 let build_branches_type env sigma mib mip (ind,u) params (pctx, p) =
140 let rtbl = mip.mind_reloc_tbl in
141 let paramsl = Array.map_to_list EConstr.of_constr params in
142 (* [build_one_branch i cty] construit le type de la ieme branche (commence
143 a 0) et les lambda correspondant aux realargs *)
144 let p = it_mkLambda_or_LetIn p pctx in (* TODO: prevent useless cut? *)
145 let build_one_branch i (ctx, _) =
146 let typi = Inductiveops.instantiate_constructor_params ((ind,i+1),u) (mib,mip) paramsl in
147 let decl,indapp = Reductionops.whd_decompose_prod env sigma typi in
148 let decl = List.map EConstr.Unsafe.(fun (na,c) -> to_binder_annot na, to_constr c) decl in
149 let ind,cargs = find_rectype_a env sigma indapp in
150 let nparams = Array.length params in
151 let carity = snd (rtbl.(i)) in
152 let crealargs = Array.sub cargs nparams (Array.length cargs - nparams) in
153 let codom =
154 let ndecl = List.length decl in
155 let papp = mkApp(lift ndecl p,crealargs) in
156 let cstr = ith_constructor_of_inductive (fst ind) (i+1) in
157 let relargs = Array.init carity (fun i -> mkRel (carity-i)) in
158 let params = Array.map (lift ndecl) params in
159 let dep_cstr = mkApp(mkApp(mkConstructU (cstr,snd ind),params),relargs) in
160 mkApp(papp,[|dep_cstr|])
161 in
162 let decl_with_letin = List.firstn mip.mind_consnrealdecls.(i) ctx in
163 let nas = get_case_annot decl_with_letin in
164 let rec get_lift decls = match decls with
165 | [] -> Esubst.el_id
166 | LocalDef _ :: decls -> Esubst.el_shft 1 (get_lift decls)
167 | LocalAssum _ :: decls -> Esubst.el_lift (get_lift decls)
168 in
169 decl, nas, get_lift decl_with_letin, codom
170 in
171 Array.mapi build_one_branch mip.mind_nf_lc
172
173 let build_case_type (pctx, p) realargs c =
174 let p = it_mkLambda_or_LetIn p pctx in (* TODO: prevent useless cut? *)
175 mkApp(mkApp(p, realargs), [|c|])
176
177 (* normalisation of values *)
178
179 let branch_of_switch lvl ans bs =
180 let tbl = ans.asw_reloc in
181 let branch i =
182 let tag,arity = tbl.(i) in
183 let ci =
184 if Int.equal arity 0 then mk_const tag
185 else mk_block tag (mk_rels_accu lvl arity) in
186 apply bs ci in
187 Array.init (Array.length tbl) branch
188
189 let get_proj env (ind, proj_arg) =
190 let p, r = Environ.get_projection env ind ~proj_arg in
191 Projection.make p true, r
192
193 let rec nf_val env sigma v typ =
194 match kind_of_value v with
195 | Vaccu accu -> nf_accu env sigma accu
196 | Vprod (na, dom, codom) -> fst @@ nf_prod env sigma (na, dom, codom)
197 | Vfix e | Vcofix e -> Empty.abort e
198 | Vfun f ->
199 let lvl = nb_rel env in
200 let name,dom,codom =
201 try decompose_prod env typ
202 with DestKO ->
203 CErrors.anomaly
204 (Pp.strbrk "Returned a functional value in a type not recognized as a product type.")
205 in
206 let env = push_rel (LocalAssum (name,dom)) env in
207 let body = nf_val env sigma (f (mk_rel_accu lvl)) codom in
208 mkLambda(name,dom,body)
209 | Vconst n -> construct_of_constr_const env sigma n typ
210 | Vint64 i -> i |> Uint63.of_int64 |> mkInt
211 | Vfloat64 f -> f |> Float64.of_float |> mkFloat
212 | Vstring s -> s |> mkString
213 | Varray t -> nf_array env sigma t typ
214 | Vblock b ->
215 let capp,ctyp = construct_of_constr_block env sigma (block_tag b) typ in
216 let args = nf_bargs env sigma b ctyp in
217 mkApp(capp,args)
218
219 and nf_type env sigma v =
220 match kind_of_value v with
221 | Vaccu accu -> nf_accu env sigma accu
222 | Vprod (na, dom, codom) -> fst @@ nf_prod env sigma (na, dom, codom)
223 | _ -> assert false
224
225 and nf_type_sort env sigma v =
226 match kind_of_value v with
227 | Vaccu accu ->
228 let t,s = nf_accu_type env sigma accu in
229 let s =
230 try
231 destSort (whd_all env s)
232 with DestKO ->
233 CErrors.anomaly (Pp.str "Value should be a sort")
234 in
235 t, s
236 | Vprod (na, dom, codom) -> nf_prod env sigma (na, dom, codom)
237 | _ -> assert false
238
239 and nf_accu env sigma accu =
240 let atom = atom_of_accu accu in
241 if Int.equal (accu_nargs accu) 0 then nf_atom env sigma atom
242 else
243 let a,typ = nf_atom_type env sigma atom in
244 let _, args = nf_args env sigma (args_of_accu accu) typ in
245 mkApp(a,Array.of_list args)
246
247 and nf_accu_type env sigma accu =
248 let atom = atom_of_accu accu in
249 if Int.equal (accu_nargs accu) 0 then nf_atom_type env sigma atom
250 else
251 let a,typ = nf_atom_type env sigma atom in
252 let t, args = nf_args env sigma (args_of_accu accu) typ in
253 mkApp(a,Array.of_list args), t
254
255 and nf_args env sigma args t =
256 let aux arg (t,l) =
257 let _,dom,codom =
258 try decompose_prod env t with
259 DestKO ->
260 CErrors.anomaly
261 (Pp.strbrk "Returned a functional value in a type not recognized as a product type.")
262 in
263 let c = nf_val env sigma arg dom in
264 (subst1 c codom, c::l)
265 in
266 let t,l = List.fold_right aux args (t,[]) in
267 t, List.rev l
268
269 and nf_bargs env sigma b t =
270 let t = ref t in
271 let len = block_size b in
272 Array.init len
273 (fun i ->
274 let _,dom,codom =
275 try decompose_prod env !t with
276 DestKO ->
277 CErrors.anomaly
278 (Pp.strbrk "Returned a functional value in a type not recognized as a product type.")
279 in
280 let c = nf_val env sigma (block_field b i) dom in
281 t := subst1 c codom; c)
282
283 and nf_prod env sigma (na, dom, codom) =
284 let dom, sdom = nf_type_sort env sigma dom in
285 let rdom = Sorts.relevance_of_sort sdom in
286 let na = make_annot na rdom in
287 let vn = mk_rel_accu (nb_rel env) in
288 let env = push_rel (LocalAssum (na, dom)) env in
289 let codom, scodom = nf_type_sort env sigma (apply codom vn) in
290 mkProd (na, dom, codom), Typeops.sort_of_product env sdom scodom
291
292 and nf_atom env sigma atom =
293 match atom with
294 | Arel i -> mkRel (nb_rel env - i)
295 | Aconstant cst -> mkConstU cst
296 | Aind ind -> mkIndU ind
297 | Asort s -> mkSort s
298 | Avar id -> mkVar id
299 | Aproj (p, c) ->
300 let c, cty = nf_accu_type env sigma c in
301 let p, r = get_proj env p in
302 let (_, u), _ = find_rectype_a env sigma (EConstr.of_constr cty) in
303 let r = UVars.subst_instance_relevance u r in
304 mkProj(p, r, c)
305 | _ -> fst (nf_atom_type env sigma atom)
306
307 and nf_atom_type env sigma atom =
308 match atom with
309 | Arel i ->
310 let n = (nb_rel env - i) in
311 mkRel n, Typeops.type_of_relative env n
312 | Aconstant cst ->
313 mkConstU cst, Typeops.type_of_constant_in env cst
314 | Aind ind ->
315 mkIndU ind, EConstr.Unsafe.to_constr @@ Inductiveops.type_of_inductive env (on_snd EConstr.EInstance.make ind)
316 | Asort s ->
317 mkSort s, Typeops.type_of_sort s
318 | Avar id ->
319 mkVar id, Typeops.type_of_variable env id
320 | Acase(ans,accu,p,bs) ->
321 let a,ta = nf_accu_type env sigma accu in
322 let ((mind, _ as ind), u),allargs = find_rectype_a env sigma (EConstr.of_constr ta) in
323 let (mib,mip) = Inductive.lookup_mind_specif env ind in
324 let nparams = mib.mind_nparams in
325 let params,realargs = Array.chop nparams allargs in
326 let pctx =
327 let realdecls, _ = List.chop mip.mind_nrealdecls mip.mind_arity_ctxt in
328 let nas = List.rev_map get_annot realdecls @ [nameR (Id.of_string "c")] in
329 expand_arity (mib, mip) (ind, u) params (Array.of_list nas)
330 in
331 let p, relevance = nf_predicate env sigma ind mip params p pctx in
332 (* Calcul du type des branches *)
333 let btypes = build_branches_type env sigma mib mip (ind, EConstr.EInstance.make u) params (pctx, p) in
334 (* calcul des branches *)
335 let bsw = branch_of_switch (nb_rel env) ans bs in
336 let mkbranch i v =
337 let decl, nas, lft, codom = btypes.(i) in
338 let b = nf_val (Termops.push_rels_assum decl env) sigma v codom in
339 nas, exliftn lft b
340 in
341 let branchs = Array.mapi mkbranch bsw in
342 let tcase = build_case_type (pctx, p) realargs a in
343 let p = (get_case_annot pctx, p) in
344 let ci = Inductiveops.make_case_info env ind RegularStyle in
345 let iv = if Inductiveops.Internal.should_invert_case env sigma relevance ci then
346 CaseInvert {indices=realargs}
347 else NoInvert
348 in
349 mkCase (ci, u, params, (p,relevance), iv, a, branchs), tcase
350 | Afix(tt,ft,rp,s) ->
351 let tt = Array.map (fun t -> nf_type_sort env sigma t) tt in
352 let tt = Array.map fst tt and rt = Array.map snd tt in
353 let name = Name (Id.of_string "Ffix") in
354 let names = Array.map (fun s -> make_annot name (Sorts.relevance_of_sort s)) rt in
355 let lvl = nb_rel env in
356 let nbfix = Array.length ft in
357 let fargs = mk_rels_accu lvl (Array.length ft) in
358 (* Body argument of the tuple is ignored by push_rec_types *)
359 let env = push_rec_types (names,tt,[||]) env in
360 (* We lift here because the types of arguments (in tt) will be evaluated
361 in an environment where the fixpoints have been pushed *)
362 let norm_body i v = nf_val env sigma (napply v fargs) (lift nbfix tt.(i)) in
363 let ft = Array.mapi norm_body ft in
364 mkFix((rp,s),(names,tt,ft)), tt.(s)
365 | Acofix (tt, ft, s, args, _) ->
366 let tt = Array.map (fun t -> nf_type_sort env sigma t) tt in
367 let tt = Array.map fst tt and rt = Array.map snd tt in
368 let name = Name (Id.of_string "Fcofix") in
369 let lvl = nb_rel env in
370 let names = Array.map (fun s -> make_annot name (Sorts.relevance_of_sort s)) rt in
371 let fargs = mk_rels_accu lvl (Array.length ft) in
372 let _, args = nf_args env sigma (Array.rev_to_list args) tt.(s) in
373 let env = push_rec_types (names,tt,[||]) env in
374 let ft = Array.mapi (fun i v -> nf_val env sigma (napply v fargs) tt.(i)) ft in
375 mkApp (mkCoFix(s,(names,tt,ft)), Array.of_list args), tt.(s)
376 | Aevar(evk,args) ->
377 nf_evar env sigma evk args
378 | Aproj(p,c) ->
379 let c,tc = nf_accu_type env sigma c in
380 let cj = make_judge c tc in
381 let p, _ = get_proj env p in
382 let r, ty = Typeops.type_of_projection env p cj.uj_val cj.uj_type in
383 mkProj (p, r, cj.uj_val), ty
384
385
386 and nf_predicate env sigma ind mip params v pctx =
387 let fold decl (k, v) = match decl with
388 | LocalDef _ -> (k + 1, v)
389 | LocalAssum _ ->
390 match kind_of_value v with
391 | Vfun f -> (k + 1, f (mk_rel_accu k))
392 | _ -> assert false
393 in
394 let (_, v) = List.fold_right fold pctx (nb_rel env, v) in
395 let env = push_rel_context pctx env in
396 let body = nf_type env sigma v in
397 let rel = Retyping.relevance_of_type env sigma (EConstr.of_constr body) in
398 body, EConstr.Unsafe.to_relevance rel
399
400 and nf_evar env sigma evk args =
401 let evi = try Evd.find_undefined sigma evk with Not_found -> assert false in
402 let hyps = EConstr.named_context_of_val (Evd.evar_filtered_hyps evi) in
403 if List.is_empty hyps then begin
404 assert (Array.is_empty args);
405 let ty = EConstr.to_constr ~abort_on_undefined_evars:false sigma @@ Evd.evar_concl evi in
406 mkEvar (evk, SList.empty), ty
407 end
408 else
409 (* Let-bound arguments are present in the evar arguments but not
410 in the type, so we turn the let into a product. *)
411 let ty = Evd.evar_concl evi in
412 let hyps = Context.Named.drop_bodies hyps in
413 let fold accu d = EConstr.mkNamedProd_or_LetIn sigma d accu in
414 let t = List.fold_left fold ty hyps in
415 let t = EConstr.to_constr ~abort_on_undefined_evars:false sigma t in
416 let ty, args = nf_args env sigma (Array.to_list args) t in
417 (* nf_args takes arguments in the reverse order but produces them
418 in the correct one, so we have to reverse them again for the
419 evar node *)
420 EConstr.(Unsafe.to_constr @@ mkLEvar sigma (evk, List.rev_map of_constr args)), ty
421
422 and nf_array env sigma t typ =
423 let ty, allargs = app_type env sigma (EConstr.of_constr typ) in
424 let typ_elem = allargs.(0) in
425 let vdef = Parray.default t in
426 (* Do not cast into an array out of fear that floats may sneak in *)
427 let init i = nf_val env sigma (Parray.get t (Uint63.of_int i)) typ_elem in
428 let t = Array.init (Parray.length_int t) init in
429 let u = snd (destConst ty) in
430 mkArray(u, t, nf_val env sigma vdef typ_elem, typ_elem)
431
432 let evars_of_evar_map sigma =
433 { Genlambda.evars_val = Evd.evar_handler sigma }
434
435 (* fork perf process, return profiler's process id *)
436 let start_profiler_linux profile_fn =
437 let rocq_pid = Unix.getpid () in (* pass pid of running coqtop *)
438 (* we don't want to see perf's console output *)
439 let dev_null = Unix.descr_of_out_channel (open_out_bin "/dev/null") in
440 let _ = Feedback.msg_info (Pp.str ("Profiling to file " ^ profile_fn)) in
441 let perf = "perf" in
442 let profiler_pid =
443 Unix.create_process
444 perf
445 [|perf; "record"; "-g"; "-o"; profile_fn; "-p"; string_of_int rocq_pid |]
446 Unix.stdin dev_null dev_null
447 in
448 (* doesn't seem to be a way to test whether process creation succeeded
449 (create_process doesn't raise until OCaml 4.12.0) *)
450 debug_native_compiler (fun () ->
451 Pp.str (Format.sprintf "Native compute profiler started, pid = %d, output to: %s" profiler_pid profile_fn));
452 Some profiler_pid
453
454 let start_profiler_linux fn =
455 try start_profiler_linux fn
456 with Unix.Unix_error _ as e ->
457 Feedback.msg_info
458 Pp.(str "Could not start native code profiler: " ++ str (Printexc.to_string e));
459 None
460
461 (* kill profiler via SIGINT *)
462 let stop_profiler_linux m_pid =
463 match m_pid with
464 | Some pid -> (
465 let _ = debug_native_compiler (fun () -> Pp.str "Stopping native code profiler") in
466 try
467 Unix.kill pid Sys.sigint;
468 let _ = Unix.waitpid [] pid in ()
469 with Unix.Unix_error (Unix.ESRCH,"kill","") ->
470 Feedback.msg_info (Pp.str "Could not stop native code profiler, no such process")
471 )
472 | None -> ()
473
474 let start_profiler () =
475 let profile_fn = get_available_profile_filename () in
476 match profiler_platform () with
477 "Unix (Linux)" -> start_profiler_linux profile_fn
478 | _ ->
479 let _ = Feedback.msg_info
480 (Pp.str (Format.sprintf "Native_compute profiling not supported on the platform: %s"
481 (profiler_platform ()))) in
482 None
483
484 let stop_profiler m_pid =
485 match profiler_platform() with
486 "Unix (Linux)" -> stop_profiler_linux m_pid
487 | _ -> ()
488
489 let native_norm env sigma c ty =
490 Nativelib.link_libraries ();
491 let c = EConstr.Unsafe.to_constr c in
492 let ty = EConstr.Unsafe.to_constr ty in
493 let profile = get_profiling_enabled () in
494 let print_timing = get_timing_enabled () in
495 let ml_filename, prefix = Nativelib.get_ml_filename () in
496 let tnc0 = Unix.gettimeofday () in
497 let code, symbols, upd = mk_norm_code env (evars_of_evar_map sigma) prefix c in
498 let tnc1 = Unix.gettimeofday () in
499 let time_info = Format.sprintf "native_compute: Conversion to native code done in %.5f" (tnc1 -. tnc0) in
500 if print_timing then Feedback.msg_info (Pp.str time_info);
501 let tc0 = Unix.gettimeofday () in
502 let fn = Nativelib.compile ml_filename code ~profile:profile in
503 let tc1 = Unix.gettimeofday () in
504 let time_info = Format.sprintf "native_compute: Compilation done in %.5f" (tc1 -. tc0) in
505 if print_timing then Feedback.msg_info (Pp.str time_info);
506 let profiler_pid = if profile then start_profiler () else None in
507 let t0 = Unix.gettimeofday () in
508 let (rt1, _) = Nativelib.execute_library ~prefix fn symbols upd in
509 let rt1 = Option.get rt1 in
510 let t1 = Unix.gettimeofday () in
511 if profile then stop_profiler profiler_pid;
512 let time_info = Format.sprintf "native_compute: Evaluation done in %.5f" (t1 -. t0) in
513 if print_timing then Feedback.msg_info (Pp.str time_info);
514 let res = nf_val env sigma rt1 ty in
515 let t2 = Unix.gettimeofday () in
516 let time_info = Format.sprintf "native_compute: Reification done in %.5f" (t2 -. t1) in
517 if print_timing then Feedback.msg_info (Pp.str time_info);
518 EConstr.of_constr res
519
520 let native_norm env sigma c ty =
521 if not (Environ.typing_flags env).enable_native_compiler then
522 user_err Pp.(str "Native_compute reduction has been disabled.");
523 native_norm env sigma c ty