File: INTGCODE.ML

package info (click to toggle)
polyml 5.8.1-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 57,736 kB
  • sloc: cpp: 44,918; ansic: 26,921; asm: 13,495; sh: 4,670; makefile: 610; exp: 525; python: 253; awk: 91
file content (1157 lines) | stat: -rw-r--r-- 53,121 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
(*
    Copyright (c) 2000
        Cambridge University Technical Services Limited
        
    Further development copyright David C.J. Matthews 2016-18,2020

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License version 2.1 as published by the Free Software Foundation.
    
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*)

(*
    Title:      Generate interpretable code for Poly system from the code tree.
    Author:     Dave Matthews, Cambridge University Computer Laboratory
    Copyright   Cambridge University 1985
*)

(* This generates byte-code that is interpreted by the run-time system.  It
   is now used as a fall-back to allow Poly/ML to run on non-X86 architectures.
   Early versions were used as a porting aid while a native code-generator
   was being developed and the "enter-int" instructions that were needed
   for that have been retained although they no longer actually generate code. *)
functor INTGCODE (
    structure CODECONS : INTCODECONSSIG
    structure BACKENDTREE: BackendIntermediateCodeSig
    structure CODE_ARRAY: CODEARRAYSIG
    
    sharing CODECONS.Sharing = BACKENDTREE.Sharing = CODE_ARRAY.Sharing

) : GENCODESIG =

