forked from icsharpcode/ILSpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransformAssignment.cs
More file actions
1115 lines (1083 loc) · 43.6 KB
/
TransformAssignment.cs
File metadata and controls
1115 lines (1083 loc) · 43.6 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) 2015 Siegfried Pammer
//
// 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.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL.Transforms
{
/// <summary>
/// Constructs compound assignments and inline assignments.
/// </summary>
/// <remarks>
/// This is a statement transform;
/// but some portions are executed as an expression transform instead
/// (with HandleCompoundAssign() as entry point)
/// </remarks>
public class TransformAssignment : IStatementTransform
{
StatementTransformContext context;
void IStatementTransform.Run(Block block, int pos, StatementTransformContext context)
{
this.context = context;
if (context.Settings.MakeAssignmentExpressions)
{
if (TransformInlineAssignmentStObjOrCall(block, pos) || TransformInlineAssignmentLocal(block, pos))
{
// both inline assignments create a top-level stloc which might affect inlining
context.RequestRerun();
return;
}
}
if (context.Settings.IntroduceIncrementAndDecrement)
{
if (TransformPostIncDecOperatorWithInlineStore(block, pos)
|| TransformPostIncDecOperator(block, pos)
|| TransformPreIncDecOperatorWithInlineStore(block, pos))
{
// again, new top-level stloc might need inlining:
context.RequestRerun();
return;
}
}
}
/// <code>
/// stloc s(value)
/// stloc l(ldloc s)
/// stobj(..., ldloc s)
/// where ... is pure and does not use s or l,
/// and where neither the 'stloc s' nor the 'stobj' truncates
/// -->
/// stloc l(stobj (..., value))
/// </code>
/// e.g. used for inline assignment to instance field
///
/// -or-
///
/// <code>
/// stloc s(value)
/// stobj (..., ldloc s)
/// where ... is pure and does not use s, and where the 'stobj' does not truncate
/// -->
/// stloc s(stobj (..., value))
/// </code>
/// e.g. used for inline assignment to static field
///
/// -or-
///
/// <code>
/// stloc s(value)
/// call set_Property(..., ldloc s)
/// where the '...' arguments are pure and not using 's'
/// -->
/// stloc s(Block InlineAssign { call set_Property(..., stloc i(value)); final: ldloc i })
/// new temporary 'i' has type of the property; transform only valid if 'stloc i' doesn't truncate
/// </code>
bool TransformInlineAssignmentStObjOrCall(Block block, int pos)
{
var inst = block.Instructions[pos] as StLoc;
// in some cases it can be a compiler-generated local
if (inst == null || (inst.Variable.Kind != VariableKind.StackSlot && inst.Variable.Kind != VariableKind.Local))
return false;
if (IsImplicitTruncation(inst.Value, inst.Variable.Type, context.TypeSystem))
{
// 'stloc s' is implicitly truncating the value
return false;
}
ILVariable local;
int nextPos;
if (block.Instructions[pos + 1] is StLoc localStore)
{ // with extra local
if (localStore.Variable.Kind != VariableKind.Local || !localStore.Value.MatchLdLoc(inst.Variable))
return false;
// if we're using an extra local, we'll delete "s", so check that that doesn't have any additional uses
if (!(inst.Variable.IsSingleDefinition && inst.Variable.LoadCount == 2))
return false;
local = localStore.Variable;
nextPos = pos + 2;
}
else
{
local = inst.Variable;
localStore = null;
nextPos = pos + 1;
if (local.LoadCount == 1 && local.AddressCount == 0)
{
// inline assignment would produce a dead store in this case, which is ugly
// and causes problems with the deconstruction transform.
return false;
}
}
if (block.Instructions[nextPos] is StObj stobj)
{
// unaligned.stobj cannot be inlined in C#
if (stobj.UnalignedPrefix > 0)
return false;
if (!stobj.Value.MatchLdLoc(inst.Variable))
return false;
if (!SemanticHelper.IsPure(stobj.Target.Flags) || inst.Variable.IsUsedWithin(stobj.Target))
return false;
var pointerType = stobj.Target.InferType(context.TypeSystem);
IType newType = stobj.Type;
if (TypeUtils.IsCompatiblePointerTypeForMemoryAccess(pointerType, stobj.Type))
{
if (pointerType is ByReferenceType byref)
newType = byref.ElementType;
else if (pointerType is PointerType pointer)
newType = pointer.ElementType;
}
var truncation = CheckImplicitTruncation(inst.Value, newType, context.TypeSystem);
if (truncation == ImplicitTruncationResult.ValueChanged)
{
// 'stobj' is implicitly truncating the value
return false;
}
if (truncation == ImplicitTruncationResult.ValueChangedDueToSignMismatch)
{
// Change the sign of the type to skip implicit truncation
newType = SwapSign(newType, context.TypeSystem);
}
context.Step("Inline assignment stobj", stobj);
stobj.Type = newType;
block.Instructions.Remove(localStore);
block.Instructions.Remove(stobj);
stobj.Value = inst.Value;
inst.ReplaceWith(new StLoc(local, stobj));
// note: our caller will trigger a re-run, which will call HandleStObjCompoundAssign if applicable
return true;
}
else if (block.Instructions[nextPos] is CallInstruction call)
{
// call must be a setter call:
if (!(call.OpCode == OpCode.Call || call.OpCode == OpCode.CallVirt))
return false;
if (call.ResultType != StackType.Void || call.Arguments.Count == 0)
return false;
IProperty property = call.Method.AccessorOwner as IProperty;
if (property == null)
return false;
if (!call.Method.Equals(property.Setter))
return false;
if (!(property.IsIndexer || property.Setter.Parameters.Count == 1))
{
// this is a parameterized property, which cannot be expressed as C# code.
// setter calls are not valid in expression context, if property syntax cannot be used.
return false;
}
if (!call.Arguments.Last().MatchLdLoc(inst.Variable))
return false;
foreach (var arg in call.Arguments.SkipLast(1))
{
if (!SemanticHelper.IsPure(arg.Flags) || inst.Variable.IsUsedWithin(arg))
return false;
}
if (IsImplicitTruncation(inst.Value, call.Method.Parameters.Last().Type, context.TypeSystem))
{
// setter call is implicitly truncating the value
return false;
}
// stloc s(Block InlineAssign { call set_Property(..., stloc i(value)); final: ldloc i })
context.Step("Inline assignment call", call);
block.Instructions.Remove(localStore);
block.Instructions.Remove(call);
var newVar = context.Function.RegisterVariable(VariableKind.StackSlot, call.Method.Parameters.Last().Type);
call.Arguments[call.Arguments.Count - 1] = new StLoc(newVar, inst.Value);
var inlineBlock = new Block(BlockKind.CallInlineAssign) {
Instructions = { call },
FinalInstruction = new LdLoc(newVar)
};
inst.ReplaceWith(new StLoc(local, inlineBlock));
// because the ExpressionTransforms don't look into inline blocks, manually trigger HandleCallCompoundAssign
if (HandleCompoundAssign(call, context))
{
// if we did construct a compound assignment, it should have made our inline block redundant:
Debug.Assert(!inlineBlock.IsConnected);
}
return true;
}
else
{
return false;
}
}
private static IType SwapSign(IType type, ICompilation compilation)
{
return type.ToPrimitiveType() switch {
PrimitiveType.I1 => compilation.FindType(KnownTypeCode.Byte),
PrimitiveType.I2 => compilation.FindType(KnownTypeCode.UInt16),
PrimitiveType.I4 => compilation.FindType(KnownTypeCode.UInt32),
PrimitiveType.I8 => compilation.FindType(KnownTypeCode.UInt64),
PrimitiveType.U1 => compilation.FindType(KnownTypeCode.SByte),
PrimitiveType.U2 => compilation.FindType(KnownTypeCode.Int16),
PrimitiveType.U4 => compilation.FindType(KnownTypeCode.Int32),
PrimitiveType.U8 => compilation.FindType(KnownTypeCode.Int64),
PrimitiveType.I => compilation.FindType(KnownTypeCode.UIntPtr),
PrimitiveType.U => compilation.FindType(KnownTypeCode.IntPtr),
_ => throw new ArgumentException("Type must have an opposing sign: " + type, nameof(type))
};
}
static ILInstruction UnwrapSmallIntegerConv(ILInstruction inst, out Conv conv)
{
conv = inst as Conv;
if (conv != null && conv.Kind == ConversionKind.Truncate && conv.TargetType.IsSmallIntegerType())
{
// for compound assignments to small integers, the compiler emits a "conv" instruction
return conv.Argument;
}
else
{
return inst;
}
}
static bool ValidateCompoundAssign(BinaryNumericInstruction binary, Conv conv, IType targetType, DecompilerSettings settings)
{
if (!NumericCompoundAssign.IsBinaryCompatibleWithType(binary, targetType, settings))
return false;
if (conv != null && !(conv.TargetType == targetType.ToPrimitiveType() && conv.CheckForOverflow == binary.CheckForOverflow))
return false; // conv does not match binary operation
return true;
}
static bool MatchingGetterAndSetterCalls(CallInstruction getterCall, CallInstruction setterCall, out Action<ILTransformContext> finalizeMatch)
{
finalizeMatch = null;
if (getterCall == null || setterCall == null || !IsSameMember(getterCall.Method.AccessorOwner, setterCall.Method.AccessorOwner))
return false;
if (setterCall.OpCode != getterCall.OpCode)
return false;
var owner = getterCall.Method.AccessorOwner as IProperty;
if (owner == null || !IsSameMember(getterCall.Method, owner.Getter) || !IsSameMember(setterCall.Method, owner.Setter))
return false;
if (setterCall.Arguments.Count != getterCall.Arguments.Count + 1)
return false;
// Ensure that same arguments are passed to getterCall and setterCall:
for (int j = 0; j < getterCall.Arguments.Count; j++)
{
if (setterCall.Arguments[j].MatchStLoc(out var v) && v.IsSingleDefinition && v.LoadCount == 1)
{
if (getterCall.Arguments[j].MatchLdLoc(v))
{
// OK, setter call argument is saved in temporary that is re-used for getter call
if (finalizeMatch == null)
{
finalizeMatch = AdjustArguments;
}
continue;
}
}
if (!SemanticHelper.IsPure(getterCall.Arguments[j].Flags))
return false;
if (!getterCall.Arguments[j].Match(setterCall.Arguments[j]).Success)
return false;
}
return true;
void AdjustArguments(ILTransformContext context)
{
Debug.Assert(setterCall.Arguments.Count == getterCall.Arguments.Count + 1);
for (int j = 0; j < getterCall.Arguments.Count; j++)
{
if (setterCall.Arguments[j].MatchStLoc(out var v, out var value))
{
Debug.Assert(v.IsSingleDefinition && v.LoadCount == 1);
Debug.Assert(getterCall.Arguments[j].MatchLdLoc(v));
getterCall.Arguments[j] = value;
}
}
}
}
/// <summary>
/// Transform compound assignments where the return value is not being used,
/// or where there's an inlined assignment within the setter call.
///
/// Patterns handled:
/// 1.
/// callvirt set_Property(ldloc S_1, binary.op(callvirt get_Property(ldloc S_1), value))
/// ==> compound.op.new(callvirt get_Property(ldloc S_1), value)
/// 2.
/// callvirt set_Property(ldloc S_1, stloc v(binary.op(callvirt get_Property(ldloc S_1), value)))
/// ==> stloc v(compound.op.new(callvirt get_Property(ldloc S_1), value))
/// 3.
/// stobj(target, binary.op(ldobj(target), ...))
/// where target is pure
/// => compound.op(target, ...)
/// </summary>
/// <remarks>
/// Called by ExpressionTransforms, or after the inline-assignment transform for setters.
/// </remarks>
internal static bool HandleCompoundAssign(ILInstruction compoundStore, StatementTransformContext context)
{
if (!context.Settings.MakeAssignmentExpressions || !context.Settings.IntroduceIncrementAndDecrement)
return false;
if (compoundStore is CallInstruction && compoundStore.SlotInfo != Block.InstructionSlot)
{
// replacing 'call set_Property' with a compound assignment instruction
// changes the return value of the expression, so this is only valid on block-level.
return false;
}
if (!IsCompoundStore(compoundStore, out var targetType, out var setterValue, context.TypeSystem))
return false;
// targetType = The type of the property/field/etc. being stored to.
// setterValue = The value being stored.
var storeInSetter = setterValue as StLoc;
if (storeInSetter != null)
{
// We'll move the stloc to top-level:
// callvirt set_Property(ldloc S_1, stloc v(binary.op(callvirt get_Property(ldloc S_1), value)))
// ==> stloc v(compound.op.new(callvirt get_Property(ldloc S_1), value))
setterValue = storeInSetter.Value;
if (storeInSetter.Variable.Type.IsSmallIntegerType())
{
// 'stloc v' implicitly truncates the value.
// Ensure that type of 'v' matches the type of the property:
if (storeInSetter.Variable.Type.GetSize() != targetType.GetSize())
return false;
if (storeInSetter.Variable.Type.GetSign() != targetType.GetSign())
return false;
}
}
ILInstruction newInst;
if (UnwrapSmallIntegerConv(setterValue, out var smallIntConv) is BinaryNumericInstruction binary)
{
if (compoundStore is StLoc)
{
// transform local variables only for user-defined operators
return false;
}
if (!IsMatchingCompoundLoad(binary.Left, compoundStore, out var target, out var targetKind, out var finalizeMatch, forbiddenVariable: storeInSetter?.Variable))
return false;
if (!ValidateCompoundAssign(binary, smallIntConv, targetType, context.Settings))
return false;
context.Step($"Compound assignment (binary.numeric)", compoundStore);
finalizeMatch?.Invoke(context);
newInst = new NumericCompoundAssign(
binary, target, targetKind, binary.Right,
targetType, CompoundEvalMode.EvaluatesToNewValue);
}
else if (setterValue is Call operatorCall && operatorCall.Method.IsOperator)
{
if (operatorCall.Arguments.Count == 0)
return false;
if (!IsMatchingCompoundLoad(operatorCall.Arguments[0], compoundStore, out var target, out var targetKind, out var finalizeMatch, forbiddenVariable: storeInSetter?.Variable))
return false;
ILInstruction rhs;
if (operatorCall.Arguments.Count == 2)
{
if (CSharp.ExpressionBuilder.GetAssignmentOperatorTypeFromMetadataName(operatorCall.Method.Name, context.Settings) == null)
return false;
rhs = operatorCall.Arguments[1];
}
else if (operatorCall.Arguments.Count == 1)
{
if (!UserDefinedCompoundAssign.IsIncrementOrDecrement(operatorCall.Method, context.Settings))
return false;
// use a dummy node so that we don't need a dedicated instruction for user-defined unary operator calls
rhs = new LdcI4(1);
}
else
{
return false;
}
if (operatorCall.IsLifted)
return false; // TODO: add tests and think about whether nullables need special considerations
context.Step($"Compound assignment (user-defined binary)", compoundStore);
finalizeMatch?.Invoke(context);
newInst = new UserDefinedCompoundAssign(operatorCall.Method, CompoundEvalMode.EvaluatesToNewValue,
target, targetKind, rhs);
}
else if (setterValue is DynamicBinaryOperatorInstruction dynamicBinaryOp)
{
if (!IsMatchingCompoundLoad(dynamicBinaryOp.Left, compoundStore, out var target, out var targetKind, out var finalizeMatch, forbiddenVariable: storeInSetter?.Variable))
return false;
context.Step($"Compound assignment (dynamic binary)", compoundStore);
finalizeMatch?.Invoke(context);
newInst = new DynamicCompoundAssign(ToCompound(dynamicBinaryOp.Operation), dynamicBinaryOp.BinderFlags, target, dynamicBinaryOp.LeftArgumentInfo, dynamicBinaryOp.Right, dynamicBinaryOp.RightArgumentInfo, targetKind);
static ExpressionType ToCompound(ExpressionType from)
{
return from switch {
ExpressionType.Add => ExpressionType.AddAssign,
ExpressionType.AddChecked => ExpressionType.AddAssignChecked,
ExpressionType.And => ExpressionType.AndAssign,
ExpressionType.Divide => ExpressionType.DivideAssign,
ExpressionType.ExclusiveOr => ExpressionType.ExclusiveOrAssign,
ExpressionType.LeftShift => ExpressionType.LeftShiftAssign,
ExpressionType.Modulo => ExpressionType.ModuloAssign,
ExpressionType.Multiply => ExpressionType.MultiplyAssign,
ExpressionType.MultiplyChecked => ExpressionType.MultiplyAssignChecked,
ExpressionType.Or => ExpressionType.OrAssign,
ExpressionType.Power => ExpressionType.PowerAssign,
ExpressionType.RightShift => ExpressionType.RightShiftAssign,
ExpressionType.Subtract => ExpressionType.SubtractAssign,
ExpressionType.SubtractChecked => ExpressionType.SubtractAssignChecked,
_ => from
};
}
}
else if (setterValue is Call concatCall && UserDefinedCompoundAssign.IsStringConcat(concatCall.Method))
{
// setterValue is a string.Concat() invocation
if (compoundStore is StLoc)
{
// transform local variables only for user-defined operators
return false;
}
if (concatCall.Arguments.Count != 2)
return false; // for now we only support binary compound assignments
if (!targetType.IsKnownType(KnownTypeCode.String))
return false;
var arg = concatCall.Arguments[0];
if (arg is Call call && CallBuilder.IsStringToReadOnlySpanCharImplicitConversion(call.Method))
{
arg = call.Arguments[0];
if (!(concatCall.Arguments[1] is NewObj { Arguments: [AddressOf addressOf] } newObj) || !ILInlining.IsReadOnlySpanCharCtor(newObj.Method))
{
return false;
}
}
if (!IsMatchingCompoundLoad(arg, compoundStore, out var target, out var targetKind, out var finalizeMatch, forbiddenVariable: storeInSetter?.Variable))
return false;
context.Step($"Compound assignment (string concatenation)", compoundStore);
finalizeMatch?.Invoke(context);
newInst = new UserDefinedCompoundAssign(concatCall.Method, CompoundEvalMode.EvaluatesToNewValue,
target, targetKind, concatCall.Arguments[1]);
}
else
{
return false;
}
newInst.AddILRange(setterValue);
if (storeInSetter != null)
{
storeInSetter.Value = newInst;
newInst = storeInSetter;
context.RequestRerun(); // moving stloc to top-level might trigger inlining
}
compoundStore.ReplaceWith(newInst);
if (newInst.Parent is Block inlineAssignBlock && inlineAssignBlock.Kind == BlockKind.CallInlineAssign)
{
// It's possible that we first replaced the instruction in an inline-assign helper block.
// In such a situation, we know from the block invariant that we're have a storeInSetter.
Debug.Assert(storeInSetter != null);
Debug.Assert(storeInSetter.Variable.IsSingleDefinition && storeInSetter.Variable.LoadCount == 1);
Debug.Assert(inlineAssignBlock.Instructions.Single() == storeInSetter);
Debug.Assert(inlineAssignBlock.FinalInstruction.MatchLdLoc(storeInSetter.Variable));
// Block CallInlineAssign { stloc I_0(compound.op(...)); final: ldloc I_0 }
// --> compound.op(...)
inlineAssignBlock.ReplaceWith(storeInSetter.Value);
}
return true;
}
/// <code>
/// stloc s(value)
/// stloc l(ldloc s)
/// where neither 'stloc s' nor 'stloc l' truncates the value
/// -->
/// stloc s(stloc l(value))
/// </code>
bool TransformInlineAssignmentLocal(Block block, int pos)
{
var inst = block.Instructions[pos] as StLoc;
var nextInst = block.Instructions.ElementAtOrDefault(pos + 1) as StLoc;
if (inst == null || nextInst == null)
return false;
if (inst.Variable.Kind != VariableKind.StackSlot)
return false;
if (!(nextInst.Variable.Kind == VariableKind.Local || nextInst.Variable.Kind == VariableKind.Parameter))
return false;
if (!nextInst.Value.MatchLdLoc(inst.Variable))
return false;
if (IsImplicitTruncation(inst.Value, inst.Variable.Type, context.TypeSystem))
{
// 'stloc s' is implicitly truncating the stack value
return false;
}
if (IsImplicitTruncation(inst.Value, nextInst.Variable.Type, context.TypeSystem))
{
// 'stloc l' is implicitly truncating the stack value
return false;
}
if (nextInst.Variable.StackType == StackType.Ref)
{
// ref locals need to be initialized when they are declared, so
// we can only use inline assignments when we know that the
// ref local is definitely assigned.
// We don't have an easy way to check for that in this transform,
// so avoid inline assignments to ref locals for now.
return false;
}
context.Step("Inline assignment to local variable", inst);
var value = inst.Value;
var var = nextInst.Variable;
var stackVar = inst.Variable;
block.Instructions.RemoveAt(pos);
nextInst.ReplaceWith(new StLoc(stackVar, new StLoc(var, value)));
return true;
}
internal static bool IsImplicitTruncation(ILInstruction value, IType type, ICompilation compilation, bool allowNullableValue = false)
{
return CheckImplicitTruncation(value, type, compilation, allowNullableValue) != ImplicitTruncationResult.ValuePreserved;
}
internal enum ImplicitTruncationResult : byte
{
/// <summary>
/// The value is not implicitly truncated.
/// </summary>
ValuePreserved,
/// <summary>
/// The value is implicitly truncated.
/// </summary>
ValueChanged,
/// <summary>
/// The value is implicitly truncated, but the sign of the target type can be changed to remove the truncation.
/// </summary>
ValueChangedDueToSignMismatch
}
/// <summary>
/// Gets whether 'stobj type(..., value)' would evaluate to a different value than 'value'
/// due to implicit truncation.
/// </summary>
internal static ImplicitTruncationResult CheckImplicitTruncation(ILInstruction value, IType type, ICompilation compilation, bool allowNullableValue = false)
{
if (!type.IsSmallIntegerType())
{
// Implicit truncation in ILAst only happens for small integer types;
// other types of implicit truncation in IL cause the ILReader to insert
// conv instructions.
return ImplicitTruncationResult.ValuePreserved;
}
// With small integer types, test whether the value might be changed by
// truncation (based on type.GetSize()) followed by sign/zero extension (based on type.GetSign()).
// (it's OK to have false-positives here if we're unsure)
if (value.MatchLdcI4(out int val))
{
bool valueFits = (type.GetEnumUnderlyingType().GetDefinition()?.KnownTypeCode) switch {
KnownTypeCode.Boolean => val == 0 || val == 1,
KnownTypeCode.Byte => val >= byte.MinValue && val <= byte.MaxValue,
KnownTypeCode.SByte => val >= sbyte.MinValue && val <= sbyte.MaxValue,
KnownTypeCode.Int16 => val >= short.MinValue && val <= short.MaxValue,
KnownTypeCode.UInt16 or KnownTypeCode.Char => val >= ushort.MinValue && val <= ushort.MaxValue,
_ => false
};
return valueFits ? ImplicitTruncationResult.ValuePreserved : ImplicitTruncationResult.ValueChanged;
}
else if (value is Conv conv)
{
PrimitiveType primitiveType = type.ToPrimitiveType();
PrimitiveType convTargetType = conv.TargetType;
if (convTargetType == primitiveType)
return ImplicitTruncationResult.ValuePreserved;
if (primitiveType.GetSize() == convTargetType.GetSize() && primitiveType.GetSign() != convTargetType.GetSign() && primitiveType.HasOppositeSign())
return ImplicitTruncationResult.ValueChangedDueToSignMismatch;
return ImplicitTruncationResult.ValueChanged;
}
else if (value is Comp)
{
return ImplicitTruncationResult.ValuePreserved; // comp returns 0 or 1, which always fits
}
else if (value is BinaryNumericInstruction bni)
{
switch (bni.Operator)
{
case BinaryNumericOperator.BitAnd:
case BinaryNumericOperator.BitOr:
case BinaryNumericOperator.BitXor:
// If both input values fit into the type without truncation,
// the result of a binary operator will also fit.
var leftTruncation = CheckImplicitTruncation(bni.Left, type, compilation, allowNullableValue);
// If the left side is truncating and a sign change is not possible we do not need to evaluate the right side
if (leftTruncation == ImplicitTruncationResult.ValueChanged)
return ImplicitTruncationResult.ValueChanged;
var rightTruncation = CheckImplicitTruncation(bni.Right, type, compilation, allowNullableValue);
return CommonImplicitTruncation(leftTruncation, rightTruncation);
}
}
else if (value is IfInstruction ifInst)
{
var trueTruncation = CheckImplicitTruncation(ifInst.TrueInst, type, compilation, allowNullableValue);
// If the true branch is truncating and a sign change is not possible we do not need to evaluate the false branch
if (trueTruncation == ImplicitTruncationResult.ValueChanged)
return ImplicitTruncationResult.ValueChanged;
var falseTruncation = CheckImplicitTruncation(ifInst.FalseInst, type, compilation, allowNullableValue);
return CommonImplicitTruncation(trueTruncation, falseTruncation);
}
else
{
IType inferredType = value.InferType(compilation);
if (allowNullableValue)
{
inferredType = NullableType.GetUnderlyingType(inferredType);
}
if (inferredType.Kind != TypeKind.Unknown)
{
var inferredPrimitive = inferredType.ToPrimitiveType();
var primitiveType = type.ToPrimitiveType();
bool sameSign = inferredPrimitive.GetSign() == primitiveType.GetSign();
if (inferredPrimitive.GetSize() <= primitiveType.GetSize() && sameSign)
return ImplicitTruncationResult.ValuePreserved;
if (inferredPrimitive.GetSize() == primitiveType.GetSize() && !sameSign && primitiveType.HasOppositeSign())
return ImplicitTruncationResult.ValueChangedDueToSignMismatch;
return ImplicitTruncationResult.ValueChanged;
}
}
// In unknown cases, assume that the value might be changed by truncation.
return ImplicitTruncationResult.ValueChanged;
}
private static ImplicitTruncationResult CommonImplicitTruncation(ImplicitTruncationResult left, ImplicitTruncationResult right)
{
if (left == right)
return left;
// Note: in all cases where left!=right, we return ValueChanged:
// if only one side can be fixed by changing the sign, we don't want to change the sign of the other side.
return ImplicitTruncationResult.ValueChanged;
}
/// <summary>
/// Gets whether 'inst' is a possible store for use as a compound store.
/// </summary>
/// <remarks>
/// Output parameters:
/// storeType: The type of the value being stored.
/// value: The value being stored (will be analyzed further to detect compound assignments)
///
/// Every IsCompoundStore() call should be followed by an IsMatchingCompoundLoad() call.
/// </remarks>
static bool IsCompoundStore(ILInstruction inst, out IType storeType,
out ILInstruction value, ICompilation compilation)
{
value = null;
storeType = null;
if (inst is StObj stobj)
{
// stobj.Type may just be 'int' (due to stind.i4) when we're actually operating on a 'ref MyEnum'.
// Try to determine the real type of the object we're modifying:
storeType = stobj.Target.InferType(compilation);
if (storeType is ByReferenceType refType)
{
if (TypeUtils.IsCompatibleTypeForMemoryAccess(refType.ElementType, stobj.Type))
{
storeType = refType.ElementType;
}
else
{
storeType = stobj.Type;
}
}
else if (storeType is PointerType pointerType)
{
if (TypeUtils.IsCompatibleTypeForMemoryAccess(pointerType.ElementType, stobj.Type))
{
storeType = pointerType.ElementType;
}
else
{
storeType = stobj.Type;
}
}
else
{
storeType = stobj.Type;
}
value = stobj.Value;
return SemanticHelper.IsPure(stobj.Target.Flags);
}
else if (inst is CallInstruction call && (call.OpCode == OpCode.Call || call.OpCode == OpCode.CallVirt))
{
if (call.Method.Parameters.Count == 0)
{
return false;
}
foreach (var arg in call.Arguments.SkipLast(1))
{
if (arg.MatchStLoc(out var v) && v.IsSingleDefinition && v.LoadCount == 1)
{
continue; // OK, IsMatchingCompoundLoad can perform an adjustment in this special case
}
if (!SemanticHelper.IsPure(arg.Flags))
{
return false;
}
}
storeType = call.Method.Parameters.Last().Type;
value = call.Arguments.Last();
return IsSameMember(call.Method, (call.Method.AccessorOwner as IProperty)?.Setter);
}
else if (inst is StLoc stloc && (stloc.Variable.Kind == VariableKind.Local || stloc.Variable.Kind == VariableKind.Parameter))
{
storeType = stloc.Variable.Type;
value = stloc.Value;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Checks whether 'load' and 'store' both access the same store, and can be combined to a compound assignment.
/// </summary>
/// <param name="load">The load instruction to test.</param>
/// <param name="store">The compound store to test against. Must have previously been tested via IsCompoundStore()</param>
/// <param name="target">The target to use for the compound assignment instruction.</param>
/// <param name="targetKind">The target kind to use for the compound assignment instruction.</param>
/// <param name="finalizeMatch">If set to a non-null value, call this delegate to fix up minor mismatches between getter and setter.</param>
/// <param name="forbiddenVariable">
/// If given a non-null value, this function returns false if the forbiddenVariable is used in the load/store instructions.
/// Some transforms effectively move a store around,
/// which is only valid if the variable stored to does not occur in the compound load/store.
/// </param>
/// <param name="previousInstruction">
/// Instruction preceding the load.
/// </param>
static bool IsMatchingCompoundLoad(ILInstruction load, ILInstruction store,
out ILInstruction target, out CompoundTargetKind targetKind,
out Action<ILTransformContext> finalizeMatch,
ILVariable forbiddenVariable = null,
ILInstruction previousInstruction = null)
{
target = null;
targetKind = 0;
finalizeMatch = null;
if (load is LdObj ldobj && store is StObj stobj)
{
Debug.Assert(SemanticHelper.IsPure(stobj.Target.Flags));
if (!SemanticHelper.IsPure(ldobj.Target.Flags))
return false;
if (forbiddenVariable != null && forbiddenVariable.IsUsedWithin(ldobj.Target))
return false;
target = ldobj.Target;
targetKind = CompoundTargetKind.Address;
if (ldobj.Target.Match(stobj.Target).Success)
{
return true;
}
else if (IsDuplicatedAddressComputation(stobj.Target, ldobj.Target))
{
// Use S_0 as target, so that S_0 can later be eliminated by inlining.
// (we can't eliminate previousInstruction right now, because it's before the transform's starting instruction)
target = stobj.Target;
return true;
}
else
{
return false;
}
}
else if (MatchingGetterAndSetterCalls(load as CallInstruction, store as CallInstruction, out finalizeMatch))
{
if (forbiddenVariable != null && forbiddenVariable.IsUsedWithin(load))
return false;
target = load;
targetKind = CompoundTargetKind.Property;
return true;
}
else if (load is LdLoc ldloc && store is StLoc stloc && ILVariableEqualityComparer.Instance.Equals(ldloc.Variable, stloc.Variable))
{
if (ILVariableEqualityComparer.Instance.Equals(ldloc.Variable, forbiddenVariable))
return false;
target = new LdLoca(ldloc.Variable).WithILRange(ldloc);
targetKind = CompoundTargetKind.Address;
finalizeMatch = context => context.Function.RecombineVariables(ldloc.Variable, stloc.Variable);
return true;
}
else
{
return false;
}
bool IsDuplicatedAddressComputation(ILInstruction storeTarget, ILInstruction loadTarget)
{
// Sometimes roslyn duplicates the address calculation:
// stloc S_0(ldloc refParam)
// stloc V_0(ldobj System.Int32(ldloc refParam))
// stobj System.Int32(ldloc S_0, binary.add.i4(ldloc V_0, ldc.i4 1))
while (storeTarget is LdFlda storeLdFlda && loadTarget is LdFlda loadLdFlda)
{
if (!storeLdFlda.Field.Equals(loadLdFlda.Field))
return false;
storeTarget = storeLdFlda.Target;
loadTarget = loadLdFlda.Target;
}
if (!storeTarget.MatchLdLoc(out var s))
return false;
if (!(s.Kind == VariableKind.StackSlot && s.IsSingleDefinition && s != forbiddenVariable))
return false;
if (s.StoreInstructions.SingleOrDefault() != previousInstruction)
return false;
return previousInstruction is StLoc addressStore && addressStore.Value.Match(loadTarget).Success;
}
}
/// <code>
/// stloc l(stloc target(binary.add(ldloc target, ldc.i4 1)))
/// </code>
bool TransformPreIncDecOperatorWithInlineStore(Block block, int pos)
{
var store = block.Instructions[pos];
if (!IsCompoundStore(store, out var targetType1, out var value1, context.TypeSystem))
{
return false;
}
if (!IsCompoundStore(value1, out var targetType2, out var value2, context.TypeSystem))
{
return false;
}
if (targetType1 != targetType2)
return false;
var targetType = targetType1;
var stloc_outer = store as StLoc;
var stloc_inner = value1 as StLoc;
LdLoc ldloc;
var binary = UnwrapSmallIntegerConv(value2, out var conv) as BinaryNumericInstruction;
if (binary != null && (binary.Right.MatchLdcI(1) || binary.Right.MatchLdcF4(1) || binary.Right.MatchLdcF8(1)))
{
if (!(binary.Operator == BinaryNumericOperator.Add || binary.Operator == BinaryNumericOperator.Sub))
return false;
if (conv is not null)
{
var primitiveType = targetType.ToPrimitiveType();
if (primitiveType.GetSize() == conv.TargetType.GetSize() && primitiveType.GetSign() != conv.TargetType.GetSign())
targetType = SwapSign(targetType, context.TypeSystem);
}
if (!ValidateCompoundAssign(binary, conv, targetType, context.Settings))
return false;
ldloc = binary.Left as LdLoc;
}
else if (value2 is Call operatorCall && operatorCall.Method.IsOperator && operatorCall.Arguments.Count == 1)
{
if (!(operatorCall.Method.Name == "op_Increment" || operatorCall.Method.Name == "op_Decrement"))
return false;
if (operatorCall.IsLifted)
return false; // TODO: add tests and think about whether nullables need special considerations
ldloc = operatorCall.Arguments[0] as LdLoc;
}
else
{
return false;
}
if (stloc_outer == null)
return false;
if (stloc_inner == null)
return false;
if (ldloc == null)
return false;
if (!(stloc_outer.Variable.Kind == VariableKind.Local || stloc_outer.Variable.Kind == VariableKind.StackSlot))
return false;
if (!IsMatchingCompoundLoad(ldloc, stloc_inner, out var target, out var targetKind, out var finalizeMatch))
return false;
if (IsImplicitTruncation(stloc_outer.Value, stloc_outer.Variable.Type, context.TypeSystem))
return false;
context.Step(nameof(TransformPreIncDecOperatorWithInlineStore), store);
finalizeMatch?.Invoke(context);
if (binary != null)
{
block.Instructions[pos] = new StLoc(stloc_outer.Variable, new NumericCompoundAssign(
binary, target, targetKind, binary.Right, targetType, CompoundEvalMode.EvaluatesToNewValue));
}
else
{
Call operatorCall = (Call)value2;
block.Instructions[pos] = new StLoc(stloc_outer.Variable, new UserDefinedCompoundAssign(
operatorCall.Method, CompoundEvalMode.EvaluatesToNewValue, target, targetKind, new LdcI4(1)));
}
return true;
}
/// <code>
/// stobj(target, binary.add(stloc l(ldobj(target)), ldc.i4 1))
/// where target is pure and does not use 'l', and the 'stloc l' does not truncate
/// -->
/// stloc l(compound.op.old(ldobj(target), ldc.i4 1))
///
/// -or-
///
/// call set_Prop(args..., binary.add(stloc l(call get_Prop(args...)), ldc.i4 1))
/// where args.. are pure and do not use 'l', and the 'stloc l' does not truncate
/// -->
/// stloc l(compound.op.old(call get_Prop(target), ldc.i4 1))
/// </code>
/// <remarks>
/// This pattern is used for post-increment by legacy csc.
///
/// Even though this transform operates only on a single expression, it's not an expression transform
/// as the result value of the expression changes (this is OK only for statements in a block).
/// </remarks>
bool TransformPostIncDecOperatorWithInlineStore(Block block, int pos)
{
var store = block.Instructions[pos];
if (!IsCompoundStore(store, out var targetType, out var value, context.TypeSystem))
{
return false;
}
StLoc stloc;
var binary = UnwrapSmallIntegerConv(value, out var conv) as BinaryNumericInstruction;
if (binary != null && (binary.Right.MatchLdcI(1) || binary.Right.MatchLdcF4(1) || binary.Right.MatchLdcF8(1)))
{
if (!(binary.Operator == BinaryNumericOperator.Add || binary.Operator == BinaryNumericOperator.Sub))
return false;
if (conv is not null)
{
var primitiveType = targetType.ToPrimitiveType();
if (primitiveType.GetSize() == conv.TargetType.GetSize() && primitiveType.GetSign() != conv.TargetType.GetSign())
targetType = SwapSign(targetType, context.TypeSystem);
}
if (!ValidateCompoundAssign(binary, conv, targetType, context.Settings))
return false;
stloc = binary.Left as StLoc;
}
else if (value is Call operatorCall && operatorCall.Method.IsOperator && operatorCall.Arguments.Count == 1)
{
if (!(operatorCall.Method.Name == "op_Increment" || operatorCall.Method.Name == "op_Decrement"))
return false;
if (operatorCall.IsLifted)
return false; // TODO: add tests and think about whether nullables need special considerations
stloc = operatorCall.Arguments[0] as StLoc;
}
else
{
return false;
}
if (stloc == null)
return false;
if (!(stloc.Variable.Kind == VariableKind.Local || stloc.Variable.Kind == VariableKind.StackSlot))
return false;
if (!IsMatchingCompoundLoad(stloc.Value, store, out var target, out var targetKind, out var finalizeMatch, forbiddenVariable: stloc.Variable))
return false;
if (IsImplicitTruncation(stloc.Value, stloc.Variable.Type, context.TypeSystem))
return false;
context.Step("TransformPostIncDecOperatorWithInlineStore", store);
finalizeMatch?.Invoke(context);
if (binary != null)
{
block.Instructions[pos] = new StLoc(stloc.Variable, new NumericCompoundAssign(
binary, target, targetKind, binary.Right, targetType, CompoundEvalMode.EvaluatesToOldValue));
}
else
{
Call operatorCall = (Call)value;
block.Instructions[pos] = new StLoc(stloc.Variable, new UserDefinedCompoundAssign(
operatorCall.Method, CompoundEvalMode.EvaluatesToOldValue, target, targetKind, new LdcI4(1)));