-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
ExpressionBuilder.cs
4767 lines (4497 loc) · 185 KB
/
ExpressionBuilder.cs
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) 2014-2020 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading;
using ICSharpCode.Decompiler.CSharp.Resolver;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.CSharp.Transforms;
using ICSharpCode.Decompiler.CSharp.TypeSystem;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.IL.Transforms;
using ICSharpCode.Decompiler.Semantics;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
using ExpressionType = System.Linq.Expressions.ExpressionType;
using PrimitiveType = ICSharpCode.Decompiler.CSharp.Syntax.PrimitiveType;
namespace ICSharpCode.Decompiler.CSharp
{
/// <summary>
/// Translates from ILAst to C# expressions.
/// </summary>
/// <remarks>
/// Every translated expression must have:
/// * an ILInstruction annotation
/// * a ResolveResult annotation
/// Post-condition for Translate() calls:
/// * The type of the ResolveResult must match the StackType of the corresponding ILInstruction,
/// except that the width of integer types does not need to match (I4, I and I8 count as the same stack type here)
/// * Evaluating the resulting C# expression shall produce the same side effects as evaluating the ILInstruction.
/// * If the IL instruction has <c>ResultType == StackType.Void</c>, the C# expression may evaluate to an arbitrary type and value.
/// * Otherwise, evaluating the resulting C# expression shall produce a similar value as evaluating the ILInstruction.
/// * If the IL instruction evaluates to an integer stack type (I4, I, or I8),
/// the C# type of the resulting expression shall also be an integer (or enum/pointer/char/bool) type.
/// * If sizeof(C# type) == sizeof(IL stack type), the values must be the same.
/// * If sizeof(C# type) > sizeof(IL stack type), the C# value truncated to the width of the IL stack type must equal the IL value.
/// * If sizeof(C# type) < sizeof(IL stack type), the C# value (sign/zero-)extended to the width of the IL stack type
/// must equal the IL value.
/// Whether sign or zero extension is used depends on the sign of the C# type (as determined by <c>IType.GetSign()</c>).
/// * If the IL instruction is a lifted nullable operation, and the underlying operation evaluates to an integer stack type,
/// the C# type of the resulting expression shall be Nullable{T}, where T is an integer type (as above).
/// The C# value shall be null iff the IL-level value evaluates to null, and otherwise the values shall correspond
/// as with non-lifted integer operations.
/// * If the IL instruction evaluates to a managed reference (Ref) created by starting tracking of an unmanaged reference,
/// the C# instruction may evaluate to any integral/enum/pointer type that when converted to pointer type
/// is equivalent to the managed reference.
/// * Otherwise, the C# type of the resulting expression shall match the IL stack type,
/// and the evaluated values shall be the same.
/// </remarks>
sealed class ExpressionBuilder : ILVisitor<TranslationContext, TranslatedExpression>
{
internal readonly StatementBuilder statementBuilder;
readonly IDecompilerTypeSystem typeSystem;
internal readonly ITypeResolveContext decompilationContext;
internal readonly ILFunction currentFunction;
internal readonly ICompilation compilation;
internal readonly CSharpResolver resolver;
internal readonly TypeSystemAstBuilder astBuilder;
internal readonly TypeInference typeInference;
internal readonly DecompilerSettings settings;
readonly CancellationToken cancellationToken;
public ExpressionBuilder(StatementBuilder statementBuilder, IDecompilerTypeSystem typeSystem, ITypeResolveContext decompilationContext, ILFunction currentFunction, DecompilerSettings settings, CancellationToken cancellationToken)
{
Debug.Assert(decompilationContext != null);
this.statementBuilder = statementBuilder;
this.typeSystem = typeSystem;
this.decompilationContext = decompilationContext;
this.currentFunction = currentFunction;
this.settings = settings;
this.cancellationToken = cancellationToken;
this.compilation = decompilationContext.Compilation;
this.resolver = new CSharpResolver(new CSharpTypeResolveContext(compilation.MainModule, null, decompilationContext.CurrentTypeDefinition, decompilationContext.CurrentMember));
this.astBuilder = new TypeSystemAstBuilder(resolver);
this.astBuilder.AlwaysUseShortTypeNames = true;
this.astBuilder.AddResolveResultAnnotations = true;
this.astBuilder.ShowAttributes = true;
this.astBuilder.UseNullableSpecifierForValueTypes = settings.LiftNullables;
this.astBuilder.AlwaysUseGlobal = settings.AlwaysUseGlobal;
this.typeInference = new TypeInference(compilation) { Algorithm = TypeInferenceAlgorithm.Improved };
}
public AstType ConvertType(IType type)
{
var astType = astBuilder.ConvertType(type);
Debug.Assert(astType.Annotation<TypeResolveResult>() != null);
return astType;
}
public ExpressionWithResolveResult ConvertConstantValue(ResolveResult rr, bool allowImplicitConversion = false)
{
var expr = astBuilder.ConvertConstantValue(rr);
if (!allowImplicitConversion)
{
if (expr is NullReferenceExpression && rr.Type.Kind != TypeKind.Null)
{
expr = new CastExpression(ConvertType(rr.Type), expr);
}
else if (rr.Type.IsCSharpSmallIntegerType())
{
expr = new CastExpression(new PrimitiveType(KnownTypeReference.GetCSharpNameByTypeCode(rr.Type.GetDefinition().KnownTypeCode)), expr);
// Note: no unchecked annotation necessary, because the constant was folded to be in-range
}
else if (rr.Type.IsCSharpNativeIntegerType())
{
expr = new CastExpression(new PrimitiveType(rr.Type.Name), expr);
// Note: no unchecked annotation necessary, because the rr wouldn't be a constant if the value wasn't in-range on 32bit
}
}
var exprRR = expr.Annotation<ResolveResult>();
if (exprRR == null)
{
exprRR = rr;
expr.AddAnnotation(rr);
}
return new ExpressionWithResolveResult(expr, exprRR);
}
public ExpressionWithResolveResult ConvertConstantValue(ResolveResult rr,
bool allowImplicitConversion = false, bool displayAsHex = false)
{
astBuilder.PrintIntegralValuesAsHex = displayAsHex;
try
{
return ConvertConstantValue(rr, allowImplicitConversion);
}
finally
{
astBuilder.PrintIntegralValuesAsHex = false;
}
}
public TranslatedExpression Translate(ILInstruction inst, IType typeHint = null)
{
Debug.Assert(inst != null);
cancellationToken.ThrowIfCancellationRequested();
TranslationContext context = new TranslationContext {
TypeHint = typeHint ?? SpecialType.UnknownType
};
var cexpr = inst.AcceptVisitor(this, context);
#if DEBUG
if (inst.ResultType != StackType.Void && cexpr.Type.Kind != TypeKind.Unknown && inst.ResultType != StackType.Unknown && cexpr.Type.Kind != TypeKind.None)
{
// Validate the Translate post-condition (documented at beginning of this file):
if (inst.ResultType.IsIntegerType())
{
Debug.Assert(cexpr.Type.GetStackType().IsIntegerType(), "IL instructions of integer type must convert into C# expressions of integer type");
Debug.Assert(cexpr.Type.GetSign() != Sign.None, "Must have a sign specified for zero/sign-extension");
}
else if (inst is ILiftableInstruction liftable && liftable.IsLifted)
{
if (liftable.UnderlyingResultType != StackType.Unknown)
{
Debug.Assert(NullableType.IsNullable(cexpr.Type));
IType underlying = NullableType.GetUnderlyingType(cexpr.Type);
if (liftable.UnderlyingResultType.IsIntegerType())
{
Debug.Assert(underlying.GetStackType().IsIntegerType(), "IL instructions of integer type must convert into C# expressions of integer type");
Debug.Assert(underlying.GetSign() != Sign.None, "Must have a sign specified for zero/sign-extension");
}
else
{
Debug.Assert(underlying.GetStackType() == liftable.UnderlyingResultType);
}
}
}
else if (inst.ResultType == StackType.Ref)
{
Debug.Assert(cexpr.Type.GetStackType() == StackType.Ref || cexpr.Type.GetStackType().IsIntegerType());
}
else
{
Debug.Assert(cexpr.Type.GetStackType() == inst.ResultType);
}
}
#endif
return cexpr;
}
public TranslatedExpression TranslateCondition(ILInstruction condition, bool negate = false)
{
Debug.Assert(condition.ResultType == StackType.I4);
var expr = Translate(condition, compilation.FindType(KnownTypeCode.Boolean));
if (expr.Type.GetStackType().GetSize() > 4)
{
expr = expr.ConvertTo(FindType(StackType.I4, expr.Type.GetSign()), this);
}
return expr.ConvertToBoolean(this, negate);
}
internal ExpressionWithResolveResult ConvertVariable(ILVariable variable)
{
Expression expr;
if (variable.Kind == VariableKind.Parameter && variable.Index < 0)
expr = new ThisReferenceExpression();
else
expr = new IdentifierExpression(variable.Name);
if (variable.Type.Kind == TypeKind.ByReference)
{
// When loading a by-ref parameter, use 'ref paramName'.
// We'll strip away the 'ref' when dereferencing.
// Ensure that the IdentifierExpression itself also gets a resolve result, as that might
// get used after the 'ref' is stripped away:
var elementType = ((ByReferenceType)variable.Type).ElementType;
var elementRR = new ILVariableResolveResult(variable, elementType);
expr.WithRR(elementRR);
expr = new DirectionExpression(FieldDirection.Ref, expr);
return expr.WithRR(new ByReferenceResolveResult(elementRR, ReferenceKind.Ref));
}
else
{
return expr.WithRR(new ILVariableResolveResult(variable, variable.Type));
}
}
internal bool HidesVariableWithName(string name)
{
return HidesVariableWithName(currentFunction, name);
}
internal static bool HidesVariableWithName(ILFunction currentFunction, string name)
{
return currentFunction.Ancestors.OfType<ILFunction>().Any(HidesVariableOrNestedFunction);
bool HidesVariableOrNestedFunction(ILFunction function)
{
foreach (var v in function.Variables)
{
if (v.Name == name)
return true;
}
foreach (var f in function.LocalFunctions)
{
if (f.Name == name)
return true;
}
return false;
}
}
internal ILFunction ResolveLocalFunction(IMethod method)
{
Debug.Assert(method.IsLocalFunction);
method = (IMethod)((IMethod)method.MemberDefinition).ReducedFrom.MemberDefinition;
foreach (var parent in currentFunction.Ancestors.OfType<ILFunction>())
{
var definition = parent.LocalFunctions.FirstOrDefault(f => f.Method.MemberDefinition.Equals(method));
if (definition != null)
{
return definition;
}
}
return null;
}
bool RequiresQualifier(IMember member, TranslatedExpression target)
{
if (settings.AlwaysQualifyMemberReferences || HidesVariableWithName(member.Name))
return true;
if (member.IsStatic)
return !IsCurrentOrContainingType(member.DeclaringTypeDefinition);
return !(target.Expression is ThisReferenceExpression || target.Expression is BaseReferenceExpression);
}
ExpressionWithResolveResult ConvertField(IField field, ILInstruction targetInstruction = null)
{
var target = TranslateTarget(targetInstruction,
nonVirtualInvocation: true,
memberStatic: field.IsStatic,
memberDeclaringType: field.DeclaringType);
bool requireTarget;
// If this is a reference to the backing field of an automatic property and we're going to transform automatic properties
// in PatternStatementTransform, then we have to do the "requires qualifier"-check based on the property instead of the field.
// It is easier to solve this special case here than in PatternStatementTransform, because here we perform all resolver checks.
// It feels a bit hacky, though.
if (settings.AutomaticProperties
&& PatternStatementTransform.IsBackingFieldOfAutomaticProperty(field, out var property)
&& decompilationContext.CurrentMember != property
&& (property.CanSet || settings.GetterOnlyAutomaticProperties))
{
requireTarget = RequiresQualifier(property, target);
}
else
{
requireTarget = RequiresQualifier(field, target);
}
bool targetCasted = false;
var targetResolveResult = requireTarget ? target.ResolveResult : null;
bool IsAmbiguousAccess(out MemberResolveResult result)
{
if (targetResolveResult == null)
{
result = resolver.ResolveSimpleName(field.Name, EmptyList<IType>.Instance, isInvocationTarget: false) as MemberResolveResult;
}
else
{
var lookup = new MemberLookup(resolver.CurrentTypeDefinition, resolver.CurrentTypeDefinition.ParentModule);
result = lookup.Lookup(target.ResolveResult, field.Name, EmptyList<IType>.Instance, isInvocation: false) as MemberResolveResult;
}
return result == null || result.IsError || !result.Member.Equals(field, NormalizeTypeVisitor.TypeErasure);
}
MemberResolveResult mrr;
while (IsAmbiguousAccess(out mrr))
{
if (!requireTarget)
{
requireTarget = true;
targetResolveResult = target.ResolveResult;
}
else if (!targetCasted)
{
targetCasted = true;
target = target.ConvertTo(field.DeclaringType, this);
targetResolveResult = target.ResolveResult;
}
else
{
// the field reference is still ambiguous, however, mrr might refer to a different member,
// e.g., in the case of auto events, their backing fields have the same name.
// "this.Event" is ambiguous, but should refer to the field, not the event.
mrr = null;
break;
}
}
if (mrr == null)
{
mrr = new MemberResolveResult(target.ResolveResult, field);
}
var expr = requireTarget
? new MemberReferenceExpression(target, field.Name).WithRR(mrr)
: new IdentifierExpression(field.Name).WithRR(mrr);
if (field.Type.Kind == TypeKind.ByReference)
{
expr = new DirectionExpression(FieldDirection.Ref, expr)
.WithRR(new ByReferenceResolveResult(mrr, ReferenceKind.Ref));
}
return expr;
}
TranslatedExpression IsType(IsInst inst)
{
var arg = Translate(inst.Argument);
arg = UnwrapBoxingConversion(arg);
return new IsExpression(arg.Expression, ConvertType(inst.Type.TupleUnderlyingTypeOrSelf()))
.WithILInstruction(inst)
.WithRR(new TypeIsResolveResult(arg.ResolveResult, inst.Type, compilation.FindType(TypeCode.Boolean)));
}
protected internal override TranslatedExpression VisitIsInst(IsInst inst, TranslationContext context)
{
var arg = Translate(inst.Argument);
if (inst.Type.IsReferenceType != true)
{
// isinst with a value type results in an expression of "boxed value type",
// which is not supported in C#.
// It's also not supported for unconstrained generic types.
// Note that several other instructions special-case isinst arguments:
// unbox.any T(isinst T(expr)) ==> "expr as T" for nullable value types and class-constrained generic types
// comp(isinst T(expr) != null) ==> "expr is T"
// on block level (StatementBuilder.VisitIsInst) => "expr is T"
if (SemanticHelper.IsPure(inst.Argument.Flags))
{
// We can emulate isinst using
// expr is T ? expr : null
return new ConditionalExpression(
new IsExpression(arg, ConvertType(inst.Type)).WithILInstruction(inst),
arg.Expression.Clone(),
new NullReferenceExpression()
).WithoutILInstruction().WithRR(new ResolveResult(arg.Type));
}
else
{
return ErrorExpression("isinst with value type is only supported in some contexts");
}
}
arg = UnwrapBoxingConversion(arg);
return new AsExpression(arg.Expression, ConvertType(inst.Type))
.WithILInstruction(inst)
.WithRR(new ConversionResolveResult(inst.Type, arg.ResolveResult, Conversion.TryCast));
}
internal static TranslatedExpression UnwrapBoxingConversion(TranslatedExpression arg)
{
if (arg.Expression is CastExpression cast
&& arg.Type.IsKnownType(KnownTypeCode.Object)
&& arg.ResolveResult is ConversionResolveResult crr
&& crr.Conversion.IsBoxingConversion)
{
// When 'is' or 'as' is used with a value type or type parameter,
// the C# compiler implicitly boxes the input.
arg = arg.UnwrapChild(cast.Expression);
}
return arg;
}
protected internal override TranslatedExpression VisitNewObj(NewObj inst, TranslationContext context)
{
var type = inst.Method.DeclaringType;
if (type.IsKnownType(KnownTypeCode.SpanOfT) || type.IsKnownType(KnownTypeCode.ReadOnlySpanOfT))
{
if (inst.Arguments.Count == 2 && inst.Arguments[0] is Block b && b.Kind == BlockKind.StackAllocInitializer)
{
return TranslateStackAllocInitializer(b, type.TypeArguments[0]);
}
}
return new CallBuilder(this, typeSystem, settings).Build(inst, context.TypeHint);
}
protected internal override TranslatedExpression VisitLdVirtDelegate(LdVirtDelegate inst, TranslationContext context)
{
return new CallBuilder(this, typeSystem, settings).Build(inst);
}
protected internal override TranslatedExpression VisitNewArr(NewArr inst, TranslationContext context)
{
var dimensions = inst.Indices.Count;
var args = inst.Indices.Select(arg => TranslateArrayIndex(arg)).ToArray();
var expr = new ArrayCreateExpression { Type = ConvertType(inst.Type) };
if (expr.Type is ComposedType ct)
{
// change "new (int[,])[10] to new int[10][,]"
ct.ArraySpecifiers.MoveTo(expr.AdditionalArraySpecifiers);
}
expr.Arguments.AddRange(args.Select(arg => arg.Expression));
return expr.WithILInstruction(inst)
.WithRR(new ArrayCreateResolveResult(new ArrayType(compilation, inst.Type, dimensions), args.Select(a => a.ResolveResult).ToList(), Empty<ResolveResult>.Array));
}
protected internal override TranslatedExpression VisitLocAlloc(LocAlloc inst, TranslationContext context)
{
return TranslateLocAlloc(inst, context.TypeHint, out var elementType)
.WithILInstruction(inst).WithRR(new ResolveResult(new PointerType(elementType)));
}
protected internal override TranslatedExpression VisitLocAllocSpan(LocAllocSpan inst, TranslationContext context)
{
return TranslateLocAllocSpan(inst, context.TypeHint, out _)
.WithILInstruction(inst).WithRR(new ResolveResult(inst.Type));
}
StackAllocExpression TranslateLocAllocSpan(LocAllocSpan inst, IType typeHint, out IType elementType)
{
elementType = inst.Type.TypeArguments[0];
TranslatedExpression countExpression = Translate(inst.Argument)
.ConvertTo(compilation.FindType(KnownTypeCode.Int32), this);
return new StackAllocExpression {
Type = ConvertType(elementType),
CountExpression = countExpression
};
}
StackAllocExpression TranslateLocAlloc(LocAlloc inst, IType typeHint, out IType elementType)
{
TranslatedExpression countExpression;
PointerType pointerType;
if (inst.Argument.MatchBinaryNumericInstruction(BinaryNumericOperator.Mul, out var left, out var right)
&& right.UnwrapConv(ConversionKind.SignExtend).UnwrapConv(ConversionKind.ZeroExtend).MatchSizeOf(out elementType))
{
// Determine the element type from the sizeof
countExpression = Translate(left.UnwrapConv(ConversionKind.ZeroExtend));
pointerType = new PointerType(elementType);
}
else
{
// Determine the element type from the expected pointer type in this context
pointerType = typeHint as PointerType;
if (pointerType != null && GetPointerArithmeticOffset(
inst.Argument, Translate(inst.Argument),
pointerType.ElementType, checkForOverflow: true,
unwrapZeroExtension: true
) is TranslatedExpression offset)
{
countExpression = offset;
elementType = pointerType.ElementType;
}
else
{
elementType = compilation.FindType(KnownTypeCode.Byte);
pointerType = new PointerType(elementType);
countExpression = Translate(inst.Argument);
}
}
countExpression = countExpression.ConvertTo(compilation.FindType(KnownTypeCode.Int32), this);
return new StackAllocExpression {
Type = ConvertType(elementType),
CountExpression = countExpression
};
}
protected internal override TranslatedExpression VisitLdcI4(LdcI4 inst, TranslationContext context)
{
ResolveResult rr;
if (context.TypeHint.GetSign() == Sign.Unsigned)
{
rr = new ConstantResolveResult(
compilation.FindType(KnownTypeCode.UInt32),
unchecked((uint)inst.Value)
);
}
else
{
rr = new ConstantResolveResult(
compilation.FindType(KnownTypeCode.Int32),
inst.Value
);
}
rr = AdjustConstantToType(rr, context.TypeHint);
return ConvertConstantValue(
rr,
allowImplicitConversion: true,
ShouldDisplayAsHex(inst.Value, rr.Type, inst.Parent)
).WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitLdcI8(LdcI8 inst, TranslationContext context)
{
ResolveResult rr;
if (context.TypeHint.GetSign() == Sign.Unsigned)
{
rr = new ConstantResolveResult(
compilation.FindType(KnownTypeCode.UInt64),
unchecked((ulong)inst.Value)
);
}
else
{
rr = new ConstantResolveResult(
compilation.FindType(KnownTypeCode.Int64),
inst.Value
);
}
rr = AdjustConstantToType(rr, context.TypeHint);
return ConvertConstantValue(
rr,
allowImplicitConversion: true,
ShouldDisplayAsHex(inst.Value, rr.Type, inst.Parent)
).WithILInstruction(inst);
}
private bool ShouldDisplayAsHex(long value, IType type, ILInstruction parent)
{
if (parent is Conv conv)
parent = conv.Parent;
if (value >= 0 && value <= 9)
return false;
if (value < 0 && type.GetSign() == Sign.Signed)
return false;
switch (parent)
{
case BinaryNumericInstruction bni:
if (bni.Operator == BinaryNumericOperator.BitAnd
|| bni.Operator == BinaryNumericOperator.BitOr
|| bni.Operator == BinaryNumericOperator.BitXor)
return true;
break;
}
return false;
}
protected internal override TranslatedExpression VisitLdcF4(LdcF4 inst, TranslationContext context)
{
var expr = astBuilder.ConvertConstantValue(compilation.FindType(KnownTypeCode.Single), inst.Value);
return new TranslatedExpression(expr.WithILInstruction(inst));
}
protected internal override TranslatedExpression VisitLdcF8(LdcF8 inst, TranslationContext context)
{
var expr = astBuilder.ConvertConstantValue(compilation.FindType(KnownTypeCode.Double), inst.Value);
return new TranslatedExpression(expr.WithILInstruction(inst));
}
protected internal override TranslatedExpression VisitLdcDecimal(LdcDecimal inst, TranslationContext context)
{
var expr = astBuilder.ConvertConstantValue(compilation.FindType(KnownTypeCode.Decimal), inst.Value);
return new TranslatedExpression(expr.WithILInstruction(inst));
}
protected internal override TranslatedExpression VisitLdStr(LdStr inst, TranslationContext context)
{
return new PrimitiveExpression(inst.Value)
.WithILInstruction(inst)
.WithRR(new ConstantResolveResult(compilation.FindType(KnownTypeCode.String), inst.Value));
}
protected internal override TranslatedExpression VisitLdStrUtf8(LdStrUtf8 inst, TranslationContext context)
{
var type = new ParameterizedType(compilation.FindType(KnownTypeCode.ReadOnlySpanOfT), new[] { compilation.FindType(KnownTypeCode.Byte) });
return new PrimitiveExpression(inst.Value, LiteralFormat.Utf8Literal)
.WithILInstruction(inst)
.WithRR(new ConstantResolveResult(type, inst.Value));
}
protected internal override TranslatedExpression VisitLdNull(LdNull inst, TranslationContext context)
{
return GetDefaultValueExpression(SpecialType.NullType).WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitDefaultValue(DefaultValue inst, TranslationContext context)
{
return GetDefaultValueExpression(inst.Type).WithILInstruction(inst);
}
internal ExpressionWithResolveResult GetDefaultValueExpression(IType type)
{
Expression expr;
IType constantType;
object constantValue;
if (type.IsReferenceType == true || type.IsKnownType(KnownTypeCode.NullableOfT))
{
expr = new NullReferenceExpression();
constantType = SpecialType.NullType;
constantValue = null;
}
else
{
expr = new DefaultValueExpression(ConvertType(type));
constantType = type;
constantValue = CSharpResolver.GetDefaultValue(type);
}
return expr.WithRR(new ConstantResolveResult(constantType, constantValue));
}
protected internal override TranslatedExpression VisitSizeOf(SizeOf inst, TranslationContext context)
{
if (inst.Type.IsUnmanagedType(allowGenerics: settings.IntroduceUnmanagedConstraint))
{
return new SizeOfExpression(ConvertType(inst.Type))
.WithILInstruction(inst)
.WithRR(new SizeOfResolveResult(compilation.FindType(KnownTypeCode.Int32), inst.Type, null));
}
else
{
return CallUnsafeIntrinsic(
name: "SizeOf",
arguments: Array.Empty<Expression>(),
returnType: compilation.FindType(KnownTypeCode.Int32),
inst: inst,
typeArguments: new[] { inst.Type }
);
}
}
protected internal override TranslatedExpression VisitLdTypeToken(LdTypeToken inst, TranslationContext context)
{
var typeofExpr = new TypeOfExpression(ConvertType(inst.Type))
.WithRR(new TypeOfResolveResult(compilation.FindType(KnownTypeCode.Type), inst.Type));
return new MemberReferenceExpression(typeofExpr, "TypeHandle")
.WithILInstruction(inst)
.WithRR(new TypeOfResolveResult(compilation.FindType(new TopLevelTypeName("System", "RuntimeTypeHandle")), inst.Type));
}
protected internal override TranslatedExpression VisitBitNot(BitNot inst, TranslationContext context)
{
var argument = Translate(inst.Argument);
var argUType = NullableType.GetUnderlyingType(argument.Type);
if (argUType.GetStackType().GetSize() < inst.UnderlyingResultType.GetSize()
|| argUType.Kind == TypeKind.Enum && argUType.IsSmallIntegerType()
|| (argUType.GetStackType() == StackType.I && !argUType.IsCSharpNativeIntegerType())
|| argUType.IsKnownType(KnownTypeCode.Boolean)
|| argUType.IsKnownType(KnownTypeCode.Char))
{
// Argument is undersized (even after implicit integral promotion to I4)
// -> we need to perform sign/zero-extension before the BitNot.
// Same if the argument is an enum based on a small integer type
// (those don't undergo numeric promotion in C# the way non-enum small integer types do).
// Same if the type is one that does not support ~ (IntPtr, bool and char).
Sign sign = context.TypeHint.GetSign();
if (sign == Sign.None)
{
sign = argUType.GetSign();
}
IType targetType = FindArithmeticType(inst.UnderlyingResultType, sign);
if (inst.IsLifted)
{
targetType = NullableType.Create(compilation, targetType);
}
argument = argument.ConvertTo(targetType, this);
}
return new UnaryOperatorExpression(UnaryOperatorType.BitNot, argument)
.WithRR(resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, argument.ResolveResult))
.WithILInstruction(inst);
}
internal ExpressionWithResolveResult LogicNot(TranslatedExpression expr)
{
// "!expr" implicitly converts to bool so we can remove the cast;
// but only if doing so wouldn't cause us to call a user-defined "operator !"
expr = expr.UnwrapImplicitBoolConversion(type => !type.GetMethods(m => m.IsOperator && m.Name == "op_LogicalNot").Any());
return new UnaryOperatorExpression(UnaryOperatorType.Not, expr.Expression)
.WithRR(new OperatorResolveResult(compilation.FindType(KnownTypeCode.Boolean), ExpressionType.Not, expr.ResolveResult));
}
readonly HashSet<ILVariable> loadedVariablesSet = new HashSet<ILVariable>();
protected internal override TranslatedExpression VisitLdLoc(LdLoc inst, TranslationContext context)
{
if (inst.Variable.Kind == VariableKind.StackSlot && inst.Variable.IsSingleDefinition)
{
loadedVariablesSet.Add(inst.Variable);
}
return ConvertVariable(inst.Variable).WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitLdLoca(LdLoca inst, TranslationContext context)
{
var expr = ConvertVariable(inst.Variable).WithILInstruction(inst);
// Note that we put the instruction on the IdentifierExpression instead of the DirectionExpression,
// because the DirectionExpression might get removed by dereferencing instructions such as LdObj
return new DirectionExpression(FieldDirection.Ref, expr.Expression)
.WithoutILInstruction()
.WithRR(new ByReferenceResolveResult(expr.ResolveResult, ReferenceKind.Ref));
}
protected internal override TranslatedExpression VisitStLoc(StLoc inst, TranslationContext context)
{
var translatedValue = Translate(inst.Value, typeHint: inst.Variable.Type);
if (inst.Variable.Kind == VariableKind.StackSlot && !loadedVariablesSet.Contains(inst.Variable))
{
// Stack slots in the ILAst have inaccurate types (e.g. System.Object for StackType.O)
// so we should replace them with more accurate types where possible:
if (CanUseTypeForStackSlot(inst.Variable, translatedValue.Type)
&& inst.Variable.StackType == translatedValue.Type.GetStackType()
&& translatedValue.Type.Kind != TypeKind.Null)
{
inst.Variable.Type = translatedValue.Type;
}
else if (inst.Value.MatchDefaultValue(out var type) && IsOtherValueType(type))
{
inst.Variable.Type = type;
}
}
var lhs = ConvertVariable(inst.Variable).WithoutILInstruction();
if (lhs.Expression is DirectionExpression dirExpr && lhs.ResolveResult is ByReferenceResolveResult lhsRefRR)
{
// ref (re-)assignment, emit "ref (a = ref b)".
lhs = lhs.UnwrapChild(dirExpr.Expression);
translatedValue = translatedValue.ConvertTo(lhsRefRR.Type, this, allowImplicitConversion: true);
var assign = new AssignmentExpression(lhs.Expression, translatedValue.Expression)
.WithRR(new OperatorResolveResult(lhs.Type, ExpressionType.Assign, lhsRefRR, translatedValue.ResolveResult));
return new DirectionExpression(FieldDirection.Ref, assign)
.WithoutILInstruction().WithRR(lhsRefRR);
}
else
{
return Assignment(lhs, translatedValue).WithILInstruction(inst);
}
bool CanUseTypeForStackSlot(ILVariable v, IType type)
{
return v.IsSingleDefinition
|| IsOtherValueType(type)
|| v.StackType == StackType.Ref
|| AllStoresUseConsistentType(v.StoreInstructions, type);
}
bool IsOtherValueType(IType type)
{
return type.IsReferenceType == false && type.GetStackType() == StackType.O;
}
bool AllStoresUseConsistentType(IReadOnlyList<IStoreInstruction> storeInstructions, IType expectedType)
{
expectedType = expectedType.AcceptVisitor(NormalizeTypeVisitor.TypeErasure);
foreach (var store in storeInstructions)
{
if (!(store is StLoc stloc))
return false;
IType type = stloc.Value.InferType(compilation).AcceptVisitor(NormalizeTypeVisitor.TypeErasure);
if (!type.Equals(expectedType))
return false;
}
return true;
}
}
protected internal override TranslatedExpression VisitComp(Comp inst, TranslationContext context)
{
if (inst.LiftingKind == ComparisonLiftingKind.ThreeValuedLogic)
{
if (inst.Kind == ComparisonKind.Equality && inst.Right.MatchLdcI4(0))
{
// lifted logic.not
var targetType = NullableType.Create(compilation, compilation.FindType(KnownTypeCode.Boolean));
var arg = Translate(inst.Left, targetType).ConvertTo(targetType, this);
return new UnaryOperatorExpression(UnaryOperatorType.Not, arg.Expression)
.WithRR(new OperatorResolveResult(targetType, ExpressionType.Not, arg.ResolveResult))
.WithILInstruction(inst);
}
return ErrorExpression("Nullable comparisons with three-valued-logic not supported in C#");
}
if (inst.InputType == StackType.Ref)
{
// Reference comparison using Unsafe intrinsics
Debug.Assert(!inst.IsLifted);
(string methodName, bool negate) = inst.Kind switch {
ComparisonKind.Equality => ("AreSame", false),
ComparisonKind.Inequality => ("AreSame", true),
ComparisonKind.LessThan => ("IsAddressLessThan", false),
ComparisonKind.LessThanOrEqual => ("IsAddressGreaterThan", true),
ComparisonKind.GreaterThan => ("IsAddressGreaterThan", false),
ComparisonKind.GreaterThanOrEqual => ("IsAddressLessThan", true),
_ => throw new InvalidOperationException("Invalid ComparisonKind")
};
var left = Translate(inst.Left);
var right = Translate(inst.Right);
if (left.Type.Kind != TypeKind.ByReference || !NormalizeTypeVisitor.TypeErasure.EquivalentTypes(left.Type, right.Type))
{
IType commonRefType = new ByReferenceType(compilation.FindType(KnownTypeCode.Byte));
left = left.ConvertTo(commonRefType, this);
right = right.ConvertTo(commonRefType, this);
}
IType boolType = compilation.FindType(KnownTypeCode.Boolean);
TranslatedExpression expr = CallUnsafeIntrinsic(
name: methodName,
arguments: new Expression[] { left, right },
returnType: boolType,
inst: inst
);
if (negate)
{
expr = new UnaryOperatorExpression(UnaryOperatorType.Not, expr)
.WithoutILInstruction().WithRR(new ResolveResult(boolType));
}
return expr;
}
if (inst.Kind.IsEqualityOrInequality())
{
var result = TranslateCeq(inst, out bool negateOutput);
if (negateOutput)
return LogicNot(result).WithILInstruction(inst);
else
return result;
}
else
{
return TranslateComp(inst);
}
}
/// <summary>
/// Translates the equality comparison between left and right.
/// </summary>
TranslatedExpression TranslateCeq(Comp inst, out bool negateOutput)
{
Debug.Assert(inst.Kind.IsEqualityOrInequality());
// Translate '(e as T) == null' to '!(e is T)'.
// This is necessary for correctness when T is a value type.
if (inst.Left.OpCode == OpCode.IsInst && inst.Right.OpCode == OpCode.LdNull)
{
negateOutput = inst.Kind == ComparisonKind.Equality;
return IsType((IsInst)inst.Left);
}
else if (inst.Right.OpCode == OpCode.IsInst && inst.Left.OpCode == OpCode.LdNull)
{
negateOutput = inst.Kind == ComparisonKind.Equality;
return IsType((IsInst)inst.Right);
}
var left = Translate(inst.Left);
var right = Translate(inst.Right);
// Remove redundant bool comparisons
if (left.Type.IsKnownType(KnownTypeCode.Boolean))
{
if (inst.Right.MatchLdcI4(0))
{
// 'b == 0' => '!b'
// 'b != 0' => 'b'
negateOutput = inst.Kind == ComparisonKind.Equality;
return left;
}
if (inst.Right.MatchLdcI4(1))
{
// 'b == 1' => 'b'
// 'b != 1' => '!b'
negateOutput = inst.Kind == ComparisonKind.Inequality;
return left;
}
}
else if (right.Type.IsKnownType(KnownTypeCode.Boolean))
{
if (inst.Left.MatchLdcI4(0))
{
// '0 == b' => '!b'
// '0 != b' => 'b'
negateOutput = inst.Kind == ComparisonKind.Equality;
return right;
}
if (inst.Left.MatchLdcI4(1))
{
// '1 == b' => 'b'
// '1 != b' => '!b'
negateOutput = inst.Kind == ComparisonKind.Inequality;
return right;
}
}
// Handle comparisons between unsafe pointers and null:
if (left.Type.Kind == TypeKind.Pointer && inst.Right.MatchLdcI(0))
{
negateOutput = false;
right = new NullReferenceExpression().WithRR(new ConstantResolveResult(SpecialType.NullType, null))
.WithILInstruction(inst.Right);
return CreateBuiltinBinaryOperator(left, inst.Kind.ToBinaryOperatorType(), right)
.WithILInstruction(inst);
}
else if (right.Type.Kind == TypeKind.Pointer && inst.Left.MatchLdcI(0))
{
negateOutput = false;
left = new NullReferenceExpression().WithRR(new ConstantResolveResult(SpecialType.NullType, null))
.WithILInstruction(inst.Left);
return CreateBuiltinBinaryOperator(left, inst.Kind.ToBinaryOperatorType(), right)
.WithILInstruction(inst);
}
// Special case comparisons with enum and char literals
left = TryUniteEqualityOperandType(left, right);
right = TryUniteEqualityOperandType(right, left);
if (IsSpecialCasedReferenceComparisonWithNull(left, right))
{
// When comparing a string/delegate with null, the C# compiler generates a reference comparison.
negateOutput = false;
return CreateBuiltinBinaryOperator(left, inst.Kind.ToBinaryOperatorType(), right)
.WithILInstruction(inst);
}
OperatorResolveResult rr = resolver.ResolveBinaryOperator(inst.Kind.ToBinaryOperatorType(), left.ResolveResult, right.ResolveResult) as OperatorResolveResult;
if (rr == null || rr.IsError || rr.UserDefinedOperatorMethod != null
|| NullableType.GetUnderlyingType(rr.Operands[0].Type).GetStackType() != inst.InputType
|| !rr.Type.IsKnownType(KnownTypeCode.Boolean))
{
IType targetType;
if (inst.InputType == StackType.O)
{
targetType = compilation.FindType(KnownTypeCode.Object);
}
else
{
var leftUType = NullableType.GetUnderlyingType(left.Type);
var rightUType = NullableType.GetUnderlyingType(right.Type);
if (leftUType.GetStackType() == inst.InputType && !leftUType.IsSmallIntegerType())
{
targetType = leftUType;
}
else if (rightUType.GetStackType() == inst.InputType && !rightUType.IsSmallIntegerType())
{
targetType = rightUType;
}
else
{
targetType = FindType(inst.InputType, leftUType.GetSign());
}
}
if (inst.IsLifted)
{
targetType = NullableType.Create(compilation, targetType);
}
if (targetType.Equals(left.Type))
{
right = right.ConvertTo(targetType, this);
}
else
{
left = left.ConvertTo(targetType, this);