This repository was archived by the owner on Jan 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 313
Expand file tree
/
Copy pathIlxGen.fs
More file actions
executable file
·7158 lines (6038 loc) · 369 KB
/
IlxGen.fs
File metadata and controls
executable file
·7158 lines (6038 loc) · 369 KB
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
//--------------------------------------------------------------------------
// The ILX generator.
//--------------------------------------------------------------------------
module internal Microsoft.FSharp.Compiler.IlxGen
open System.IO
open System.Reflection
open System.Collections.Generic
open Internal.Utilities
open Internal.Utilities.Collections
open Microsoft.FSharp.Compiler.AbstractIL
open Microsoft.FSharp.Compiler.AbstractIL.IL
open Microsoft.FSharp.Compiler.AbstractIL.Internal
open Microsoft.FSharp.Compiler.AbstractIL.Internal.Library
open Microsoft.FSharp.Compiler.AbstractIL.Extensions.ILX
open Microsoft.FSharp.Compiler.AbstractIL.Extensions.ILX.Types
open Microsoft.FSharp.Compiler.AbstractIL.Internal.BinaryConstants
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.AttributeChecking
open Microsoft.FSharp.Compiler.Ast
open Microsoft.FSharp.Compiler.ErrorLogger
open Microsoft.FSharp.Compiler.Infos
open Microsoft.FSharp.Compiler.Import
open Microsoft.FSharp.Compiler.Layout
open Microsoft.FSharp.Compiler.Lib
open Microsoft.FSharp.Compiler.PrettyNaming
open Microsoft.FSharp.Compiler.Range
open Microsoft.FSharp.Compiler.Tast
open Microsoft.FSharp.Compiler.Tastops
open Microsoft.FSharp.Compiler.Tastops.DebugPrint
open Microsoft.FSharp.Compiler.TcGlobals
open Microsoft.FSharp.Compiler.TypeRelations
let IsNonErasedTypar (tp:Typar) = not tp.IsErased
let DropErasedTypars (tps:Typar list) = tps |> List.filter IsNonErasedTypar
let DropErasedTyargs tys = tys |> List.filter (fun ty -> match ty with TType_measure _ -> false | _ -> true)
let AddNonUserCompilerGeneratedAttribs (g: TcGlobals) (mdef:ILMethodDef) = g.AddMethodGeneratedAttributes mdef
let debugDisplayMethodName = "__DebugDisplay"
let useHiddenInitCode = true
//--------------------------------------------------------------------------
// misc
//--------------------------------------------------------------------------
let iLdcZero = AI_ldc (DT_I4,ILConst.I4 0)
let iLdcInt64 i = AI_ldc (DT_I8,ILConst.I8 i)
let iLdcDouble i = AI_ldc (DT_R8,ILConst.R8 i)
let iLdcSingle i = AI_ldc (DT_R4,ILConst.R4 i)
/// Make a method that simply loads a field
let mkLdfldMethodDef (ilMethName,reprAccess,isStatic,ilTy,ilFieldName,ilPropType) =
let ilFieldSpec = mkILFieldSpecInTy(ilTy,ilFieldName,ilPropType)
let ilReturn = mkILReturn ilPropType
let ilMethodDef =
if isStatic then
mkILNonGenericStaticMethod (ilMethName,reprAccess,[],ilReturn,mkMethodBody(true,[],2,nonBranchingInstrsToCode [mkNormalLdsfld ilFieldSpec],None))
else
mkILNonGenericInstanceMethod (ilMethName,reprAccess,[],ilReturn,mkMethodBody (true,[],2,nonBranchingInstrsToCode [ mkLdarg0; mkNormalLdfld ilFieldSpec],None))
ilMethodDef.WithSpecialName
let ChooseParamNames fieldNamesAndTypes =
let takenFieldNames = fieldNamesAndTypes |> List.map p23 |> Set.ofList
fieldNamesAndTypes
|> List.map (fun (ilPropName,ilFieldName,ilPropType) ->
let lowerPropName = String.uncapitalize ilPropName
let ilParamName = if takenFieldNames.Contains(lowerPropName) then ilPropName else lowerPropName
ilParamName,ilFieldName,ilPropType)
let markup s = Seq.indexed s
// Approximation for purposes of optimization and giving a warning when compiling definition-only files as EXEs
let rec CheckCodeDoesSomething (code: ILCode) =
code.Instrs |> Array.exists (function AI_ldnull | AI_nop | AI_pop | I_ret | I_seqpoint _ -> false | _ -> true)
let ChooseFreeVarNames takenNames ts =
let tns = List.map (fun t -> (t,None)) ts
let rec chooseName names (t,nOpt) =
let tn = match nOpt with None -> t | Some n -> t + string n
if Zset.contains tn names then
chooseName names (t,Some(match nOpt with None -> 0 | Some n -> (n+1)))
else
let names = Zset.add tn names
tn,names
let names = Zset.empty String.order |> Zset.addList takenNames
let ts,_names = List.mapFold chooseName names tns
ts
let ilxgenGlobalNng = NiceNameGenerator ()
// We can't tailcall to methods taking byrefs. This helper helps search for them
let IsILTypeByref = function ILType.Byref _ -> true | _ -> false
let mainMethName = CompilerGeneratedName "main"
type AttributeDecoder(namedArgs) =
let nameMap = namedArgs |> List.map (fun (AttribNamedArg(s,_,_,c)) -> s,c) |> NameMap.ofList
let findConst x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_,Expr.Const(c,_,_))) -> Some c | _ -> None
let findAppTr x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_,Expr.App(_,_,[TType_app(tr,_)],_,_))) -> Some tr | _ -> None
member self.FindInt16 x dflt = match findConst x with | Some(Const.Int16 x) -> x | _ -> dflt
member self.FindInt32 x dflt = match findConst x with | Some(Const.Int32 x) -> x | _ -> dflt
member self.FindBool x dflt = match findConst x with | Some(Const.Bool x) -> x | _ -> dflt
member self.FindString x dflt = match findConst x with | Some(Const.String x) -> x | _ -> dflt
member self.FindTypeName x dflt = match findAppTr x with | Some(tr) -> tr.DisplayName | _ -> dflt
//--------------------------------------------------------------------------
// Statistics
//--------------------------------------------------------------------------
let mutable reports = (fun _ -> ())
let AddReport f = let old = reports in reports <- (fun oc -> old oc; f oc)
let ReportStatistics (oc:TextWriter) = reports oc
let NewCounter nm =
let count = ref 0
AddReport (fun oc -> if !count <> 0 then oc.WriteLine (string !count + " " + nm))
(fun () -> incr count)
let CountClosure = NewCounter "closures"
let CountMethodDef = NewCounter "IL method defintitions corresponding to values"
let CountStaticFieldDef = NewCounter "IL field defintitions corresponding to values"
let CountCallFuncInstructions = NewCounter "callfunc instructions (indirect calls)"
/// Non-local information related to internals of code generation within an assembly
type IlxGenIntraAssemblyInfo =
{ /// A table recording the generated name of the static backing fields for each mutable top level value where
/// we may need to take the address of that value, e.g. static mutable module-bound values which are structs. These are
/// only accessible intra-assembly. Across assemblies, taking the address of static mutable module-bound values is not permitted.
/// The key to the table is the method ref for the property getter for the value, which is a stable name for the Val's
/// that come from both the signature and the implementation.
StaticFieldInfo : Dictionary<ILMethodRef, ILFieldSpec> }
//--------------------------------------------------------------------------
/// Indicates how the generated IL code is ultimately emitted
type IlxGenBackend =
| IlWriteBackend
| IlReflectBackend
[<NoEquality; NoComparison>]
type IlxGenOptions =
{ fragName: string
generateFilterBlocks: bool
workAroundReflectionEmitBugs: bool
emitConstantArraysUsingStaticDataBlobs: bool
/// If this is set, then the last module becomes the "main" module and its toplevel bindings are executed at startup
mainMethodInfo: Tast.Attribs option
localOptimizationsAreOn: bool
generateDebugSymbols: bool
testFlagEmitFeeFeeAs100001: bool
ilxBackend: IlxGenBackend
/// Indicates the code is being generated in FSI.EXE and is executed immediately after code generation
/// This includes all interactively compiled code, including #load, definitions, and expressions
isInteractive: bool
/// Indicates the code generated is an interactive 'it' expression. We generate a setter to allow clearing of the underlying
/// storage, even though 'it' is not logically mutable
isInteractiveItExpr: bool
/// Whenever possible, use callvirt instead of call
alwaysCallVirt: bool }
/// Compilation environment for compiling a fragment of an assembly
[<NoEquality; NoComparison>]
type cenv =
{ g: TcGlobals
TcVal : ConstraintSolver.TcValF
viewCcu: CcuThunk
opts: IlxGenOptions
/// Cache the generation of the "unit" type
mutable ilUnitTy: ILType option
amap: ImportMap
intraAssemblyInfo : IlxGenIntraAssemblyInfo
/// Cache methods with SecurityAttribute applied to them, to prevent unnecessary calls to ExistsInEntireHierarchyOfType
casApplied : Dictionary<Stamp,bool>
/// Used to apply forced inlining optimizations to witnesses generated late during codegen
mutable optimizeDuringCodeGen : (Expr -> Expr) }
let mkTypeOfExpr cenv m ilty =
mkAsmExpr ([ mkNormalCall (mspec_Type_GetTypeFromHandle cenv.g) ], [],
[mkAsmExpr ([ I_ldtoken (ILToken.ILType ilty) ], [],[],[cenv.g.system_RuntimeTypeHandle_ty],m)],
[cenv.g.system_Type_ty],m)
let mkGetNameExpr cenv (ilt : ILType) m =
mkAsmExpr ([I_ldstr ilt.BasicQualifiedName],[],[],[cenv.g.string_ty],m)
let useCallVirt cenv boxity (mspec : ILMethodSpec) isBaseCall =
cenv.opts.alwaysCallVirt &&
(boxity = AsObject) &&
not mspec.CallingConv.IsStatic &&
not isBaseCall
//--------------------------------------------------------------------------
// CompileLocation
//--------------------------------------------------------------------------
/// compilation location = path to a ccu, namespace or class
/// Referencing other stuff, and descriptions of where items are to be placed
/// within the generated IL namespace/typespace. This should be cleaned up.
type CompileLocation =
{ clocScope: IL.ILScopeRef
clocTopImplQualifiedName: string
clocNamespace: string option
clocEncl: string list
clocQualifiedNameOfFile : string }
//--------------------------------------------------------------------------
// Access this and other assemblies
//--------------------------------------------------------------------------
let mkTopName ns n = String.concat "." (match ns with Some x -> [x;n] | None -> [n])
let CompLocForFragment fragName (ccu:CcuThunk) =
{ clocQualifiedNameOfFile =fragName
clocTopImplQualifiedName= fragName
clocScope=ccu.ILScopeRef
clocNamespace=None
clocEncl=[]}
let CompLocForCcu (ccu:CcuThunk) = CompLocForFragment ccu.AssemblyName ccu
let CompLocForSubModuleOrNamespace cloc (submod:ModuleOrNamespace) =
let n = submod.CompiledName
match submod.ModuleOrNamespaceType.ModuleOrNamespaceKind with
| FSharpModuleWithSuffix | ModuleOrType -> { cloc with clocEncl= cloc.clocEncl @ [n]}
| Namespace -> {cloc with clocNamespace=Some (mkTopName cloc.clocNamespace n)}
let CompLocForFixedPath fragName qname (CompPath(sref,cpath)) =
let ns,t = List.takeUntil (fun (_,mkind) -> mkind <> Namespace) cpath
let ns = List.map fst ns
let ns = textOfPath ns
let encl = t |> List.map (fun (s ,_)-> s)
let ns = if ns = "" then None else Some ns
{ clocQualifiedNameOfFile =fragName
clocTopImplQualifiedName=qname
clocScope=sref
clocNamespace=ns
clocEncl=encl }
let CompLocForFixedModule fragName qname (mspec:ModuleOrNamespace) =
let cloc = CompLocForFixedPath fragName qname mspec.CompilationPath
let cloc = CompLocForSubModuleOrNamespace cloc mspec
cloc
let NestedTypeRefForCompLoc cloc n =
match cloc.clocEncl with
| [] ->
let tyname = mkTopName cloc.clocNamespace n
mkILTyRef(cloc.clocScope,tyname)
| h::t -> mkILNestedTyRef(cloc.clocScope,mkTopName cloc.clocNamespace h :: t,n)
let CleanUpGeneratedTypeName (nm:string) =
if nm.IndexOfAny IllegalCharactersInTypeAndNamespaceNames = -1 then
nm
else
(nm,IllegalCharactersInTypeAndNamespaceNames) ||> Array.fold (fun nm c -> nm.Replace(string c, "-"))
let TypeNameForInitClass cloc = "<StartupCode$" + (CleanUpGeneratedTypeName cloc.clocQualifiedNameOfFile) + ">.$" + cloc.clocTopImplQualifiedName
let TypeNameForImplicitMainMethod cloc = TypeNameForInitClass cloc + "$Main"
let TypeNameForPrivateImplementationDetails cloc = "<PrivateImplementationDetails$" + (CleanUpGeneratedTypeName cloc.clocQualifiedNameOfFile) + ">"
let CompLocForInitClass cloc =
{cloc with clocEncl=[TypeNameForInitClass cloc]; clocNamespace=None}
let CompLocForImplicitMainMethod cloc =
{cloc with clocEncl=[TypeNameForImplicitMainMethod cloc]; clocNamespace=None}
let CompLocForPrivateImplementationDetails cloc =
{cloc with
clocEncl=[TypeNameForPrivateImplementationDetails cloc]; clocNamespace=None}
let rec TypeRefForCompLoc cloc =
match cloc.clocEncl with
| [] ->
mkILTyRef(cloc.clocScope,TypeNameForPrivateImplementationDetails cloc)
| [h] ->
let tyname = mkTopName cloc.clocNamespace h
mkILTyRef(cloc.clocScope,tyname)
| _ ->
let encl,n = List.frontAndBack cloc.clocEncl
NestedTypeRefForCompLoc {cloc with clocEncl=encl} n
let mkILTyForCompLoc cloc = mkILNonGenericBoxedTy (TypeRefForCompLoc cloc)
let ComputeMemberAccess hidden = if hidden then ILMemberAccess.Assembly else ILMemberAccess.Public
// Under --publicasinternal change types from Public to Private (internal for types)
let ComputePublicTypeAccess() = ILTypeDefAccess.Public
let ComputeTypeAccess (tref:ILTypeRef) hidden =
match tref.Enclosing with
| [] -> if hidden then ILTypeDefAccess.Private else ComputePublicTypeAccess()
| _ -> ILTypeDefAccess.Nested (ComputeMemberAccess hidden)
//--------------------------------------------------------------------------
// TypeReprEnv
//--------------------------------------------------------------------------
/// Indicates how type parameters are mapped to IL type variables
[<NoEquality; NoComparison>]
type TypeReprEnv(reprs : Map<Stamp, uint16>, count: int) =
member tyenv.Item (tp:Typar, m:range) =
try reprs.[tp.Stamp]
with :? KeyNotFoundException ->
errorR(InternalError("Undefined or unsolved type variable: " + showL(typarL tp),m))
// Random value for post-hoc diagnostic analysis on generated tree *
uint16 666
member tyenv.AddOne (tp: Typar) =
if IsNonErasedTypar tp then
TypeReprEnv(reprs.Add (tp.Stamp, uint16 count), count + 1)
else
tyenv
member tyenv.Add tps =
(tyenv,tps) ||> List.fold (fun tyenv tp -> tyenv.AddOne tp)
member tyenv.Count = count
static member Empty =
TypeReprEnv(count = 0, reprs = Map.empty)
static member ForTypars tps =
TypeReprEnv.Empty.Add tps
static member ForTycon (tycon:Tycon) =
TypeReprEnv.ForTypars (tycon.TyparsNoRange)
static member ForTyconRef (tycon:TyconRef) =
TypeReprEnv.ForTycon tycon.Deref
//--------------------------------------------------------------------------
// Generate type references
//--------------------------------------------------------------------------
let GenTyconRef (tcref:TyconRef) =
assert(not tcref.IsTypeAbbrev)
tcref.CompiledRepresentation
type VoidNotOK = VoidNotOK | VoidOK
#if DEBUG
let voidCheck m g permits ty =
if permits=VoidNotOK && isVoidTy g ty then
error(InternalError("System.Void unexpectedly detected in IL code generation. This should not occur.",m))
#endif
/// When generating parameter and return types generate precise .NET IL pointer types.
/// These can't be generated for generic instantiations, since .NET generics doesn't
/// permit this. But for 'naked' values (locals, parameters, return values etc.) machine
/// integer values and native pointer values are compatible (though the code is unverifiable).
type PtrsOK =
| PtrTypesOK
| PtrTypesNotOK
let GenReadOnlyAttributeIfNecessary (g: TcGlobals) ty =
let add = isInByrefTy g ty && g.attrib_IsReadOnlyAttribute.TyconRef.CanDeref
if add then
let attr = mkILCustomAttribute g.ilg (g.attrib_IsReadOnlyAttribute.TypeRef, [], [], [])
Some attr
else
None
/// Generate "modreq([mscorlib]System.Runtime.InteropServices.InAttribute)" on inref types.
let GenReadOnlyModReqIfNecessary (g: TcGlobals) ty ilTy =
let add = isInByrefTy g ty && g.attrib_InAttribute.TyconRef.CanDeref
if add then
ILType.Modified(true, g.attrib_InAttribute.TypeRef, ilTy)
else
ilTy
let rec GenTypeArgAux amap m tyenv tyarg =
GenTypeAux amap m tyenv VoidNotOK PtrTypesNotOK tyarg
and GenTypeArgsAux amap m tyenv tyargs =
List.map (GenTypeArgAux amap m tyenv) (DropErasedTyargs tyargs)
and GenTyAppAux amap m tyenv repr tinst =
match repr with
| CompiledTypeRepr.ILAsmOpen ty ->
let ilTypeInst = GenTypeArgsAux amap m tyenv tinst
let ty = IL.instILType ilTypeInst ty
ty
| CompiledTypeRepr.ILAsmNamed (tref, boxity, ilTypeOpt) ->
match ilTypeOpt with
| None ->
let ilTypeInst = GenTypeArgsAux amap m tyenv tinst
mkILTy boxity (mkILTySpec (tref,ilTypeInst))
| Some ilType ->
ilType // monomorphic types include a cached ilType to avoid reallocation of an ILType node
and GenNamedTyAppAux (amap:ImportMap) m tyenv ptrsOK tcref tinst =
let g = amap.g
let tinst = DropErasedTyargs tinst
// See above note on ptrsOK
if ptrsOK = PtrTypesOK && tyconRefEq g tcref g.nativeptr_tcr && (freeInTypes CollectTypars tinst).FreeTypars.IsEmpty then
GenNamedTyAppAux amap m tyenv ptrsOK g.ilsigptr_tcr tinst
else
#if !NO_EXTENSIONTYPING
match tcref.TypeReprInfo with
// Generate the base type, because that is always the representation of the erased type, unless the assembly is being injected
| TProvidedTypeExtensionPoint info when info.IsErased ->
GenTypeAux amap m tyenv VoidNotOK ptrsOK (info.BaseTypeForErased (m,g.obj_ty))
| _ ->
#endif
GenTyAppAux amap m tyenv (GenTyconRef tcref) tinst
and GenTypeAux amap m (tyenv: TypeReprEnv) voidOK ptrsOK ty =
let g = amap.g
#if DEBUG
voidCheck m g voidOK ty
#else
ignore voidOK
#endif
match stripTyEqnsAndMeasureEqns g ty with
| TType_app (tcref, tinst) -> GenNamedTyAppAux amap m tyenv ptrsOK tcref tinst
| TType_tuple (tupInfo, args) -> GenTypeAux amap m tyenv VoidNotOK ptrsOK (mkCompiledTupleTy g (evalTupInfoIsStruct tupInfo) args)
| TType_fun (dty, returnTy) -> EraseClosures.mkILFuncTy g.ilxPubCloEnv (GenTypeArgAux amap m tyenv dty) (GenTypeArgAux amap m tyenv returnTy)
| TType_ucase (ucref, args) ->
let cuspec,idx = GenUnionCaseSpec amap m tyenv ucref args
EraseUnions.GetILTypeForAlternative cuspec idx
| TType_forall (tps, tau) ->
let tps = DropErasedTypars tps
if tps.IsEmpty then GenTypeAux amap m tyenv VoidNotOK ptrsOK tau
else EraseClosures.mkILTyFuncTy g.ilxPubCloEnv
| TType_var tp -> mkILTyvarTy tyenv.[tp,m]
| TType_measure _ -> g.ilg.typ_Int32
//--------------------------------------------------------------------------
// Generate ILX references to closures, classunions etc. given a tyenv
//--------------------------------------------------------------------------
and GenUnionCaseRef (amap: ImportMap) m tyenv i (fspecs:RecdField[]) =
let g = amap.g
fspecs |> Array.mapi (fun j fspec ->
let ilFieldDef = IL.mkILInstanceField(fspec.Name,GenType amap m tyenv fspec.FormalType, None, ILMemberAccess.Public)
// These properties on the "field" of an alternative end up going on a property generated by cu_erase.fs
IlxUnionField
(ilFieldDef.With(customAttrs = mkILCustomAttrs [(mkCompilationMappingAttrWithVariantNumAndSeqNum g (int SourceConstructFlags.Field) i j )])))
and GenUnionRef (amap: ImportMap) m (tcref: TyconRef) =
let g = amap.g
let tycon = tcref.Deref
assert(not tycon.IsTypeAbbrev)
match tycon.UnionTypeInfo with
| None -> failwith "GenUnionRef m"
| Some funion ->
cached funion.CompiledRepresentation (fun () ->
let tyenvinner = TypeReprEnv.ForTycon tycon
match tcref.CompiledRepresentation with
| CompiledTypeRepr.ILAsmOpen _ -> failwith "GenUnionRef m: unexpected ASM tyrep"
| CompiledTypeRepr.ILAsmNamed (tref,_,_) ->
let alternatives =
tycon.UnionCasesArray |> Array.mapi (fun i cspec ->
{ altName=cspec.CompiledName
altCustomAttrs=emptyILCustomAttrs
altFields=GenUnionCaseRef amap m tyenvinner i cspec.RecdFieldsArray })
let nullPermitted = IsUnionTypeWithNullAsTrueValue g tycon
let hasHelpers = ComputeUnionHasHelpers g tcref
let boxity = (if tcref.IsStructOrEnumTycon then ILBoxity.AsValue else ILBoxity.AsObject)
IlxUnionRef(boxity, tref,alternatives,nullPermitted,hasHelpers))
and ComputeUnionHasHelpers g (tcref : TyconRef) =
if tyconRefEq g tcref g.unit_tcr_canon then NoHelpers
elif tyconRefEq g tcref g.list_tcr_canon then SpecialFSharpListHelpers
elif tyconRefEq g tcref g.option_tcr_canon then SpecialFSharpOptionHelpers
else
match TryFindFSharpAttribute g g.attrib_DefaultAugmentationAttribute tcref.Attribs with
| Some(Attrib(_,_,[ AttribBoolArg (b) ],_,_,_,_)) ->
if b then AllHelpers else NoHelpers
| Some (Attrib(_,_,_,_,_,_,m)) ->
errorR(Error(FSComp.SR.ilDefaultAugmentationAttributeCouldNotBeDecoded(),m))
AllHelpers
| _ ->
AllHelpers (* not hiddenRepr *)
and GenUnionSpec amap m tyenv tcref tyargs =
let curef = GenUnionRef amap m tcref
let tinst = GenTypeArgs amap m tyenv tyargs
IlxUnionSpec(curef,tinst)
and GenUnionCaseSpec amap m tyenv (ucref:UnionCaseRef) tyargs =
let cuspec = GenUnionSpec amap m tyenv ucref.TyconRef tyargs
cuspec, ucref.Index
and GenType amap m tyenv ty =
GenTypeAux amap m tyenv VoidNotOK PtrTypesNotOK ty
and GenTypes amap m tyenv tys = List.map (GenType amap m tyenv) tys
and GenTypePermitVoid amap m tyenv ty = (GenTypeAux amap m tyenv VoidOK PtrTypesNotOK ty)
and GenTypesPermitVoid amap m tyenv tys = List.map (GenTypePermitVoid amap m tyenv) tys
and GenTyApp amap m tyenv repr tyargs = GenTyAppAux amap m tyenv repr tyargs
and GenNamedTyApp amap m tyenv tcref tinst = GenNamedTyAppAux amap m tyenv PtrTypesNotOK tcref tinst
/// IL void types are only generated for return types
and GenReturnType amap m tyenv returnTyOpt =
match returnTyOpt with
| None -> ILType.Void
| Some returnTy ->
let ilTy = GenTypeAux amap m tyenv VoidNotOK(*1*) PtrTypesOK returnTy (*1: generate void from unit, but not accept void *)
GenReadOnlyModReqIfNecessary amap.g returnTy ilTy
and GenParamType amap m tyenv isSlotSig ty =
let ilTy = GenTypeAux amap m tyenv VoidNotOK PtrTypesOK ty
if isSlotSig then
GenReadOnlyModReqIfNecessary amap.g ty ilTy
else
ilTy
and GenParamTypes amap m tyenv isSlotSig tys =
tys |> List.map (GenParamType amap m tyenv isSlotSig)
and GenTypeArgs amap m tyenv tyargs = GenTypeArgsAux amap m tyenv tyargs
let GenericParamHasConstraint (gp: ILGenericParameterDef) =
gp.Constraints.Length <> 0 ||
gp.Variance <> NonVariant ||
gp.HasReferenceTypeConstraint ||
gp.HasNotNullableValueTypeConstraint ||
gp.HasDefaultConstructorConstraint
// Static fields generally go in a private InitializationCodeAndBackingFields section. This is to ensure all static
// fields are initialized only in their class constructors (we generate one primary
// cctor for each file to ensure initialization coherence across the file, regardless
// of how many modules are in the file). This means F# passes an extra check applied by SQL Server when it
// verifies stored procedures: SQL Server checks that all 'initionly' static fields are only initialized from
// their own class constructor.
//
// However, mutable static fields must be accessible across compilation units. This means we place them in their "natural" location
// which may be in a nested module etc. This means mutable static fields can't be used in code to be loaded by SQL Server.
//
// Computes the location where the static field for a value lives.
// - Literals go in their type/module.
// - For interactive code, we always place fields in their type/module with an accurate name
let GenFieldSpecForStaticField (isInteractive, g, ilContainerTy, vspec:Val, nm, m, cloc, ilTy) =
if isInteractive || HasFSharpAttribute g g.attrib_LiteralAttribute vspec.Attribs then
let fieldName = vspec.CompiledName
let fieldName = if isInteractive then CompilerGeneratedName fieldName else fieldName
mkILFieldSpecInTy (ilContainerTy, fieldName, ilTy)
else
let fieldName = ilxgenGlobalNng.FreshCompilerGeneratedName (nm,m)
let ilFieldContainerTy = mkILTyForCompLoc (CompLocForInitClass cloc)
mkILFieldSpecInTy (ilFieldContainerTy, fieldName, ilTy)
let GenRecdFieldRef m cenv tyenv (rfref:RecdFieldRef) tyargs =
let tyenvinner = TypeReprEnv.ForTycon rfref.Tycon
mkILFieldSpecInTy(GenTyApp cenv.amap m tyenv rfref.TyconRef.CompiledRepresentation tyargs,
ComputeFieldName rfref.Tycon rfref.RecdField,
GenType cenv.amap m tyenvinner rfref.RecdField.FormalType)
let GenExnType amap m tyenv (ecref:TyconRef) = GenTyApp amap m tyenv ecref.CompiledRepresentation []
//--------------------------------------------------------------------------
// Closure summaries
//--------------------------------------------------------------------------
type ArityInfo = int list
[<NoEquality; NoComparison>]
type IlxClosureInfo =
{ cloExpr: Expr
cloName: string
cloArityInfo: ArityInfo
cloILFormalRetTy: ILType
/// An immutable array of free variable descriptions for the closure
cloILFreeVars: IlxClosureFreeVar[]
cloSpec: IlxClosureSpec
cloAttribs: Attribs
cloILGenericParams: IL.ILGenericParameterDefs
cloFreeVars: Val list (* nb. the freevars we actually close over *)
ilCloLambdas: IlxClosureLambdas
(* local type func support *)
/// The free type parameters occuring in the type of the closure (and not just its body)
/// This is used for local type functions, whose contract class must use these types
/// type Contract<'fv> =
/// abstract DirectInvoke : ty['fv]
/// type Implementation<'fv,'fv2> : Contract<'fv> =
/// override DirectInvoke : ty['fv] = expr['fv,'fv2]
///
/// At the callsite we generate
/// unbox ty['fv]
/// callvirt clo.DirectInvoke
localTypeFuncILGenericArgs: ILType list
localTypeFuncContractFreeTypars: Typar list
localTypeFuncDirectILGenericParams: IL.ILGenericParameterDefs
localTypeFuncInternalFreeTypars: Typar list}
//--------------------------------------------------------------------------
// Representation of term declarations = Environments for compiling expressions.
//--------------------------------------------------------------------------
[<NoEquality; NoComparison>]
type ValStorage =
/// Indicates the value is always null
| Null
/// Indicates the value is stored in a static field.
| StaticField of ILFieldSpec * ValRef * (*hasLiteralAttr:*)bool * ILType * string * ILType * ILMethodRef * ILMethodRef * OptionalShadowLocal
/// Indicates the value is "stored" as a property that recomputes it each time it is referenced. Used for simple constants that do not cause initialization triggers
| StaticProperty of ILMethodSpec * OptionalShadowLocal
/// Indicates the value is "stored" as a IL static method (in a "main" class for a F#
/// compilation unit, or as a member) according to its inferred or specified arity.
| Method of ValReprInfo * ValRef * ILMethodSpec * Range.range * ArgReprInfo list * TType list * ArgReprInfo
/// Indicates the value is stored at the given position in the closure environment accessed via "ldarg 0"
| Env of ILType * int * ILFieldSpec * NamedLocalIlxClosureInfo ref option
/// Indicates that the value is an argument of a method being generated
| Arg of int
/// Indicates that the value is stored in local of the method being generated. NamedLocalIlxClosureInfo is normally empty.
/// It is non-empty for 'local type functions', see comments on definition of NamedLocalIlxClosureInfo.
| Local of int * NamedLocalIlxClosureInfo ref option
and OptionalShadowLocal =
| NoShadowLocal
| ShadowLocal of ValStorage
/// The representation of a NamedLocalClosure is based on a cloinfo. However we can't generate a cloinfo until we've
/// decided the representations of other items in the recursive set. Hence we use two phases to decide representations in
/// a recursive set. Yuck.
and NamedLocalIlxClosureInfo =
| NamedLocalIlxClosureInfoGenerator of (IlxGenEnv -> IlxClosureInfo)
| NamedLocalIlxClosureInfoGenerated of IlxClosureInfo
and ModuleStorage =
{ Vals: Lazy<NameMap<ValStorage>>
SubModules: Lazy<NameMap<ModuleStorage>> }
/// BranchCallItems are those where a call to the value can be implemented as
/// a branch. At the moment these are only used for generating branch calls back to
/// the entry label of the method currently being generated.
and BranchCallItem =
| BranchCallClosure of ArityInfo
| BranchCallMethod of
// Argument counts for compiled form of F# method or value
ArityInfo *
// Arg infos for compiled form of F# method or value
(TType * ArgReprInfo) list list *
// Typars for F# method or value
Tast.Typars *
// Typars for F# method or value
int *
// num obj args
int
and Mark =
| Mark of ILCodeLabel (* places we can branch to *)
member x.CodeLabel = (let (Mark(lab)) = x in lab)
and IlxGenEnv =
{ tyenv: TypeReprEnv
someTypeInThisAssembly: ILType
isFinalFile: bool
/// Where to place the stuff we're currently generating
cloc: CompileLocation
/// Hiding information down the signature chain, used to compute what's public to the assembly
sigToImplRemapInfo: (Remap * SignatureHidingInfo) list
/// All values in scope
valsInScope: ValMap<Lazy<ValStorage>>
/// For optimizing direct tail recursion to a loop - mark says where to branch to. Length is 0 or 1.
/// REVIEW: generalize to arbitrary nested local loops??
innerVals: (ValRef * (BranchCallItem * Mark)) list
/// Full list of enclosing bound values. First non-compiler-generated element is used to help give nice names for closures and other expressions.
letBoundVars: ValRef list
/// The set of IL local variable indexes currently in use by lexically scoped variables, to allow reuse on different branches.
/// Really an integer set.
liveLocals: IntMap<unit>
/// Are we under the scope of a try, catch or finally? If so we can't tailcall. SEH = structured exception handling
withinSEH: bool }
let ReplaceTyenv tyenv (eenv: IlxGenEnv) = {eenv with tyenv = tyenv }
let EnvForTypars tps eenv = {eenv with tyenv = TypeReprEnv.ForTypars tps }
let AddTyparsToEnv typars (eenv: IlxGenEnv) = {eenv with tyenv = eenv.tyenv.Add typars}
let AddSignatureRemapInfo _msg (rpi, mhi) eenv =
{ eenv with sigToImplRemapInfo = (mkRepackageRemapping rpi,mhi) :: eenv.sigToImplRemapInfo }
//--------------------------------------------------------------------------
// Print eenv
//--------------------------------------------------------------------------
let OutputStorage (pps: TextWriter) s =
match s with
| StaticField _ -> pps.Write "(top)"
| StaticProperty _ -> pps.Write "(top)"
| Method _ -> pps.Write "(top)"
| Local _ -> pps.Write "(local)"
| Arg _ -> pps.Write "(arg)"
| Env _ -> pps.Write "(env)"
| Null -> pps.Write "(null)"
//--------------------------------------------------------------------------
// Augment eenv with values
//--------------------------------------------------------------------------
let AddStorageForVal (g: TcGlobals) (v,s) eenv =
let eenv = { eenv with valsInScope = eenv.valsInScope.Add v s }
// If we're compiling fslib then also bind the value as a non-local path to
// allow us to resolve the compiler-non-local-references that arise from env.fs
//
// Do this by generating a fake "looking from the outside in" non-local value reference for
// v, dereferencing it to find the corresponding signature Val, and adding an entry for the signature val.
//
// A similar code path exists in ilxgen.fs for the tables of "optimization data" for values
if g.compilingFslib then
// Passing an empty remap is sufficient for FSharp.Core.dll because it turns out the remapped type signature can
// still be resolved.
match tryRescopeVal g.fslibCcu Remap.Empty v with
| None -> eenv
| Some vref ->
match vref.TryDeref with
| ValueNone ->
//let msg = sprintf "could not dereference external value reference to something in FSharp.Core.dll during code generation, v.MangledName = '%s', v.Range = %s" v.MangledName (stringOfRange v.Range)
//System.Diagnostics.Debug.Assert(false, msg)
eenv
| ValueSome gv ->
{ eenv with valsInScope = eenv.valsInScope.Add gv s }
else
eenv
let AddStorageForLocalVals g vals eenv = List.foldBack (fun (v,s) acc -> AddStorageForVal g (v,notlazy s) acc) vals eenv
//--------------------------------------------------------------------------
// Lookup eenv
//--------------------------------------------------------------------------
open Microsoft.FSharp.Compiler.AbstractIL
open Microsoft.FSharp.Compiler.AbstractIL.Internal
open Microsoft.FSharp.Compiler.AbstractIL.Internal.Library
let StorageForVal m v eenv =
let v =
try eenv.valsInScope.[v]
with :? KeyNotFoundException ->
assert false
errorR(Error(FSComp.SR.ilUndefinedValue(showL(vspecAtBindL v)),m))
notlazy (Arg 668(* random value for post-hoc diagnostic analysis on generated tree *) )
v.Force()
let StorageForValRef m (v: ValRef) eenv = StorageForVal m v.Deref eenv
//--------------------------------------------------------------------------
// Imported modules and the environment
//
// How a top level value is represented depends on its type. If it's a
// function or is polymorphic, then it gets represented as a
// method (possibly and instance method). Otherwise it gets represented as a
// static field.
//--------------------------------------------------------------------------
let IsValRefIsDllImport g (vref:ValRef) =
vref.Attribs |> HasFSharpAttributeOpt g g.attrib_DllImportAttribute
let GetMethodSpecForMemberVal amap g (memberInfo:ValMemberInfo) (vref:ValRef) =
let m = vref.Range
let tps,curriedArgInfos,returnTy,retInfo =
assert(vref.ValReprInfo.IsSome)
GetTopValTypeInCompiledForm g (Option.get vref.ValReprInfo) vref.Type m
let tyenvUnderTypars = TypeReprEnv.ForTypars tps
let flatArgInfos = List.concat curriedArgInfos
let isCtor = (memberInfo.MemberFlags.MemberKind = MemberKind.Constructor)
let cctor = (memberInfo.MemberFlags.MemberKind = MemberKind.ClassConstructor)
let parentTcref = vref.TopValDeclaringEntity
let parentTypars = parentTcref.TyparsNoRange
let numParentTypars = parentTypars.Length
if tps.Length < numParentTypars then error(InternalError("CodeGen check: type checking did not ensure that this method is sufficiently generic", m))
let ctps,mtps = List.splitAt numParentTypars tps
let isCompiledAsInstance = ValRefIsCompiledAsInstanceMember g vref
let ilActualRetTy =
let ilRetTy = GenReturnType amap m tyenvUnderTypars returnTy
if isCtor || cctor then ILType.Void else ilRetTy
let ilTy = GenType amap m tyenvUnderTypars (mkAppTy parentTcref (List.map mkTyparTy ctps))
if isCompiledAsInstance || isCtor then
// Find the 'this' argument type if any
let thisTy,flatArgInfos =
if isCtor then (GetFSharpViewOfReturnType g returnTy),flatArgInfos
else
match flatArgInfos with
| [] -> error(InternalError("This instance method '" + vref.LogicalName + "' has no arguments", m))
| (h,_):: t -> h,t
let thisTy = if isByrefTy g thisTy then destByrefTy g thisTy else thisTy
let thisArgTys = argsOfAppTy g thisTy
if numParentTypars <> thisArgTys.Length then
warning(InternalError(sprintf "CodeGen check: type checking did not quantify the correct number of type variables for this method, #parentTypars = %d, #mtps = %d, #thisArgTys = %d" numParentTypars mtps.Length thisArgTys.Length,m))
else
List.iter2
(fun gtp ty2 ->
if not (typeEquiv g (mkTyparTy gtp) ty2) then
warning(InternalError("CodeGen check: type checking did not quantify the correct type variables for this method: generalization list contained " + gtp.Name + "#" + string gtp.Stamp + " and list from 'this' pointer contained " + (showL(typeL ty2)), m)))
ctps
thisArgTys
let methodArgTys,paramInfos = List.unzip flatArgInfos
let isSlotSig = memberInfo.MemberFlags.IsDispatchSlot || memberInfo.MemberFlags.IsOverrideOrExplicitImpl
let ilMethodArgTys = GenParamTypes amap m tyenvUnderTypars isSlotSig methodArgTys
let ilMethodInst = GenTypeArgs amap m tyenvUnderTypars (List.map mkTyparTy mtps)
let mspec = mkILInstanceMethSpecInTy (ilTy,vref.CompiledName,ilMethodArgTys,ilActualRetTy,ilMethodInst)
mspec,ctps,mtps,paramInfos,retInfo,methodArgTys
else
let methodArgTys,paramInfos = List.unzip flatArgInfos
let ilMethodArgTys = GenParamTypes amap m tyenvUnderTypars false methodArgTys
let ilMethodInst = GenTypeArgs amap m tyenvUnderTypars (List.map mkTyparTy mtps)
let mspec = mkILStaticMethSpecInTy (ilTy,vref.CompiledName,ilMethodArgTys,ilActualRetTy,ilMethodInst)
mspec,ctps,mtps,paramInfos,retInfo,methodArgTys
// Generate the ILFieldSpec for a top-level value
let ComputeFieldSpecForVal(optIntraAssemblyInfo:IlxGenIntraAssemblyInfo option, isInteractive, g, ilTyForProperty, vspec:Val, nm, m, cloc, ilTy, ilGetterMethRef) =
assert vspec.IsCompiledAsTopLevel
let generate() = GenFieldSpecForStaticField (isInteractive, g, ilTyForProperty, vspec, nm, m, cloc, ilTy)
match optIntraAssemblyInfo with
| None -> generate()
| Some intraAssemblyInfo ->
if vspec.IsMutable && vspec.IsCompiledAsTopLevel && isStructTy g vspec.Type then
let ok, res = intraAssemblyInfo.StaticFieldInfo.TryGetValue ilGetterMethRef
if ok then
res
else
let res = generate()
intraAssemblyInfo.StaticFieldInfo.[ilGetterMethRef] <- res
res
else
generate()
let IsValCompiledAsMethod g (v:Val) =
match v.ValReprInfo with
| None -> false
| Some topValInfo ->
not (isUnitTy g v.Type && not v.IsMemberOrModuleBinding && not v.IsMutable) &&
not v.IsCompiledAsStaticPropertyWithoutField &&
match GetTopValTypeInFSharpForm g topValInfo v.Type v.Range with
| [],[],_,_ when not v.IsMember -> false
| _ -> true
// This called via 2 routes.
// (a) ComputeAndAddStorageForLocalTopVal
// (b) ComputeStorageForNonLocalTopVal
//
/// This function decides the storage for the val.
/// The decision is based on arityInfo.
let ComputeStorageForTopVal (amap, g, optIntraAssemblyInfo:IlxGenIntraAssemblyInfo option, isInteractive, optShadowLocal, vref:ValRef, cloc) =
if isUnitTy g vref.Type && not vref.IsMemberOrModuleBinding && not vref.IsMutable then
Null
else
let topValInfo =
match vref.ValReprInfo with
| None -> error(InternalError("ComputeStorageForTopVal: no arity found for " + showL(valRefL vref),vref.Range))
| Some a -> a
let m = vref.Range
let nm = vref.CompiledName
if vref.Deref.IsCompiledAsStaticPropertyWithoutField then
let nm = "get_"+nm
let tyenvUnderTypars = TypeReprEnv.ForTypars []
let ilRetTy = GenType amap m tyenvUnderTypars vref.Type
let ty = mkILTyForCompLoc cloc
let mspec = mkILStaticMethSpecInTy (ty, nm, [], ilRetTy, [])
StaticProperty (mspec, optShadowLocal)
else
// Determine when a static field is required.
//
// REVIEW: This call to GetTopValTypeInFSharpForm is only needed to determine if this is a (type) function or a value
// We should just look at the arity
match GetTopValTypeInFSharpForm g topValInfo vref.Type vref.Range with
| [],[], returnTy,_ when not vref.IsMember ->
// Mutable and literal static fields must have stable names and live in the "public" location
// See notes on GenFieldSpecForStaticField above.
let vspec = vref.Deref
let ilTy = GenType amap m TypeReprEnv.Empty returnTy (* TypeReprEnv.Empty ok: not a field in a generic class *)
let ilTyForProperty = mkILTyForCompLoc cloc
let attribs = vspec.Attribs
let hasLiteralAttr = HasFSharpAttribute g g.attrib_LiteralAttribute attribs
let ilTypeRefForProperty = ilTyForProperty.TypeRef
let ilGetterMethRef = mkILMethRef (ilTypeRefForProperty, ILCallingConv.Static, "get_"+nm, 0, [], ilTy)
let ilSetterMethRef = mkILMethRef (ilTypeRefForProperty, ILCallingConv.Static, "set_"+nm, 0, [ilTy], ILType.Void)
let fspec = ComputeFieldSpecForVal(optIntraAssemblyInfo, isInteractive, g, ilTyForProperty, vspec, nm, m, cloc, ilTy, ilGetterMethRef)
StaticField (fspec, vref, hasLiteralAttr, ilTyForProperty, nm, ilTy, ilGetterMethRef, ilSetterMethRef, optShadowLocal)
| _ ->
match vref.MemberInfo with
| Some memberInfo when not vref.IsExtensionMember ->
let mspec,_,_,paramInfos,retInfo,methodArgTys = GetMethodSpecForMemberVal amap g memberInfo vref
Method (topValInfo, vref, mspec, m, paramInfos, methodArgTys, retInfo)
| _ ->
let (tps, curriedArgInfos, returnTy, retInfo) = GetTopValTypeInCompiledForm g topValInfo vref.Type m
let tyenvUnderTypars = TypeReprEnv.ForTypars tps
let (methodArgTys,paramInfos) = curriedArgInfos |> List.concat |> List.unzip
let ilMethodArgTys = GenParamTypes amap m tyenvUnderTypars false methodArgTys
let ilRetTy = GenReturnType amap m tyenvUnderTypars returnTy
let ilLocTy = mkILTyForCompLoc cloc
let ilMethodInst = GenTypeArgs amap m tyenvUnderTypars (List.map mkTyparTy tps)
let mspec = mkILStaticMethSpecInTy (ilLocTy, nm, ilMethodArgTys, ilRetTy, ilMethodInst)
Method (topValInfo, vref, mspec, m, paramInfos, methodArgTys, retInfo)
let ComputeAndAddStorageForLocalTopVal (amap, g, intraAssemblyFieldTable, isInteractive, optShadowLocal) cloc (v:Val) eenv =
let storage = ComputeStorageForTopVal (amap, g, Some intraAssemblyFieldTable, isInteractive, optShadowLocal, mkLocalValRef v, cloc)
AddStorageForVal g (v,notlazy storage) eenv
let ComputeStorageForNonLocalTopVal amap g cloc modref (v:Val) =
match v.ValReprInfo with
| None -> error(InternalError("ComputeStorageForNonLocalTopVal, expected an arity for " + v.LogicalName,v.Range))
| Some _ -> ComputeStorageForTopVal (amap, g, None, false, NoShadowLocal, mkNestedValRef modref v, cloc)
let rec ComputeStorageForNonLocalModuleOrNamespaceRef amap g cloc acc (modref:ModuleOrNamespaceRef) (modul:ModuleOrNamespace) =
let acc =
(acc, modul.ModuleOrNamespaceType.ModuleAndNamespaceDefinitions) ||> List.fold (fun acc smodul ->
ComputeStorageForNonLocalModuleOrNamespaceRef amap g (CompLocForSubModuleOrNamespace cloc smodul) acc (modref.NestedTyconRef smodul) smodul)
let acc =
(acc, modul.ModuleOrNamespaceType.AllValsAndMembers) ||> Seq.fold (fun acc v ->
AddStorageForVal g (v, lazy (ComputeStorageForNonLocalTopVal amap g cloc modref v)) acc)
acc
let ComputeStorageForExternalCcu amap g eenv (ccu:CcuThunk) =
if not ccu.IsFSharp then eenv else
let cloc = CompLocForCcu ccu
let eenv =
List.foldBack
(fun smodul acc ->
let cloc = CompLocForSubModuleOrNamespace cloc smodul
let modref = mkNonLocalCcuRootEntityRef ccu smodul
ComputeStorageForNonLocalModuleOrNamespaceRef amap g cloc acc modref smodul)
ccu.RootModulesAndNamespaces
eenv
let eenv =
let eref = ERefNonLocalPreResolved ccu.Contents (mkNonLocalEntityRef ccu [| |])
(eenv, ccu.Contents.ModuleOrNamespaceType.AllValsAndMembers) ||> Seq.fold (fun acc v ->
AddStorageForVal g (v, lazy (ComputeStorageForNonLocalTopVal amap g cloc eref v)) acc)
eenv
let rec AddBindingsForLocalModuleType allocVal cloc eenv (mty:ModuleOrNamespaceType) =
let eenv = List.fold (fun eenv submodul -> AddBindingsForLocalModuleType allocVal (CompLocForSubModuleOrNamespace cloc submodul) eenv submodul.ModuleOrNamespaceType) eenv mty.ModuleAndNamespaceDefinitions
let eenv = Seq.fold (fun eenv v -> allocVal cloc v eenv) eenv mty.AllValsAndMembers
eenv
let AddExternalCcusToIlxGenEnv amap g eenv ccus = List.fold (ComputeStorageForExternalCcu amap g) eenv ccus
let AddBindingsForTycon allocVal (cloc:CompileLocation) (tycon:Tycon) eenv =
let unrealizedSlots =
if tycon.IsFSharpObjectModelTycon
then tycon.FSharpObjectModelTypeInfo.fsobjmodel_vslots
else []
(eenv,unrealizedSlots) ||> List.fold (fun eenv vref -> allocVal cloc vref.Deref eenv)
let rec AddBindingsForModuleDefs allocVal (cloc:CompileLocation) eenv mdefs =
List.fold (AddBindingsForModuleDef allocVal cloc) eenv mdefs
and AddBindingsForModuleDef allocVal cloc eenv x =
match x with
| TMDefRec(_isRec,tycons,mbinds,_) ->
(* Virtual don't have 'let' bindings and must be added to the environment *)
let eenv = List.foldBack (AddBindingsForTycon allocVal cloc) tycons eenv
let eenv = List.foldBack (AddBindingsForModule allocVal cloc) mbinds eenv
eenv