struct

    open CODECONS
    open Address
    open BACKENDTREE
    open Misc
    open CODE_ARRAY

    val word0 = toMachineWord 0;
  
    val DummyValue : machineWord = word0; (* used as result of "raise e" etc. *)

    type caseForm =
        {
            cases   : (backendIC * word) list,
            test    : backendIC,
            caseType: caseType,
            default : backendIC
        }
   
    (* Where the result, if any, should go *)
    datatype whereto =
        NoResult     (* discard result *)
    |   ToStack     (* Need a result but it can stay on the pseudo-stack *);
  
    (* Are we at the end of the function. *)
    datatype tail =
        EndOfProc
    |   NotEnd

    (* Code generate a function or global declaration *)
    fun codegen (pt, cvec, resultClosure, numOfArgs, localCount, parameters) =
    let
        datatype decEntry =
            StackAddr of int
        |   Empty
    
        val decVec = Array.array (localCount, Empty)
    
        (* Count of number of items on the stack. *)
        val realstackptr = ref 1 (* The closure ptr is already there *)
        
        (* Maximum size of the stack. *)
        val maxStack = ref 1
        (* Exited - set to true if we have jumped out. *)
        val exited = ref false;

        (* Push a value onto the stack. *)
        fun incsp () =
        (
            realstackptr := !realstackptr + 1;
            if !realstackptr > !maxStack
            then maxStack := !realstackptr
            else ()
        )

        (* An entry has been removed from the stack. *)
        fun decsp () = realstackptr := !realstackptr - 1;
 
        fun pushLocalStackValue addr = ( genLocal(!realstackptr + addr, cvec); incsp() )

        (* Loads a local, argument or closure value; translating local
           stack addresses to real stack offsets. *)
        fun locaddr(BICLoadArgument locn) = pushLocalStackValue (numOfArgs-locn)

        |   locaddr(BICLoadLocal locn) =
            (
                (* positive address - on the stack. *)
                    case Array.sub (decVec, locn) of
                        StackAddr n => pushLocalStackValue (~ n)
                    |   _ => (* Should be on the stack, not a function. *)
                        raise InternalError "locaddr: bad stack address"
            )

        |   locaddr(BICLoadClosure locn) = (* closure-pointer relative *)
            (
                pushLocalStackValue ~1; (* The closure itself. *)
                genIndirect (locn+1, cvec) (* The value in the closure. +1 because first item is code addr. *)
            )

        |   locaddr BICLoadRecursive =
                pushLocalStackValue ~1 (* The closure itself - first value on the stack. *)

   (* generates code from the tree *)
   fun gencde (pt : backendIC, whereto : whereto, tailKind : tail, loopAddr) : unit =
   let
     (* Save the stack pointer value here. We may want to reset the stack. *)
     val oldsp = !realstackptr;

        (* Load the address and index value for byte operations.
           For ML memory operations the base is the address of an ML heap cell
           whereas for C operations it is a large-word box containing an
           address in C memory.  That doesn't affect this code but the interpreter
           has to deal with these differently. *)
        fun genByteAddress{base, index, offset} =
        (
            gencde (base, ToStack, NotEnd, loopAddr);
            (* Because the index and offset are both byte counts we can just add
               them if we need both. *)
            case (index, offset) of
                (NONE, offset) => (pushConst (toMachineWord offset, cvec); incsp())
            |   (SOME indexVal, 0w0) => gencde (indexVal, ToStack, NotEnd, loopAddr)
            |   (SOME indexVal, offset) =>
                (
                    gencde (indexVal, ToStack, NotEnd, loopAddr);
                    pushConst (toMachineWord offset, cvec);
                    genOpcode(opcode_wordAdd, cvec)
                )
       )
       
       (* Load the address, index value and offset for non-byte operations.
          Because the offset has already been scaled by the size of the operand
          we have to load the index and offset separately. *)
       fun genNonByteAddress{base, index, offset} =
        (
            gencde (base, ToStack, NotEnd, loopAddr);
            case index of
                NONE => (pushConst (toMachineWord 0, cvec); incsp())
            |   SOME indexVal => gencde (indexVal, ToStack, NotEnd, loopAddr);
            pushConst (toMachineWord offset, cvec); incsp()
        )

     val () =
       case pt of
            BICEval evl => genEval (evl, tailKind)

        |   BICExtract ext =>
            (* This may just be being used to discard a value which isn't
              used on this branch. *)
                if whereto = NoResult then () else locaddr ext

        |   BICField {base, offset} =>
                (gencde (base, ToStack, NotEnd, loopAddr); genIndirect (offset, cvec))

        |   BICLoadContainer {base, offset} =>
                (gencde (base, ToStack, NotEnd, loopAddr); genIndirect (offset, cvec))
       
        |   BICLambda lam => genProc (lam, false, fn () => ())
           
        |   BICConstnt(w, _) =>
            let
                val () = pushConst (w, cvec);
            in
                incsp ()
            end
  
        |   BICCond (testPart, thenPart, elsePart) =>
                genCond (testPart, thenPart, elsePart, whereto, tailKind, loopAddr)
  
        |   BICNewenv(decls, exp) =>
            let         
                (* Processes a list of entries. *)
            
                (* Mutually recursive declarations. May be either lambdas or constants. Recurse down
                   the list pushing the addresses of the closure vectors, then unwind the 
                   recursion and fill them in. *)
                fun genMutualDecs [] = ()

                |   genMutualDecs ({lambda, addr, ...} :: otherDecs) =
                        genProc (lambda, true,
                            fn() =>
                            (
                                Array.update (decVec, addr, StackAddr (! realstackptr));
                                genMutualDecs (otherDecs)
                            ))

                fun codeDecls(BICRecDecs dl) = genMutualDecs dl

                |   codeDecls(BICDecContainer{size, addr}) =
                    (
                        (* If this is a container we have to process it here otherwise it
                           will be removed in the stack adjustment code. *)
                        genContainer(size, cvec); (* Push the address of this container. *)
                        realstackptr := !realstackptr + size + 1; (* Pushes N words plus the address. *)
                        Array.update (decVec, addr, StackAddr(!realstackptr))
                    )

                |   codeDecls(BICDeclar{value, addr, ...}) =
                    (
                        gencde (value, ToStack, NotEnd, loopAddr);
                        Array.update (decVec, addr, StackAddr(!realstackptr))
                    )
                |   codeDecls(BICNullBinding exp) = gencde (exp, NoResult, NotEnd, loopAddr)
            in
                List.app codeDecls decls;
                gencde (exp, whereto, tailKind, loopAddr)
            end
          
        |   BICBeginLoop {loop=body, arguments} =>
            (* Execute the body which will contain at least one Loop instruction.
               There will also be path(s) which don't contain Loops and these
               will drop through. *)
            let
                val args = List.map #1 arguments
                (* Evaluate each of the arguments, pushing the result onto the stack. *)
                fun genLoopArg ({addr, value, ...}) =
                    (
                     gencde (value, ToStack, NotEnd, loopAddr);
                     Array.update (decVec, addr, StackAddr (!realstackptr));
                     !realstackptr (* Return the posn on the stack. *)
                    )
                val argIndexList = map genLoopArg args;

                val startSp = ! realstackptr; (* Remember the current top of stack. *)
                val startLoop = createLabel ()
                val () = setLabel(startLoop, cvec) (* Start of loop *)
            in
                (* Process the body, passing the jump-back address down for the Loop instruction(s). *)
                gencde (body, whereto, tailKind, SOME(startLoop, startSp, argIndexList))
                (* Leave the arguments on the stack.  They can be cleared later if needed. *)
            end

        |   BICLoop argList => (* Jump back to the enclosing BeginLoop. *)
            let
                val (startLoop, startSp, argIndexList) =
                    case loopAddr of
                        SOME l => l
                    |   NONE => raise InternalError "No BeginLoop for Loop instr"
                (* Evaluate the arguments.  First push them to the stack because evaluating
                   an argument may depend on the current value of others.  Only when we've
                   evaluated all of them can we overwrite the original argument positions. *)
                fun loadArgs ([], []) = !realstackptr - startSp (* The offset of all the args. *)
                  | loadArgs (arg:: argList, _ :: argIndexList) =
                    let
                        (* Evaluate all the arguments. *)
                        val () = gencde (arg, ToStack, NotEnd, NONE);
                        val argOffset = loadArgs(argList, argIndexList);
                    in
                        genSetStackVal(argOffset, cvec); (* Copy the arg over. *)
                        decsp(); (* The argument has now been popped. *)
                        argOffset
                    end
                  | loadArgs _ = raise InternalError "loadArgs: Mismatched arguments";

                val _: int = loadArgs(List.map #1 argList, argIndexList)
            in
                if !realstackptr <> startSp
                then resetStack (!realstackptr - startSp, false, cvec) (* Remove any local variables. *)
                else ();
            
                (* Jump back to the start of the loop. *)
                putBranchInstruction(Jump, startLoop, cvec)
            end
  
        |   BICRaise exp =>
            let
                val () = gencde (exp, ToStack, NotEnd, loopAddr)
                val () = genRaiseEx cvec;
            in
                exited := true
            end
  
        |   BICHandle {exp, handler, exPacketAddr} =>
            let
                (* Save old handler *)
                val () = genPushHandler cvec
                val () = incsp ()
                val handlerLabel = createLabel()
                val () = putBranchInstruction (SetHandler, handlerLabel, cvec)
                val () = incsp()
                (* Code generate the body; "NotEnd" because we have to come back
                 to remove the handler; "ToStack" because delHandler needs
                 a result to carry down. *)
                val () = gencde (exp, ToStack, NotEnd, loopAddr)
      
                (* Now get out of the handler and restore the old one. *)
                val () = genOpcode(opcode_deleteHandler, cvec)
                val skipHandler = createLabel()
                val () = putBranchInstruction (Jump, skipHandler, cvec)
          
                (* Now process the handler itself. First we have to reset the stack.
                   Note that we have to use "ToStack" again to be consistent with
                   the stack-handling in the body-part. If we actually wanted "NoResult",
                   the stack adjustment code at the end of gencde will take care
                   of this. This means that I don't want to do any clever "end-of-function"
                   optimisation either. SPF 6/1/97
                *)
                val () = realstackptr := oldsp
                val () = exited := false
                val () = setLabel (handlerLabel, cvec)
                (* If we were executing machine code we must re-enter the interpreter. *)
                val () = genEnterIntCatch cvec
                (* Push the exception packet and set the address. *)
                val () = genLdexc cvec
                val () = incsp ()
                val () = Array.update (decVec, exPacketAddr, StackAddr(!realstackptr))
                val () = gencde (handler, ToStack, NotEnd, loopAddr)
                (* Have to remove the exception packet. *)
                val () = resetStack(1, true, cvec)
                val () = decsp()
          
                (* Finally fix-up the jump around the handler *)
                val () = setLabel (skipHandler, cvec)
            in
                exited := false
            end
  
        |   BICCase ({cases, test, default, firstIndex, ...}) =>
            let
                val () = gencde (test, ToStack, NotEnd, loopAddr)
                (* Label to jump to at the end of each case. *)
                val exitJump = createLabel()

                val () =
                    if firstIndex = 0w0 then ()
                    else
                    (   (* Subtract lower limit.  Don't check for overflow.  Instead
                           allow large value to wrap around and check in "case" instruction. *)
                        pushConst(toMachineWord firstIndex, cvec);
                        genOpcode(opcode_wordSub, cvec)
                    )

                (* Generate the case instruction followed by the table of jumps.  *)
                val nCases = List.length cases
                val caseLabels = genCase (nCases, cvec)
                val () = decsp ()

                (* The default case, if any, follows the case statement. *)
                (* If we have a jump to the default set it to jump here. *)
                local
                    fun fixDefault(NONE, defCase) = setLabel(defCase, cvec)
                    |   fixDefault(SOME _, _) = ()
                in
                    val () = ListPair.appEq fixDefault (cases, caseLabels)
                end
                val () = gencde (default, whereto, tailKind, loopAddr);

                val () = exited := false;
                
                fun genCases(SOME body, label) =
                    (
                        (* First exit from the previous case or the default if
                           this is the first. *)
                        if !exited then () else putBranchInstruction(Jump, exitJump, cvec);
                        (* Remove the result - the last case will leave it. *)
                        case whereto of ToStack => decsp () | NoResult => ();
                        (* Fix up the jump to come here. *)
                        setLabel(label, cvec);
                        exited := false;
                        gencde (body, whereto, tailKind, loopAddr)
                    )
                |   genCases(NONE, _) = ()
                
                val () = ListPair.appEq genCases (cases, caseLabels)
     
                (* Finally set the exit jump to come here. *)
                val () = setLabel (exitJump, cvec)
            in
                exited := false
            end
  
        |   BICTuple recList =>
            let
                val size = List.length recList
            in
                (* Move the fields into the vector. *)
                List.app(fn v => gencde (v, ToStack, NotEnd, loopAddr)) recList;
                genTuple (size, cvec);
                realstackptr := !realstackptr - (size - 1)
            end

        |   BICSetContainer{container, tuple, filter} =>
            (* Copy the contents of a tuple into a container.  If the tuple is a
               Tuple instruction we can avoid generating the tuple and then
               unpacking it and simply copy the fields that make up the tuple
               directly into the container. *)
            (
                case tuple of
                    BICTuple cl =>
                        (* Simply set the container from the values. *)
                    let
                        (* Load the address of the container. *)
                        val _ = gencde (container, ToStack, NotEnd, loopAddr);
                        fun setValues([], _, _) = ()

                        |   setValues(v::tl, sourceOffset, destOffset) =
                            if sourceOffset < BoolVector.length filter andalso BoolVector.sub(filter, sourceOffset)
                            then
                            (
                                gencde (v, ToStack, NotEnd, loopAddr);
                                (* Move the entry into the container. This instruction
                                   pops the value to be moved but not the destination. *)
                                genMoveToVec(destOffset, cvec);
                                decsp();
                                setValues(tl, sourceOffset+1, destOffset+1)
                            )
                            else setValues(tl, sourceOffset+1, destOffset)
                    in
                        setValues(cl, 0, 0)
                        (* The container address is still on the stack. *)
                    end

                |   _ =>
                    let (* General case. *)
                        (* First the target tuple, then the container. *)
                        val () = gencde (tuple, ToStack, NotEnd, loopAddr)
                        val () = gencde (container, ToStack, NotEnd, loopAddr)
                        val last = BoolVector.foldli(fn (i, true, _) => i | (_, false, n) => n) ~1 filter

                        fun copy (sourceOffset, destOffset) =
                            if BoolVector.sub(filter, sourceOffset)
                            then
                            (
                                (* Duplicate the tuple address . *)
                                genLocal(1, cvec);
                                genIndirect(sourceOffset, cvec);
                                genMoveToVec(destOffset, cvec);
                                if sourceOffset = last
                                then ()
                                else copy (sourceOffset+1, destOffset+1)
                            )
                            else copy(sourceOffset+1, destOffset)
                    in
                        copy (0, 0)
                        (* The container and tuple addresses are still on the stack. *)
                    end
            )

        |   BICTagTest { test, tag, ... } =>
            (
                (* Convert this into a simple equality function. *)
                gencde (test, ToStack, NotEnd, loopAddr);
                pushConst (toMachineWord tag, cvec);
                genOpcode(opcode_equalWord, cvec)
            )

        |   BICGetThreadId =>
            (
                genOpcode(opcode_getThreadId, cvec);
                incsp()
            )

        |   BICUnary { oper, arg1 } =>
            let
                open BuiltIns
                val () = gencde (arg1, ToStack, NotEnd, loopAddr)
            in
                case oper of
                    NotBoolean => genOpcode(opcode_notBoolean, cvec)
                |   IsTaggedValue => genOpcode(opcode_isTagged, cvec)
                |   MemoryCellLength => genOpcode(opcode_cellLength, cvec)
                |   MemoryCellFlags => genOpcode(opcode_cellFlags, cvec)
                |   ClearMutableFlag => genOpcode(opcode_clearMutable, cvec)
                |   AtomicIncrement => genOpcode(opcode_atomicIncr, cvec)
                |   AtomicDecrement => genOpcode(opcode_atomicDecr, cvec)
                |   AtomicReset => genOpcode(opcode_atomicReset, cvec)
                |   LongWordToTagged => genOpcode(opcode_longWToTagged, cvec)
                |   SignedToLongWord => genOpcode(opcode_signedToLongW, cvec)
                |   UnsignedToLongWord => genOpcode(opcode_unsignedToLongW, cvec)
                |   RealAbs PrecDouble => genOpcode(opcode_realAbs, cvec)
                |   RealNeg PrecDouble => genOpcode(opcode_realNeg, cvec)
                |   RealFixedInt PrecDouble => genOpcode(opcode_fixedIntToReal, cvec)
                |   RealAbs PrecSingle => genOpcode(opcode_floatAbs, cvec)
                |   RealNeg PrecSingle => genOpcode(opcode_floatNeg, cvec)
                |   RealFixedInt PrecSingle => genOpcode(opcode_fixedIntToFloat, cvec)
                |   FloatToDouble => genOpcode(opcode_floatToReal, cvec)
                |   DoubleToFloat rnding => genDoubleToFloat(rnding, cvec)
                |   RealToInt (PrecDouble, rnding) => genRealToInt(rnding, cvec)
                |   RealToInt (PrecSingle, rnding) => genFloatToInt(rnding, cvec)
                |   TouchAddress => resetStack(1, false, cvec) (* Discard this *)
            end

        |   BICBinary { oper, arg1, arg2 } =>
            let
                open BuiltIns
                val () = gencde (arg1, ToStack, NotEnd, loopAddr)
                val () = gencde (arg2, ToStack, NotEnd, loopAddr)
            in
                case oper of
                    WordComparison{test=TestEqual, ...} => genOpcode(opcode_equalWord, cvec)
                |   WordComparison{test=TestLess, isSigned=true} => genOpcode(opcode_lessSigned, cvec)
                |   WordComparison{test=TestLessEqual, isSigned=true} => genOpcode(opcode_lessEqSigned, cvec)
                |   WordComparison{test=TestGreater, isSigned=true} => genOpcode(opcode_greaterSigned, cvec)
                |   WordComparison{test=TestGreaterEqual, isSigned=true} => genOpcode(opcode_greaterEqSigned, cvec)
                |   WordComparison{test=TestLess, isSigned=false} => genOpcode(opcode_lessUnsigned, cvec)
                |   WordComparison{test=TestLessEqual, isSigned=false} => genOpcode(opcode_lessEqUnsigned, cvec)
                |   WordComparison{test=TestGreater, isSigned=false} => genOpcode(opcode_greaterUnsigned, cvec)
                |   WordComparison{test=TestGreaterEqual, isSigned=false} => genOpcode(opcode_greaterEqUnsigned, cvec)
                |   WordComparison{test=TestUnordered, ...} => raise InternalError "WordComparison: TestUnordered"

                |   FixedPrecisionArith ArithAdd => genOpcode(opcode_fixedAdd, cvec)
                |   FixedPrecisionArith ArithSub => genOpcode(opcode_fixedSub, cvec)
                |   FixedPrecisionArith ArithMult => genOpcode(opcode_fixedMult, cvec)
                |   FixedPrecisionArith ArithQuot => genOpcode(opcode_fixedQuot, cvec)
                |   FixedPrecisionArith ArithRem => genOpcode(opcode_fixedRem, cvec)
                |   FixedPrecisionArith ArithDiv => raise InternalError "TODO: FixedPrecisionArith ArithDiv"
                |   FixedPrecisionArith ArithMod => raise InternalError "TODO: FixedPrecisionArith ArithMod"

                |   WordArith ArithAdd => genOpcode(opcode_wordAdd, cvec)
                |   WordArith ArithSub => genOpcode(opcode_wordSub, cvec)
                |   WordArith ArithMult => genOpcode(opcode_wordMult, cvec)
                |   WordArith ArithDiv => genOpcode(opcode_wordDiv, cvec)
                |   WordArith ArithMod => genOpcode(opcode_wordMod, cvec)
                |   WordArith _ => raise InternalError "WordArith - unimplemented instruction"
                
                |   WordLogical LogicalAnd => genOpcode(opcode_wordAnd, cvec)
                |   WordLogical LogicalOr => genOpcode(opcode_wordOr, cvec)
                |   WordLogical LogicalXor => genOpcode(opcode_wordXor, cvec)

                |   WordShift ShiftLeft => genOpcode(opcode_wordShiftLeft, cvec)
                |   WordShift ShiftRightLogical => genOpcode(opcode_wordShiftRLog, cvec)
                |   WordShift ShiftRightArithmetic => genOpcode(opcode_wordShiftRArith, cvec)
                 
                |   AllocateByteMemory => genOpcode(opcode_allocByteMem, cvec)
                
                |   LargeWordComparison TestEqual => genOpcode(opcode_lgWordEqual, cvec)
                |   LargeWordComparison TestLess => genOpcode(opcode_lgWordLess, cvec)
                |   LargeWordComparison TestLessEqual => genOpcode(opcode_lgWordLessEq, cvec)
                |   LargeWordComparison TestGreater => genOpcode(opcode_lgWordGreater, cvec)
                |   LargeWordComparison TestGreaterEqual => genOpcode(opcode_lgWordGreaterEq, cvec)
                |   LargeWordComparison TestUnordered => raise InternalError "LargeWordComparison: TestUnordered"
                
                |   LargeWordArith ArithAdd => genOpcode(opcode_lgWordAdd, cvec)
                |   LargeWordArith ArithSub => genOpcode(opcode_lgWordSub, cvec)
                |   LargeWordArith ArithMult => genOpcode(opcode_lgWordMult, cvec)
                |   LargeWordArith ArithDiv => genOpcode(opcode_lgWordDiv, cvec)
                |   LargeWordArith ArithMod => genOpcode(opcode_lgWordMod, cvec)
                |   LargeWordArith _ => raise InternalError "LargeWordArith - unimplemented instruction"

                |   LargeWordLogical LogicalAnd => genOpcode(opcode_lgWordAnd, cvec)
                |   LargeWordLogical LogicalOr => genOpcode(opcode_lgWordOr, cvec)
                |   LargeWordLogical LogicalXor => genOpcode(opcode_lgWordXor, cvec)
                |   LargeWordShift ShiftLeft => genOpcode(opcode_lgWordShiftLeft, cvec)
                |   LargeWordShift ShiftRightLogical => genOpcode(opcode_lgWordShiftRLog, cvec)
                |   LargeWordShift ShiftRightArithmetic => genOpcode(opcode_lgWordShiftRArith, cvec)

                |   RealComparison (TestEqual, PrecDouble) => genOpcode(opcode_realEqual, cvec)
                |   RealComparison (TestLess, PrecDouble) => genOpcode(opcode_realLess, cvec)
                |   RealComparison (TestLessEqual, PrecDouble) => genOpcode(opcode_realLessEq, cvec)
                |   RealComparison (TestGreater, PrecDouble) => genOpcode(opcode_realGreater, cvec)
                |   RealComparison (TestGreaterEqual, PrecDouble) => genOpcode(opcode_realGreaterEq, cvec)
                |   RealComparison (TestUnordered, PrecDouble) => genOpcode(opcode_realUnordered, cvec)

                |   RealComparison (TestEqual, PrecSingle) => genOpcode(opcode_floatEqual, cvec)
                |   RealComparison (TestLess, PrecSingle) => genOpcode(opcode_floatLess, cvec)
                |   RealComparison (TestLessEqual, PrecSingle) => genOpcode(opcode_floatLessEq, cvec)
                |   RealComparison (TestGreater, PrecSingle) => genOpcode(opcode_floatGreater, cvec)
                |   RealComparison (TestGreaterEqual, PrecSingle) => genOpcode(opcode_floatGreaterEq, cvec)
                |   RealComparison (TestUnordered, PrecSingle) => genOpcode(opcode_floatUnordered, cvec)

                |   RealArith (ArithAdd, PrecDouble) => genOpcode(opcode_realAdd, cvec)
                |   RealArith (ArithSub, PrecDouble) => genOpcode(opcode_realSub, cvec)
                |   RealArith (ArithMult, PrecDouble) => genOpcode(opcode_realMult, cvec)
                |   RealArith (ArithDiv, PrecDouble) => genOpcode(opcode_realDiv, cvec)

                |   RealArith (ArithAdd, PrecSingle) => genOpcode(opcode_floatAdd, cvec)
                |   RealArith (ArithSub, PrecSingle) => genOpcode(opcode_floatSub, cvec)
                |   RealArith (ArithMult, PrecSingle) => genOpcode(opcode_floatMult, cvec)
                |   RealArith (ArithDiv, PrecSingle) => genOpcode(opcode_floatDiv, cvec)

                |   RealArith _ => raise InternalError "RealArith - unimplemented instruction"
                 ;
                decsp() (* Removes one item from the stack. *)
            end
            
        |   BICAllocateWordMemory {numWords as BICConstnt(length, _), flags as BICConstnt(flagByte, _), initial } =>
            if isShort length andalso toShort length = 0w1 andalso isShort flagByte andalso toShort flagByte = 0wx40
            then (* This is a very common case. *)
            (
                gencde (initial, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_alloc_ref, cvec)
            )
            else
            let
                val () = gencde (numWords, ToStack, NotEnd, loopAddr)
                val () = gencde (flags, ToStack, NotEnd, loopAddr)
                val () = gencde (initial, ToStack, NotEnd, loopAddr)
            in
                genOpcode(opcode_allocWordMemory, cvec);
                decsp(); decsp()
            end

        |   BICAllocateWordMemory { numWords, flags, initial } =>
            let
                val () = gencde (numWords, ToStack, NotEnd, loopAddr)
                val () = gencde (flags, ToStack, NotEnd, loopAddr)
                val () = gencde (initial, ToStack, NotEnd, loopAddr)
            in
                genOpcode(opcode_allocWordMemory, cvec);
                decsp(); decsp()
            end

        |   BICLoadOperation { kind=LoadStoreMLWord _, address={base, index=NONE, offset}} =>
            (
                (* If the index is a constant, frequently zero, we can use indirection.
                   The offset is a byte count so has to be divided by the word size but
                   it should always be an exact multiple. *)
                gencde (base, ToStack, NotEnd, loopAddr);
                offset mod wordSize = 0w0 orelse raise InternalError "gencde: BICLoadOperation - not word multiple";
                genIndirect (Word.toInt(offset div wordSize), cvec)
            )

        |   BICLoadOperation { kind=LoadStoreMLWord _, address={base, index=SOME indexVal, offset}} =>
            let
                (* Variable index. *)
                val () = gencde (base, ToStack, NotEnd, loopAddr)
                val () = gencde (indexVal, ToStack, NotEnd, loopAddr)
                val () = (pushConst (toMachineWord offset, cvec); incsp())
            in
                genOpcode(opcode_loadMLWord, cvec);
                decsp(); decsp()
            end

        |   BICLoadOperation { kind=LoadStoreMLByte _, address} =>
            (
                genByteAddress address;
                genOpcode(opcode_loadMLByte, cvec);
                decsp()
            )

        |   BICLoadOperation { kind=LoadStoreC8, address} =>
            (
                genByteAddress address;
                genOpcode(opcode_loadC8, cvec);
                decsp()
            )

        |   BICLoadOperation { kind=LoadStoreC16, address} =>
            (
                genNonByteAddress address;
                genOpcode(opcode_loadC16, cvec);
                decsp(); decsp()
            )

        |   BICLoadOperation { kind=LoadStoreC32, address} =>
            (
                genNonByteAddress address;
                genOpcode(opcode_loadC32, cvec);
                decsp(); decsp()
            )

        |   BICLoadOperation { kind=LoadStoreC64, address} =>
            (
                wordSize = 0w8 orelse raise InternalError "LoadStoreC64 but not 64-bit mode";
                genNonByteAddress address;
                genOpcode(opcode_loadC64, cvec);
                decsp(); decsp()
            )

        |   BICLoadOperation { kind=LoadStoreCFloat, address} =>
            (
                genNonByteAddress address;
                genOpcode(opcode_loadCFloat, cvec);
                decsp(); decsp()
            )

        |   BICLoadOperation { kind=LoadStoreCDouble, address} =>
            (
                genNonByteAddress address;
                genOpcode(opcode_loadCDouble, cvec);
                decsp(); decsp()
            )

        |   BICLoadOperation { kind=LoadStoreUntaggedUnsigned, address} =>
            (
                genNonByteAddress address;
                genOpcode(opcode_loadUntagged, cvec);
                decsp(); decsp()
            )

        |   BICStoreOperation { kind=LoadStoreMLWord _, address={base, index=NONE, offset}, value } =>
            let
                (* No index.  We could almost use move_to_vec here except that it leaves
                   the destination address on the stack instead of replacing it with "unit". *)
                val () = gencde (base, ToStack, NotEnd, loopAddr)
                val () = pushConst (toMachineWord 0, cvec)
                val () = incsp()
                val () = pushConst (toMachineWord offset, cvec)
                val () = incsp()
                val () = gencde (value, ToStack, NotEnd, loopAddr)
            in
                genOpcode(opcode_storeMLWord, cvec);
                decsp(); decsp(); decsp()
            end

        |   BICStoreOperation { kind=LoadStoreMLWord _, address={base, index=SOME indexVal, offset}, value } =>
            let
                (* Variable index *)
                val () = gencde (base, ToStack, NotEnd, loopAddr)
                val () = gencde (indexVal, ToStack, NotEnd, loopAddr)
                val () = pushConst (toMachineWord offset, cvec)
                val () = incsp()
                val () = gencde (value, ToStack, NotEnd, loopAddr)
            in
                genOpcode(opcode_storeMLWord, cvec);
                decsp(); decsp(); decsp()
            end

        |   BICStoreOperation { kind=LoadStoreMLByte _, address, value } =>
            (
                genByteAddress address;
                gencde (value, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_storeMLByte, cvec);
                decsp(); decsp()
            )

        |   BICStoreOperation { kind=LoadStoreC8, address, value} =>
            (
                genByteAddress address;
                gencde (value, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_storeC8, cvec);
                decsp(); decsp()
            )

        |   BICStoreOperation { kind=LoadStoreC16, address, value} =>
            (
                genNonByteAddress address;
                gencde (value, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_storeC16, cvec);
                decsp(); decsp(); decsp()
            )

        |   BICStoreOperation { kind=LoadStoreC32, address, value} =>
            (
                genNonByteAddress address;
                gencde (value, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_storeC32, cvec);
                decsp(); decsp(); decsp()
            )

        |   BICStoreOperation { kind=LoadStoreC64, address, value} =>
            (
                genNonByteAddress address;
                gencde (value, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_storeC64, cvec);
                decsp(); decsp(); decsp()
            )

        |   BICStoreOperation { kind=LoadStoreCFloat, address, value} =>
            (
                genNonByteAddress address;
                gencde (value, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_storeCFloat, cvec);
                decsp(); decsp(); decsp()
            )

        |   BICStoreOperation { kind=LoadStoreCDouble, address, value} =>
            (
                genNonByteAddress address;
                gencde (value, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_storeCDouble, cvec);
                decsp(); decsp(); decsp()
            )

        |   BICStoreOperation { kind=LoadStoreUntaggedUnsigned, address, value} =>
            (
                genNonByteAddress address;
                gencde (value, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_storeUntagged, cvec);
                decsp(); decsp(); decsp()
            )

        |   BICBlockOperation { kind=BlockOpMove{isByteMove=true}, sourceLeft, destRight, length } =>
            (
                genByteAddress sourceLeft;
                genByteAddress destRight;
                gencde (length, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_blockMoveByte, cvec);
                decsp(); decsp(); decsp(); decsp()
            )

        |   BICBlockOperation { kind=BlockOpMove{isByteMove=false}, sourceLeft, destRight, length } =>
            (
                genNonByteAddress sourceLeft;
                genNonByteAddress destRight;
                gencde (length, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_blockMoveWord, cvec);
                decsp(); decsp(); decsp(); decsp(); decsp(); decsp()
            )

        |   BICBlockOperation { kind=BlockOpEqualByte, sourceLeft, destRight, length } =>
            (
                genByteAddress sourceLeft;
                genByteAddress destRight;
                gencde (length, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_blockEqualByte, cvec);
                decsp(); decsp(); decsp(); decsp()
            )

        |   BICBlockOperation { kind=BlockOpCompareByte, sourceLeft, destRight, length } =>
            (
                genByteAddress sourceLeft;
                genByteAddress destRight;
                gencde (length, ToStack, NotEnd, loopAddr);
                genOpcode(opcode_blockCompareByte, cvec);
                decsp(); decsp(); decsp(); decsp()
            )
       
       |    BICArbitrary { longCall, ... } =>
                (* Just use the long-precision case in the interpreted version. *)
            (
                gencde (longCall, whereto, tailKind, loopAddr)
            )

    in (* body of gencde *) 

      (* This ensures that there is precisely one item on the stack if
         whereto = ToStack and no items if whereto = NoResult. 
         There are two points to note carefully here:
           (1) Negative stack adjustments are legal if we have exited.
               This is because matchFailFn can cut the stack back too
               far for its immediately enclosing expression. This is
               harmless because the code actually exits that expression.
           (2) A stack adjustment of ~1 is legal if we're generating
               a declaration in "ToStack" mode, because not all declarations
               actually generate the dummy value that we expect. This
               used to be handled in resetStack itself, but it's more
               transparent to do it here. (In addition, there was a bug in
               resetStack - it accumulated the stack resets, but didn't
               correctly accumulate these "~1" dummy value pushes.)
               It's all much better now.
               SPF 9/1/97
     *)
        case whereto of
            ToStack =>
            let
                val newsp = oldsp + 1;
                val adjustment = !realstackptr - newsp

                val () =
                    if !exited orelse adjustment = 0
                    then ()
                    else if adjustment < ~1
                    then raise InternalError ("gencde: bad adjustment " ^ Int.toString adjustment)
                    (* Hack for declarations that should push values, but don't *)
                    else if adjustment = ~1
                    then pushConst (DummyValue, cvec)
                    else resetStack (adjustment, true, cvec)
            in
                realstackptr := newsp
            end
          
        |   NoResult =>
            let
                val adjustment = !realstackptr - oldsp

                val () =
                    if !exited orelse adjustment = 0
                    then ()
                    else if adjustment < 0
                    then raise InternalError ("gencde: bad adjustment " ^ Int.toString adjustment)
                    else resetStack (adjustment, false, cvec)
            in
                realstackptr := oldsp
            end
    end (* gencde *)

   (* doNext is only used for mutually recursive functions where a
     function may not be able to fill in its closure if it does not have
     all the remaining declarations. *)
    (* TODO: This always creates the closure on the heap even when makeClosure is false. *) 
   and genProc ({ closure=[], localCount, body, argTypes, name, ...}: bicLambdaForm, mutualDecs, doNext: unit -> unit) : unit =
        let
            (* Create a one word item for the closure.  This is returned for recursive references
               and filled in with the address of the code when we've finished. *)
            val closure = makeConstantClosure()
            val newCode : code = codeCreate(name, parameters);

            (* Code-gen function. No non-local references. *)
             val () =
               codegen (body, newCode, closure, List.length argTypes, localCount, parameters);
            val () = pushConst(closureAsAddress closure, cvec);
            val () = incsp();
        in
            if mutualDecs then doNext () else ()
        end

    |   genProc ({ localCount, body, name, argTypes, closure, ...}, mutualDecs, doNext) =
        let (* Full closure required. *)
            val resClosure = makeConstantClosure()
            val newCode = codeCreate (name, parameters)
            (* Code-gen function. *)
            val () = codegen (body, newCode, resClosure, List.length argTypes, localCount, parameters)
            val sizeOfClosure = List.length closure + 1;
        in
            if mutualDecs
            then
            let (* Have to make the closure now and fill it in later. *)
                (* This previously used genGetStore which at one time was widely used. *)
                val () = pushConst(toMachineWord sizeOfClosure, cvec) (* Length *)
                val () = pushConst(toMachineWord F_mutable, cvec) (* Flags *)
                val () = pushConst(toMachineWord 0, cvec) (* Initialise to zero. *)
                val () = genOpcode(opcode_allocWordMemory, cvec) (* Allocate the memory. *)
                val () = incsp ()
           
                (* Put code address into closure *) 
                val () = pushConst(codeAddressFromClosure resClosure, cvec) 
                val () = genMoveToVec(0, cvec)
           
                val entryAddr : int = !realstackptr

                val () = doNext () (* Any mutually recursive functions. *)

                (* Push the address of the vector - If we have processed other
                   closures the vector will no longer be on the top of the stack. *)
                val () = pushLocalStackValue (~ entryAddr)

                (* Load items for the closure. *)
                fun loadItems ([], _) = ()
                |   loadItems (v :: vs, addr : int) =
                let
                    (* Generate an item and move it into the vector *)
                    val () = gencde (BICExtract v, ToStack, NotEnd, NONE)
                    val () = genMoveToVec(addr, cvec)
                    val () = decsp ()
                in
                    loadItems (vs, addr + 1)
                end
             
                val () = loadItems (closure, 1)
                val () = genLock cvec (* Lock it. *)
           
                (* Remove the extra reference. *)
                val () = resetStack (1, false, cvec)
            in
                realstackptr := !realstackptr - 1
            end
         
            else
            let
                (* Put it on the stack. *)
                val () = pushConst (codeAddressFromClosure resClosure, cvec)
                val () = incsp ()
                val () = List.app (fn pt => gencde (BICExtract pt, ToStack, NotEnd, NONE)) closure
                val () = genTuple (sizeOfClosure, cvec)
            in
                realstackptr := !realstackptr - (sizeOfClosure - 1)
            end
        end

    and genCond (testCode, thenCode, elseCode, whereto, tailKind, loopAddr) =
    let
        val () = gencde (testCode, ToStack, NotEnd, loopAddr)
        val toElse = createLabel() and exitJump = createLabel()
        val () = putBranchInstruction(JumpFalse, toElse, cvec)
        val () = decsp()
        val () = gencde (thenCode, whereto, tailKind, loopAddr)
        (* Get rid of the result from the stack. If there is a result then the
        ``else-part'' will push it. *)
        val () = case whereto of ToStack => decsp () | NoResult => ()

        val thenExited = !exited

        val () = if thenExited then () else putBranchInstruction (Jump, exitJump, cvec)

        (* start of "else part" *)
        val () = setLabel (toElse, cvec)
        val () = exited := false
        val () = gencde (elseCode, whereto, tailKind, loopAddr)

        val elseExited = !exited

        val () = setLabel (exitJump, cvec)
    in
        exited := (thenExited andalso elseExited) (* Only exited if both sides did. *)
    end (* genCond *)

    and genEval (eval, tailKind : tail) : unit =
    let
        val argList : backendIC list = List.map #1 (#argList eval)
        val argsToPass : int = List.length argList;

        (* Load arguments *)
        fun loadArgs [] = ()
        |   loadArgs (v :: vs) =
        let (* Push each expression onto the stack. *)
            val () = gencde(v, ToStack, NotEnd, NONE)
        in
            loadArgs vs
        end;

        (* Called after the args and the closure to call have been pushed
            onto the stack. *)
        fun callClosure () : unit =
            case tailKind of
                NotEnd => (* Normal call. *) genCallClosure cvec
         
            |   EndOfProc => (* Tail recursive call. *)
                let
                    (* Get the return address onto the top of the stack. *)
                    val () = pushLocalStackValue 0
           
                    (* Slide the return address, closure and args over the
                      old closure, return address and args, and reset the
                      stack. Then jump to the closure. *)
                    val () =
                        genTailCall(argsToPass + 2, !realstackptr - 1 + (numOfArgs - argsToPass), cvec);
                        (* It's "-1" not "-2", because we didn't bump the realstackptr
                           when we pushed the return address. SPF 3/1/97 *)
                in
                    exited := true
                end

        (* Have to guarantee that the expression to return the function
          is evaluated before the arguments. *)

        (* Returns true if evaluating it later is safe. *)
        fun safeToLeave (BICConstnt _) = true
        |   safeToLeave (BICLambda _) = true
        |   safeToLeave (BICExtract _) = true
        |   safeToLeave (BICField {base, ...}) = safeToLeave base
        |   safeToLeave (BICLoadContainer {base, ...}) = safeToLeave base
        |   safeToLeave _ = false

        val () =
            if (case argList of [] => true | _ => safeToLeave (#function eval))
            then
            let
                (* Can load the args first. *)
                val () = loadArgs argList
            in 
                gencde (#function eval, ToStack, NotEnd, NONE)
            end

            else
            let
                (* The expression for the function is too complicated to
                   risk leaving. It might have a side-effect and we must
                   ensure that any side-effects it has are done before the
                   arguments are loaded. *)
                val () = gencde(#function eval, ToStack, NotEnd, NONE);
                val () = loadArgs(argList);
                (* Load the function again. *)
                val () = genLocal(argsToPass, cvec);
            in
                incsp ()
            end

        val () = callClosure () (* Call the function. *)

        (* Make sure we interpret when we return from the call *)
        val () = genEnterIntCall (cvec, argsToPass)

    in (* body of genEval *)
        realstackptr := !realstackptr - argsToPass (* Args popped by caller. *)
    end

   (* Generate the function. *)
   (* Assume we always want a result. There is otherwise a problem if the
      called routine returns a result of type void (i.e. no result) but the
      caller wants a result (e.g. the identity function). *)
    val () = gencde (pt, ToStack, EndOfProc, NONE)

    val () = if !exited then () else genReturn (numOfArgs, cvec);
    in (* body of codegen *)
       (* Having code-generated the body of the function, it is copied
          into a new data segment. *)
        copyCode(cvec, !maxStack, resultClosure)
    end (* codegen *);

    fun gencodeLambda({ name, body, argTypes, localCount, ...}:bicLambdaForm, parameters, closure) =
    let
        (* make the code buffer for the new function. *)
        val newCode : code = codeCreate (name, parameters)
        (* This function must have no non-local references. *)
    in
        codegen (body, newCode, closure, List.length argTypes, localCount, parameters)
    end

    local
        val makeEntryPoint: string -> machineWord = RunCall.rtsCallFull1 "PolyCreateEntryPointObject"

        fun rtsCall makeCall (entryName: string, numOfArgs, debugArgs: Universal.universal list): machineWord =
        let
            open Address
            val cvec = codeCreate (entryName, debugArgs)
            
            val entryPointAddr = makeEntryPoint entryName

            (* Each argument is at the same offset, essentially we're just shifting them *)
            fun genLocals 0 = ()
            |   genLocals n = (genLocal(numOfArgs +1, cvec); genLocals (n-1))
            val () = genLocals numOfArgs

            val () = pushConst(entryPointAddr, cvec)
            val () = makeCall(numOfArgs, cvec)
            val () = genReturn (numOfArgs, cvec)
            val closure = makeConstantClosure()
        
            val () = copyCode(cvec, numOfArgs+1, closure)
        in
            closureAsAddress closure
        end
    in
        structure Foreign = 
        struct

            val rtsCallFast = rtsCall genRTSCallFast
            and rtsCallFull = rtsCall genRTSCallFull
            
            fun rtsCallFastRealtoReal(entryName, debugArgs) =
                rtsCall (fn (_, c) => genRTSCallFastRealtoReal c) (entryName, 1, debugArgs)
            and rtsCallFastRealRealtoReal(entryName, debugArgs) =
                rtsCall (fn (_, c) => genRTSCallFastRealRealtoReal c) (entryName, 2, debugArgs)
            and rtsCallFastGeneraltoReal(entryName, debugArgs) =
                rtsCall (fn (_, c) => genRTSCallFastGeneraltoReal c) (entryName, 1, debugArgs)
            and rtsCallFastRealGeneraltoReal(entryName, debugArgs) =
                rtsCall (fn (_, c) => genRTSCallFastRealGeneraltoReal c) (entryName, 2, debugArgs)
            
            fun rtsCallFastFloattoFloat(entryName, debugArgs) =
                rtsCall (fn (_, c) => genRTSCallFastFloattoFloat c) (entryName, 1, debugArgs)
            and rtsCallFastFloatFloattoFloat(entryName, debugArgs) =
                rtsCall (fn (_, c) => genRTSCallFastFloatFloattoFloat c) (entryName, 2, debugArgs)
            and rtsCallFastGeneraltoFloat(entryName, debugArgs) =
                rtsCall (fn (_, c) => genRTSCallFastGeneraltoFloat c) (entryName, 1, debugArgs)
            and rtsCallFastFloatGeneraltoFloat(entryName, debugArgs) =
                rtsCall (fn (_, c) => genRTSCallFastFloatGeneraltoFloat c) (entryName, 2, debugArgs)
        end
    end

    structure Sharing =
    struct
        open BACKENDTREE.Sharing
        type closureRef = closureRef
    end
end;