source: src/Clight/toCminor.ma @ 2896

Last change on this file since 2896 was 2877, checked in by garnier, 7 years ago

Correction of a bug in my former bug correction.

File size: 78.9 KB
Line 
1include "Clight/ClassifyOp.ma".
2include "basics/lists/list.ma".
3include "Clight/fresh.ma".
4
5(* Identify local variables that must be allocated memory. *)
6(* These are the variables whose addresses are taken. *)
7let rec gather_mem_vars_expr (e:expr) : identifier_set SymbolTag ≝
8match e with
9[ Expr ed ty ⇒
10    match ed with
11    [ Ederef e1 ⇒ gather_mem_vars_expr e1
12    | Eaddrof e1 ⇒ gather_mem_vars_addr e1
13    | Eunop _ e1 ⇒ gather_mem_vars_expr e1
14    | Ebinop _ e1 e2 ⇒ gather_mem_vars_expr e1 ∪
15                       gather_mem_vars_expr e2
16    | Ecast _ e1 ⇒ gather_mem_vars_expr e1
17    | Econdition e1 e2 e3 ⇒ gather_mem_vars_expr e1 ∪
18                            gather_mem_vars_expr e2 ∪
19                            gather_mem_vars_expr e3
20    | Eandbool e1 e2 ⇒ gather_mem_vars_expr e1 ∪
21                       gather_mem_vars_expr e2
22    | Eorbool e1 e2 ⇒ gather_mem_vars_expr e1 ∪
23                      gather_mem_vars_expr e2
24    | Efield e1 _ ⇒ gather_mem_vars_expr e1
25    | Ecost _ e1 ⇒ gather_mem_vars_expr e1
26    | _ ⇒ ∅
27    ]
28]
29and gather_mem_vars_addr (e:expr) : identifier_set SymbolTag ≝
30match e with
31[ Expr ed ty ⇒
32    match ed with
33    [ Evar x ⇒ { (x) }
34    | Ederef e1 ⇒ gather_mem_vars_expr e1
35    | Efield e1 _ ⇒ gather_mem_vars_addr e1
36    | _ ⇒ ∅ (* not an lvalue *)
37    ]
38].
39
40let rec gather_mem_vars_stmt (s:statement) : identifier_set SymbolTag ≝
41match s with
42[ Sskip ⇒ ∅
43| Sassign e1 e2 ⇒ gather_mem_vars_expr e1 ∪
44                  gather_mem_vars_expr e2
45| Scall oe1 e2 es ⇒ match oe1 with [ None ⇒ ∅ | Some e1 ⇒ gather_mem_vars_expr e1 ] ∪
46                    gather_mem_vars_expr e2 ∪
47                    (foldl ?? (λs,e. s ∪ gather_mem_vars_expr e) ∅ es)
48| Ssequence s1 s2 ⇒ gather_mem_vars_stmt s1 ∪
49                    gather_mem_vars_stmt s2
50| Sifthenelse e1 s1 s2 ⇒ gather_mem_vars_expr e1 ∪
51                         gather_mem_vars_stmt s1 ∪
52                         gather_mem_vars_stmt s2
53| Swhile e1 s1 ⇒ gather_mem_vars_expr e1 ∪
54                 gather_mem_vars_stmt s1
55| Sdowhile e1 s1 ⇒ gather_mem_vars_expr e1 ∪
56                   gather_mem_vars_stmt s1
57| Sfor s1 e1 s2 s3 ⇒ gather_mem_vars_stmt s1 ∪
58                     gather_mem_vars_expr e1 ∪
59                     gather_mem_vars_stmt s2 ∪
60                     gather_mem_vars_stmt s3
61| Sbreak ⇒ ∅
62| Scontinue ⇒ ∅
63| Sreturn oe1 ⇒ match oe1 with [ None ⇒ ∅ | Some e1 ⇒ gather_mem_vars_expr e1 ]
64| Sswitch e1 ls ⇒ gather_mem_vars_expr e1 ∪
65                  gather_mem_vars_ls ls
66| Slabel _ s1 ⇒ gather_mem_vars_stmt s1
67| Sgoto _ ⇒ ∅
68| Scost _ s1 ⇒ gather_mem_vars_stmt s1
69]
70and gather_mem_vars_ls (ls:labeled_statements) on ls : identifier_set SymbolTag ≝
71match ls with
72[ LSdefault s1 ⇒ gather_mem_vars_stmt s1
73| LScase _ _ s1 ls1 ⇒ gather_mem_vars_stmt s1 ∪
74                      gather_mem_vars_ls ls1
75].
76
77(* Defines where a variable should be allocated. *)
78inductive var_type : Type[0] ≝
79| Global : region → var_type  (* A global, allocated statically in a given region (which one ???)  *)
80| Stack  : nat → var_type     (* On the stack, at a given height *)
81| Local  : var_type           (* Locally (hopefully, in a register) *)
82.
83
84(* A map associating each variable identifier to its allocation mode and its type. *)
85definition var_types ≝ identifier_map SymbolTag (var_type × type).
86
87definition lookup' ≝
88λvars:var_types.λid. opt_to_res … [MSG UndeclaredIdentifier; CTX ? id] (lookup ?? vars id).
89
90(* Assert that an identifier is a local variable with the given typ. *)
91definition local_id : var_types → ident → typ → Prop ≝
92λvars,id,t. match lookup' vars id with [ OK vt ⇒ match (\fst vt) with [ Global _ ⇒ False | _ ⇒ t = typ_of_type (\snd vt) ] | _ ⇒ False ].
93
94(* Note that the semantics allows locals to shadow globals.
95   Parameters start out as locals, but get stack allocated if their address
96   is taken.  We will add code to store them if that's the case.
97 *)
98
99(* Some kind of data is never allocated in registers, even if it fits, typically structured data. *)
100definition always_alloc : type → bool ≝
101λt. match t with
102[ Tarray _ _ ⇒ true
103| Tstruct _ _ ⇒ true
104| Tunion _ _ ⇒ true
105| _ ⇒ false
106].
107
108(* This builds a [var_types] map characterizing the allocation mode, of variables,
109 * and it returns a stack usage for the function (in bytes, according to [sizeof]) *)
110definition characterise_vars : list (ident×region×type) → function → var_types × nat ≝
111λglobals, f.
112  (* globals are added into a map, with var_type Global, region π_2(idrt) and type π_3(idrt) *)
113  let m ≝ foldr ?? (λidrt,m. add ?? m (\fst (\fst idrt)) 〈Global (\snd (\fst idrt)), \snd idrt〉) (empty_map ??) globals in
114  (* variables whose addr is taken in the body of the function are gathered in [mem_vars] *)
115  let mem_vars ≝ gather_mem_vars_stmt (fn_body f) in
116  (* iterate on the parameters and local variables of the function, with a tuple (map, stack_high) as an accumulator *)
117  let 〈m,stacksize〉 ≝ foldr ?? (λv,ms.
118    let 〈m,stack_high〉 ≝ ms in
119    let 〈id,ty〉 ≝ v in         
120    let 〈c,stack_high〉 ≝
121      (* if the (local, parameter) variable is of a compound type OR if its adress is taken, we allocate it on the stack. *)
122      if always_alloc ty ∨ id ∈ mem_vars then
123        〈Stack stack_high,stack_high + sizeof ty〉
124      else
125        〈Local, stack_high〉
126    in
127      〈add ?? m id 〈c, ty〉, stack_high〉) 〈m,0〉 (fn_params f @ fn_vars f) in
128  〈m,stacksize〉.
129
130(* A local variable id' status is not modified by the removal of a global variable id : id' is still local *)
131lemma local_id_add_global : ∀vars,id,r,t,id',t'.
132  local_id (add ?? vars id 〈Global r, t〉) id' t' → local_id vars id' t'.
133#var #id #r #t #id' #t'
134whd in ⊢ (% → ?); whd in ⊢ (match % with [ _ ⇒ ? | _ ⇒ ?] → ?);
135cases (identifier_eq ? id id')
136[ #E >E >lookup_add_hit whd in ⊢ (% → ?); *
137| #NE >lookup_add_miss /2/
138] qed.
139
140(* If I add a variable id ≠ id', then id' is still local *)
141lemma local_id_add_miss : ∀vars,id,vt,id',t'.
142  id ≠ id' → local_id (add ?? vars id vt) id' t' → local_id vars id' t'.
143#vars #id #vt #id' #t' #NE
144whd in ⊢ (% → %);
145whd in ⊢ (match % with [ _ ⇒ ? | _ ⇒ ? ] → match % with [ _ ⇒ ? | _ ⇒ ? ]);
146>lookup_add_miss
147[ #H @H | /2/ ]
148qed.
149
150(* After characterise_vars, a variable in the resulting map is either a global or a "local"(register or stack allocated) *)
151lemma characterise_vars_src : ∀gl,f,vars,n.
152  characterise_vars gl f = 〈vars,n〉 →
153  ∀id. present ?? vars id →
154   (∃r,ty. lookup' vars id = OK ? 〈Global r,ty〉 ∧ Exists ? (λx.x = 〈〈id,r〉,ty〉) gl) ∨
155   ∃t.local_id vars id t.
156#globals #f
157whd in ⊢ (∀_.∀_.??%? → ?);
158elim (fn_params f @ fn_vars f)
159[ #vars #n whd in ⊢ (??%? → ?); #E destruct #i #H %1
160  elim globals in H ⊢ %;
161  [ normalize * #H cases (H (refl ??))
162  | * * #id #rg #ty #tl #IH #H
163    cases (identifier_eq ? i id)
164    [ #E <E %{rg} %{ty} % [ whd in ⊢ (??%?); >lookup_add_hit // | %1 // ]
165    | #NE cases (IH ?)
166      [ #rg' * #ty' * #H1 #H2 %{rg'} %{ty'} %
167        [ whd in ⊢ (??%?); >lookup_add_miss  [ @H1 | @NE ]
168        | %2 @H2
169        ]
170      | whd in H ⊢ %; >lookup_add_miss in H; //
171      ]
172    ]
173  ]
174| * #id #ty #tl #IH #vars #n whd in ⊢ (??(match % with [ _ ⇒ ? ])? → ?); #E #i
175  #H >(contract_pair var_types nat ?) in E;
176  whd in ⊢ (??(match ? with [ _ ⇒ (λ_.λ_.%) ])? → ?);
177  cases (always_alloc ty ∨ id ∈ ?) whd in ⊢ (??(match ? with [ _ ⇒ (λ_.λ_.%) ])? → ?);
178  #H' lapply (extract_pair ???????? H') -H' * #m0 * #n0 * #EQ #EQ2
179  cases (identifier_eq ? i id)
180  [ 1,3: #E' <E' in EQ2:%; #EQ2 %2 %{(typ_of_type ty)}
181         destruct (EQ2) whd whd in ⊢ (match % with [_ ⇒ ? | _ ⇒ ?]);
182         >lookup_add_hit @refl
183  | *: #NE cases (IH m0 n0 ? i ?)
184    [ 1,5: * #rg' * #ty' * #H1 #H2 %1 %{rg'} %{ty'} % //
185           destruct (EQ2) whd in ⊢ (??%?); >lookup_add_miss try @NE @H1
186    | 2,6: * #t #H1 %2 %{t} destruct (EQ2) whd whd in ⊢ (match % with [_ ⇒ ?|_ ⇒ ?]);
187           >lookup_add_miss //
188    | 3,7: <EQ @refl
189    | *: destruct (EQ2) whd in H; >lookup_add_miss in H; //
190    ]
191  ]
192] qed.
193
194(* A local variable in a function is either a parameter or a "local" (:=register or stack alloc'd)
195 * variable, with the right type *)
196lemma characterise_vars_all : ∀l,f,vars,n.
197  characterise_vars l f = 〈vars,n〉 →
198  ∀i,t. local_id vars i t →
199        Exists ? (λx.\fst x = i ∧ typ_of_type (\snd x) = t) (fn_params f @ fn_vars f).
200#globals #f
201whd in ⊢ (∀_.∀_.??%? → ?);
202elim (fn_params f @ fn_vars f)
203[ #vars #n whd in ⊢ (??%? → ?); #E destruct #i #t #H @False_ind
204  elim globals in H;
205  [ normalize //
206  | * * #id #rg #t #tl #IH whd in ⊢ (?%?? → ?); #H @IH @(local_id_add_global … H)
207  ]
208| * #id #ty #tl #IH #vars #n whd in ⊢ (??(match % with [ _ ⇒ ? ])? → ?); #E #i #t
209
210  #H >(contract_pair var_types nat ?) in E;
211  whd in ⊢ (??(match ? with [ _ ⇒ (λ_.λ_.%) ])? → ?);
212  cases (always_alloc ty ∨ id ∈ ?) whd in ⊢ (??(match ? with [ _ ⇒ (λ_.λ_.%) ])? → ?);
213  #H' lapply (extract_pair ???????? H') -H' * #m0 * #n0 * #EQ #EQ2
214
215  cases (identifier_eq ? id i)
216  [ 1,3: #E' >E' in EQ2:%; #EQ2 % %
217    [ 1,3: @refl
218    | *: destruct (EQ2) change with (add ?????) in H:(?%??);
219      whd in H; whd in H:(match % with [_ ⇒ ?|_ ⇒ ?]); >lookup_add_hit in H;
220      whd in ⊢ (% → ?); #E'' >E'' @refl
221    ]
222  | *: #NE %2 @(IH m0 n0)
223    [ 1,3: @sym_eq whd in ⊢ (???(match ?????% with [ _ ⇒ ? ])); >contract_pair @EQ
224    | 2,4: destruct (EQ2) @(local_id_add_miss … H) @NE
225    ]
226  ]
227] qed.
228
229(* The map generated by characterise_vars is "correct" wrt the fresh ident generator of tag [u],
230   i.e. by generating fresh idents with u, we risk no collision with the idents in the map domain. *)
231lemma characterise_vars_fresh : ∀gl,f,vars,n,u.
232  characterise_vars gl f = 〈vars,n〉 →              (* If we generate a map ... *)
233  globals_fresh_for_univ ? gl u →                  (* and the globals are out of the idents generated by u *)
234  fn_fresh_for_univ f u →                          (* and the variables of the function f are cool with u too ... *)
235  fresh_map_for_univ … vars u.                     (* then there won't be collisions between the map and idents made from u *)
236#gl #f #vars #n #u #CH #GL #FN
237#id #H
238cases (characterise_vars_src … CH … H)
239[ * #rg * #ty * #H1 #H2
240  cases (Exists_All … H2 GL) * * #id' #rg' #ty' * #E #H destruct //
241| * #t #H lapply (characterise_vars_all … CH id t H) #EX
242  cases (Exists_All … EX FN) * #id' #ty' * * #E1 #E2 #H' -H destruct //
243] qed.
244
245include "Cminor/Cminor_syntax.ma".
246include "common/Errors.ma".
247
248alias id "CMexpr" = "cic:/matita/cerco/Cminor/Cminor_syntax/expr.ind(1,0,0)".
249
250(* type_should_eq enforces that two types are equal and eliminates this equality by
251   transporting P ty1 to P ty2. If ty1 != ty2, then Error *)
252definition type_should_eq : ∀ty1,ty2. ∀P:type → Type[0]. P ty1 → res (P ty2) ≝
253λty1,ty2,P,p.
254  do E ← assert_type_eq ty1 ty2;
255  OK ? (match E return λx.λ_. P ty1 → P x with [ refl ⇒ λp.p ] p).
256 
257(* associated reasoning principle *)
258lemma type_should_eq_inversion :
259  ∀ty1,ty2,P,f,res.
260    type_should_eq ty1 ty2 P f = OK ? res →
261    ty1 = ty2 ∧ f ≃ res.
262#ty1 #ty2 #P #f #res normalize
263cases (type_eq_dec ty1 ty2) normalize nodelta
264[ 2: #Hneq #Habsurd destruct ]
265#Heq #Heq2 @conj try assumption
266destruct (Heq2) cases Heq normalize nodelta
267@eq_to_jmeq @refl
268qed. 
269
270(* same gig for regions *)
271definition region_should_eq : ∀r1,r2. ∀P:region → Type[0]. P r1 → res (P r2).
272* * #P #p try @(OK ? p) @(Error ? (msg TypeMismatch))
273qed.
274
275(* same gig for AST typs *)
276definition typ_should_eq : ∀ty1,ty2. ∀P:typ → Type[0]. P ty1 → res (P ty2) ≝
277λty1,ty2,P,p.
278  match typ_eq ty1 ty2 with
279  [ inl E ⇒ OK ? (p⌈P ty1 ↦ P ty2⌉)
280  | inr _ ⇒ Error ? (msg TypeMismatch)
281  ].
282destruct %
283qed.
284
285(* associated reasoning principle *)
286lemma typ_should_eq_inversion :
287  ∀ty1,ty2,P,a,x.
288    typ_should_eq ty1 ty2 P a = OK ? x →
289    ty1 = ty2 ∧ a ≃ x.
290* [ #sz #sg ] * [ 1,3: #sz2 #sg2 ]
291[ 4: #P #a #x normalize #H destruct (H) @conj try @refl @refl_jmeq
292| 3: cases sz cases sg #P #A #x normalize #H destruct
293| 2: cases sz2 cases sg2 #P #a #x normalize #H destruct ]
294cases sz cases sz2 cases sg cases sg2
295#P #a #x #H normalize in H:(??%?); destruct (H)
296try @conj try @refl try @refl_jmeq
297qed.
298
299alias id "CLunop" = "cic:/matita/cerco/Clight/Csyntax/unary_operation.ind(1,0,0)".
300alias id "CMunop" = "cic:/matita/cerco/common/FrontEndOps/unary_operation.ind(1,0,0)".
301
302(* XXX: For some reason matita refuses to pick the right one unless forced. *)
303alias id "CMnotbool" = "cic:/matita/cerco/common/FrontEndOps/unary_operation.con(0,3,0)".
304
305(* Translates a Clight unary operation into a Cminor one, while checking
306 * that the domain and codomain types are consistent. *)
307definition translate_unop : ∀t,t':typ. CLunop → res (CMunop t t') ≝
308λt,t'.λop:CLunop.
309  match op with
310  [ Onotbool ⇒
311      match t return λt. res (CMunop t t') with
312      [ ASTint sz sg ⇒
313          match t' return λt'. res (CMunop ? t') with
314          [ ASTint sz' sg' ⇒ OK ? (CMnotbool ????)
315          | _ ⇒ Error ? (msg TypeMismatch)
316          ]
317      | ASTptr ⇒
318          match t' return λt'. res (CMunop ? t') with
319          [ ASTint sz' sg' ⇒ OK ? (CMnotbool ????)
320          | _ ⇒ Error ? (msg TypeMismatch)
321          ]
322      | _ ⇒ Error ? (msg TypeMismatch)
323      ]
324  | Onotint ⇒
325      match t' return λt'. res (CMunop t t') with
326      [ ASTint sz sg ⇒ typ_should_eq ?? (λt. CMunop t (ASTint ??)) (Onotint sz sg)
327      | _ ⇒ Error ? (msg TypeMismatch)
328      ]
329  | Oneg ⇒
330      match t' return λt'. res (CMunop t t') with
331      [ ASTint sz sg ⇒ typ_should_eq ?? (λt.CMunop t (ASTint ??)) (Onegint sz sg)
332    (*  | ASTfloat sz ⇒ typ_should_eq ?? (λt.CMunop t (ASTfloat sz)) (Onegf sz) *)
333      | _ ⇒ Error ? (msg TypeMismatch)
334      ]
335  ]. @I qed.
336
337(* Translates a Clight addition into a Cminor one. Four cases to consider :
338  - integer/integer add
339  - fp/fp add
340  - pointer/integer
341  - integer/pointer.
342  Consistency of the type is enforced by explicit checks.
343*)
344
345(* First, how to get rid of a abstract-away pointer or array type *)
346definition fix_ptr_type : ∀ty,n. expr (typ_of_type (ptr_type ty n)) → expr ASTptr ≝
347λty,n,e. e⌈expr (typ_of_type (ptr_type ty n)) ↦ expr ASTptr⌉.
348cases n //
349qed.
350
351definition translate_add ≝
352λty1,ty2,ty'.
353let ty1' ≝ typ_of_type ty1 in
354let ty2' ≝ typ_of_type ty2 in
355match classify_add ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
356[ add_case_ii sz sg ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Oadd ??) e1 e2)
357(* XXX we cast up to I16 Signed to prevent overflow, but often we could use I8 *)
358| add_case_pi n ty sz sg ⇒
359    λe1,e2. typ_should_eq ??? (Op2 ??? (Oaddpi I16) (fix_ptr_type … e1) (Op2 ??? (Omul I16 Signed) (Op1 ?? (Ocastint sz sg I16 Signed) e2) (Cst ? (Ointconst I16 Signed (repr ? (sizeof ty))))))
360| add_case_ip n sz sg ty ⇒
361    λe1,e2. typ_should_eq ??? (Op2 ??? (Oaddip I16) (Op2 ??? (Omul I16 Signed) (Op1 ?? (Ocastint sz sg I16 Signed) e1) (Cst ? (Ointconst I16 Signed (repr ? (sizeof ty))))) (fix_ptr_type … e2))
362| add_default _ _ ⇒ λe1,e2. Error ? (msg TypeMismatch)
363].
364
365
366(* XXX Clight pointer/int subtraction uses neg_shift_pointer_n, which boils down to (sub32 lhs (mul32 (const32 sizeof_ty) (sext32/zext32 rhs))),
367 * whereas Cminor uses neg_shift_pointer, which translates into (sub32 lhs (sext32 rhs)). We have to translate the multiplication as actual
368 * Cminor code, yielding something like (sub32 lhs (sext32 (mulXX (constXX sizeof_ty) (sextXX/zextXX rhs)))). In the original translate_sub,
369 * XX=16, which we can't prove equivalent in general. Moreover, Osubpi expects a /signed/ integer argument, whereas Clight does not care and
370 * casesplits on the sign to select either a zero extension or a sign extension.
371 * λe1,e2. typ_should_eq ??? (Op2 ??? (Osubpi I16) (fix_ptr_type … e1) (Op2 ??? (Omul I16 Signed) (Op1 ?? (Ocastint sz sg I16 Signed) e2) (Cst ? (Ointconst I16 Signed (repr ? (sizeof ty))))))
372      corresponding cl value: Some ? (Vptr (shift_pointer_n ? ptr1 (sizeof ty) sg n2))  =
373      mk_offset (sub32 lhs (mult32 (const32 (sizeof ty)) (sext32/zext32 rhs)))
374
375      cminor
376      mk_offset (sub32 lhs (sext32 ))
377 *)
378definition translate_sub ≝
379λty1,ty2,ty'.
380let ty1' ≝ typ_of_type ty1 in
381let ty2' ≝ typ_of_type ty2 in
382match classify_sub ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
383[ sub_case_ii sz sg ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Osub ??) e1 e2)
384(* XXX could optimise cast as above *)
385| sub_case_pi n ty sz sg ⇒
386    (* XXX This is so ugly. *)
387    λe1,e2. typ_should_eq ??? (Op2 ??? (Osubpi I32) (fix_ptr_type … e1)
388                                                    (Op1 ?? (Ocastint ?? I32 Signed) (Op2 ??? (Omul I16 sg) (Op1 ?? (Ocastint ??? sg) e2)
389                                                                                     (Cst ? (Ointconst I16 sg (repr I16 (sizeof ty)))))))
390(* XXX check in detail? *)
391| sub_case_pp n1 n2 ty1 ty2 ⇒
392    λe1,e2. match ty' return λty'. res (CMexpr (typ_of_type ty')) with
393    [ Tint sz sg ⇒
394      (* XXX we make the constant unsigned to match CL semantics. We also use 32 bits, still for CL semantics. Documented in Csem.ma@sem_sub *)
395      (* OK ? (Op1 ?? (Ocastint I16 Signed sz sg) (Op2 ??? (Odiv I16) (Op2 ??? (Osubpp I16) (fix_ptr_type … e1) (fix_ptr_type ?? e2)) (Cst ? (Ointconst I16 Signed (repr ? (sizeof ty2)))))) *)
396         OK ? (Op1 ?? (Ocastint I32 Unsigned sz sg) (Op2 ??? (Odivu I32) (Op2 ??? (Osubpp I32) (fix_ptr_type … e1) (fix_ptr_type ?? e2)) (Cst ? (Ointconst I32 Unsigned (repr ? (sizeof ty1))))))
397    | _ ⇒ Error ? (msg TypeMismatch)
398    ]
399| sub_default _ _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
400].
401
402definition translate_mul ≝
403λty1,ty2,ty'.
404let ty1' ≝ typ_of_type ty1 in
405let ty2' ≝ typ_of_type ty2 in
406match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
407[ aop_case_ii sz sg ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omul …) e1 e2)
408(* | aop_case_ff sz ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omulf …) e1 e2) *)
409| aop_default _ _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
410].
411
412definition translate_div ≝
413λty1,ty2,ty'.
414let ty1' ≝ typ_of_type ty1 in
415let ty2' ≝ typ_of_type ty2 in
416match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
417[ aop_case_ii sz sg ⇒
418    match sg return λsg. CMexpr (ASTint sz sg) → CMexpr (ASTint sz sg) → res (CMexpr (typ_of_type ty')) with
419    [ Unsigned ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Odivu …) e1 e2)
420    | Signed ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Odiv …) e1 e2)
421    ]
422(* | aop_case_ff sz ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Odivf …) e1 e2) *)
423| aop_default _ _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
424].
425
426definition translate_mod ≝
427λty1,ty2,ty'.
428let ty1' ≝ typ_of_type ty1 in
429let ty2' ≝ typ_of_type ty2 in
430match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
431[ aop_case_ii sz sg ⇒
432    match sg return λsg. CMexpr (ASTint sz sg) → CMexpr (ASTint sz sg) → res (CMexpr (typ_of_type ty')) with
433    [ Unsigned ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omodu …) e1 e2)
434    | Signed ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omod …) e1 e2)
435    ]
436(* no float case *)
437| _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
438].
439
440definition translate_shr ≝
441λty1,ty2,ty'.
442let ty1' ≝ typ_of_type ty1 in
443let ty2' ≝ typ_of_type ty2 in
444match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
445[ aop_case_ii sz sg ⇒
446    match sg return λsg. CMexpr (ASTint sz sg) → CMexpr (ASTint sz sg) → res (CMexpr (typ_of_type ty')) with
447    [ Unsigned ⇒ λe1,e2.  typ_should_eq ??? (Op2 ??? (Oshru …) e1 e2)
448    | Signed ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Oshr …) e1 e2)
449    ]
450(* no float case *)
451| _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
452].
453
454definition complete_cmp : ∀ty'. CMexpr (ASTint I8 Unsigned) → res (CMexpr (typ_of_type ty')) ≝
455λty',e.
456match ty' return λty'. res (CMexpr (typ_of_type ty')) with
457[ Tint sz sg ⇒ OK ? (Op1 ?? (Ocastint I8 Unsigned sz sg) e)
458| _ ⇒ Error ? (msg TypeMismatch)
459].
460 
461definition translate_cmp ≝
462λc,ty1,ty2,ty'.
463let ty1' ≝ typ_of_type ty1 in
464let ty2' ≝ typ_of_type ty2 in
465match classify_cmp ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
466[ cmp_case_ii sz sg ⇒
467    match sg return λsg. CMexpr (ASTint sz sg) → CMexpr (ASTint sz sg) → res (CMexpr (typ_of_type ty')) with
468    [ Unsigned ⇒ λe1,e2. complete_cmp ty' (Op2 ??? (Ocmpu … c) e1 e2)
469    | Signed ⇒ λe1,e2. complete_cmp ty' (Op2 ??? (Ocmp … c) e1 e2)
470    ]
471| cmp_case_pp n ty ⇒
472    λe1,e2. complete_cmp ty' (Op2 ??? (Ocmpp … c) (fix_ptr_type … e1) (fix_ptr_type … e2))
473(* | cmp_case_ff sz ⇒ λe1,e2. complete_cmp ty' (Op2 ??? (Ocmpf … c) e1 e2) *)
474| cmp_default _ _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
475].
476
477definition translate_misc_aop ≝
478λty1,ty2,ty',op.
479let ty1' ≝ typ_of_type ty1 in
480let ty2' ≝ typ_of_type ty2 in
481match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
482[ aop_case_ii sz sg ⇒ λe1,e2. typ_should_eq ??? (Op2 ?? (ASTint sz sg) (op sz sg) e1 e2)
483| _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
484].
485
486definition translate_binop : binary_operation → type → CMexpr ? → type → CMexpr ? → type → res (CMexpr ?) ≝
487λop,ty1,e1,ty2,e2,ty.
488let ty' ≝ typ_of_type ty in
489match op with
490[ Oadd ⇒ translate_add ty1 ty2 ty e1 e2
491| Osub ⇒ translate_sub ty1 ty2 ty e1 e2
492| Omul ⇒ translate_mul ty1 ty2 ty e1 e2
493| Omod ⇒ translate_mod ty1 ty2 ty e1 e2
494| Odiv ⇒ translate_div ty1 ty2 ty e1 e2
495| Oand ⇒ translate_misc_aop ty1 ty2 ty Oand e1 e2
496| Oor  ⇒ translate_misc_aop ty1 ty2 ty Oor e1 e2
497| Oxor ⇒ translate_misc_aop ty1 ty2 ty Oxor e1 e2
498| Oshl ⇒ translate_misc_aop ty1 ty2 ty Oshl e1 e2
499(*| Oshr ⇒ translate_misc_aop ty1 ty2 ty Oshr e1 e2 *)
500| Oshr ⇒ translate_shr ty1 ty2 ty e1 e2  (* split on signed/unsigned *)
501| Oeq ⇒ translate_cmp Ceq ty1 ty2 ty e1 e2
502| One ⇒ translate_cmp Cne ty1 ty2 ty e1 e2
503| Olt ⇒ translate_cmp Clt ty1 ty2 ty e1 e2
504| Ogt ⇒ translate_cmp Cgt ty1 ty2 ty e1 e2
505| Ole ⇒ translate_cmp Cle ty1 ty2 ty e1 e2
506| Oge ⇒ translate_cmp Cge ty1 ty2 ty e1 e2
507].
508
509lemma typ_equals : ∀t1,t2. ∀P:∀t. expr t → Prop. ∀v1,v2.
510  typ_should_eq t1 t2 expr v1 = OK ? v2 →
511  P t1 v1 →
512  P t2 v2.
513#t1 #t2 #P #v1 #v2
514whd in ⊢ (??%? → ?); cases (typ_eq t1 t2)
515[ #E destruct #E whd in E:(??%?); destruct //
516| #NE #E normalize in E; destruct
517] qed.
518
519lemma unfix_ptr_type : ∀ty,n,e.∀P:∀t. expr t → Prop.
520  P (typ_of_type (ptr_type ty n)) e →
521  P ASTptr (fix_ptr_type ty n e).
522#ty * [ 2: #n ] #e #P #H @H
523qed.
524
525(* Recall that [expr_vars], defined in Cminor/Syntax.ma, asserts a predicate on
526  all the variables of a program. [translate_binop_vars], given
527  a predicate verified for all variables of subexprs e1 and e2, produces
528  a proof that all variables of [translate_binop op _ e1 _ e2 _] satisfy this
529  predicate. *)
530
531lemma translate_binop_vars : ∀P,op,ty1,e1,ty2,e2,ty,e.
532  expr_vars ? e1 P →
533  expr_vars ? e2 P →
534  translate_binop op ty1 e1 ty2 e2 ty = OK ? e →
535  expr_vars ? e P.
536#P * #ty1 #e1 #ty2 #e2 #ty #e #H1 #H2
537whd in ⊢ (??%? → ?);
538[ inversion (classify_add ty1 ty2) in ⊢ ?;
539  [ #sz #sg #E1 #E2 #E3 destruct >E3 #E4 -E3 change with (typ_should_eq ???? = OK ??) in E4;
540    @(typ_equals … E4) % //
541(*  | #sz #E1 #E2 #E3 destruct >E3 #E4
542    @(typ_equals … E4) % // *)
543  | #n #ty0 #sz #sg #E1 #E2 #E3 destruct >E3 #E4
544    @(typ_equals … E4) -E4 -E3 % [ @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H1)| % // ]
545  | #n #sz #sg #ty0 #E1 #E2 #E3 destruct >E3 #E4
546    @(typ_equals … E4) % [ 2: @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H2) | 1: % // ]
547  | #ty1' #ty2' #E1 #E2 #E3 destruct >E3 #E4 whd in E4:(??%?); destruct
548  ]
549 
550| inversion (classify_sub ty1 ty2) in ⊢ ?;
551  [ #sz #sg #E1 #E2 #E3 destruct >E3 #E4
552    @(typ_equals … E4) % //
553(*  | #sz #E1 #E2 #E3 destruct >E3 #E4
554    @(typ_equals … E4) % // *)
555  | #n #ty0 #sz #sg #E1 #E2 #E3 destruct >E3 #E4
556    @(typ_equals … E4) % [ @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H1)| % // ]
557  | #n1 #n2 #ty1' #ty2' #E1 #E2 #E3 destruct >E3
558    whd in ⊢ (??%? → ?); cases ty in e ⊢ %;
559    [ 2: #sz #sg #e #E4 | 3: #ty #e #E4 | 4: #ty' #n' #e #E4
560    | *: normalize #X1 #X2 try #X3 try #X4 destruct
561    ] whd in E4:(??%?); destruct % // %
562    [ @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H1) | @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H2) ]
563  | #ty1' #ty2' #E1 #E2 #E3 destruct >E3 #E4 whd in E4:(??%?); destruct
564  ]
565| 3,4,5,6,7,8,9,10: inversion (classify_aop ty1 ty2) in ⊢ ?;
566  (* Note that some cases require a split on signedness of integer type. *)
567  [ 1,3,5,7,9,11,13,15: #sz * #E1 #E2 #E3 destruct >E3 #E4
568    @(typ_equals … E4) % //
569  | 2,4,6,8,10,12,14,16,18: #ty1' #ty2' #E1 #E2 #E3 destruct >E3 #E4 whd in E4:(??%?); destruct
570  ]
571| *: inversion (classify_cmp ty1 ty2) in ⊢ ?;
572  [ 1,4,7,10,13,16: #sz * #E1 #E2 #E3 destruct >E3
573  | 2,5,8,11,14,17: #n #ty' #E1 #E2 #E3 destruct >E3
574  | *: #ty1' #ty2' #E1 #E2 #E3 destruct >E3 #E4 whd in E4:(??%?); @⊥ destruct
575  ] whd in ⊢ (??%? → ?); cases ty in e ⊢ %; normalize nodelta
576  try (normalize #X1 #X2 try #X3 try #X4 try #X5 destruct #FAIL)
577  #sz #sg #e #E4
578  whd in E4:(??%?); destruct % try @H1 try @H2
579  try  @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H1)
580  try  @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H2)
581] qed. 
582
583(* We'll need to implement proper translation of pointers if we really do memory
584   spaces.
585(* This function performs leibniz-style subst if r1 = r2, and fails otherwise. *)
586definition check_region : ∀r1:region. ∀r2:region. ∀P:region → Type[0]. P r1 → res (P r2) ≝
587λr1,r2,P.
588  match r1 return λx.P x → res (P r2) with
589  [ Any ⇒   match r2 return λx.P Any → res (P x) with [ Any ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
590  | Data ⇒  match r2 return λx.P Data → res (P x) with [ Data ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
591  | IData ⇒ match r2 return λx.P IData → res (P x) with [ IData ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
592  | PData ⇒ match r2 return λx.P PData → res (P x) with [ PData ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
593  | XData ⇒ match r2 return λx.P XData → res (P x) with [ XData ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
594  | Code ⇒  match r2 return λx.P Code → res (P x) with [ Code ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
595  ].
596
597(* Simple application of [check_region] to translate between terms. *)
598definition translate_ptr : ∀P,r1,r2. (Σe:CMexpr (ASTptr r1). expr_vars ? e P) → res (Σe':CMexpr (ASTptr r2).expr_vars ? e' P) ≝
599λP,r1,r2,e. check_region r1 r2 (λr.Σe:CMexpr (ASTptr r).expr_vars ? e P) e.
600*)
601
602(* Given a source and target type, translate an expession of type source to type target *)
603definition translate_cast : ∀P. ∀ty1:type.∀ty2:type. (Σe:CMexpr (typ_of_type ty1). expr_vars ? e P) → res (Σe':CMexpr (typ_of_type ty2). expr_vars ? e' P) ≝
604λP,ty1,ty2.
605match ty1 return λx.(Σe:CMexpr (typ_of_type x). expr_vars ? e P) → ? with
606[ Tint sz1 sg1 ⇒ λe.
607    match ty2 return λx.res (Σe':CMexpr (typ_of_type x).expr_vars ? e' P) with
608    [ Tint sz2 sg2 ⇒ OK ? (Op1 ?? (Ocastint ? sg1 sz2 ?) e)
609  (*  | Tfloat sz2 ⇒ OK ? (Op1 ?? (match sg1 with [ Unsigned ⇒ Ofloatofintu ?? | _ ⇒ Ofloatofint ??]) e)*)
610    | Tpointer _ ⇒ OK ? (Op1 ?? (Optrofint ??) e)
611    | Tarray _ _ ⇒ OK ? (Op1 ?? (Optrofint ??) e)
612    | _ ⇒ Error ? (msg TypeMismatch)
613    ]
614(* | Tfloat sz1 ⇒ λe.
615    match ty2 return λx.res (Σe':CMexpr (typ_of_type x).expr_vars ? e' P) with
616    [ Tint sz2 sg2 ⇒ OK ? «Op1 ?? (match sg2 with [ Unsigned ⇒ Ointuoffloat ? sz2 | _ ⇒ Ointoffloat ? sz2 ]) e, ?»
617    | Tfloat sz2 ⇒ Error ? (msg FIXME) (* OK ? «Op1 ?? (Oid ?) e, ?» (* FIXME *) *)
618    | _ ⇒ Error ? (msg TypeMismatch)
619    ] *)
620| Tpointer _ ⇒ λe. (* will need changed for memory regions *)
621    match ty2 return λx.res (Σe':CMexpr (typ_of_type x). expr_vars ? e' P) with
622    [ Tint sz2 sg2 ⇒ OK ? «Op1 ?? (Ointofptr sz2 ?) e, ?»
623    | Tarray _ _ ⇒ (*translate_ptr ? r1 r2 e*) OK ? e
624    | Tpointer _ ⇒ OK ? e
625    | _ ⇒ Error ? (msg TypeMismatch)
626    ]
627| Tarray _ _ ⇒ λe. (* will need changed for memory regions *)
628    match ty2 return λx.res (Σe':CMexpr (typ_of_type x).expr_vars ? e' P) with
629    [ Tint sz2 sg2 ⇒ OK ? «Op1 ASTptr (ASTint sz2 sg2) (Ointofptr sz2 ?) e, ?»
630    | Tarray _ _ ⇒ OK ? e
631    | Tpointer _ ⇒ OK ? e
632    | _ ⇒ Error ? (msg TypeMismatch)
633    ]
634| _ ⇒ λ_. Error ? (msg TypeMismatch)
635]. whd normalize nodelta @pi2
636qed.
637
638definition cm_zero ≝ λsz,sg. Cst ? (Ointconst sz sg (zero ?)).
639definition cm_one  ≝ λsz,sg. Cst ? (Ointconst sz sg (repr sz 1)).
640
641(* Translate Clight exprs into Cminor ones.
642  Arguments :
643  - vars:var_types, an environment mapping each variable to a couple (allocation mode, type)
644  - e:expr, the expression to be converted
645  Result : res (Σe':CMexpr (typ_of_type (typeof e)). expr_vars ? e' (local_id vars))
646  that is, either
647  . an error
648  . an expression e', matching the type of e, such that e' respect the property that all variables
649    in it are not global. In effect, [translate_expr] will replace global variables by constant symbols.
650*)
651let rec translate_expr (vars:var_types) (e:expr) on e : res (Σe':CMexpr (typ_of_type (typeof e)). expr_vars ? e' (local_id vars)) ≝
652match e return λe. res (Σe':CMexpr (typ_of_type (typeof e)). expr_vars ? e' (local_id vars)) with
653[ Expr ed ty ⇒
654  match ed with
655  [ Econst_int sz i ⇒
656      match ty return λty. res (Σe':CMexpr (typ_of_type ty).  expr_vars ? e' (local_id vars)) with
657      [ Tint sz' sg ⇒ intsize_eq_elim' sz sz' (λsz,sz'. res (Σe':CMexpr (typ_of_type (Tint sz' sg)). expr_vars ? e' (local_id vars)))
658                        (OK ? «Cst ? (Ointconst sz sg i), ?»)
659                        (Error ? (msg TypeMismatch))
660      | _ ⇒ Error ? (msg TypeMismatch)
661      ]
662 (* | Econst_float f ⇒
663      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
664      [ Tfloat sz ⇒ OK ? «Cst ? (Ofloatconst sz f), ?»
665      | _ ⇒ Error ? (msg TypeMismatch)
666      ] *)
667  | Evar id ⇒
668      (* E is an equality proof of the shape "lookup' vars id = Ok <c,t>" *) 
669      do 〈c,t〉 as E ← lookup' vars id;
670      match c return λx. (c = x) → res (Σe':CMexpr ?. ?) with
671      [ Global r ⇒ λHeq_c.
672          (* We are accessing a global variable in an expression. Its Cminor counterpart also depends on
673             its access mode:
674             - By_value q, where q is a memory chunk specification (whitch should match the type of the global)
675             - By_reference, and we only take the adress of the variable
676             - By_nothing : error
677           *)
678          match access_mode ty return λt.λ_. res (Σe':CMexpr t. expr_vars ? e' (local_id vars)) with
679          [ By_value t ⇒ OK ? «Mem t (Cst ? (Oaddrsymbol id 0)), ?» (* Mem is "load" in compcert *)
680          | By_reference ⇒ OK ? «Cst ? (Oaddrsymbol id 0), ?»
681          | By_nothing _ ⇒ Error ? [MSG BadlyTypedAccess; CTX ? id]
682          ]
683      | Stack n ⇒ λHeq_c.
684          (* We have decided that the variable should be allocated on the stack,
685           * because its adress was taken somewhere or becauste it's a structured data. *)
686          match access_mode ty return λt.λ_. res (Σe':CMexpr t. expr_vars ? e' (local_id vars)) with
687          [ By_value t ⇒ OK ? «Mem t (Cst ? (Oaddrstack n)), ?»
688          | By_reference ⇒ (*match r return λr. res (Σe':CMexpr (ASTptr r). ?) with
689                             [ Any ⇒*) OK ? «Cst ? (Oaddrstack n), ?» (*
690                             | _ ⇒ Error  ? [MSG BadlyTypedAccess; CTX ? id]
691                             ]*)
692          | By_nothing _ ⇒ Error ? [MSG BadlyTypedAccess; CTX ? id]
693          ]
694          (* This is a local variable. Keep it as an identifier in the Cminor code, ensuring that the type of the original expr and of ty match. *)
695      | Local ⇒ λHeq_c. type_should_eq t ty (λt.Σe':CMexpr (typ_of_type t).expr_vars (typ_of_type t) e' (local_id vars))  («Id (typ_of_type t) id, ?»)
696      ] (refl ? c)
697  | Ederef e1 ⇒
698      do e1' ← translate_expr vars e1;
699      (* According to the way the data pointed to by e1 is accessed, the generated Cminor code will vary.
700        - if e1 is a kind of int* ptr, then we load ("Mem") the ptr returned by e1
701        - if e1 is a struct* or a function ptr, then we acess by reference, in which case we :
702           1) check the consistency of the regions in the type of e1 and in the access mode of its type
703           2) return directly the converted CMinor expression "as is"
704      *)
705      match typ_of_type (typeof e1) return λx.(Σz:CMexpr x.expr_vars ? z (local_id vars)) → ? with
706      [ ASTptr ⇒ λe1'.
707          match access_mode ty return λt.λ_. res (Σe':CMexpr t. expr_vars ? e' (local_id vars)) with
708          [ By_value t ⇒ OK ? «Mem t (pi1 … e1'), ?»
709          | By_reference ⇒ OK ? e1'
710          | By_nothing _ ⇒ Error ? (msg BadlyTypedAccess)
711          ]
712      | _ ⇒ λ_. Error ? (msg TypeMismatch)
713      ] e1'             
714  | Eaddrof e1 ⇒
715      do e1' ← translate_addr vars e1;
716      match typ_of_type ty return λx.res (Σz:CMexpr x.?) with
717      [ ASTptr ⇒ OK ? e1'
718(*          match e1' with
719          [ mk_DPair r1 e1' ⇒ region_should_eq r1 r ? e1'
720          ]*)
721      | _ ⇒ Error ? (msg TypeMismatch)
722      ]
723  | Eunop op e1 ⇒
724     match op
725      return λx. (op = x) → res (Σe':CMexpr (typ_of_type ty). expr_vars ? e' (local_id vars))
726      with
727      [ Onotbool ⇒ λHop.
728        match typ_of_type ty
729        return λy. (typ_of_type ty = y) → res (Σe':CMexpr (typ_of_type ty). expr_vars ? e' (local_id vars))
730        with
731        [ ASTint sz sg ⇒  λHtyp_of_type.
732          match sz
733          return λz. (sz = z) → res (Σe':CMexpr (typ_of_type ty). expr_vars ? e' (local_id vars))
734          with
735          [ I32 ⇒ λHsz.
736            do op' ← translate_unop (typ_of_type (typeof e1)) (typ_of_type ty) op;
737            do e1' ← translate_expr vars e1;
738            OK ? «Op1 ?? op' e1', ?»
739          | _ ⇒ λHsz.
740            Error ? (msg TypeMismatch)
741          ] (refl ? sz)
742        | _ ⇒ λHtyp_of_type.
743          Error ? (msg TypeMismatch)
744        ] (refl ? (typ_of_type ty))       
745      | _ ⇒ λHop.
746        do op' ← translate_unop (typ_of_type (typeof e1)) (typ_of_type ty) op;
747        do e1' ← translate_expr vars e1;
748        OK ? «Op1 ?? op' e1', ?»
749      ] (refl ? op)
750  | Ebinop op e1 e2 ⇒
751      do e1' ← translate_expr vars e1;
752      do e2' ← translate_expr vars e2;
753      do e' as E ← translate_binop op (typeof e1) e1' (typeof e2) e2' ty;
754      OK ? «e', ?»
755  | Ecast ty1 e1 ⇒
756      do e1' ← translate_expr vars e1;
757      do e' ← translate_cast ? (typeof e1) ty1 e1';
758      do e' ← typ_should_eq (typ_of_type ty1) (typ_of_type ty) ? e';
759      OK ? e'
760  | Econdition e1 e2 e3 ⇒
761      do e1' ← translate_expr vars e1;
762      do e2' ← translate_expr vars e2;
763      do e2' ← typ_should_eq (typ_of_type (typeof e2)) (typ_of_type ty) ? e2';
764      do e3' ← translate_expr vars e3;
765      do e3' ← typ_should_eq (typ_of_type (typeof e3)) (typ_of_type ty) ? e3';
766      match typ_of_type (typeof e1) return λx.(Σe1':CMexpr x. expr_vars ? e1' (local_id vars)) → res ? with
767      [ ASTint _ _ ⇒ λe1'. OK ? «Cond ??? e1' e2' e3', ?»
768      | _ ⇒ λ_.Error ? (msg TypeMismatch)
769      ] e1'
770  | Eandbool e1 e2 ⇒
771      do e1' ← translate_expr vars e1;
772      do e2' ← translate_expr vars e2;
773      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
774      [ Tint sz sg ⇒
775          do e2' ← type_should_eq ? (Tint sz sg) (λx.Σe:CMexpr (typ_of_type x).?) e2';
776          match typ_of_type (typeof e1)
777          return λx.
778            (Σe:CMexpr x. expr_vars ? e (local_id vars)) → (res ?)
779          with
780          [ ASTint sz1 _ ⇒ λe1'.
781            (* Producing a nested comparison to match CL. *)
782            OK ? «Cond ??? e1' (Cond ??? e2' (cm_one sz sg) (cm_zero sz sg)) (cm_zero sz sg), ?»
783          | _ ⇒ λ_. Error ? (msg TypeMismatch)
784          ] e1'
785      | _ ⇒ Error ? (msg TypeMismatch)
786      ]
787  | Eorbool e1 e2 ⇒
788      do e1' ← translate_expr vars e1;
789      do e2' ← translate_expr vars e2;
790      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
791      [ Tint sz sg ⇒
792        do e2' ← type_should_eq ? (Tint sz sg) (λx.Σe:CMexpr (typ_of_type x).?) e2';
793        match typ_of_type (typeof e1)
794        return λx.(Σe:CMexpr x. expr_vars ? e (local_id vars)) → res ? with
795        [ ASTint _ _ ⇒ λe1'.
796          OK ? «Cond ??? e1' (cm_one sz sg) (Cond ??? e2' (cm_one sz sg) (cm_zero sz sg)), ?»
797        | _ ⇒ λ_. Error ? (msg TypeMismatch)
798        ] e1'
799      | _ ⇒ Error ? (msg TypeMismatch)
800      ]     
801  | Esizeof ty1 ⇒
802      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
803      [ Tint sz sg ⇒ OK ? «Cst ? (Ointconst sz sg (repr ? (sizeof ty1))), ?»
804      | _ ⇒ Error ? (msg TypeMismatch)
805      ]     
806  | Efield e1 id ⇒
807      match typeof e1 with
808      [ Tstruct _ fl ⇒
809          do e1' ← translate_addr vars e1;
810(*          match e1' with
811          [ mk_DPair r e1' ⇒*)
812            do off ← field_offset id fl;
813            match access_mode ty return λt.λ_. res (Σe':CMexpr t. expr_vars ? e' (local_id vars)) with
814            [ By_value t ⇒
815                OK ? «Mem t (Op2 ? (ASTint I16 Signed (* XXX efficiency? *)) ?
816                                   (Oaddpi …) e1' (Cst ? (Ointconst I16 Signed (repr ? off)))),?»
817            | By_reference ⇒
818(*                do e1' ← region_should_eq r r' ? e1';*)
819                OK ? «Op2 ASTptr (ASTint I16 Signed (* XXX efficiency? *)) ASTptr
820                        (Oaddpi …) e1' (Cst ? (Ointconst I16 Signed (repr ? off))),?»
821            | By_nothing _ ⇒ Error ? (msg BadlyTypedAccess)
822            ]
823      | Tunion _ _ ⇒
824          do e1' ← translate_addr vars e1;
825            match access_mode ty return λt.λ_. res (Σz:CMexpr t.?) with
826            [ By_value t ⇒ OK ? «Mem t e1', ?»
827            | By_reference ⇒ OK ? e1'
828            | By_nothing _ ⇒ Error ? (msg BadlyTypedAccess)
829            ]
830      | _ ⇒ Error ? (msg BadlyTypedAccess)
831      ]           
832  | Ecost l e1 ⇒
833      do e1' ← translate_expr vars e1;
834      do e' ← OK ? «Ecost ? l e1',?»;
835      typ_should_eq (typ_of_type (typeof e1)) (typ_of_type ty) (λx.Σe:CMexpr x.?) e'     
836  ]
837]
838
839(* Translate addr takes an expression e1, and returns a Cminor code computing the address of the result of [e1].   *)
840and translate_addr (vars:var_types) (e:expr) on e : res ((*𝚺r.*) Σe':CMexpr ASTptr. expr_vars ? e' (local_id vars)) ≝
841match e with
842[ Expr ed _ ⇒
843  match ed with
844  [ Evar id ⇒
845      do 〈c,t〉 ← lookup' vars id;
846      match c return λ_. res (Σz:CMexpr ASTptr.?) with
847      [ Global r ⇒ OK ? «Cst ? (Oaddrsymbol id 0), ?»
848      | Stack n ⇒ OK ? «Cst ? (Oaddrstack n), ?»
849      | Local ⇒ Error ? [MSG BadlyTypedAccess; CTX ? id] (* TODO: could rule out? *)
850      ]
851  | Ederef e1 ⇒
852      do e1' ← translate_expr vars e1;
853      match typ_of_type (typeof e1) return λx. (Σz:CMexpr x.expr_vars ? z (local_id vars)) → res (Σz:CMexpr ASTptr. expr_vars ? z (local_id vars)) with
854      [ ASTptr ⇒ λe1'.OK ? e1'
855      | _ ⇒ λ_.Error ? (msg BadlyTypedAccess)
856      ] e1'
857  | Efield e1 id ⇒
858      match typeof e1 with
859      [ Tstruct _ fl ⇒
860          do e1' ← translate_addr vars e1;
861          do off ← field_offset id fl;
862(*          match e1' with
863          [ mk_DPair r e1'' ⇒ OK (𝚺r:region.Σe:CMexpr (ASTptr r).?)*)
864             OK ? «Op2 ASTptr (ASTint I16 Signed (* FIXME inefficient?*)) ASTptr
865                   (Oaddpi I16) e1' (Cst ? (Ointconst I16 Signed (repr ? off))), ?»
866      | Tunion _ _ ⇒ translate_addr vars e1
867      | _ ⇒ Error ? (msg BadlyTypedAccess)
868      ]
869  | _ ⇒ Error ? (msg BadLvalue)
870  ]
871].
872whd try @I
873[ >E whd >Heq_c @refl
874| 2,3: @pi2
875| cases e1' //
876| cases e1' //
877| @(translate_binop_vars … E) @pi2
878| % [ % ] @pi2
879| % [ % try @pi2 whd @conj try @conj try // @pi2 ] whd @I
880| % [ % [ @pi2 | @I ] | % try @conj try // @pi2 ]
881| % [ @pi2 | @I ]
882| % [ @pi2 | @I ]
883| @pi2
884| @pi2
885| % [ @pi2 | @I ]
886] qed.
887
888(* We provide a function to work out how to do an assignment to an lvalue
889   expression.  It is used for both Clight assignments and Clight function call
890   destinations, but doesn't take the value to be assigned so that we can use
891   it to form a single St_store when possible (and avoid introducing an
892   unnecessary temporary variable and assignment).
893   *)
894inductive destination (vars:var_types) : Type[0] ≝
895| IdDest : ∀id,ty. local_id vars id (typ_of_type ty) → destination vars
896| MemDest : (Σe:CMexpr ASTptr.expr_vars ? e (local_id vars)) → destination vars.
897
898(* Let a source Clight expression be assign(e1, e2). First of all, observe that [e1] is a
899  /Clight/ expression, not converted by translate_expr. We thus have to do part of the work
900  of [translate_expr] in this function. [translate_dest] will convert e1
901   into a proper destination for an assignement operation. We proceed by case analysis on e1.
902   - if e1 is a variable [id], then we proceed by case analysis on its allocation mode:
903      - if [id] is allocated locally (in a register), then id becomes directly
904        the target for the assignement, as (IdDest vars id t H), where t is the type
905        of id, and H asserts that id is indeed a local variable.
906      - if [id] is a global variable stored in region [r], then we perform [translate_expr]'s
907        job and return an adress, given as a constant symbol corresponding to [id], with
908        region r and memory chunk specified by the access mode of the rhs type ty2 of [e2].
909      - same thing for stack-allocated variables, except that we don't specify any region.
910   - if e1 is not a variable, we use [translate_addr] to generate a Cminor expression computing
911    the adres of e1
912*)
913definition translate_dest ≝
914λvars,e1.
915  match e1 with
916  [ Expr ed1 ty1 ⇒
917      match ed1 with
918      [ Evar id ⇒
919          do 〈c,t〉 as E ← lookup' vars id;
920          match c return λx.? → ? with
921          [ Local ⇒ λE. OK ? (IdDest vars id t ?)
922          | Global r ⇒ λE. OK ? (MemDest ? (Cst ? (Oaddrsymbol id 0)))
923          | Stack n ⇒ λE. OK ? (MemDest ? (Cst ? (Oaddrstack n)))
924          ] E
925      | _ ⇒
926          do e1' ← translate_addr vars e1;
927          OK ? (MemDest ? e1')
928      ]
929  ].
930whd // >E @refl
931qed.
932
933(* [lenv] is the type of maps from Clight labels to Cminor labels. *)
934definition lenv ≝ identifier_map SymbolTag (identifier Label).
935
936(* Find the Cminor label corresponding to [l] or fail. *)
937definition lookup_label ≝
938λlbls:lenv.λl. opt_to_res … [MSG MissingLabel; CTX ? l] (lookup ?? lbls l).
939
940(* True iff the Cminor label [l] is in the codomain of [lbls] *)
941definition lpresent ≝ λlbls:lenv. λl. ∃l'. lookup_label lbls l' = OK ? l.
942
943(* True iff The Clight label [l] is in the domain of [lbls] *)
944definition label_in_domain ≝ λlbls:lenv. λl. present ?? lbls l.
945
946let rec fresh_list_for_univ (l:list (identifier Label)) (u:universe Label) ≝
947match l with
948[ nil ⇒ True
949| cons elt tl ⇒ fresh_for_univ ? elt u ∧ fresh_list_for_univ tl u].
950
951record labgen : Type[0] ≝ {
952  labuniverse   : universe Label;
953  label_genlist    : list (identifier Label);
954  genlist_is_fresh : fresh_list_for_univ label_genlist labuniverse
955}.
956
957lemma fresh_list_stays_fresh : ∀l,tmp,u,u'. fresh_list_for_univ l u → 〈tmp,u'〉=fresh Label u → fresh_list_for_univ l u'.
958#l elim l
959[ 1: normalize //
960| 2: #hd #tl #Hind #tmp #u #u' #HA #HB
961  whd
962  @conj
963  [ 1: whd in HA ⊢ ?;
964    elim HA #HAleft #HAright
965    @(fresh_remains_fresh ? hd tmp u u') assumption
966  | 2: whd in HA ⊢ ?;
967    elim HA #HAleft #HAright   
968    @Hind //
969  ]
970]
971qed.
972
973definition In ≝ λelttype.λelt.λl.Exists elttype (λx.x=elt) l.   
974
975definition generate_fresh_label :
976 ∀ul. Σlul:(identifier Label × labgen).
977               (And (∀lab. In ? lab (label_genlist ul) → In ? lab (label_genlist (snd … lul)))
978                   (In ? (fst … lul) (label_genlist (snd … lul)))) ≝
979λul.
980let 〈tmp,u〉 as E ≝ fresh ? (labuniverse ul) in
981 «〈tmp, mk_labgen u (tmp::(label_genlist ul)) ?〉, ?».
982[ 1: normalize @conj
983  [ 1: @(fresh_is_fresh ? tmp u (labuniverse ul) ?) assumption
984  | 2: @fresh_list_stays_fresh // ]
985| @conj /2/
986]
987qed.
988
989let rec labels_defined (s:statement) : list ident ≝
990match s with
991[ Ssequence s1 s2 ⇒ labels_defined s1 @ labels_defined s2
992| Sifthenelse _ s1 s2 ⇒ labels_defined s1 @ labels_defined s2
993| Swhile _ s ⇒ labels_defined s
994| Sdowhile _ s ⇒ labels_defined s
995| Sfor s1 _ s2 s3 ⇒ labels_defined s1 @ labels_defined s2 @ labels_defined s3
996| Sswitch _ ls ⇒ labels_defined_switch ls
997| Slabel l s ⇒ l::(labels_defined s)
998| Scost _ s ⇒ labels_defined s
999| _ ⇒ [ ]
1000]
1001and labels_defined_switch (ls:labeled_statements) : list ident ≝
1002match ls with
1003[ LSdefault s ⇒ labels_defined s
1004| LScase _ _ s ls ⇒ labels_defined s @ labels_defined_switch ls
1005].
1006
1007definition ldefined ≝ λs.λl.Exists ? (λl'.l' = l) (labels_of s).
1008
1009(* For each label l in s, there exists a matching label l' = lenv(l) defined in s' *)
1010definition labels_translated : lenv → statement → stmt → Prop ≝
1011λlbls,s,s'.  ∀l.
1012  (Exists ? (λl'.l' = l) (labels_defined s)) →
1013  ∃l'. lookup_label lbls l = (OK ? l') ∧ ldefined s' l'.
1014
1015
1016(* Invariant on statements, holds during conversion to Cminor *)
1017definition stmt_inv ≝  λvars. stmt_P (stmt_vars (local_id vars)).
1018
1019definition m_option_map : ∀A,B:Type[0]. (A → res B) → option A → res (option B) ≝
1020λA,B,f,oa.
1021match oa with
1022[ None ⇒ OK ? (None ?)
1023| Some a ⇒ do b ← f a; OK ? (Some ? b)
1024].
1025
1026definition translate_expr_sigma : ∀vars:var_types. expr → res (Σe:(𝚺t:typ.CMexpr t). match e with [ mk_DPair t e ⇒ expr_vars t e (local_id vars) ]) ≝
1027λv,e.
1028  do e' ← translate_expr v e;
1029  OK (Σe:(𝚺t:typ.CMexpr t).?) «❬?, e'❭, ?».
1030whd @pi2
1031qed.
1032
1033(* Add the list of typed variables tmpenv to the environment [var_types] with
1034   the allocation mode Local. *)
1035definition add_tmps : var_types → list (ident × type) → var_types ≝
1036λvs,tmpenv.
1037  foldr ?? (λidty,vs. add ?? vs (\fst idty) 〈Local, \snd idty〉) vs tmpenv.
1038
1039record tmpgen (vars:var_types) : Type[0] ≝ {
1040  tmp_universe : universe SymbolTag;
1041  tmp_env : list (ident × type);
1042  tmp_ok : fresh_map_for_univ … (add_tmps vars tmp_env) tmp_universe;
1043  tmp_preserved :
1044    ∀id,ty. local_id vars id ty → local_id (add_tmps vars tmp_env) id ty
1045}.
1046
1047definition alloc_tmp : ∀vars. type → tmpgen vars → ident × (tmpgen vars) ≝
1048λvars,ty,g.
1049  let 〈tmp,u〉 as E ≝ fresh ? (tmp_universe ? g) in
1050  〈tmp, mk_tmpgen ? u (〈tmp, ty〉::(tmp_env ? g)) ??〉.
1051[ #id #ty'
1052  whd in ⊢ (? → ?%??);
1053  whd in ⊢ (% → %);
1054  whd in ⊢ (? → match % with [_ ⇒ ? | _ ⇒ ?]); #H
1055  >lookup_add_miss
1056  [ @(tmp_preserved … g) @H
1057  | @(fresh_distinct … E) @(tmp_ok … g)
1058    lapply (tmp_preserved … g id ty' H)
1059    whd in ⊢ (% → %);
1060    whd in ⊢ (match % with [_ ⇒ ? | _ ⇒ ?] → ?);
1061    cases (lookup ?? (add_tmps …) id)
1062    [ * | #x #_ % #E destruct ]
1063  ]
1064| @fresh_map_add
1065  [ @(fresh_map_preserved … E) @(tmp_ok … g)
1066  | @(fresh_is_fresh … E)
1067  ]
1068] qed.
1069
1070
1071lemma lookup_label_hit : ∀lbls,l,l'.
1072  lookup_label lbls l = OK ? l' →
1073  lpresent lbls l'.
1074#lbls #l #l' #E whd %{l} @E
1075qed.
1076
1077(* TODO: is this really needed now? *)
1078
1079definition tmps_preserved : ∀vars:var_types. tmpgen vars → tmpgen vars → Prop ≝
1080λvars,u1,u2.
1081  ∀id,ty. local_id (add_tmps vars (tmp_env … u1)) id ty → local_id (add_tmps vars (tmp_env … u2)) id ty.
1082
1083lemma alloc_tmp_preserves : ∀vars,tmp,u,u',q.
1084  〈tmp,u'〉 = alloc_tmp ? q u → tmps_preserved vars u u'.
1085#vars #tmp * #u1 #e1 #F1 #P1 * #u2 #e2 #F2 #P2 #q
1086whd in ⊢ (???% → ?); generalize in ⊢ (???(?%) → ?);
1087cases (fresh SymbolTag u1) in ⊢ (??%? → ???(match % with [ _ ⇒ ? ]?) → ?);
1088#tmp' #u' #E1 #E2 whd in E2:(???%); destruct
1089#id #ty #H whd in ⊢ (?%??); whd in H ⊢ %;
1090whd in ⊢ match % with [ _ ⇒ ? | _ ⇒ ? ];
1091>lookup_add_miss // @(fresh_distinct … E1) @F1
1092whd in H:(match % with [_ ⇒ ?|_ ⇒ ?]) ⊢ %;
1093cases (lookup ?? (add_tmps …) id) in H ⊢ %;
1094[ * | #x #_ % #E destruct ]
1095qed.
1096
1097lemma add_tmps_oblivious : ∀vars,s,u.
1098  stmt_inv vars s → stmt_inv (add_tmps vars (tmp_env vars u)) s.
1099#vars #s #u #H
1100@(stmt_P_mp … H)
1101#s' #H1 @(stmt_vars_mp … H1) #id #t #H @(tmp_preserved ? u ?? H)
1102qed.
1103
1104lemma local_id_fresh_tmp : ∀vars,tmp,u,ty,u0.
1105  〈tmp,u〉 = alloc_tmp vars ty u0 → local_id (add_tmps vars (tmp_env … u)) tmp (typ_of_type ty).
1106#vars #tmp #u #ty #u0
1107whd in ⊢ (???% → ?); generalize in ⊢ (???(?%) → ?);
1108cases (fresh SymbolTag (tmp_universe vars u0)) in ⊢ (??%? → ???(match % with [_⇒?]?) → ?);
1109* #tmp' #u' #e #E whd in E:(???%);
1110destruct
1111whd in ⊢ (?%??); whd whd in ⊢ match % with [ _ ⇒ ? | _ ⇒ ? ]; >lookup_add_hit
1112@refl
1113qed.
1114
1115
1116let rec mklabels (ul:labgen) : (identifier Label) × (identifier Label) × labgen ≝
1117  match generate_fresh_label ul with
1118  [ mk_Sig res1 H1 ⇒
1119     let 〈entry_label, ul1〉 as E1 ≝ res1 in
1120     match generate_fresh_label ul1 with
1121     [ mk_Sig res2 H2 ⇒
1122        let 〈exit_label, ul2〉 as E2 ≝ res2 in
1123        〈entry_label, exit_label, ul2〉
1124     ]
1125  ].
1126
1127(* When converting loops into gotos, and in order to eliminate blocks, we have
1128 * to convert continues and breaks into goto's, too. We add some "flags" in
1129 * in argument to [translate_statement], meaning that the next encountered break
1130 * or continue has to be converted into a goto to some contained label.
1131 * ConvertTo l1 l2 means "convert continue to goto l1 and convert break to goto l2".
1132 *)
1133inductive convert_flag : Type[0] ≝
1134| DoNotConvert : convert_flag
1135| ConvertTo    : identifier Label → identifier Label → convert_flag. (* continue, break *)
1136
1137let rec labels_of_flag (flag : convert_flag) : list (identifier Label) ≝
1138match flag with
1139[ DoNotConvert ⇒ [ ]
1140| ConvertTo continue break ⇒ continue :: break :: [ ]
1141].
1142
1143(* For a top-level expression, [label-wf] collapses to "all labels are properly declared" *)
1144definition label_wf ≝
1145λ (s : statement) .λ (s' : stmt) .λ (lbls : lenv). λ (flag : convert_flag).
1146    stmt_P (λs1. stmt_labels (λl.ldefined s' l ∨ lpresent lbls l ∨ In ? l (labels_of_flag flag)) s1) s'.
1147
1148definition return_ok : option typ → stmt → Prop ≝
1149λot.
1150stmt_P (λs.
1151  match s with [ St_return oe ⇒
1152    match oe with [ Some e ⇒ Some ? (dpi1 … e) = ot | None ⇒ None ? = ot ]
1153  | _ ⇒ True ]).
1154
1155(* trans_inv is the invariant which is enforced during the translation from Clight to Cminor.
1156  The involved arguments are the following:
1157  . vars:var_types, an environment mapping variables to their types and allocation modes
1158  . lbls:lenv, a mapping from old (Clight) to fresh and new (Cminor) labels,
1159  . s:statement, a Clight statement,
1160  . uv, a fresh variable generator (containing itself some invariants)
1161  . flag, wich maps "break" and "continue" to "gotos"
1162  . su', a couple of a Cminor statement and fresh variable generator.
1163*)
1164definition trans_inv : ∀vars:var_types . ∀lbls:lenv . statement → tmpgen vars → convert_flag → option typ → ((tmpgen vars) × labgen × stmt) → Prop ≝
1165λvars,lbls,s,uv,flag,rettyp,su'.
1166  let 〈uv', ul', s'〉 ≝ su' in
1167  stmt_inv (add_tmps vars (tmp_env … uv')) s' ∧   (* remaining variables in s' are local*)
1168  labels_translated lbls s s' ∧                   (* all the labels in s are transformed in label of s' using [lbls] as a map *)
1169  tmps_preserved vars uv uv' ∧                    (* the variables generated are local and grows in a monotonic fashion *)
1170  return_ok rettyp s' ∧                           (* return statements have correct typ *)
1171  label_wf s s' lbls flag.                        (* labels are "properly" declared, as defined in [ŀabel_wf].*)
1172
1173let rec translate_statement (vars:var_types) (uv:tmpgen vars) (ul:labgen) (lbls:lenv) (flag:convert_flag) (rettyp:option typ) (s:statement) on s
1174  : res (Σsu:(tmpgen vars)×labgen×stmt.trans_inv vars lbls s uv flag rettyp su) ≝
1175match s return λs.res (Σsu:(tmpgen vars)×labgen×stmt.trans_inv vars lbls s uv flag rettyp su) with
1176[ Sskip ⇒ OK ? «〈uv, ul, St_skip〉, ?»
1177| Sassign e1 e2 ⇒
1178    do e2' ← translate_expr vars e2;  (* rhs *)
1179    do dest ← translate_dest vars e1; (* e1 *)
1180    match dest with
1181    [ IdDest id ty p ⇒
1182       (* Don't compare the Clight types, or we'll have to deal with
1183          array/pointer punning. *)
1184       do e2' ← typ_should_eq (typ_of_type (typeof e2)) (typ_of_type ty) ? e2';
1185       OK ? «〈uv, ul, St_assign ? id e2'〉, ?»
1186    | MemDest e1' ⇒
1187       match type_eq_dec (typeof e1) (typeof e2) with
1188       [ inl Hcl_typ_eq ⇒       
1189         OK ? «〈uv, ul, St_store ? e1' e2'〉, ?»
1190       | inr Hcl_typ_neq ⇒
1191         Error ? (msg TypeMismatch)
1192       ]
1193    ]
1194| Scall ret ef args ⇒
1195    do ef' ← translate_expr vars ef;
1196    do ef' ← typ_should_eq (typ_of_type (typeof ef)) ASTptr ? ef';
1197    do args' ← mmap_sigma ??? (translate_expr_sigma vars) args;
1198    match ret with
1199    [ None ⇒ OK ? «〈uv, ul, St_call (None ?) ef' args'〉, ?»
1200    | Some e1 ⇒
1201        do dest ← translate_dest vars e1;
1202        match dest with
1203        [ IdDest id ty p ⇒
1204            (* No trace generated here, by inversion on translate_dest _ _ = IdDest _ _ _ *)
1205            OK ? «〈uv, ul, St_call (Some ? 〈id,typ_of_type ty〉) ef' args'〉, ?»
1206        | MemDest e1' ⇒
1207            let 〈tmp, uv1〉 as Etmp ≝ alloc_tmp ? (typeof e1) uv in
1208            (* alloc a new variable to serve as a placeholder for the evaluation of e1',
1209             * which /must/ happen before the call. Otherwise, the cost labels are not
1210             * emitted as in Clight.  *)
1211            let 〈tmp2, uv2〉 as Etmp' ≝ alloc_tmp ? (Tpointer (typeof e1)) uv1 in
1212            OK ? «〈uv2, ul,
1213                    (St_seq (St_assign ? tmp2 e1')
1214                    (St_seq (St_call (Some ? 〈tmp,typ_of_type (typeof e1)〉) ef' args')
1215                            (St_store (typ_of_type (typeof e1)) (Id ? tmp2) (Id ? tmp))))〉, ?»
1216        ]
1217    ]
1218| Ssequence s1 s2 ⇒
1219    do «fgens1, s1', H1» ← translate_statement vars uv ul lbls flag rettyp s1;
1220    do «fgens2, s2', H2» ← translate_statement vars (fst … fgens1) (snd … fgens1) lbls flag rettyp s2;
1221    OK ? «〈fgens2, St_seq s1' s2'〉, ?»
1222| Sifthenelse e1 s1 s2 ⇒
1223    do e1' ← translate_expr vars e1;
1224    match typ_of_type (typeof e1) return λx.(Σe:CMexpr x.expr_vars ? e ?) → res ? with
1225    [ ASTint _ _ ⇒ λe1'.
1226         do «fgens1, s1', H1» ← translate_statement vars uv ul lbls flag rettyp s1;
1227         do «fgens2, s2', H2» ← translate_statement vars (fst … fgens1) (snd … fgens1) lbls flag rettyp s2;
1228        OK ? «〈fgens2, St_ifthenelse ?? e1' s1' s2'〉, ?»
1229    | _ ⇒ λ_.Error ? (msg TypeMismatch)
1230    ] e1'
1231(* Performing loop conversions while keeping good cost labelling properties is
1232   a little tricky.  In principle we should have a cost label in each branch,
1233   but the behaviour of the next stage means that we can put in Cminor skips and
1234   goto labels before the cost label. *)
1235| Swhile e1 s1 ⇒
1236    do e1' ← translate_expr vars e1;
1237    match typ_of_type (typeof e1) return λx.(Σe:CMexpr x.expr_vars ? e ?) → res ? with
1238    [ ASTint _ _ ⇒ λe1'.         
1239        let 〈labels, ul1〉 as E1 ≝ mklabels ul in
1240        let 〈entry, exit〉 as E2 ≝ labels in
1241        do «fgens2, s1',H1» ← translate_statement vars uv ul1 lbls (ConvertTo entry exit) rettyp s1;
1242        let converted_loop ≝
1243          St_label entry
1244          (St_seq
1245            (St_ifthenelse ?? e1' (St_seq s1' (St_goto entry)) St_skip)
1246            (St_label exit St_skip))
1247        in         
1248          OK ? «〈fgens2, converted_loop〉, ?»
1249    | _ ⇒ λ_.Error ? (msg TypeMismatch)
1250    ] e1'
1251| Sdowhile e1 s1 ⇒
1252    do e1' ← translate_expr vars e1;
1253    match typ_of_type (typeof e1) return λx.(Σe:CMexpr x. expr_vars ? e ?) → res ? with
1254    [ ASTint _ _ ⇒ λe1'.
1255        let 〈labels, ul1〉 as E1 ≝ mklabels ul in
1256        let 〈condexpr, exit〉 as E2 ≝ labels in
1257        let 〈body, ul2〉 ≝ generate_fresh_label … ul1 in
1258        do «fgens2, s1', H1» ← translate_statement vars uv ul2 lbls (ConvertTo condexpr exit) rettyp s1;
1259        (* This is particularly carefully implemented, we need to reach the
1260           cost label in s1' or the cost label after the loop (if they are
1261           present) after the ifthenelse, and we're only allowed skips and
1262           goto labels in between.  So we structure it like a while with a goto
1263           into the middle (the CFG will be essentially the same, anyway.) *)
1264        let converted_loop ≝
1265        St_seq
1266          (St_seq
1267            (St_goto body)
1268            (St_label condexpr
1269              (St_ifthenelse ?? e1'
1270                (St_label body
1271                  (St_seq
1272                    s1'
1273                    (St_goto condexpr)))
1274                St_skip)))
1275          (St_label exit St_skip)
1276        in
1277        OK ? «〈fgens2, converted_loop〉, ?»
1278    | _ ⇒ λ_.Error ? (msg TypeMismatch)
1279    ] e1'
1280| Sfor s1 e1 s2 s3 ⇒
1281    do e1' ← translate_expr vars e1;
1282    match typ_of_type (typeof e1) return λx.(Σe:CMexpr x. expr_vars ? e ?) → res ? with
1283    [ ASTint _ _ ⇒ λe1'.
1284        let 〈labels, ul1〉 as E ≝ mklabels ul in
1285        let 〈continue, exit〉 as E2 ≝ labels in
1286        let 〈entry, ul2〉 ≝ generate_fresh_label … ul1 in
1287        do «fgens2, s1', H1» ← translate_statement vars uv ul2 lbls flag rettyp s1;
1288        (* The choice of flag is arbitrary - Clight's semantics give no meaning
1289           to continue or break in s2 because in C it must be an expression. *)
1290        do «fgens3, s2', H2» ← translate_statement vars (fst … fgens2) (snd … fgens2) lbls flag rettyp s2;
1291        do «fgens4, s3', H3» ← translate_statement vars (fst … fgens3) (snd … fgens3) lbls (ConvertTo continue exit) rettyp s3;
1292        let converted_loop ≝
1293          St_seq
1294            s1'
1295            (St_label entry
1296              (St_seq
1297                (St_ifthenelse ?? e1' (St_seq s3' (St_label continue (St_seq s2' (St_goto entry)))) St_skip)
1298                (St_label exit St_skip)
1299            ))
1300        in
1301          OK ? «〈fgens4, converted_loop〉, ?»
1302    | _ ⇒ λ_.Error ? (msg TypeMismatch)
1303    ] e1'
1304| Sbreak ⇒
1305   match flag return λf.flag = f → ? with
1306   [ DoNotConvert ⇒ λEflag.
1307     Error ? (msg FIXME)
1308   | ConvertTo continue_label break_label ⇒ λEflag.
1309     OK ? «〈uv, ul, St_goto break_label〉, ?»
1310   ] (refl ? flag)
1311| Scontinue ⇒
1312  match flag return λf.flag = f → ? with
1313  [ DoNotConvert ⇒ λEflag.
1314    Error ? (msg FIXME)
1315  | ConvertTo continue_label break_label ⇒ λEflag.
1316    OK ? «〈uv, ul, St_goto continue_label〉, ?»
1317  ] (refl ? flag)
1318| Sreturn ret ⇒
1319    match ret with
1320    [ None ⇒
1321        match rettyp return λx.res (Σy.trans_inv … x y) with
1322        [ None ⇒ OK ? «〈uv, ul, St_return (None ?)〉, ?»
1323        | _ ⇒ Error ? (msg ReturnMismatch)
1324        ]
1325    | Some e1 ⇒
1326        match rettyp return λx.res (Σy.trans_inv … x y) with
1327        [ Some rty ⇒
1328            do e1' ← translate_expr vars e1;
1329            do e1' ← typ_should_eq (typ_of_type (typeof e1)) rty ? e1';
1330            OK ? «〈uv, ul, St_return (Some ? (mk_DPair … e1'))〉, ?»
1331        | _ ⇒ Error ? (msg ReturnMismatch)
1332        ]
1333    ]
1334| Sswitch e1 ls ⇒ Error ? (msg FIXME)
1335| Slabel l s1 ⇒
1336    do l' as E ← lookup_label lbls l;
1337    do «fgens1, s1', H1» ← translate_statement vars uv ul lbls flag rettyp s1;
1338    OK ? «〈fgens1, St_label l' s1'〉, ?»
1339| Sgoto l ⇒
1340    do l' as E ← lookup_label lbls l;
1341    OK ? «〈uv, ul, St_goto l'〉, ?»
1342| Scost l s1 ⇒
1343    do «fgens1, s1', H1» ← translate_statement vars uv ul lbls flag rettyp s1;
1344    OK ? «〈fgens1, St_cost l s1'〉, ?»
1345].
1346try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj
1347try (@I)
1348try (#l #H elim H)
1349try (#size #sign #H assumption)
1350try (#H1 try #H2 assumption)
1351[ 1,5: @(tmp_preserved … p) ]
1352[ 6: @(local_id_fresh_tmp vars tmp2 uv2 (Tpointer (typeof e1)) uv1 Etmp')
1353| 7: cases e1' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal)
1354| 8: @conj try @conj normalize nodelta
1355     [ 1: cases e1' #e #Hvars lapply (local_id_fresh_tmp vars tmp uv1 (typeof e1) uv Etmp)
1356          @(alloc_tmp_preserves … Etmp')
1357     | 3: @All_mp [ 1: @(λe.match e with [ mk_DPair t e0 ⇒ expr_vars t e0 (local_id vars) ])
1358                  | 2: * #t #e #Hev whd in Hev ⊢ %; @(expr_vars_mp … Hev) #i #t #Hp @(tmp_preserved … Hp)
1359                  | 3: elim args' // ]
1360     | 2: cases ef' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal) ] ]
1361[ 5: @All_mp [ 1: @(λe.match e with [ mk_DPair t e0 ⇒ expr_vars t e0 (local_id vars) ])
1362             | 2: * #t #e #Hev whd in Hev ⊢ %; @(expr_vars_mp … Hev) #i #t #Hp @(tmp_preserved … Hp)
1363             | 3: elim args' // ] ]
1364(*[ 5: whd @conj
1365     [ 1: cases e1' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal)
1366     | 2: @(alloc_tmp_preserves … Etmp') @(local_id_fresh_tmp … Etmp) ] ]     
1367     *)
1368[ 1,3: elim e2' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal)
1369| 2: elim e1' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal)
1370| 4,8: elim ef' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal) ]
1371[ 4: @All_mp [ 1: @(λe.match e with [ mk_DPair t e0 ⇒ expr_vars t e0 (local_id vars) ])
1372             | 2: * #t #e #Hev whd in Hev ⊢ %; @(expr_vars_mp … Hev) #i #t #Hp @(tmp_preserved … Hp)
1373             | 3: elim args' // ]
1374| 3: #H @(alloc_tmp_preserves … Etmp' l ASTptr) @(alloc_tmp_preserves … Etmp l ASTptr) @H
1375| 2: #sz #sg #H @(alloc_tmp_preserves … Etmp' l) @(alloc_tmp_preserves … Etmp l) @H
1376| 1: whd @conj
1377     [ 1: @(local_id_fresh_tmp vars tmp2 uv2 (Tpointer (typeof e1)) uv1 Etmp')
1378     | 2: @(alloc_tmp_preserves … Etmp') @(local_id_fresh_tmp vars tmp uv1 ((typeof e1)) uv Etmp) ] ]
1379try @refl (* Does (at least) the return_ok cases *)
1380try @(match fgens1 return λx.x=fgens1 → ? with
1381     [ mk_Prod uv1 ul1 ⇒ λHfgens1.? ] (refl ? fgens1))
1382try @(match fgens2 return λx.x=fgens2 → ? with
1383     [ mk_Prod uv2 ul2 ⇒ λHfgens2.? ] (refl ? fgens2))
1384try @(match fgens3 return λx.x=fgens3 → ? with
1385     [ mk_Prod uv3 ul3 ⇒ λHfgens3.? ] (refl ? fgens3))
1386try @(match fgens4 return λx.x=fgens4 → ? with
1387     [ mk_Prod uv4 ul4 ⇒ λHfgens4.? ] (refl ? fgens4))
1388whd in H1 H2 H3 ⊢ ?; destruct whd nodelta in H1 H2 H3;
1389try (elim H1 -H1 * * * #Hstmt_inv1 #Hlabels_tr1 #Htmps_pres1 #Hret1)
1390try (elim H2 -H2 * * * #Hstmt_inv2 #Hlabels_tr2 #Htmps_pres2 #Hret2)
1391try (elim H3 -H3 * * * #Hstmt_inv3 #Hlabels_tr3 #Htmps_pres3 #Hret3)
1392[ 8: whd cases e1' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal) ]
1393[ 1,2: #Hind1 #Hind2 | 3,4,8,10: #Hind | 5: #Hind1 #Hind2 #Hind3 ]
1394try @conj try @conj try @conj try @conj try @conj try @conj try (whd @I) try assumption
1395[ 1,7: @(stmt_P_mp … Hstmt_inv1) #e #Hvars @(stmt_vars_mp … Hvars) #i #t #Hlocal @(Htmps_pres2 … Hlocal)
1396| 2: #l #H cases (Exists_append ???? H) #Hcase
1397         [ 1: elim (Hlabels_tr1 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1398           [ 1: @(proj1 ?? Hlabel)
1399           | 2: normalize @Exists_append_l @(proj2 … Hlabel) ]
1400         | 2: elim (Hlabels_tr2 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1401           [ 1: @(proj1 ?? Hlabel)
1402           | 2: normalize @Exists_append_r @(proj2 … Hlabel) ]
1403         ]
1404| 3,9: #id #ty #H @(Htmps_pres2 … (Htmps_pres1 id ty H)) ]
1405[ 1: @(stmt_P_mp … Hind2) | 2: @(stmt_P_mp … Hind1) ]
1406[ 1,2: #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1407     #l * try * [ 1,4: #H %1 %1 normalize in H ⊢ %; try (@Exists_append_l @H); try (@Exists_append_r @H)
1408                | 2,5: #H %1 %2 assumption
1409                | 3,6: #H %2 assumption ]
1410(* if/then/else *)
1411| 3: whd elim e1' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal)
1412| 4: whd #l #H
1413       cases (Exists_append ???? H) #Hcase
1414         [ 1: elim (Hlabels_tr1 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1415           [ 1: @(proj1 ?? Hlabel)
1416           | 2: normalize @Exists_append_l @(proj2 … Hlabel) ]
1417         | 2: elim (Hlabels_tr2 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1418           [ 1: @(proj1 ?? Hlabel)
1419           | 2: normalize @Exists_append_r @(proj2 … Hlabel) ]
1420         ]
1421]                 
1422[ 1: 1: @(stmt_P_mp … Hind2) | 2: @(stmt_P_mp … Hind1) ]
1423[ 1,2: #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1424     #l * try * [ 1,4: #H %1 %1 normalize in H ⊢ %; try (@Exists_append_l @H); try (@Exists_append_r @H)
1425                | 2,5: #H %1 %2 assumption
1426                | 3,6: #H %2 assumption ] ]
1427try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @I try assumption
1428[ 1,7,19: whd elim e1' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal)
1429| 2,8: whd #l #H normalize in H;
1430       elim (Hlabels_tr1 … H) #label #Hlabel @(ex_intro … label)
1431       @conj
1432       [ 1,3: @(proj1 … Hlabel)
1433       | 2,4: whd @or_intror normalize in ⊢ (???%);
1434              [ @Exists_append_l @Exists_append_l @Exists_append_l | %2 @Exists_append_l @Exists_append_l @Exists_append_l ]
1435              @(proj2 … Hlabel) ]
1436| whd %1 %1 normalize /2/
1437| 4,12: @(stmt_P_mp … Hind) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1438   #l * try * [ 1,5: #H %1 %1 normalize %2 [ 2: %2 ] @Exists_append_l @Exists_append_l try @Exists_append_l @H
1439              | 2,6: #H %1 %2 assumption
1440              | 3,7: #H <H %1 %1 normalize /2/
1441              | 4,8: #H normalize in H; elim H [ 1,3: #E <E %1 %1 normalize %2 [2: %2]
1442                                                 @Exists_append_r normalize /2/
1443                                               | 2,4: * ]
1444              ]
1445| normalize %1 %1 %1 //
1446| 6,11: normalize %1 %1 %2 [ @Exists_append_r normalize /2/ | %1 % ]
1447| whd %1 %1 normalize %2 %1 %
1448| 10,13: normalize %1 %1 %1 %
1449| normalize %1 %1 %2 %2 /2/
1450| whd #label * [ 1: #Eq @(ex_intro … l') @conj [ 1: destruct // | whd /2/ ]
1451               | 2: #H elim (Hlabels_tr1 label H)
1452                    #lab * #Hlookup #Hdef @(ex_intro … lab) @conj
1453                    [ 1: // | 2: whd %2 assumption ]
1454               ]
1455| normalize %1 %1 %1 %
1456| @(stmt_P_mp … Hind) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1457  #l * try * [ 1: #H %1 %1 normalize %2 @H
1458             | 2: #H %1 %2 assumption
1459             | 3: #H %2 assumption ]
1460| @(stmt_P_mp … Hstmt_inv1) #s0 #Hstmt_vars @(stmt_vars_mp … Hstmt_vars) #i #t
1461  #H @(Htmps_pres3 … (Htmps_pres2 … H))
1462| @(stmt_P_mp … Hstmt_inv2) #s0 #Hstmt_vars @(stmt_vars_mp … Hstmt_vars) #i #t
1463  #H @(Htmps_pres3 … H)
1464| % //
1465| whd #l #H normalize in H;
1466  cases (Exists_append … H) #Hcase
1467  [ 1: elim (Hlabels_tr1 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1468    [ 1: @(proj1 … Hlabel)
1469    | 2: normalize @Exists_append_l @(proj2 … Hlabel)
1470    ]
1471  | 2: cases (Exists_append … Hcase) #Hcase2
1472    [ 1: elim (Hlabels_tr2 l Hcase2) #label #Hlabel @(ex_intro … label) @conj
1473      [ 1: @(proj1 … Hlabel)
1474      | 2: normalize >append_nil >append_nil >append_cons
1475           @Exists_append_r @Exists_append_l @Exists_append_r %2
1476           @(proj2 … Hlabel)
1477      ]
1478    | 2: elim (Hlabels_tr3 l Hcase2) #label #Hlabel @(ex_intro … label) @conj
1479      [ 1: @(proj1 … Hlabel)
1480      | 2: normalize >append_nil >append_nil >append_cons
1481         @Exists_append_r @Exists_append_l @Exists_append_l
1482         @(proj2 … Hlabel)
1483      ]
1484    ]
1485  ]
1486| #id #ty #H @(Htmps_pres3 … (Htmps_pres2 … (Htmps_pres1 … H)))
1487| @(stmt_P_mp … Hind3) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1488   #l * try * [ 1: #H %1 %1 normalize @Exists_append_l @H
1489              | 2: #H %1 %2 assumption
1490              | 3: #H %2 assumption ]
1491| whd %1 %1 normalize /2/
1492| @(stmt_P_mp … Hind1) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1493   #l * try * [ 1: #H %1 %1 normalize @Exists_append_r @(Exists_add ?? (nil ?))
1494                   @Exists_append_r @Exists_append_l @Exists_append_l
1495                   @Exists_append_l assumption
1496              | 2: #H %1 %2 assumption
1497              | 3: #H <H %1 %1 normalize
1498                   @Exists_append_r %2 @Exists_append_l @Exists_append_l
1499                   @Exists_append_r %1 %
1500              | 4: * [ 1: #Eq <Eq %1 %1 whd normalize
1501                       @Exists_append_r @(Exists_add ?? (nil ?)) @Exists_append_r
1502                       @Exists_append_r whd %1 //
1503                     | 2: * ]
1504              ]
1505| % %1 normalize @Exists_append_r %2 @Exists_append_l @Exists_append_l
1506  @Exists_append_r % %
1507| @(stmt_P_mp … Hind2) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1508   #l * try * [ 1: #H %1 %1 normalize @Exists_append_r @(Exists_add ?? (nil ?))
1509                   @Exists_append_r @Exists_append_l @Exists_append_l                   
1510                   @Exists_append_r %2 @Exists_append_l assumption
1511              | 2: #H %1 %2 assumption
1512              | 3: /2/
1513              ]
1514| whd %1 %1 normalize /2/
1515| whd %1 %1 normalize
1516  @Exists_append_r @(Exists_add ?? (nil ?)) @Exists_append_r @Exists_append_r
1517  whd %1 //
1518| normalize %2 /3/
1519| normalize /4/
1520| whd %1 %2 whd @(ex_intro … l) @E
1521] qed.
1522
1523(* params and statement aren't real parameters, they're just there for giving the invariant. *)
1524definition alloc_params :
1525 ∀vars:var_types.∀lbls,statement,uv,flag,rettyp. list (ident×type) → (Σsu:(tmpgen vars)×labgen×stmt. trans_inv vars lbls statement uv flag rettyp su)
1526   → res (Σsu:(tmpgen vars)×labgen×stmt.trans_inv vars lbls statement uv flag rettyp su) ≝   
1527λvars,lbls,statement,uv,ul,rettyp,params,s. foldl ?? (λsu,it.
1528  let 〈id,ty〉 ≝ it in
1529  do «result,Is» ← su;
1530  let 〈fgens1, s〉 as Eresult ≝ result in
1531  do 〈t,ty'〉 as E ← lookup' vars id;
1532  match t return λx.? → res (Σsu:(tmpgen vars)×labgen×stmt.trans_inv vars lbls statement uv ul rettyp su) with
1533  [ Local ⇒ λE. OK (Σs:(tmpgen vars)×labgen×stmt.?) «result,Is»
1534  | Stack n ⇒ λE.
1535      OK ? «〈fgens1, St_seq (St_store ? (Cst ? (Oaddrstack n)) (Id (typ_of_type ty') id)) s〉, ?»
1536  | Global _ ⇒ λE. Error ? [MSG ParamGlobalMixup; CTX ? id]
1537  ] E) (OK ? s) params.
1538whd
1539@(match fgens1 return λx.x=fgens1 → ? with
1540  [ mk_Prod uv1 ul1 ⇒ λHfgens1.? ] (refl ? fgens1))
1541whd in Is ⊢ %; destruct whd in Is;
1542try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @I
1543elim Is * * * #Hincl #Hstmt_inv #Hlab_tr #Hret #Htmp_pr try assumption
1544@(expr_vars_mp … (tmp_preserved … uv1)) whd >E @refl
1545qed.
1546
1547definition lenv_list_inv : lenv → lenv → list ident → Prop ≝
1548λlbls0,lbls,ls.
1549 ∀l,l'. lookup_label lbls l = OK ? l' →
1550 Exists ? (λl'. l' = l) ls ∨ lookup_label lbls0 l = OK ? l'.
1551
1552lemma lookup_label_add : ∀lbls,l,l'.
1553  lookup_label (add … lbls l l') l = OK ? l'.
1554#lbls #l #l' whd in ⊢ (??%?); >lookup_add_hit @refl
1555qed.
1556
1557lemma lookup_label_miss : ∀lbls,l,l',l0.
1558  l0 ≠ l →
1559  lookup_label (add … lbls l l') l0 = lookup_label lbls l0.
1560#lbls #l #l' #l0 #NE
1561whd in ⊢ (??%%);
1562>lookup_add_miss
1563[ @refl | @NE ]
1564qed.
1565
1566let rec populate_lenv (ls:list ident) (ul:labgen) (lbls:lenv): res ((Σlbls':lenv. lenv_list_inv lbls lbls' ls) × labgen) ≝
1567match ls return λls.res ((Σlbls':lenv. lenv_list_inv lbls lbls' ls) × labgen) with
1568[ nil ⇒ OK ? 〈«lbls, ?», ul〉
1569| cons l t ⇒
1570  match lookup_label lbls l return λlook. lookup_label lbls l = look → ? with
1571  [ OK _    ⇒ λ_.Error ? (msg DuplicateLabel)
1572  | Error _ ⇒ λLOOK.
1573    match generate_fresh_label … ul with
1574    [ mk_Sig ret H ⇒
1575       do 〈packed_lbls, ul1〉 ← populate_lenv t (snd ?? ret) (add … lbls l (fst ?? ret));
1576       match packed_lbls with
1577       [ mk_Sig lbls' Hinv ⇒ OK ? 〈«lbls', ?», ul1〉 ]
1578    ]
1579  ] (refl ? (lookup_label lbls l))
1580].
1581[ 1: whd #l #l' #Hlookup %2 assumption
1582| 2: whd in Hinv; whd #cl_lab #cm_lab #Hlookup
1583     @(eq_identifier_elim … l cl_lab)
1584     [ 1: #Heq %1 >Heq whd %1 //
1585     | 2: #Hneq cases (Hinv cl_lab cm_lab Hlookup)
1586           [ 1: #H %1 %2 @H
1587           | 2: #LOOK' %2 >lookup_label_miss in LOOK'; /2/ #H @H ]
1588     ]
1589]
1590qed.
1591
1592definition build_label_env :
1593   ∀body:statement. res ((Σlbls:lenv. ∀l,l'.lookup_label lbls l = OK ? l' → Exists ? (λl'.l' = l) (labels_defined body)) × labgen) ≝
1594λbody.
1595  let initial_labgen ≝ mk_labgen (new_universe ?) (nil ?) ?  in
1596  do 〈label_map, u〉 ← populate_lenv (labels_defined body) initial_labgen (empty_map ??);
1597  let lbls ≝ pi1 ?? label_map in
1598  let H    ≝ pi2 ?? label_map in
1599  OK ? 〈«lbls, ?», u〉.
1600[ 1: #l #l' #E cases (H l l' E) //
1601     whd in ⊢ (??%? → ?); #H destruct
1602| 2: whd @I ]
1603qed.
1604
1605lemma local_id_split : ∀vars,tmpgen,i,t.
1606  local_id (add_tmps vars (tmp_env vars tmpgen)) i t →
1607  local_id vars i t ∨ Exists ? (λx. \fst x = i ∧ typ_of_type (\snd x) = t) (tmp_env … tmpgen).
1608#vars #tmpgen #i #t
1609whd in ⊢ (?%?? → ?);
1610elim (tmp_env vars tmpgen)
1611[ #H %1 @H
1612| * #id #ty #tl #IH
1613  cases (identifier_eq ? i id)
1614  [ #E >E #H %2 whd %1 % [ @refl | whd in H; whd in H:(match % with [_⇒?|_⇒?]); >lookup_add_hit in H; #E1 >E1 @refl ]
1615  | #NE #H cases (IH ?)
1616    [ #H' %1 @H'
1617    | #H' %2 %2 @H'
1618    | whd in H; whd in H:(match % with [ _ ⇒ ? | _ ⇒ ? ]);
1619      >lookup_add_miss in H; [ #H @H | @NE ]
1620    ]
1621  ]
1622] qed.
1623
1624lemma Exists_squeeze : ∀A,P,l1,l2,l3.
1625  Exists A P (l1@l3) → Exists A P (l1@l2@l3).
1626#A #P #l1 #l2 #l3 #EX
1627cases (Exists_append … EX)
1628[ #EX1 @Exists_append_l @EX1
1629| #EX3 @Exists_append_r @Exists_append_r @EX3
1630] qed.
1631
1632(* This lemma allows to merge two stmt_P in one. Used in the following parts to merge an invariant on variables
1633   and an invariant on labels. *)
1634lemma stmt_P_conj : ∀ (P1:stmt → Prop). ∀ (P2:stmt → Prop). ∀ s. stmt_P P1 s → stmt_P P2 s → stmt_P (λs.P1 s ∧ P2 s) s.
1635#P1 #P2 #s elim s
1636normalize /6 by proj1, proj2, conj/
1637qed.
1638
1639definition translate_function :
1640  ∀tmpuniverse:universe SymbolTag.
1641  ∀globals:list (ident×region×type).
1642  ∀f:function.
1643    globals_fresh_for_univ ? globals tmpuniverse →
1644    fn_fresh_for_univ f tmpuniverse →
1645  res internal_function ≝
1646λtmpuniverse, globals, f, Fglobals, Ffn.
1647  do 〈env_pack, ul〉 ← build_label_env (fn_body f);
1648    match env_pack with
1649    [ mk_Sig lbls Ilbls ⇒
1650      let 〈vartypes, stacksize〉 as E ≝ characterise_vars globals f in
1651      let uv ≝ mk_tmpgen vartypes tmpuniverse [ ] ?? in
1652      do s0 ← translate_statement vartypes uv ul lbls DoNotConvert (opttyp_of_type (fn_return f)) (fn_body f);
1653      do «fgens, s1, Is» ← alloc_params vartypes lbls ? uv DoNotConvert (opttyp_of_type (fn_return f)) (fn_params f) s0;
1654      let params ≝ map ?? (λv.〈\fst v, typ_of_type (\snd v)〉) (fn_params f) in
1655      let vars ≝ map ?? (λv.〈\fst v, typ_of_type (\snd v)〉) (tmp_env ? (fst ?? fgens) @ fn_vars f) in
1656      do D ← check_distinct_env ?? (params @ vars);
1657      OK ? (mk_internal_function
1658        (opttyp_of_type (fn_return f))
1659        params
1660        vars
1661        D
1662        stacksize
1663        s1 ?)
1664  ].
1665[ 1: #i #t #Hloc whd @Hloc
1666| 2: whd #id #Hpresent normalize in Hpresent:(???%?); whd in Hpresent;
1667      @(characterise_vars_fresh … (sym_eq … E)) //
1668| 3: @(match fgens return λx.x=fgens → ? with
1669     [ mk_Prod uv' ul' ⇒ λHfgens.? ] (refl ? fgens))
1670     whd in Is; <Hfgens in Is; #Is whd in Is ⊢ %;
1671     elim Is * * * #Hstmt_inv #Hlab_trans #Htmps_pres #Hreturn #Hlabel_wf
1672     (* merge Hlabel_wf with Hstmt_inv and eliminate right away *)
1673     @(stmt_P_mp … (stmt_P_conj … (stmt_P_conj … Hstmt_inv Hlabel_wf) Hreturn))
1674     #s * * #Hstmt_vars #Hstmt_labels #Hstmt_return %
1675     [ 1: (* prove that variables are either parameters or locals *)
1676        @(stmt_vars_mp … Hstmt_vars) #i #t #H
1677        (* Case analysis: (i, t) is either in vartypes, or in (tmp_env vartypes uv) *)
1678        cases (local_id_split … H)
1679        [ 1: #H' >map_append
1680          @Exists_map [ 1: #x @(And (\fst x = i) (typ_of_type (\snd x) = t))  (* * #id #ty @(〈id, typ_of_type ty〉=〈i, t〉)*)
1681                      | 2: whd @Exists_squeeze @(characterise_vars_all globals f ?? (sym_eq ??? E) i t H')
1682                      | 3: * #id #ty * #E1 #E2 <E1 <E2 @refl
1683                      ]
1684        | 2: #EX @Exists_append_r whd in ⊢ (???%); <map_append @Exists_append_l
1685          @Exists_map [ 1: #x @(And (\fst x = i) (typ_of_type (\snd x) = t))
1686                      | 2: <Hfgens @EX
1687                      | 3: * #id #ty * #E1 #E2 <E1 <E2 % @refl
1688                      ]
1689        ]
1690     | 2: (* prove that labels are properly declared. *)
1691          @(stmt_labels_mp … Hstmt_labels) #l * *
1692          [ 1: #H assumption
1693          | 2: * #cl_label #Hlookup lapply (Ilbls cl_label l Hlookup) #Hdefined
1694                cases (Hlab_trans … Hdefined) #lx * #LOOKUPx >LOOKUPx in Hlookup; #Ex destruct (Ex)
1695                #H @H
1696          ]
1697     | cases s in Hstmt_return; // * normalize [2: * #t #e ]
1698       cases (fn_return f) normalize #A try #B try #C try #D try #E destruct //
1699    ]
1700] qed.   
1701
1702definition translate_fundef :
1703  ∀tmpuniverse:universe SymbolTag.
1704  ∀globals:list (ident×region×type).
1705    globals_fresh_for_univ ? globals tmpuniverse →
1706  ∀f:clight_fundef.
1707    fd_fresh_for_univ f tmpuniverse →
1708  res (fundef internal_function) ≝
1709λtmpuniverse,globals,Fglobals,f.
1710match f return λf. fd_fresh_for_univ f ? → ? with
1711[ CL_Internal fn ⇒ λFf. do fn' ← translate_function tmpuniverse globals fn Fglobals Ff; OK ? (Internal ? fn')
1712| CL_External fn argtys retty ⇒ λ_. OK ? (External ? (mk_external_function fn (signature_of_type argtys retty)))
1713].
1714
1715let rec map_partial_All (A,B:Type[0]) (P:A → Prop) (f:∀a:A. P a → res B)
1716  (l:list A) (H:All A P l) on l : res (list B) ≝
1717match l return λl. All A P l → ? with
1718[ nil ⇒ λ_. OK (list B) (nil B)
1719| cons hd tl ⇒ λH.
1720    do b_hd ← f hd (proj1 … H);
1721    do b_tl ← map_partial_All A B P f tl (proj2 … H);
1722      OK (list B) (cons B b_hd b_tl)
1723] H.
1724
1725definition clight_to_cminor : clight_program → res Cminor_program ≝
1726λp.
1727  let tmpuniverse ≝ universe_for_program p in
1728  let fun_globals ≝ map ?? (λidf. 〈\fst idf,Code,type_of_fundef (\snd idf)〉) (prog_funct ?? p) in
1729  let var_globals ≝ map ?? (λv. 〈\fst (\fst v), \snd (\fst v), \snd (\snd v)〉) (prog_vars ?? p) in
1730  let globals ≝ fun_globals @ var_globals in
1731  do fns ← map_partial_All ??? (λx,H. do f ← translate_fundef tmpuniverse globals ? (\snd x) H; OK ? 〈\fst x, f〉) (prog_funct ?? p) ?;
1732    OK ? (mk_program ??
1733      (map ?? (λv. 〈\fst v, \fst (\snd v)〉) (prog_vars ?? p))
1734      fns
1735      (prog_main ?? p)).
1736cases (prog_fresh p) * #H1 #H2 #H3
1737[ @(All_mp … H1) #x * //
1738| @All_append
1739  [ elim (prog_funct ?? p) in H1 ⊢ %; // * #id #fd #tl #IH * * #Hhd1 #Hhd2 #Htl % // @IH @Htl
1740  | whd in H3; elim (prog_vars ?? p) in H3 ⊢ %; // #hd #tl #IH * #Hhd #Htl % /2/
1741  ]
1742] qed.
1743
1744(* It'd be nice to go back to some generic thing like
1745
1746 transform_partial_program2 … p (translate_fundef tmpuniverse globals) (λi. OK ? (\fst i)).
1747
1748   rather than the messier definition above.
1749*)
Note: See TracBrowser for help on using the repository browser.