source: src/Clight/toCminor.ma @ 2582

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

Some progress on CL to CM.

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