Merge pull request #1066 from esdrubal/bug19313
[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)
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 ContainsEmitWithAwait ()
439                 {
440                         return unwrap.ContainsEmitWithAwait ();
441                 }
442                 
443                 public override Expression CreateExpressionTree (ResolveContext ec)
444                 {
445                         return expr.CreateExpressionTree (ec);
446                 }                       
447
448                 protected override Expression DoResolve (ResolveContext ec)
449                 {
450                         //
451                         // It's null when lifting non-nullable type
452                         //
453                         if (unwrap == null) {
454                                 // S -> T? is wrap only
455                                 if (type.IsNullableType)
456                                         return Wrap.Create (expr, type);
457
458                                 // S -> T can be simplified
459                                 return expr;
460                         }
461
462                         // Wrap target for T?
463                         if (type.IsNullableType) {
464                                 if (!expr.Type.IsNullableType) {
465                                         expr = Wrap.Create (expr, type);
466                                         if (expr == null)
467                                                 return null;
468                                 }
469
470                                 null_value = LiftedNull.Create (type, loc);
471                         } else if (TypeSpec.IsValueType (type)) {
472                                 null_value = LiftedNull.Create (type, loc);
473                         } else {
474                                 null_value = new NullConstant (type, loc);
475                         }
476
477                         eclass = ExprClass.Value;
478                         return this;
479                 }
480
481                 public override void Emit (EmitContext ec)
482                 {
483                         Label is_null_label = ec.DefineLabel ();
484                         Label end_label = ec.DefineLabel ();
485
486                         unwrap.EmitCheck (ec);
487                         ec.Emit (OpCodes.Brfalse, is_null_label);
488
489                         expr.Emit (ec);
490
491                         ec.Emit (OpCodes.Br, end_label);
492                         ec.MarkLabel (is_null_label);
493
494                         null_value.Emit (ec);
495
496                         ec.MarkLabel (end_label);
497                 }
498
499                 public override void FlowAnalysis (FlowAnalysisContext fc)
500                 {
501                         expr.FlowAnalysis (fc);
502                 }
503
504                 public void AddressOf (EmitContext ec, AddressOp mode)
505                 {
506                         unwrap.AddressOf (ec, mode);
507                 }
508         }
509
510         public class LiftedUnaryOperator : Unary, IMemoryLocation
511         {
512                 Unwrap unwrap;
513                 Expression user_operator;
514
515                 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
516                         : base (op, expr, loc)
517                 {
518                 }
519
520                 public void AddressOf (EmitContext ec, AddressOp mode)
521                 {
522                         unwrap.AddressOf (ec, mode);
523                 }
524
525                 public override Expression CreateExpressionTree (ResolveContext ec)
526                 {
527                         if (user_operator != null)
528                                 return user_operator.CreateExpressionTree (ec);
529
530                         if (Oper == Operator.UnaryPlus)
531                                 return Expr.CreateExpressionTree (ec);
532
533                         return base.CreateExpressionTree (ec);
534                 }
535
536                 protected override Expression DoResolve (ResolveContext ec)
537                 {
538                         unwrap = Unwrap.Create (Expr, false);
539                         if (unwrap == null)
540                                 return null;
541
542                         Expression res = base.ResolveOperator (ec, unwrap);
543                         if (res == null) {
544                                 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
545                                 return null;
546                         }
547
548                         if (res != this) {
549                                 if (user_operator == null)
550                                         return res;
551                         } else {
552                                 res = Expr = LiftExpression (ec, Expr);
553                         }
554
555                         if (res == null)
556                                 return null;
557
558                         eclass = ExprClass.Value;
559                         type = res.Type;
560                         return this;
561                 }
562
563                 public override void Emit (EmitContext ec)
564                 {
565                         Label is_null_label = ec.DefineLabel ();
566                         Label end_label = ec.DefineLabel ();
567
568                         unwrap.EmitCheck (ec);
569                         ec.Emit (OpCodes.Brfalse, is_null_label);
570
571                         if (user_operator != null) {
572                                 user_operator.Emit (ec);
573                         } else {
574                                 EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
575                         }
576
577                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
578                         ec.Emit (OpCodes.Br_S, end_label);
579
580                         ec.MarkLabel (is_null_label);
581                         LiftedNull.Create (type, loc).Emit (ec);
582
583                         ec.MarkLabel (end_label);
584                 }
585
586                 static Expression LiftExpression (ResolveContext ec, Expression expr)
587                 {
588                         var lifted_type = new NullableType (expr.Type, expr.Location);
589                         if (lifted_type.ResolveAsType (ec) == null)
590                                 return null;
591
592                         expr.Type = lifted_type.Type;
593                         return expr;
594                 }
595
596                 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
597                 {
598                         expr = base.ResolveEnumOperator (ec, expr, predefined);
599                         if (expr == null)
600                                 return null;
601
602                         Expr = LiftExpression (ec, Expr);
603                         return LiftExpression (ec, expr);
604                 }
605
606                 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
607                 {
608                         expr = base.ResolveUserOperator (ec, expr);
609                         if (expr == null)
610                                 return null;
611
612                         //
613                         // When a user operator is of non-nullable type
614                         //
615                         if (Expr is Unwrap) {
616                                 user_operator = LiftExpression (ec, expr);
617                                 return user_operator;
618                         }
619
620                         return expr;
621                 }
622         }
623
624         //
625         // Lifted version of binary operators
626         //
627         class LiftedBinaryOperator : Expression
628         {
629                 public LiftedBinaryOperator (Binary b)
630                 {
631                         this.Binary = b;
632                         this.loc = b.Location;
633                 }
634
635                 public Binary Binary { get; private set; }
636
637                 public Expression Left { get; set; }
638
639                 public Expression Right { get; set; }
640
641                 public Unwrap UnwrapLeft { get; set; }
642
643                 public Unwrap UnwrapRight { get; set; }
644
645                 public MethodSpec UserOperator { get; set; }
646
647                 bool IsBitwiseBoolean {
648                         get {
649                                 return (Binary.Oper == Binary.Operator.BitwiseAnd || Binary.Oper == Binary.Operator.BitwiseOr) &&
650                                 ((UnwrapLeft != null && UnwrapLeft.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) ||
651                                  (UnwrapRight != null && UnwrapRight.Type.BuiltinType == BuiltinTypeSpec.Type.Bool));
652                         }
653                 }
654
655                 public override bool ContainsEmitWithAwait ()
656                 {
657                         return Left.ContainsEmitWithAwait () || Right.ContainsEmitWithAwait ();
658                 }
659
660                 public override Expression CreateExpressionTree (ResolveContext rc)
661                 {
662                         if (UserOperator != null) {
663                                 Arguments args = new Arguments (2);
664                                 args.Add (new Argument (Binary.Left));
665                                 args.Add (new Argument (Binary.Right));
666
667                                 var method = new UserOperatorCall (UserOperator, args, Binary.CreateExpressionTree, loc);
668                                 return method.CreateExpressionTree (rc);
669                         }
670
671                         return Binary.CreateExpressionTree (rc);
672                 }
673
674                 protected override Expression DoResolve (ResolveContext rc)
675                 {
676                         if (rc.IsRuntimeBinder) {
677                                 if (UnwrapLeft == null && !Left.Type.IsNullableType)
678                                         Left = LiftOperand (rc, Left);
679
680                                 if (UnwrapRight == null && !Right.Type.IsNullableType)
681                                         Right = LiftOperand (rc, Right);
682                         } else {
683                                 if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) {
684                                         Left = Unwrap.CreateUnwrapped (Left);
685                                         UnwrapLeft = Left as Unwrap;
686                                 }
687
688                                 if (UnwrapRight == null && Right != null && Right.Type.IsNullableType) {
689                                         Right = Unwrap.CreateUnwrapped (Right);
690                                         UnwrapRight = Right as Unwrap;
691                                 }
692                         }
693
694                         type = Binary.Type;
695                         eclass = Binary.eclass; 
696
697                         return this;
698                 }
699
700                 Expression LiftOperand (ResolveContext rc, Expression expr)
701                 {
702                         TypeSpec type;
703                         if (expr.IsNull) {
704                                 type = Left.IsNull ? Right.Type : Left.Type;
705                         } else {
706                                 type = expr.Type;
707                         }
708
709                         if (!type.IsNullableType)
710                                 type = NullableInfo.MakeType (rc.Module, type);
711
712                         return Wrap.Create (expr, type);
713                 }
714
715                 public override void Emit (EmitContext ec)
716                 {
717                         if (IsBitwiseBoolean && UserOperator == null) {
718                                 EmitBitwiseBoolean (ec);
719                                 return;
720                         }
721
722                         if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) {
723                                 EmitEquality (ec);
724                                 return;
725                         }
726
727                         Label is_null_label = ec.DefineLabel ();
728                         Label end_label = ec.DefineLabel ();
729
730                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) {
731                                 Left = Left.EmitToField (ec);
732                                 Right = Right.EmitToField (ec);
733                         }
734
735                         if (UnwrapLeft != null) {
736                                 UnwrapLeft.EmitCheck (ec);
737                         }
738
739                         //
740                         // Don't emit HasValue check when left and right expressions are same
741                         //
742                         if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) {
743                                 UnwrapRight.EmitCheck (ec);
744                                 if (UnwrapLeft != null) {
745                                         ec.Emit (OpCodes.And);
746                                 }
747                         }
748
749                         ec.Emit (OpCodes.Brfalse, is_null_label);
750
751                         if (UserOperator != null) {
752                                 var args = new Arguments (2);
753                                 args.Add (new Argument (Left));
754                                 args.Add (new Argument (Right));
755
756                                 var call = new CallEmitter ();
757                                 call.EmitPredefined (ec, UserOperator, args);
758                         } else {
759                                 Binary.EmitOperator (ec, Left, Right);
760                         }
761
762                         //
763                         // Wrap the result when the operator return type is nullable type
764                         //
765                         if (type.IsNullableType)
766                                 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
767
768                         ec.Emit (OpCodes.Br_S, end_label);
769                         ec.MarkLabel (is_null_label);
770
771                         if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) {
772                                 ec.EmitInt (0);
773                         } else {
774                                 LiftedNull.Create (type, loc).Emit (ec);
775                         }
776
777                         ec.MarkLabel (end_label);
778                 }
779
780                 void EmitBitwiseBoolean (EmitContext ec)
781                 {
782                         Label load_left = ec.DefineLabel ();
783                         Label load_right = ec.DefineLabel ();
784                         Label end_label = ec.DefineLabel ();
785                         Label is_null_label = ec.DefineLabel ();
786
787                         bool or = Binary.Oper == Binary.Operator.BitwiseOr;
788
789                         //
790                         // Both operands are bool? types
791                         //
792                         if (UnwrapLeft != null && UnwrapRight != null) {
793                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
794                                         Left = Left.EmitToField (ec);
795                                         Right = Right.EmitToField (ec);
796                                 } else {
797                                         UnwrapLeft.Store (ec);
798                                         UnwrapRight.Store (ec);
799                                 }
800
801                                 Left.Emit (ec);
802                                 ec.Emit (OpCodes.Brtrue_S, load_right);
803
804                                 Right.Emit (ec);
805                                 ec.Emit (OpCodes.Brtrue_S, load_left);
806
807                                 UnwrapLeft.EmitCheck (ec);
808                                 ec.Emit (OpCodes.Brfalse_S, load_right);
809
810                                 // load left
811                                 ec.MarkLabel (load_left);
812                                 if (or)
813                                         UnwrapRight.Load (ec);
814                                 else
815                                         UnwrapLeft.Load (ec);
816
817                                 ec.Emit (OpCodes.Br_S, end_label);
818
819                                 // load right
820                                 ec.MarkLabel (load_right);
821                                 if (or)
822                                         UnwrapLeft.Load (ec);
823                                 else
824                                         UnwrapRight.Load (ec);
825
826                                 ec.MarkLabel (end_label);
827                                 return;
828                         }
829
830                         //
831                         // Faster version when one operand is bool
832                         //
833                         if (UnwrapLeft == null) {
834                                 //
835                                 // (bool, bool?)
836                                 //
837                                 // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
838                                 // in binary expression reduction
839                                 //
840                                 var c = Left as BoolConstant;
841                                 if (c != null) {
842                                         // Keep evaluation order
843                                         UnwrapRight.Store (ec);
844
845                                         ec.EmitInt (or ? 1 : 0);
846                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
847                                 } else if (Left.IsNull) {
848                                         UnwrapRight.Emit (ec);
849                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
850
851                                         UnwrapRight.Load (ec);
852                                         ec.Emit (OpCodes.Br_S, end_label);
853
854                                         ec.MarkLabel (is_null_label);
855                                         LiftedNull.Create (type, loc).Emit (ec);
856                                 } else {
857                                         Left.Emit (ec);
858                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
859
860                                         ec.EmitInt (or ? 1 : 0);
861                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
862
863                                         ec.Emit (OpCodes.Br_S, end_label);
864
865                                         ec.MarkLabel (load_right);
866                                         UnwrapRight.Original.Emit (ec);
867                                 }
868                         } else {
869                                 //
870                                 // (bool?, bool)
871                                 //
872                                 // Keep left-right evaluation order
873                                 UnwrapLeft.Store (ec);
874
875                                 //
876                                 // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
877                                 // in binary expression reduction
878                                 //
879                                 var c = Right as BoolConstant;
880                                 if (c != null) {
881                                         ec.EmitInt (or ? 1 : 0);
882                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
883                                 } else if (Right.IsNull) {
884                                         UnwrapLeft.Emit (ec);
885                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
886
887                                         UnwrapLeft.Load (ec);
888                                         ec.Emit (OpCodes.Br_S, end_label);
889
890                                         ec.MarkLabel (is_null_label);
891                                         LiftedNull.Create (type, loc).Emit (ec);
892                                 } else {
893                                         Right.Emit (ec);
894                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
895
896                                         ec.EmitInt (or ? 1 : 0);
897                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
898
899                                         ec.Emit (OpCodes.Br_S, end_label);
900
901                                         ec.MarkLabel (load_right);
902
903                                         UnwrapLeft.Load (ec);
904                                 }
905                         }
906
907                         ec.MarkLabel (end_label);
908                 }
909
910                 //
911                 // Emits optimized equality or inequality operator when possible
912                 //
913                 void EmitEquality (EmitContext ec)
914                 {
915                         //
916                         // Either left or right is null
917                         // 
918                         if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
919                                 //
920                                 // left.HasValue == false 
921                                 //
922                                 UnwrapLeft.EmitCheck (ec);
923                                 if (Binary.Oper == Binary.Operator.Equality) {
924                                         ec.EmitInt (0);
925                                         ec.Emit (OpCodes.Ceq);
926                                 }
927                                 return;
928                         }
929
930                         if (UnwrapRight != null && Binary.Left.IsNull) {
931                                 //
932                                 // right.HasValue == false 
933                                 //
934                                 UnwrapRight.EmitCheck (ec);
935                                 if (Binary.Oper == Binary.Operator.Equality) {
936                                         ec.EmitInt (0);
937                                         ec.Emit (OpCodes.Ceq);
938                                 }
939                                 return;
940                         }
941
942                         Label dissimilar_label = ec.DefineLabel ();
943                         Label end_label = ec.DefineLabel ();
944
945                         if (UserOperator != null) {
946                                 var left = Left;
947
948                                 if (UnwrapLeft != null) {
949                                         UnwrapLeft.EmitCheck (ec);
950                                 } else {
951                                         // Keep evaluation order same
952                                         if (!(Left is VariableReference)) {
953                                                 Left.Emit (ec);
954                                                 var lt = new LocalTemporary (Left.Type);
955                                                 lt.Store (ec);
956                                                 left = lt;
957                                         }
958                                 }
959
960                                 if (UnwrapRight != null) {
961                                         UnwrapRight.EmitCheck (ec);
962
963                                         if (UnwrapLeft != null) {
964                                                 ec.Emit (OpCodes.Bne_Un, dissimilar_label);
965
966                                                 Label compare_label = ec.DefineLabel ();
967                                                 UnwrapLeft.EmitCheck (ec);
968                                                 ec.Emit (OpCodes.Brtrue, compare_label);
969
970                                                 if (Binary.Oper == Binary.Operator.Equality)
971                                                         ec.EmitInt (1);
972                                                 else
973                                                         ec.EmitInt (0);
974
975                                                 ec.Emit (OpCodes.Br, end_label);
976
977                                                 ec.MarkLabel (compare_label);
978                                         } else {
979                                                 ec.Emit (OpCodes.Brfalse, dissimilar_label);
980                                         }
981                                 } else {
982                                         ec.Emit (OpCodes.Brfalse, dissimilar_label);
983                                 }
984
985                                 var args = new Arguments (2);
986                                 args.Add (new Argument (left));
987                                 args.Add (new Argument (Right));
988
989                                 var call = new CallEmitter ();
990                                 call.EmitPredefined (ec, UserOperator, args);
991                         } else {
992                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
993                                         Left = Left.EmitToField (ec);
994                                         Right = Right.EmitToField (ec);
995                                 }
996
997                                 //
998                                 // Emit underlying value comparison first.
999                                 //
1000                                 // For this code: int? a = 1; bool b = a == 1;
1001                                 //
1002                                 // We emit something similar to this. Expressions with side effects have local
1003                                 // variable created by Unwrap expression
1004                                 //
1005                                 //      left.GetValueOrDefault ()
1006                                 //      right
1007                                 //      bne.un.s   dissimilar_label
1008                                 //  left.HasValue
1009                                 //      br.s       end_label
1010                                 // dissimilar_label:
1011                                 //      ldc.i4.0
1012                                 // end_label:
1013                                 //
1014
1015                                 Left.Emit (ec);
1016                                 Right.Emit (ec);
1017
1018                                 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
1019
1020                                 //
1021                                 // Check both left and right expressions for Unwrap call in which
1022                                 // case we need to run get_HasValue() check because the type is
1023                                 // nullable and could have null value
1024                                 //
1025                                 if (UnwrapLeft != null)
1026                                         UnwrapLeft.EmitCheck (ec);
1027
1028                                 if (UnwrapRight != null)
1029                                         UnwrapRight.EmitCheck (ec);
1030
1031                                 if (UnwrapLeft != null && UnwrapRight != null) {
1032                                         if (Binary.Oper == Binary.Operator.Inequality)
1033                                                 ec.Emit (OpCodes.Xor);
1034                                         else
1035                                                 ec.Emit (OpCodes.Ceq);
1036                                 } else {
1037                                         if (Binary.Oper == Binary.Operator.Inequality) {
1038                                                 ec.EmitInt (0);
1039                                                 ec.Emit (OpCodes.Ceq);
1040                                         }
1041                                 }
1042                         }
1043
1044                         ec.Emit (OpCodes.Br_S, end_label);
1045
1046                         ec.MarkLabel (dissimilar_label);
1047                         if (Binary.Oper == Binary.Operator.Inequality)
1048                                 ec.EmitInt (1);
1049                         else
1050                                 ec.EmitInt (0);
1051
1052                         ec.MarkLabel (end_label);
1053                 }
1054
1055                 public override void FlowAnalysis (FlowAnalysisContext fc)
1056                 {
1057                         Binary.FlowAnalysis (fc);
1058                 }
1059
1060                 public override SLE.Expression MakeExpression (BuilderContext ctx)
1061                 {
1062                         return Binary.MakeExpression (ctx, Left, Right);
1063                 }
1064         }
1065
1066         public class NullCoalescingOperator : Expression
1067         {
1068                 Expression left, right;
1069                 Unwrap unwrap;
1070
1071                 public NullCoalescingOperator (Expression left, Expression right)
1072                 {
1073                         this.left = left;
1074                         this.right = right;
1075                         this.loc = left.Location;
1076                 }
1077
1078                 public Expression LeftExpression {
1079                         get {
1080                                 return left;
1081                         }
1082                 }
1083
1084                 public Expression RightExpression {
1085                         get {
1086                                 return right;
1087                         }
1088                 }
1089                 
1090                 public override Expression CreateExpressionTree (ResolveContext ec)
1091                 {
1092                         if (left is NullLiteral)
1093                                 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1094
1095                         UserCast uc = left as UserCast;
1096                         Expression conversion = null;
1097                         if (uc != null) {
1098                                 left = uc.Source;
1099
1100                                 Arguments c_args = new Arguments (2);
1101                                 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
1102                                 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
1103                                 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
1104                         }
1105
1106                         Arguments args = new Arguments (3);
1107                         args.Add (new Argument (left.CreateExpressionTree (ec)));
1108                         args.Add (new Argument (right.CreateExpressionTree (ec)));
1109                         if (conversion != null)
1110                                 args.Add (new Argument (conversion));
1111                         
1112                         return CreateExpressionFactoryCall (ec, "Coalesce", args);
1113                 }
1114
1115                 Expression ConvertExpression (ResolveContext ec)
1116                 {
1117                         // TODO: ImplicitConversionExists should take care of this
1118                         if (left.eclass == ExprClass.MethodGroup)
1119                                 return null;
1120
1121                         TypeSpec ltype = left.Type;
1122
1123                         //
1124                         // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
1125                         // the result is underlying type of left
1126                         //
1127                         if (ltype.IsNullableType) {
1128                                 unwrap = Unwrap.Create (left, false);
1129                                 if (unwrap == null)
1130                                         return null;
1131
1132                                 //
1133                                 // Reduce (left ?? null) to left
1134                                 //
1135                                 if (right.IsNull)
1136                                         return ReducedExpression.Create (left, this);
1137
1138                                 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
1139                                         left = unwrap;
1140                                         ltype = left.Type;
1141
1142                                         //
1143                                         // If right is a dynamic expression, the result type is dynamic
1144                                         //
1145                                         if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1146                                                 type = right.Type;
1147
1148                                                 // Need to box underlying value type
1149                                                 left = Convert.ImplicitBoxingConversion (left, ltype, type);
1150                                                 return this;
1151                                         }
1152
1153                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
1154                                         type = ltype;
1155                                         return this;
1156                                 }
1157                         } else if (TypeSpec.IsReferenceType (ltype)) {
1158                                 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1159                                         //
1160                                         // If right is a dynamic expression, the result type is dynamic
1161                                         //
1162                                         if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1163                                                 type = right.Type;
1164                                                 return this;
1165                                         }
1166
1167                                         //
1168                                         // Reduce ("foo" ?? expr) to expression
1169                                         //
1170                                         Constant lc = left as Constant;
1171                                         if (lc != null && !lc.IsDefaultValue)
1172                                                 return ReducedExpression.Create (lc, this, false);
1173
1174                                         //
1175                                         // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1176                                         //
1177                                         if (right.IsNull || lc != null) {
1178                                                 //
1179                                                 // Special case null ?? null
1180                                                 //
1181                                                 if (right.IsNull && ltype == right.Type)
1182                                                         return null;
1183
1184                                                 return ReducedExpression.Create (lc != null ? right : left, this, false);
1185                                         }
1186
1187                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
1188                                         type = ltype;
1189                                         return this;
1190                                 }
1191                         } else {
1192                                 return null;
1193                         }
1194
1195                         TypeSpec rtype = right.Type;
1196                         if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
1197                                 return null;
1198
1199                         //
1200                         // Reduce (null ?? right) to right
1201                         //
1202                         if (left.IsNull)
1203                                 return ReducedExpression.Create (right, this, false).Resolve (ec);
1204
1205                         left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
1206
1207                         if (TypeSpec.IsValueType (left.Type) && !left.Type.IsNullableType) {
1208                                 Warning_UnreachableExpression (ec, right.Location);
1209                                 return ReducedExpression.Create (left, this, false).Resolve (ec);
1210                         }
1211
1212                         type = rtype;
1213                         return this;
1214                 }
1215
1216                 public override bool ContainsEmitWithAwait ()
1217                 {
1218                         if (unwrap != null)
1219                                 return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1220
1221                         return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1222                 }
1223
1224                 protected override Expression DoResolve (ResolveContext ec)
1225                 {
1226                         left = left.Resolve (ec);
1227                         right = right.Resolve (ec);
1228
1229                         if (left == null || right == null)
1230                                 return null;
1231
1232                         eclass = ExprClass.Value;
1233
1234                         Expression e = ConvertExpression (ec);
1235                         if (e == null) {
1236                                 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1237                                 return null;
1238                         }
1239
1240                         return e;
1241                 }
1242
1243                 public override void Emit (EmitContext ec)
1244                 {
1245                         Label end_label = ec.DefineLabel ();
1246
1247                         if (unwrap != null) {
1248                                 Label is_null_label = ec.DefineLabel ();
1249
1250                                 unwrap.EmitCheck (ec);
1251                                 ec.Emit (OpCodes.Brfalse, is_null_label);
1252
1253                                 //
1254                                 // When both expressions are nullable the unwrap
1255                                 // is needed only for null check not for value uwrap
1256                                 //
1257                                 if (type.IsNullableType && TypeSpecComparer.IsEqual (NullableInfo.GetUnderlyingType (type), unwrap.Type))
1258                                         unwrap.Load (ec);
1259                                 else
1260                                         left.Emit (ec);
1261
1262                                 ec.Emit (OpCodes.Br, end_label);
1263
1264                                 ec.MarkLabel (is_null_label);
1265                                 right.Emit (ec);
1266
1267                                 ec.MarkLabel (end_label);
1268                                 return;
1269                         }
1270
1271                         left.Emit (ec);
1272                         ec.Emit (OpCodes.Dup);
1273
1274                         // Only to make verifier happy
1275                         if (left.Type.IsGenericParameter)
1276                                 ec.Emit (OpCodes.Box, left.Type);
1277
1278                         ec.Emit (OpCodes.Brtrue, end_label);
1279
1280                         ec.Emit (OpCodes.Pop);
1281                         right.Emit (ec);
1282
1283                         ec.MarkLabel (end_label);
1284                 }
1285
1286                 public override void FlowAnalysis (FlowAnalysisContext fc)
1287                 {
1288                         left.FlowAnalysis (fc);
1289                         var left_da = fc.BranchDefiniteAssignment ();
1290                         right.FlowAnalysis (fc);
1291                         fc.DefiniteAssignment = left_da;
1292                 }
1293
1294                 protected override void CloneTo (CloneContext clonectx, Expression t)
1295                 {
1296                         NullCoalescingOperator target = (NullCoalescingOperator) t;
1297
1298                         target.left = left.Clone (clonectx);
1299                         target.right = right.Clone (clonectx);
1300                 }
1301                 
1302                 public override object Accept (StructuralVisitor visitor)
1303                 {
1304                         return visitor.Visit (this);
1305                 }
1306         }
1307
1308         class LiftedUnaryMutator : UnaryMutator
1309         {
1310                 public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
1311                         : base (mode, expr, loc)
1312                 {
1313                 }
1314
1315                 protected override Expression DoResolve (ResolveContext ec)
1316                 {
1317                         var orig_expr = expr;
1318
1319                         expr = Unwrap.Create (expr);
1320
1321                         var res = base.DoResolveOperation (ec);
1322
1323                         expr = orig_expr;
1324                         type = expr.Type;
1325
1326                         return res;
1327                 }
1328
1329                 protected override void EmitOperation (EmitContext ec)
1330                 {
1331                         Label is_null_label = ec.DefineLabel ();
1332                         Label end_label = ec.DefineLabel ();
1333
1334                         LocalTemporary lt = new LocalTemporary (type);
1335
1336                         // Value is on the stack
1337                         lt.Store (ec);
1338
1339                         var call = new CallEmitter ();
1340                         call.InstanceExpression = lt;
1341                         call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
1342
1343                         ec.Emit (OpCodes.Brfalse, is_null_label);
1344
1345                         call = new CallEmitter ();
1346                         call.InstanceExpression = lt;
1347                         call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
1348
1349                         lt.Release (ec);
1350
1351                         base.EmitOperation (ec);
1352
1353                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
1354                         ec.Emit (OpCodes.Br_S, end_label);
1355
1356                         ec.MarkLabel (is_null_label);
1357                         LiftedNull.Create (type, loc).Emit (ec);
1358
1359                         ec.MarkLabel (end_label);
1360                 }
1361         }
1362 }
1363