cce1f8419ce4c470eb5880c529786d337c7f693b
[mono.git] / mcs / mcs / nullable.cs
1 //
2 // nullable.cs: Nullable types support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 //          Miguel de Icaza (miguel@ximian.com)
6 //          Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin Inc
13 //
14
15 using System;
16 using SLE = System.Linq.Expressions;
17
18 #if STATIC
19 using IKVM.Reflection.Emit;
20 #else
21 using System.Reflection.Emit;
22 #endif
23         
24 namespace Mono.CSharp.Nullable
25 {
26         public class NullableType : TypeExpr
27         {
28                 readonly TypeSpec underlying;
29
30                 public NullableType (TypeSpec type, Location loc)
31                 {
32                         this.underlying = type;
33                         this.loc = loc;
34                 }
35
36                 public override TypeSpec ResolveAsType (IMemberContext ec, bool allowUnboundTypeArguments = false)
37                 {
38                         eclass = ExprClass.Type;
39
40                         var otype = ec.Module.PredefinedTypes.Nullable.Resolve ();
41                         if (otype == null)
42                                 return null;
43
44                         TypeArguments args = new TypeArguments (new TypeExpression (underlying, loc));
45                         GenericTypeExpr ctype = new GenericTypeExpr (otype, args, loc);
46                         
47                         type = ctype.ResolveAsType (ec);
48                         return type;
49                 }
50         }
51
52         static class NullableInfo
53         {
54                 public static MethodSpec GetConstructor (TypeSpec nullableType)
55                 {
56                         return (MethodSpec) MemberCache.FindMember (nullableType,
57                                 MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (GetUnderlyingType (nullableType))), BindingRestriction.DeclaredOnly);
58                 }
59
60                 public static MethodSpec GetHasValue (TypeSpec nullableType)
61                 {
62                         return (MethodSpec) MemberCache.FindMember (nullableType,
63                                 MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
64                 }
65
66                 public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
67                 {
68                         return (MethodSpec) MemberCache.FindMember (nullableType,
69                                 MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
70                 }
71
72                 //
73                 // Don't use unless really required for correctness, see Unwrap::Emit
74                 //
75                 public static MethodSpec GetValue (TypeSpec nullableType)
76                 {
77                         return (MethodSpec) MemberCache.FindMember (nullableType,
78                                 MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
79                 }
80
81                 public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
82                 {
83                         return ((InflatedTypeSpec) nullableType).TypeArguments[0];
84                 }
85
86                 public static TypeSpec GetEnumUnderlyingType (ModuleContainer module, TypeSpec nullableEnum)
87                 {
88                         return MakeType (module, EnumSpec.GetUnderlyingType (GetUnderlyingType (nullableEnum)));
89                 }
90
91                 public static TypeSpec MakeType (ModuleContainer module, TypeSpec underlyingType)
92                 {
93                         return module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (module,
94                                 new[] { underlyingType });
95
96                 }
97         }
98
99         public class Unwrap : Expression, IMemoryLocation
100         {
101                 Expression expr;
102
103                 LocalTemporary temp;
104                 Expression temp_field;
105                 readonly bool useDefaultValue;
106
107                 public Unwrap (Expression expr, bool useDefaultValue = true)
108                 {
109                         this.expr = expr;
110                         this.loc = expr.Location;
111                         this.useDefaultValue = useDefaultValue;
112
113                         type = NullableInfo.GetUnderlyingType (expr.Type);
114                         eclass = expr.eclass;
115                 }
116
117                 public override bool ContainsEmitWithAwait ()
118                 {
119                         return expr.ContainsEmitWithAwait ();
120                 }
121
122                 // TODO: REMOVE
123                 public static Expression Create (Expression expr)
124                 {
125                         //
126                         // Avoid unwraping and wraping of same type
127                         //
128                         Wrap wrap = expr as Wrap;
129                         if (wrap != null)
130                                 return wrap.Child;
131
132                         return Create (expr, false);
133                 }
134
135                 public static Expression CreateUnwrapped (Expression expr)
136                 {
137                         //
138                         // Avoid unwraping and wraping of same type
139                         //
140                         Wrap wrap = expr as Wrap;
141                         if (wrap != null)
142                                 return wrap.Child;
143
144                         return Create (expr, true);
145                 }
146
147                 public static Unwrap Create (Expression expr, bool useDefaultValue)
148                 {
149                         return new Unwrap (expr, useDefaultValue);
150                 }
151                 
152                 public override Expression CreateExpressionTree (ResolveContext ec)
153                 {
154                         return expr.CreateExpressionTree (ec);
155                 }
156
157                 protected override Expression DoResolve (ResolveContext ec)
158                 {
159                         return this;
160                 }
161
162                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
163                 {
164                         expr = expr.DoResolveLValue (ec, right_side);
165                         return this;
166                 }
167
168                 public override void Emit (EmitContext ec)
169                 {
170                         Store (ec);
171
172                         var call = new CallEmitter ();
173                         call.InstanceExpression = this;
174
175                         //
176                         // Using GetGetValueOrDefault is prefered because JIT can possibly
177                         // inline it whereas Value property contains a throw which is very
178                         // unlikely to be inlined
179                         //
180                         if (useDefaultValue)
181                                 call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
182                         else
183                                 call.EmitPredefined (ec, NullableInfo.GetValue (expr.Type), null);
184                 }
185
186                 public void EmitCheck (EmitContext ec)
187                 {
188                         Store (ec);
189
190                         var call = new CallEmitter ();
191                         call.InstanceExpression = this;
192
193                         call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
194                 }
195
196                 public override void EmitSideEffect (EmitContext ec)
197                 {
198                         expr.EmitSideEffect (ec);
199                 }
200
201                 public override Expression EmitToField (EmitContext ec)
202                 {
203                         if (temp_field == null)
204                                 temp_field = this.expr.EmitToField (ec);
205                         
206                         return this;
207                 }
208
209                 public override bool Equals (object obj)
210                 {
211                         Unwrap uw = obj as Unwrap;
212                         return uw != null && expr.Equals (uw.expr);
213                 }
214
215                 public override void FlowAnalysis (FlowAnalysisContext fc)
216                 {
217                         expr.FlowAnalysis (fc);
218                 }
219
220                 public Expression Original {
221                         get {
222                                 return expr;
223                         }
224                 }
225                 
226                 public override int GetHashCode ()
227                 {
228                         return expr.GetHashCode ();
229                 }
230
231                 public override bool IsNull {
232                         get {
233                                 return expr.IsNull;
234                         }
235                 }
236
237                 public void Store (EmitContext ec)
238                 {
239                         if (temp != null || temp_field != null)
240                                 return;
241
242                         if (expr is VariableReference)
243                                 return;
244
245                         expr.Emit (ec);
246                         LocalVariable.Store (ec);
247                 }
248
249                 public void Load (EmitContext ec)
250                 {
251                         if (temp_field != null)
252                                 temp_field.Emit (ec);
253                         else if (expr is VariableReference)
254                                 expr.Emit (ec);
255                         else
256                                 LocalVariable.Emit (ec);
257                 }
258
259                 public override SLE.Expression MakeExpression (BuilderContext ctx)
260                 {
261                         return expr.MakeExpression (ctx);
262                 }
263
264                 public void AddressOf (EmitContext ec, AddressOp mode)
265                 {
266                         IMemoryLocation ml;
267
268                         if (temp_field != null) {
269                                 ml = temp_field as IMemoryLocation;
270                                 if (ml == null) {
271                                         var lt = new LocalTemporary (temp_field.Type);
272                                         temp_field.Emit (ec);
273                                         lt.Store (ec);
274                                         ml = lt;
275                                 }
276                         } else {
277                                 ml = expr as VariableReference;
278                         }
279
280                         if (ml != null)
281                                 ml.AddressOf (ec, mode);
282                         else
283                                 LocalVariable.AddressOf (ec, mode);
284                 }
285
286                 //
287                 // Keeps result of non-variable expression
288                 //
289                 LocalTemporary LocalVariable {
290                         get {
291                                 if (temp == null && temp_field == null)
292                                         temp = new LocalTemporary (expr.Type);
293                                 return temp;
294                         }
295                 }
296         }
297
298         //
299         // Calls get_Value method on nullable expression
300         //
301         public class UnwrapCall : CompositeExpression
302         {
303                 public UnwrapCall (Expression expr)
304                         : base (expr)
305                 {
306                 }
307
308                 protected override Expression DoResolve (ResolveContext rc)
309                 {
310                         base.DoResolve (rc);
311
312                         if (type != null)
313                                 type = NullableInfo.GetUnderlyingType (type);
314
315                         return this;
316                 }
317
318                 public override void Emit (EmitContext ec)
319                 {
320                         var call = new CallEmitter ();
321                         call.InstanceExpression = Child;
322                         call.EmitPredefined (ec, NullableInfo.GetValue (Child.Type), null);
323                 }
324         }
325
326         public class Wrap : TypeCast
327         {
328                 private Wrap (Expression expr, TypeSpec type)
329                         : base (expr, type)
330                 {
331                         eclass = ExprClass.Value;
332                 }
333
334                 public override Expression CreateExpressionTree (ResolveContext ec)
335                 {
336                         TypeCast child_cast = child as TypeCast;
337                         if (child_cast != null) {
338                                 child.Type = type;
339                                 return child_cast.CreateExpressionTree (ec);
340                         }
341
342                         var user_cast = child as UserCast;
343                         if (user_cast != null) {
344                                 child.Type = type;
345                                 return user_cast.CreateExpressionTree (ec);
346                         }
347
348                         return base.CreateExpressionTree (ec);
349                 }
350
351                 public static Expression Create (Expression expr, TypeSpec type)
352                 {
353                         //
354                         // Avoid unwraping and wraping of the same type
355                         //
356                         Unwrap unwrap = expr as Unwrap;
357                         if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
358                                 return unwrap.Original;
359                 
360                         return new Wrap (expr, type);
361                 }
362                 
363                 public override void Emit (EmitContext ec)
364                 {
365                         child.Emit (ec);
366                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
367                 }
368         }
369
370         //
371         // Represents null literal lifted to nullable type
372         //
373         public class LiftedNull : NullConstant, IMemoryLocation
374         {
375                 private LiftedNull (TypeSpec nullable_type, Location loc)
376                         : base (nullable_type, loc)
377                 {
378                         eclass = ExprClass.Value;
379                 }
380
381                 public static Constant Create (TypeSpec nullable, Location loc)
382                 {
383                         return new LiftedNull (nullable, loc);
384                 }
385
386                 public static Constant CreateFromExpression (ResolveContext rc, Expression e)
387                 {
388                         if (!rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
389                                 rc.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
390                                         e.Type.GetSignatureForError ());
391                         }
392
393                         return ReducedExpression.Create (Create (e.Type, e.Location), e);
394                 }
395
396                 public override void Emit (EmitContext ec)
397                 {
398                         // TODO: generate less temporary variables
399                         LocalTemporary value_target = new LocalTemporary (type);
400
401                         value_target.AddressOf (ec, AddressOp.Store);
402                         ec.Emit (OpCodes.Initobj, type);
403                         value_target.Emit (ec);
404                         value_target.Release (ec);
405                 }
406
407                 public void AddressOf (EmitContext ec, AddressOp Mode)
408                 {
409                         LocalTemporary value_target = new LocalTemporary (type);
410                                 
411                         value_target.AddressOf (ec, AddressOp.Store);
412                         ec.Emit (OpCodes.Initobj, type);
413                         value_target.AddressOf (ec, Mode);
414                 }
415         }
416
417         //
418         // Generic lifting expression, supports all S/S? -> T/T? cases
419         //
420         public class LiftedConversion : Expression, IMemoryLocation
421         {
422                 Expression expr, null_value;
423                 Unwrap unwrap;
424
425                 public LiftedConversion (Expression expr, Unwrap unwrap, TypeSpec type)
426                 {
427                         this.expr = expr;
428                         this.unwrap = unwrap;
429                         this.loc = expr.Location;
430                         this.type = type;
431                 }
432
433                 public LiftedConversion (Expression expr, Expression unwrap, TypeSpec type)
434                         : this (expr, unwrap as Unwrap, type)
435                 {
436                 }
437
438                 public override bool IsNull {
439                         get {
440                                 return expr.IsNull;
441                         }
442                 }
443
444                 public override bool ContainsEmitWithAwait ()
445                 {
446                         return unwrap.ContainsEmitWithAwait ();
447                 }
448                 
449                 public override Expression CreateExpressionTree (ResolveContext ec)
450                 {
451                         return expr.CreateExpressionTree (ec);
452                 }                       
453
454                 protected override Expression DoResolve (ResolveContext ec)
455                 {
456                         //
457                         // It's null when lifting non-nullable type
458                         //
459                         if (unwrap == null) {
460                                 // S -> T? is wrap only
461                                 if (type.IsNullableType)
462                                         return Wrap.Create (expr, type);
463
464                                 // S -> T can be simplified
465                                 return expr;
466                         }
467
468                         // Wrap target for T?
469                         if (type.IsNullableType) {
470                                 if (!expr.Type.IsNullableType) {
471                                         expr = Wrap.Create (expr, type);
472                                         if (expr == null)
473                                                 return null;
474                                 }
475
476                                 null_value = LiftedNull.Create (type, loc);
477                         } else if (TypeSpec.IsValueType (type)) {
478                                 null_value = LiftedNull.Create (type, loc);
479                         } else {
480                                 null_value = new NullConstant (type, loc);
481                         }
482
483                         eclass = ExprClass.Value;
484                         return this;
485                 }
486
487                 public override void Emit (EmitContext ec)
488                 {
489                         Label is_null_label = ec.DefineLabel ();
490                         Label end_label = ec.DefineLabel ();
491
492                         unwrap.EmitCheck (ec);
493                         ec.Emit (OpCodes.Brfalse, is_null_label);
494
495                         expr.Emit (ec);
496
497                         ec.Emit (OpCodes.Br, end_label);
498                         ec.MarkLabel (is_null_label);
499
500                         null_value.Emit (ec);
501
502                         ec.MarkLabel (end_label);
503                 }
504
505                 public override void FlowAnalysis (FlowAnalysisContext fc)
506                 {
507                         expr.FlowAnalysis (fc);
508                 }
509
510                 public void AddressOf (EmitContext ec, AddressOp mode)
511                 {
512                         unwrap.AddressOf (ec, mode);
513                 }
514         }
515
516         public class LiftedUnaryOperator : Unary, IMemoryLocation
517         {
518                 Unwrap unwrap;
519                 Expression user_operator;
520
521                 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
522                         : base (op, expr, loc)
523                 {
524                 }
525
526                 public void AddressOf (EmitContext ec, AddressOp mode)
527                 {
528                         unwrap.AddressOf (ec, mode);
529                 }
530
531                 public override Expression CreateExpressionTree (ResolveContext ec)
532                 {
533                         if (user_operator != null)
534                                 return user_operator.CreateExpressionTree (ec);
535
536                         if (Oper == Operator.UnaryPlus)
537                                 return Expr.CreateExpressionTree (ec);
538
539                         return base.CreateExpressionTree (ec);
540                 }
541
542                 protected override Expression DoResolve (ResolveContext ec)
543                 {
544                         unwrap = Unwrap.Create (Expr, false);
545                         if (unwrap == null)
546                                 return null;
547
548                         Expression res = base.ResolveOperator (ec, unwrap);
549                         if (res == null) {
550                                 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
551                                 return null;
552                         }
553
554                         if (res != this) {
555                                 if (user_operator == null)
556                                         return res;
557                         } else {
558                                 res = Expr = LiftExpression (ec, Expr);
559                         }
560
561                         if (res == null)
562                                 return null;
563
564                         eclass = ExprClass.Value;
565                         type = res.Type;
566                         return this;
567                 }
568
569                 public override void Emit (EmitContext ec)
570                 {
571                         Label is_null_label = ec.DefineLabel ();
572                         Label end_label = ec.DefineLabel ();
573
574                         unwrap.EmitCheck (ec);
575                         ec.Emit (OpCodes.Brfalse, is_null_label);
576
577                         if (user_operator != null) {
578                                 user_operator.Emit (ec);
579                         } else {
580                                 EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
581                         }
582
583                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
584                         ec.Emit (OpCodes.Br_S, end_label);
585
586                         ec.MarkLabel (is_null_label);
587                         LiftedNull.Create (type, loc).Emit (ec);
588
589                         ec.MarkLabel (end_label);
590                 }
591
592                 static Expression LiftExpression (ResolveContext ec, Expression expr)
593                 {
594                         var lifted_type = new NullableType (expr.Type, expr.Location);
595                         if (lifted_type.ResolveAsType (ec) == null)
596                                 return null;
597
598                         expr.Type = lifted_type.Type;
599                         return expr;
600                 }
601
602                 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
603                 {
604                         expr = base.ResolveEnumOperator (ec, expr, predefined);
605                         if (expr == null)
606                                 return null;
607
608                         Expr = LiftExpression (ec, Expr);
609                         return LiftExpression (ec, expr);
610                 }
611
612                 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
613                 {
614                         expr = base.ResolveUserOperator (ec, expr);
615                         if (expr == null)
616                                 return null;
617
618                         //
619                         // When a user operator is of non-nullable type
620                         //
621                         if (Expr is Unwrap) {
622                                 user_operator = LiftExpression (ec, expr);
623                                 return user_operator;
624                         }
625
626                         return expr;
627                 }
628         }
629
630         //
631         // Lifted version of binary operators
632         //
633         class LiftedBinaryOperator : Expression
634         {
635                 public LiftedBinaryOperator (Binary b)
636                 {
637                         this.Binary = b;
638                         this.loc = b.Location;
639                 }
640
641                 public Binary Binary { get; private set; }
642
643                 public Expression Left { get; set; }
644
645                 public Expression Right { get; set; }
646
647                 public Unwrap UnwrapLeft { get; set; }
648
649                 public Unwrap UnwrapRight { get; set; }
650
651                 public MethodSpec UserOperator { get; set; }
652
653                 bool IsBitwiseBoolean {
654                         get {
655                                 return (Binary.Oper == Binary.Operator.BitwiseAnd || Binary.Oper == Binary.Operator.BitwiseOr) &&
656                                 ((UnwrapLeft != null && UnwrapLeft.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) ||
657                                  (UnwrapRight != null && UnwrapRight.Type.BuiltinType == BuiltinTypeSpec.Type.Bool));
658                         }
659                 }
660
661                 public override bool ContainsEmitWithAwait ()
662                 {
663                         return Left.ContainsEmitWithAwait () || Right.ContainsEmitWithAwait ();
664                 }
665
666                 public override Expression CreateExpressionTree (ResolveContext rc)
667                 {
668                         if (UserOperator != null) {
669                                 Arguments args = new Arguments (2);
670                                 args.Add (new Argument (Binary.Left));
671                                 args.Add (new Argument (Binary.Right));
672
673                                 var method = new UserOperatorCall (UserOperator, args, Binary.CreateExpressionTree, loc);
674                                 return method.CreateExpressionTree (rc);
675                         }
676
677                         return Binary.CreateExpressionTree (rc);
678                 }
679
680                 protected override Expression DoResolve (ResolveContext rc)
681                 {
682                         if (rc.IsRuntimeBinder) {
683                                 if (UnwrapLeft == null && !Left.Type.IsNullableType)
684                                         Left = LiftOperand (rc, Left);
685
686                                 if (UnwrapRight == null && !Right.Type.IsNullableType)
687                                         Right = LiftOperand (rc, Right);
688                         } else {
689                                 if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) {
690                                         Left = Unwrap.CreateUnwrapped (Left);
691                                         UnwrapLeft = Left as Unwrap;
692                                 }
693
694                                 if (UnwrapRight == null && Right != null && Right.Type.IsNullableType) {
695                                         Right = Unwrap.CreateUnwrapped (Right);
696                                         UnwrapRight = Right as Unwrap;
697                                 }
698                         }
699
700                         type = Binary.Type;
701                         eclass = Binary.eclass; 
702
703                         return this;
704                 }
705
706                 Expression LiftOperand (ResolveContext rc, Expression expr)
707                 {
708                         TypeSpec type;
709                         if (expr.IsNull) {
710                                 type = Left.IsNull ? Right.Type : Left.Type;
711                         } else {
712                                 type = expr.Type;
713                         }
714
715                         if (!type.IsNullableType)
716                                 type = NullableInfo.MakeType (rc.Module, type);
717
718                         return Wrap.Create (expr, type);
719                 }
720
721                 public override void Emit (EmitContext ec)
722                 {
723                         if (IsBitwiseBoolean && UserOperator == null) {
724                                 EmitBitwiseBoolean (ec);
725                                 return;
726                         }
727
728                         if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) {
729                                 EmitEquality (ec);
730                                 return;
731                         }
732
733                         Label is_null_label = ec.DefineLabel ();
734                         Label end_label = ec.DefineLabel ();
735
736                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) {
737                                 Left = Left.EmitToField (ec);
738                                 Right = Right.EmitToField (ec);
739                         }
740
741                         if (UnwrapLeft != null) {
742                                 UnwrapLeft.EmitCheck (ec);
743                         }
744
745                         //
746                         // Don't emit HasValue check when left and right expressions are same
747                         //
748                         if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) {
749                                 UnwrapRight.EmitCheck (ec);
750                                 if (UnwrapLeft != null) {
751                                         ec.Emit (OpCodes.And);
752                                 }
753                         }
754
755                         ec.Emit (OpCodes.Brfalse, is_null_label);
756
757                         if (UserOperator != null) {
758                                 var args = new Arguments (2);
759                                 args.Add (new Argument (Left));
760                                 args.Add (new Argument (Right));
761
762                                 var call = new CallEmitter ();
763                                 call.EmitPredefined (ec, UserOperator, args);
764                         } else {
765                                 Binary.EmitOperator (ec, Left, Right);
766                         }
767
768                         //
769                         // Wrap the result when the operator return type is nullable type
770                         //
771                         if (type.IsNullableType)
772                                 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
773
774                         ec.Emit (OpCodes.Br_S, end_label);
775                         ec.MarkLabel (is_null_label);
776
777                         if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) {
778                                 ec.EmitInt (0);
779                         } else {
780                                 LiftedNull.Create (type, loc).Emit (ec);
781                         }
782
783                         ec.MarkLabel (end_label);
784                 }
785
786                 void EmitBitwiseBoolean (EmitContext ec)
787                 {
788                         Label load_left = ec.DefineLabel ();
789                         Label load_right = ec.DefineLabel ();
790                         Label end_label = ec.DefineLabel ();
791                         Label is_null_label = ec.DefineLabel ();
792
793                         bool or = Binary.Oper == Binary.Operator.BitwiseOr;
794
795                         //
796                         // Both operands are bool? types
797                         //
798                         if ((UnwrapLeft != null && !Left.IsNull) && (UnwrapRight != null && !Right.IsNull)) {
799                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
800                                         Left = Left.EmitToField (ec);
801                                         Right = Right.EmitToField (ec);
802                                 } else {
803                                         UnwrapLeft.Store (ec);
804                                         UnwrapRight.Store (ec);
805                                 }
806
807                                 Left.Emit (ec);
808                                 ec.Emit (OpCodes.Brtrue_S, load_right);
809
810                                 Right.Emit (ec);
811                                 ec.Emit (OpCodes.Brtrue_S, load_left);
812
813                                 UnwrapLeft.EmitCheck (ec);
814                                 ec.Emit (OpCodes.Brfalse_S, load_right);
815
816                                 // load left
817                                 ec.MarkLabel (load_left);
818                                 if (or)
819                                         UnwrapRight.Load (ec);
820                                 else
821                                         UnwrapLeft.Load (ec);
822
823                                 ec.Emit (OpCodes.Br_S, end_label);
824
825                                 // load right
826                                 ec.MarkLabel (load_right);
827                                 if (or)
828                                         UnwrapLeft.Load (ec);
829                                 else
830                                         UnwrapRight.Load (ec);
831
832                                 ec.MarkLabel (end_label);
833                                 return;
834                         }
835
836                         //
837                         // Faster version when one operand is bool
838                         //
839                         if (UnwrapLeft == null) {
840                                 //
841                                 // (bool, bool?)
842                                 //
843                                 // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
844                                 // in binary expression reduction
845                                 //
846                                 var c = Left as BoolConstant;
847                                 if (c != null) {
848                                         // Keep evaluation order
849                                         UnwrapRight.Store (ec);
850
851                                         ec.EmitInt (or ? 1 : 0);
852                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
853                                 } else if (Left.IsNull) {
854                                         UnwrapRight.Emit (ec);
855                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
856
857                                         UnwrapRight.Load (ec);
858                                         ec.Emit (OpCodes.Br_S, end_label);
859
860                                         ec.MarkLabel (is_null_label);
861                                         LiftedNull.Create (type, loc).Emit (ec);
862                                 } else {
863                                         Left.Emit (ec);
864                                         UnwrapRight.Store (ec);
865
866                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
867
868                                         ec.EmitInt (or ? 1 : 0);
869                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
870
871                                         ec.Emit (OpCodes.Br_S, end_label);
872
873                                         ec.MarkLabel (load_right);
874                                         UnwrapRight.Load (ec);
875                                 }
876                         } else {
877                                 //
878                                 // (bool?, bool)
879                                 //
880                                 // Keep left-right evaluation order
881                                 UnwrapLeft.Store (ec);
882
883                                 //
884                                 // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
885                                 // in binary expression reduction
886                                 //
887                                 var c = Right as BoolConstant;
888                                 if (c != null) {
889                                         ec.EmitInt (or ? 1 : 0);
890                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
891                                 } else if (Right.IsNull) {
892                                         UnwrapLeft.Emit (ec);
893                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
894
895                                         UnwrapLeft.Load (ec);
896                                         ec.Emit (OpCodes.Br_S, end_label);
897
898                                         ec.MarkLabel (is_null_label);
899                                         LiftedNull.Create (type, loc).Emit (ec);
900                                 } else if (Left.IsNull && UnwrapRight != null) {
901                                         UnwrapRight.Emit (ec);
902
903                                         ec.Emit (or ? OpCodes.Brtrue_S : OpCodes.Brfalse_S, load_right);
904
905                                         LiftedNull.Create (type, loc).Emit (ec);
906
907                                         ec.Emit (OpCodes.Br_S, end_label);
908
909                                         ec.MarkLabel (load_right);
910
911                                         UnwrapRight.Load (ec);
912                                 } else {
913                                         Right.Emit (ec);
914                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_left);
915
916                                         ec.EmitInt (or ? 1 : 0);
917                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
918
919                                         ec.Emit (OpCodes.Br_S, end_label);
920
921                                         ec.MarkLabel (load_left);
922
923                                         UnwrapLeft.Load (ec);
924                                 }
925                         }
926
927                         ec.MarkLabel (end_label);
928                 }
929
930                 //
931                 // Emits optimized equality or inequality operator when possible
932                 //
933                 void EmitEquality (EmitContext ec)
934                 {
935                         //
936                         // Either left or right is null
937                         // 
938                         if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
939                                 //
940                                 // left.HasValue == false 
941                                 //
942                                 UnwrapLeft.EmitCheck (ec);
943                                 if (Binary.Oper == Binary.Operator.Equality) {
944                                         ec.EmitInt (0);
945                                         ec.Emit (OpCodes.Ceq);
946                                 }
947                                 return;
948                         }
949
950                         if (UnwrapRight != null && Binary.Left.IsNull) {
951                                 //
952                                 // right.HasValue == false 
953                                 //
954                                 UnwrapRight.EmitCheck (ec);
955                                 if (Binary.Oper == Binary.Operator.Equality) {
956                                         ec.EmitInt (0);
957                                         ec.Emit (OpCodes.Ceq);
958                                 }
959                                 return;
960                         }
961
962                         Label dissimilar_label = ec.DefineLabel ();
963                         Label end_label = ec.DefineLabel ();
964
965                         if (UserOperator != null) {
966                                 var left = Left;
967
968                                 if (UnwrapLeft != null) {
969                                         UnwrapLeft.EmitCheck (ec);
970                                 } else {
971                                         // Keep evaluation order same
972                                         if (!(Left is VariableReference)) {
973                                                 Left.Emit (ec);
974                                                 var lt = new LocalTemporary (Left.Type);
975                                                 lt.Store (ec);
976                                                 left = lt;
977                                         }
978                                 }
979
980                                 if (UnwrapRight != null) {
981                                         UnwrapRight.EmitCheck (ec);
982
983                                         if (UnwrapLeft != null) {
984                                                 ec.Emit (OpCodes.Bne_Un, dissimilar_label);
985
986                                                 Label compare_label = ec.DefineLabel ();
987                                                 UnwrapLeft.EmitCheck (ec);
988                                                 ec.Emit (OpCodes.Brtrue, compare_label);
989
990                                                 if (Binary.Oper == Binary.Operator.Equality)
991                                                         ec.EmitInt (1);
992                                                 else
993                                                         ec.EmitInt (0);
994
995                                                 ec.Emit (OpCodes.Br, end_label);
996
997                                                 ec.MarkLabel (compare_label);
998                                         } else {
999                                                 ec.Emit (OpCodes.Brfalse, dissimilar_label);
1000                                         }
1001                                 } else {
1002                                         ec.Emit (OpCodes.Brfalse, dissimilar_label);
1003                                 }
1004
1005                                 var args = new Arguments (2);
1006                                 args.Add (new Argument (left));
1007                                 args.Add (new Argument (Right));
1008
1009                                 var call = new CallEmitter ();
1010                                 call.EmitPredefined (ec, UserOperator, args);
1011                         } else {
1012                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
1013                                         Left = Left.EmitToField (ec);
1014                                         Right = Right.EmitToField (ec);
1015                                 }
1016
1017                                 //
1018                                 // Emit underlying value comparison first.
1019                                 //
1020                                 // For this code: int? a = 1; bool b = a == 1;
1021                                 //
1022                                 // We emit something similar to this. Expressions with side effects have local
1023                                 // variable created by Unwrap expression
1024                                 //
1025                                 //      left.GetValueOrDefault ()
1026                                 //      right
1027                                 //      bne.un.s   dissimilar_label
1028                                 //  left.HasValue
1029                                 //      br.s       end_label
1030                                 // dissimilar_label:
1031                                 //      ldc.i4.0
1032                                 // end_label:
1033                                 //
1034
1035                                 Left.Emit (ec);
1036                                 Right.Emit (ec);
1037
1038                                 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
1039
1040                                 //
1041                                 // Check both left and right expressions for Unwrap call in which
1042                                 // case we need to run get_HasValue() check because the type is
1043                                 // nullable and could have null value
1044                                 //
1045                                 if (UnwrapLeft != null)
1046                                         UnwrapLeft.EmitCheck (ec);
1047
1048                                 if (UnwrapRight != null)
1049                                         UnwrapRight.EmitCheck (ec);
1050
1051                                 if (UnwrapLeft != null && UnwrapRight != null) {
1052                                         if (Binary.Oper == Binary.Operator.Inequality)
1053                                                 ec.Emit (OpCodes.Xor);
1054                                         else
1055                                                 ec.Emit (OpCodes.Ceq);
1056                                 } else {
1057                                         if (Binary.Oper == Binary.Operator.Inequality) {
1058                                                 ec.EmitInt (0);
1059                                                 ec.Emit (OpCodes.Ceq);
1060                                         }
1061                                 }
1062                         }
1063
1064                         ec.Emit (OpCodes.Br_S, end_label);
1065
1066                         ec.MarkLabel (dissimilar_label);
1067                         if (Binary.Oper == Binary.Operator.Inequality)
1068                                 ec.EmitInt (1);
1069                         else
1070                                 ec.EmitInt (0);
1071
1072                         ec.MarkLabel (end_label);
1073                 }
1074
1075                 public override void FlowAnalysis (FlowAnalysisContext fc)
1076                 {
1077                         Binary.FlowAnalysis (fc);
1078                 }
1079
1080                 public override SLE.Expression MakeExpression (BuilderContext ctx)
1081                 {
1082                         return Binary.MakeExpression (ctx, Left, Right);
1083                 }
1084         }
1085
1086         public class NullCoalescingOperator : Expression
1087         {
1088                 Expression left, right;
1089                 Unwrap unwrap;
1090                 bool user_conversion_left;
1091
1092                 public NullCoalescingOperator (Expression left, Expression right)
1093                 {
1094                         this.left = left;
1095                         this.right = right;
1096                         this.loc = left.Location;
1097                 }
1098
1099                 public Expression LeftExpression {
1100                         get {
1101                                 return left;
1102                         }
1103                 }
1104
1105                 public Expression RightExpression {
1106                         get {
1107                                 return right;
1108                         }
1109                 }
1110                 
1111                 public override Expression CreateExpressionTree (ResolveContext ec)
1112                 {
1113                         if (left is NullLiteral)
1114                                 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1115
1116                         UserCast uc = left as UserCast;
1117                         Expression conversion = null;
1118                         if (uc != null) {
1119                                 left = uc.Source;
1120
1121                                 Arguments c_args = new Arguments (2);
1122                                 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
1123                                 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
1124                                 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
1125                         }
1126
1127                         Arguments args = new Arguments (3);
1128                         args.Add (new Argument (left.CreateExpressionTree (ec)));
1129                         args.Add (new Argument (right.CreateExpressionTree (ec)));
1130                         if (conversion != null)
1131                                 args.Add (new Argument (conversion));
1132                         
1133                         return CreateExpressionFactoryCall (ec, "Coalesce", args);
1134                 }
1135
1136                 Expression ConvertExpression (ResolveContext ec)
1137                 {
1138                         // TODO: ImplicitConversionExists should take care of this
1139                         if (left.eclass == ExprClass.MethodGroup)
1140                                 return null;
1141
1142                         TypeSpec ltype = left.Type;
1143
1144                         //
1145                         // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
1146                         // the result is underlying type of left
1147                         //
1148                         if (ltype.IsNullableType) {
1149                                 unwrap = Unwrap.Create (left, false);
1150                                 if (unwrap == null)
1151                                         return null;
1152
1153                                 //
1154                                 // Reduce (left ?? null) to left
1155                                 //
1156                                 if (right.IsNull)
1157                                         return ReducedExpression.Create (left, this);
1158
1159                                 Expression conv;
1160                                 if (right.Type.IsNullableType) {
1161                                         conv = right.Type == ltype ? right : Convert.ImplicitNulableConversion (ec, right, ltype);
1162                                         if (conv != null) {
1163                                                 right = conv;
1164                                                 type = ltype;
1165                                                 return this;
1166                                         }
1167                                 } else {
1168                                         conv = Convert.ImplicitConversion (ec, right, unwrap.Type, loc);
1169                                         if (conv != null) {
1170                                                 left = unwrap;
1171                                                 ltype = left.Type;
1172
1173                                                 //
1174                                                 // If right is a dynamic expression, the result type is dynamic
1175                                                 //
1176                                                 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1177                                                         type = right.Type;
1178
1179                                                         // Need to box underlying value type
1180                                                         left = Convert.ImplicitBoxingConversion (left, ltype, type);
1181                                                         return this;
1182                                                 }
1183
1184                                                 right = conv;
1185                                                 type = ltype;
1186                                                 return this;
1187                                         }
1188                                 }
1189                         } else if (TypeSpec.IsReferenceType (ltype)) {
1190                                 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1191                                         //
1192                                         // If right is a dynamic expression, the result type is dynamic
1193                                         //
1194                                         if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1195                                                 type = right.Type;
1196                                                 return this;
1197                                         }
1198
1199                                         //
1200                                         // Reduce ("foo" ?? expr) to expression
1201                                         //
1202                                         Constant lc = left as Constant;
1203                                         if (lc != null && !lc.IsDefaultValue)
1204                                                 return ReducedExpression.Create (lc, this, false);
1205
1206                                         //
1207                                         // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1208                                         //
1209                                         if (right.IsNull || lc != null) {
1210                                                 //
1211                                                 // Special case null ?? null
1212                                                 //
1213                                                 if (right.IsNull && ltype == right.Type)
1214                                                         return null;
1215
1216                                                 return ReducedExpression.Create (lc != null ? right : left, this, false);
1217                                         }
1218
1219                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
1220                                         type = ltype;
1221                                         return this;
1222                                 }
1223                         } else {
1224                                 return null;
1225                         }
1226
1227                         TypeSpec rtype = right.Type;
1228                         if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
1229                                 return null;
1230
1231                         //
1232                         // Reduce (null ?? right) to right
1233                         //
1234                         if (left.IsNull)
1235                                 return ReducedExpression.Create (right, this, false).Resolve (ec);
1236
1237                         left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
1238                         user_conversion_left = left is UserCast;
1239                         type = rtype;
1240                         return this;
1241                 }
1242
1243                 public override bool ContainsEmitWithAwait ()
1244                 {
1245                         if (unwrap != null)
1246                                 return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1247
1248                         return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1249                 }
1250
1251                 protected override Expression DoResolve (ResolveContext ec)
1252                 {
1253                         left = left.Resolve (ec);
1254                         right = right.Resolve (ec);
1255
1256                         if (left == null || right == null)
1257                                 return null;
1258
1259                         eclass = ExprClass.Value;
1260
1261                         Expression e = ConvertExpression (ec);
1262                         if (e == null) {
1263                                 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1264                                 return null;
1265                         }
1266
1267                         return e;
1268                 }
1269
1270                 public override void Emit (EmitContext ec)
1271                 {
1272                         Label end_label = ec.DefineLabel ();
1273
1274                         if (unwrap != null) {
1275                                 Label is_null_label = ec.DefineLabel ();
1276
1277                                 unwrap.EmitCheck (ec);
1278                                 ec.Emit (OpCodes.Brfalse, is_null_label);
1279
1280                                 //
1281                                 // When both expressions are nullable the unwrap
1282                                 // is needed only for null check not for value uwrap
1283                                 //
1284                                 if (type.IsNullableType && TypeSpecComparer.IsEqual (NullableInfo.GetUnderlyingType (type), unwrap.Type))
1285                                         unwrap.Load (ec);
1286                                 else
1287                                         left.Emit (ec);
1288
1289                                 ec.Emit (OpCodes.Br, end_label);
1290
1291                                 ec.MarkLabel (is_null_label);
1292                                 right.Emit (ec);
1293
1294                                 ec.MarkLabel (end_label);
1295                                 return;
1296                         }
1297
1298                         //
1299                         // Null check is done on original expression not after expression is converted to
1300                         // result type. This is in most cases same but when user conversion is involved
1301                         // we can end up in situation when user operator does the null handling which is
1302                         // not what the operator is supposed to do.
1303                         // There is tricky case where cast of left expression is meant to be cast of
1304                         // whole source expression (null check is done on it) and cast from right-to-left
1305                         // conversion needs to do null check on unconverted source expression.
1306                         //
1307                         if (user_conversion_left) {
1308                                 var op_expr = (UserCast) left;
1309
1310                                 op_expr.Source.Emit (ec);
1311                                 LocalTemporary temp;
1312
1313                                 // TODO: More load kinds can be special cased
1314                                 if (!(op_expr.Source is VariableReference)) {
1315                                         temp = new LocalTemporary (op_expr.Source.Type);
1316                                         temp.Store (ec);
1317                                         temp.Emit (ec);
1318                                         op_expr.Source = temp;
1319                                 } else {
1320                                         temp = null;
1321                                 }
1322
1323                                 var right_label = ec.DefineLabel ();
1324                                 ec.Emit (OpCodes.Brfalse_S, right_label);
1325                                 left.Emit (ec);
1326                                 ec.Emit (OpCodes.Br, end_label);
1327                                 ec.MarkLabel (right_label);
1328
1329                                 if (temp != null)
1330                                         temp.Release (ec);
1331                         } else {
1332                                 //
1333                                 // Common case where expression is not modified before null check and
1334                                 // we generate better/smaller code
1335                                 //
1336                                 left.Emit (ec);
1337                                 ec.Emit (OpCodes.Dup);
1338
1339                                 // Only to make verifier happy
1340                                 if (left.Type.IsGenericParameter)
1341                                         ec.Emit (OpCodes.Box, left.Type);
1342
1343                                 ec.Emit (OpCodes.Brtrue, end_label);
1344
1345                                 ec.Emit (OpCodes.Pop);
1346                         }
1347
1348                         right.Emit (ec);
1349
1350                         ec.MarkLabel (end_label);
1351                 }
1352
1353                 public override void FlowAnalysis (FlowAnalysisContext fc)
1354                 {
1355                         left.FlowAnalysis (fc);
1356                         var left_da = fc.BranchDefiniteAssignment ();
1357                         right.FlowAnalysis (fc);
1358                         fc.DefiniteAssignment = left_da;
1359                 }
1360
1361                 protected override void CloneTo (CloneContext clonectx, Expression t)
1362                 {
1363                         NullCoalescingOperator target = (NullCoalescingOperator) t;
1364
1365                         target.left = left.Clone (clonectx);
1366                         target.right = right.Clone (clonectx);
1367                 }
1368                 
1369                 public override object Accept (StructuralVisitor visitor)
1370                 {
1371                         return visitor.Visit (this);
1372                 }
1373         }
1374
1375         class LiftedUnaryMutator : UnaryMutator
1376         {
1377                 public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
1378                         : base (mode, expr, loc)
1379                 {
1380                 }
1381
1382                 protected override Expression DoResolve (ResolveContext ec)
1383                 {
1384                         var orig_expr = expr;
1385
1386                         expr = Unwrap.Create (expr);
1387
1388                         var res = base.DoResolveOperation (ec);
1389
1390                         expr = orig_expr;
1391                         type = expr.Type;
1392
1393                         return res;
1394                 }
1395
1396                 protected override void EmitOperation (EmitContext ec)
1397                 {
1398                         Label is_null_label = ec.DefineLabel ();
1399                         Label end_label = ec.DefineLabel ();
1400
1401                         LocalTemporary lt = new LocalTemporary (type);
1402
1403                         // Value is on the stack
1404                         lt.Store (ec);
1405
1406                         var call = new CallEmitter ();
1407                         call.InstanceExpression = lt;
1408                         call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
1409
1410                         ec.Emit (OpCodes.Brfalse, is_null_label);
1411
1412                         call = new CallEmitter ();
1413                         call.InstanceExpression = lt;
1414                         call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
1415
1416                         lt.Release (ec);
1417
1418                         base.EmitOperation (ec);
1419
1420                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
1421                         ec.Emit (OpCodes.Br_S, end_label);
1422
1423                         ec.MarkLabel (is_null_label);
1424                         LiftedNull.Create (type, loc).Emit (ec);
1425
1426                         ec.MarkLabel (end_label);
1427                 }
1428         }
1429 }
1430