Merge pull request #1072 from esdrubal/bug19862
[mono.git] / mcs / mcs / expression.cs
1 //
2 // expression.cs: Expression representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
10 // Copyright 2011 Xamarin Inc.
11 //
12
13 using System;
14 using System.Collections.Generic;
15 using System.Linq;
16 using SLE = System.Linq.Expressions;
17
18 #if STATIC
19 using MetaType = IKVM.Reflection.Type;
20 using IKVM.Reflection;
21 using IKVM.Reflection.Emit;
22 #else
23 using MetaType = System.Type;
24 using System.Reflection;
25 using System.Reflection.Emit;
26 #endif
27
28 namespace Mono.CSharp
29 {
30         //
31         // This is an user operator expression, automatically created during
32         // resolve phase
33         //
34         public class UserOperatorCall : Expression {
35                 protected readonly Arguments arguments;
36                 protected readonly MethodSpec oper;
37                 readonly Func<ResolveContext, Expression, Expression> expr_tree;
38
39                 public UserOperatorCall (MethodSpec oper, Arguments args, Func<ResolveContext, Expression, Expression> expr_tree, Location loc)
40                 {
41                         this.oper = oper;
42                         this.arguments = args;
43                         this.expr_tree = expr_tree;
44
45                         type = oper.ReturnType;
46                         eclass = ExprClass.Value;
47                         this.loc = loc;
48                 }
49
50                 public override bool ContainsEmitWithAwait ()
51                 {
52                         return arguments.ContainsEmitWithAwait ();
53                 }
54
55                 public override Expression CreateExpressionTree (ResolveContext ec)
56                 {
57                         if (expr_tree != null)
58                                 return expr_tree (ec, new TypeOfMethod (oper, loc));
59
60                         Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
61                                 new NullLiteral (loc),
62                                 new TypeOfMethod (oper, loc));
63
64                         return CreateExpressionFactoryCall (ec, "Call", args);
65                 }
66
67                 protected override void CloneTo (CloneContext context, Expression target)
68                 {
69                         // Nothing to clone
70                 }
71                 
72                 protected override Expression DoResolve (ResolveContext ec)
73                 {
74                         //
75                         // We are born fully resolved
76                         //
77                         return this;
78                 }
79
80                 public override void Emit (EmitContext ec)
81                 {
82                         var call = new CallEmitter ();
83                         call.EmitPredefined (ec, oper, arguments, loc);
84                 }
85
86                 public override void FlowAnalysis (FlowAnalysisContext fc)
87                 {
88                         arguments.FlowAnalysis (fc);
89                 }
90
91                 public override SLE.Expression MakeExpression (BuilderContext ctx)
92                 {
93 #if STATIC
94                         return base.MakeExpression (ctx);
95 #else
96                         return SLE.Expression.Call ((MethodInfo) oper.GetMetaInfo (), Arguments.MakeExpression (arguments, ctx));
97 #endif
98                 }
99         }
100
101         public class ParenthesizedExpression : ShimExpression
102         {
103                 public ParenthesizedExpression (Expression expr, Location loc)
104                         : base (expr)
105                 {
106                         this.loc = loc;
107                 }
108
109                 protected override Expression DoResolve (ResolveContext ec)
110                 {
111                         var res = expr.Resolve (ec);
112                         var constant = res as Constant;
113                         if (constant != null && constant.IsLiteral)
114                                 return Constant.CreateConstantFromValue (res.Type, constant.GetValue (), expr.Location);
115
116                         return res;
117                 }
118
119                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
120                 {
121                         return expr.DoResolveLValue (ec, right_side);
122                 }
123                 
124                 public override object Accept (StructuralVisitor visitor)
125                 {
126                         return visitor.Visit (this);
127                 }
128         }
129         
130         //
131         //   Unary implements unary expressions.
132         //
133         public class Unary : Expression
134         {
135                 public enum Operator : byte {
136                         UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
137                         AddressOf,  TOP
138                 }
139
140                 public readonly Operator Oper;
141                 public Expression Expr;
142                 Expression enum_conversion;
143
144                 public Unary (Operator op, Expression expr, Location loc)
145                 {
146                         Oper = op;
147                         Expr = expr;
148                         this.loc = loc;
149                 }
150
151                 // <summary>
152                 //   This routine will attempt to simplify the unary expression when the
153                 //   argument is a constant.
154                 // </summary>
155                 Constant TryReduceConstant (ResolveContext ec, Constant constant)
156                 {
157                         var e = constant;
158
159                         while (e is EmptyConstantCast)
160                                 e = ((EmptyConstantCast) e).child;
161                         
162                         if (e is SideEffectConstant) {
163                                 Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
164                                 return r == null ? null : new SideEffectConstant (r, e, r.Location);
165                         }
166
167                         TypeSpec expr_type = e.Type;
168                         
169                         switch (Oper){
170                         case Operator.UnaryPlus:
171                                 // Unary numeric promotions
172                                 switch (expr_type.BuiltinType) {
173                                 case BuiltinTypeSpec.Type.Byte:
174                                         return new IntConstant (ec.BuiltinTypes, ((ByteConstant) e).Value, e.Location);
175                                 case BuiltinTypeSpec.Type.SByte:
176                                         return new IntConstant (ec.BuiltinTypes, ((SByteConstant) e).Value, e.Location);
177                                 case BuiltinTypeSpec.Type.Short:
178                                         return new IntConstant (ec.BuiltinTypes, ((ShortConstant) e).Value, e.Location);
179                                 case BuiltinTypeSpec.Type.UShort:
180                                         return new IntConstant (ec.BuiltinTypes, ((UShortConstant) e).Value, e.Location);
181                                 case BuiltinTypeSpec.Type.Char:
182                                         return new IntConstant (ec.BuiltinTypes, ((CharConstant) e).Value, e.Location);
183                                 
184                                 // Predefined operators
185                                 case BuiltinTypeSpec.Type.Int:
186                                 case BuiltinTypeSpec.Type.UInt:
187                                 case BuiltinTypeSpec.Type.Long:
188                                 case BuiltinTypeSpec.Type.ULong:
189                                 case BuiltinTypeSpec.Type.Float:
190                                 case BuiltinTypeSpec.Type.Double:
191                                 case BuiltinTypeSpec.Type.Decimal:
192                                         return e;
193                                 }
194                                 
195                                 return null;
196                                 
197                         case Operator.UnaryNegation:
198                                 // Unary numeric promotions
199                                 switch (expr_type.BuiltinType) {
200                                 case BuiltinTypeSpec.Type.Byte:
201                                         return new IntConstant (ec.BuiltinTypes, -((ByteConstant) e).Value, e.Location);
202                                 case BuiltinTypeSpec.Type.SByte:
203                                         return new IntConstant (ec.BuiltinTypes, -((SByteConstant) e).Value, e.Location);
204                                 case BuiltinTypeSpec.Type.Short:
205                                         return new IntConstant (ec.BuiltinTypes, -((ShortConstant) e).Value, e.Location);
206                                 case BuiltinTypeSpec.Type.UShort:
207                                         return new IntConstant (ec.BuiltinTypes, -((UShortConstant) e).Value, e.Location);
208                                 case BuiltinTypeSpec.Type.Char:
209                                         return new IntConstant (ec.BuiltinTypes, -((CharConstant) e).Value, e.Location);
210
211                                 // Predefined operators
212                                 case BuiltinTypeSpec.Type.Int:
213                                         int ivalue = ((IntConstant) e).Value;
214                                         if (ivalue == int.MinValue) {
215                                                 if (ec.ConstantCheckState) {
216                                                         ConstantFold.Error_CompileTimeOverflow (ec, loc);
217                                                         return null;
218                                                 }
219                                                 return e;
220                                         }
221                                         return new IntConstant (ec.BuiltinTypes, -ivalue, e.Location);
222
223                                 case BuiltinTypeSpec.Type.Long:
224                                         long lvalue = ((LongConstant) e).Value;
225                                         if (lvalue == long.MinValue) {
226                                                 if (ec.ConstantCheckState) {
227                                                         ConstantFold.Error_CompileTimeOverflow (ec, loc);
228                                                         return null;
229                                                 }
230                                                 return e;
231                                         }
232                                         return new LongConstant (ec.BuiltinTypes, -lvalue, e.Location);
233
234                                 case BuiltinTypeSpec.Type.UInt:
235                                         UIntLiteral uil = constant as UIntLiteral;
236                                         if (uil != null) {
237                                                 if (uil.Value == int.MaxValue + (uint) 1)
238                                                         return new IntLiteral (ec.BuiltinTypes, int.MinValue, e.Location);
239                                                 return new LongLiteral (ec.BuiltinTypes, -uil.Value, e.Location);
240                                         }
241                                         return new LongConstant (ec.BuiltinTypes, -((UIntConstant) e).Value, e.Location);
242
243
244                                 case BuiltinTypeSpec.Type.ULong:
245                                         ULongLiteral ull = constant as ULongLiteral;
246                                         if (ull != null && ull.Value == 9223372036854775808)
247                                                 return new LongLiteral (ec.BuiltinTypes, long.MinValue, e.Location);
248                                         return null;
249
250                                 case BuiltinTypeSpec.Type.Float:
251                                         FloatLiteral fl = constant as FloatLiteral;
252                                         // For better error reporting
253                                         if (fl != null)
254                                                 return new FloatLiteral (ec.BuiltinTypes, -fl.Value, e.Location);
255
256                                         return new FloatConstant (ec.BuiltinTypes, -((FloatConstant) e).Value, e.Location);
257
258                                 case BuiltinTypeSpec.Type.Double:
259                                         DoubleLiteral dl = constant as DoubleLiteral;
260                                         // For better error reporting
261                                         if (dl != null)
262                                                 return new DoubleLiteral (ec.BuiltinTypes, -dl.Value, e.Location);
263
264                                         return new DoubleConstant (ec.BuiltinTypes, -((DoubleConstant) e).Value, e.Location);
265
266                                 case BuiltinTypeSpec.Type.Decimal:
267                                         return new DecimalConstant (ec.BuiltinTypes, -((DecimalConstant) e).Value, e.Location);
268                                 }
269
270                                 return null;
271                                 
272                         case Operator.LogicalNot:
273                                 if (expr_type.BuiltinType != BuiltinTypeSpec.Type.Bool)
274                                         return null;
275                                 
276                                 bool b = (bool)e.GetValue ();
277                                 return new BoolConstant (ec.BuiltinTypes, !b, e.Location);
278                                 
279                         case Operator.OnesComplement:
280                                 // Unary numeric promotions
281                                 switch (expr_type.BuiltinType) {
282                                 case BuiltinTypeSpec.Type.Byte:
283                                         return new IntConstant (ec.BuiltinTypes, ~((ByteConstant) e).Value, e.Location);
284                                 case BuiltinTypeSpec.Type.SByte:
285                                         return new IntConstant (ec.BuiltinTypes, ~((SByteConstant) e).Value, e.Location);
286                                 case BuiltinTypeSpec.Type.Short:
287                                         return new IntConstant (ec.BuiltinTypes, ~((ShortConstant) e).Value, e.Location);
288                                 case BuiltinTypeSpec.Type.UShort:
289                                         return new IntConstant (ec.BuiltinTypes, ~((UShortConstant) e).Value, e.Location);
290                                 case BuiltinTypeSpec.Type.Char:
291                                         return new IntConstant (ec.BuiltinTypes, ~((CharConstant) e).Value, e.Location);
292                                 
293                                 // Predefined operators
294                                 case BuiltinTypeSpec.Type.Int:
295                                         return new IntConstant (ec.BuiltinTypes, ~((IntConstant)e).Value, e.Location);
296                                 case BuiltinTypeSpec.Type.UInt:
297                                         return new UIntConstant (ec.BuiltinTypes, ~((UIntConstant) e).Value, e.Location);
298                                 case BuiltinTypeSpec.Type.Long:
299                                         return new LongConstant (ec.BuiltinTypes, ~((LongConstant) e).Value, e.Location);
300                                 case BuiltinTypeSpec.Type.ULong:
301                                         return new ULongConstant (ec.BuiltinTypes, ~((ULongConstant) e).Value, e.Location);
302                                 }
303                                 if (e is EnumConstant) {
304                                         var res = TryReduceConstant (ec, ((EnumConstant)e).Child);
305                                         if (res != null) {
306                                                 //
307                                                 // Numeric promotion upgraded types to int but for enum constant
308                                                 // original underlying constant type is needed
309                                                 //
310                                                 if (res.Type.BuiltinType == BuiltinTypeSpec.Type.Int) {
311                                                         int v = ((IntConstant) res).Value;
312                                                         switch (((EnumConstant) e).Child.Type.BuiltinType) {
313                                                                 case BuiltinTypeSpec.Type.UShort:
314                                                                 res = new UShortConstant (ec.BuiltinTypes, (ushort) v, e.Location);
315                                                                 break;
316                                                                 case BuiltinTypeSpec.Type.Short:
317                                                                 res = new ShortConstant (ec.BuiltinTypes, (short) v, e.Location);
318                                                                 break;
319                                                                 case BuiltinTypeSpec.Type.Byte:
320                                                                 res = new ByteConstant (ec.BuiltinTypes, (byte) v, e.Location);
321                                                                 break;
322                                                                 case BuiltinTypeSpec.Type.SByte:
323                                                                 res = new SByteConstant (ec.BuiltinTypes, (sbyte) v, e.Location);
324                                                                 break;
325                                                         }
326                                                 }
327
328                                                 res = new EnumConstant (res, expr_type);
329                                         }
330                                         return res;
331                                 }
332                                 return null;
333                         }
334                         throw new Exception ("Can not constant fold: " + Oper.ToString());
335                 }
336                 
337                 protected virtual Expression ResolveOperator (ResolveContext ec, Expression expr)
338                 {
339                         eclass = ExprClass.Value;
340
341                         TypeSpec expr_type = expr.Type;
342                         Expression best_expr;
343
344                         TypeSpec[] predefined = ec.BuiltinTypes.OperatorsUnary [(int) Oper];
345
346                         //
347                         // Primitive types first
348                         //
349                         if (BuiltinTypeSpec.IsPrimitiveType (expr_type)) {
350                                 best_expr = ResolvePrimitivePredefinedType (ec, expr, predefined);
351                                 if (best_expr == null)
352                                         return null;
353
354                                 type = best_expr.Type;
355                                 Expr = best_expr;
356                                 return this;
357                         }
358
359                         //
360                         // E operator ~(E x);
361                         //
362                         if (Oper == Operator.OnesComplement && expr_type.IsEnum)
363                                 return ResolveEnumOperator (ec, expr, predefined);
364
365                         return ResolveUserType (ec, expr, predefined);
366                 }
367
368                 protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
369                 {
370                         TypeSpec underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
371                         Expression best_expr = ResolvePrimitivePredefinedType (ec, EmptyCast.Create (expr, underlying_type), predefined);
372                         if (best_expr == null)
373                                 return null;
374
375                         Expr = best_expr;
376                         enum_conversion = Convert.ExplicitNumericConversion (ec, new EmptyExpression (best_expr.Type), underlying_type);
377                         type = expr.Type;
378                         return EmptyCast.Create (this, type);
379                 }
380
381                 public override bool ContainsEmitWithAwait ()
382                 {
383                         return Expr.ContainsEmitWithAwait ();
384                 }
385
386                 public override Expression CreateExpressionTree (ResolveContext ec)
387                 {
388                         return CreateExpressionTree (ec, null);
389                 }
390
391                 Expression CreateExpressionTree (ResolveContext ec, Expression user_op)
392                 {
393                         string method_name;
394                         switch (Oper) {
395                         case Operator.AddressOf:
396                                 Error_PointerInsideExpressionTree (ec);
397                                 return null;
398                         case Operator.UnaryNegation:
399                                 if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
400                                         method_name = "NegateChecked";
401                                 else
402                                         method_name = "Negate";
403                                 break;
404                         case Operator.OnesComplement:
405                         case Operator.LogicalNot:
406                                 method_name = "Not";
407                                 break;
408                         case Operator.UnaryPlus:
409                                 method_name = "UnaryPlus";
410                                 break;
411                         default:
412                                 throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
413                         }
414
415                         Arguments args = new Arguments (2);
416                         args.Add (new Argument (Expr.CreateExpressionTree (ec)));
417                         if (user_op != null)
418                                 args.Add (new Argument (user_op));
419
420                         return CreateExpressionFactoryCall (ec, method_name, args);
421                 }
422
423                 public static TypeSpec[][] CreatePredefinedOperatorsTable (BuiltinTypes types)
424                 {
425                         var predefined_operators = new TypeSpec[(int) Operator.TOP][];
426
427                         //
428                         // 7.6.1 Unary plus operator
429                         //
430                         predefined_operators [(int) Operator.UnaryPlus] = new TypeSpec [] {
431                                 types.Int, types.UInt,
432                                 types.Long, types.ULong,
433                                 types.Float, types.Double,
434                                 types.Decimal
435                         };
436
437                         //
438                         // 7.6.2 Unary minus operator
439                         //
440                         predefined_operators [(int) Operator.UnaryNegation] = new TypeSpec [] {
441                                 types.Int,  types.Long,
442                                 types.Float, types.Double,
443                                 types.Decimal
444                         };
445
446                         //
447                         // 7.6.3 Logical negation operator
448                         //
449                         predefined_operators [(int) Operator.LogicalNot] = new TypeSpec [] {
450                                 types.Bool
451                         };
452
453                         //
454                         // 7.6.4 Bitwise complement operator
455                         //
456                         predefined_operators [(int) Operator.OnesComplement] = new TypeSpec [] {
457                                 types.Int, types.UInt,
458                                 types.Long, types.ULong
459                         };
460
461                         return predefined_operators;
462                 }
463
464                 //
465                 // Unary numeric promotions
466                 //
467                 static Expression DoNumericPromotion (ResolveContext rc, Operator op, Expression expr)
468                 {
469                         TypeSpec expr_type = expr.Type;
470                         if (op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) {
471                                 switch (expr_type.BuiltinType) {
472                                 case BuiltinTypeSpec.Type.Byte:
473                                 case BuiltinTypeSpec.Type.SByte:
474                                 case BuiltinTypeSpec.Type.Short:
475                                 case BuiltinTypeSpec.Type.UShort:
476                                 case BuiltinTypeSpec.Type.Char:
477                                         return Convert.ImplicitNumericConversion (expr, rc.BuiltinTypes.Int);
478                                 }
479                         }
480
481                         if (op == Operator.UnaryNegation && expr_type.BuiltinType == BuiltinTypeSpec.Type.UInt)
482                                 return Convert.ImplicitNumericConversion (expr, rc.BuiltinTypes.Long);
483
484                         return expr;
485                 }
486
487                 protected override Expression DoResolve (ResolveContext ec)
488                 {
489                         if (Oper == Operator.AddressOf) {
490                                 return ResolveAddressOf (ec);
491                         }
492
493                         Expr = Expr.Resolve (ec);
494                         if (Expr == null)
495                                 return null;
496
497                         if (Expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
498                                 Arguments args = new Arguments (1);
499                                 args.Add (new Argument (Expr));
500                                 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
501                         }
502
503                         if (Expr.Type.IsNullableType)
504                                 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
505
506                         //
507                         // Attempt to use a constant folding operation.
508                         //
509                         Constant cexpr = Expr as Constant;
510                         if (cexpr != null) {
511                                 cexpr = TryReduceConstant (ec, cexpr);
512                                 if (cexpr != null)
513                                         return cexpr;
514                         }
515
516                         Expression expr = ResolveOperator (ec, Expr);
517                         if (expr == null)
518                                 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
519                         
520                         //
521                         // Reduce unary operator on predefined types
522                         //
523                         if (expr == this && Oper == Operator.UnaryPlus)
524                                 return Expr;
525
526                         return expr;
527                 }
528
529                 public override Expression DoResolveLValue (ResolveContext ec, Expression right)
530                 {
531                         return null;
532                 }
533
534                 public override void Emit (EmitContext ec)
535                 {
536                         EmitOperator (ec, type);
537                 }
538
539                 protected void EmitOperator (EmitContext ec, TypeSpec type)
540                 {
541                         switch (Oper) {
542                         case Operator.UnaryPlus:
543                                 Expr.Emit (ec);
544                                 break;
545                                 
546                         case Operator.UnaryNegation:
547                                 if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
548                                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && Expr.ContainsEmitWithAwait ())
549                                                 Expr = Expr.EmitToField (ec);
550
551                                         ec.EmitInt (0);
552                                         if (type.BuiltinType == BuiltinTypeSpec.Type.Long)
553                                                 ec.Emit (OpCodes.Conv_U8);
554                                         Expr.Emit (ec);
555                                         ec.Emit (OpCodes.Sub_Ovf);
556                                 } else {
557                                         Expr.Emit (ec);
558                                         ec.Emit (OpCodes.Neg);
559                                 }
560                                 
561                                 break;
562                                 
563                         case Operator.LogicalNot:
564                                 Expr.Emit (ec);
565                                 ec.EmitInt (0);
566                                 ec.Emit (OpCodes.Ceq);
567                                 break;
568                                 
569                         case Operator.OnesComplement:
570                                 Expr.Emit (ec);
571                                 ec.Emit (OpCodes.Not);
572                                 break;
573                                 
574                         case Operator.AddressOf:
575                                 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
576                                 break;
577                                 
578                         default:
579                                 throw new Exception ("This should not happen: Operator = "
580                                                      + Oper.ToString ());
581                         }
582
583                         //
584                         // Same trick as in Binary expression
585                         //
586                         if (enum_conversion != null)
587                                 enum_conversion.Emit (ec);
588                 }
589
590                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
591                 {
592                         if (Oper == Operator.LogicalNot)
593                                 Expr.EmitBranchable (ec, target, !on_true);
594                         else
595                                 base.EmitBranchable (ec, target, on_true);
596                 }
597
598                 public override void EmitSideEffect (EmitContext ec)
599                 {
600                         Expr.EmitSideEffect (ec);
601                 }
602
603                 public static void Error_Ambiguous (ResolveContext rc, string oper, TypeSpec type, Location loc)
604                 {
605                         rc.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
606                                 oper, type.GetSignatureForError ());
607                 }
608
609                 public override void FlowAnalysis (FlowAnalysisContext fc)
610                 {
611                         if (Oper == Operator.AddressOf) {
612                                 var vr = Expr as VariableReference;
613                                 if (vr != null && vr.VariableInfo != null)
614                                         fc.SetVariableAssigned (vr.VariableInfo);
615
616                                 return;
617                         }
618
619                         Expr.FlowAnalysis (fc);
620
621                         if (Oper == Operator.LogicalNot) {
622                                 var temp = fc.DefiniteAssignmentOnTrue;
623                                 fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse;
624                                 fc.DefiniteAssignmentOnFalse = temp;
625                         }
626                 }
627
628                 //
629                 // Converts operator to System.Linq.Expressions.ExpressionType enum name
630                 //
631                 string GetOperatorExpressionTypeName ()
632                 {
633                         switch (Oper) {
634                         case Operator.OnesComplement:
635                                 return "OnesComplement";
636                         case Operator.LogicalNot:
637                                 return "Not";
638                         case Operator.UnaryNegation:
639                                 return "Negate";
640                         case Operator.UnaryPlus:
641                                 return "UnaryPlus";
642                         default:
643                                 throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
644                         }
645                 }
646
647                 static bool IsFloat (TypeSpec t)
648                 {
649                         return t.BuiltinType == BuiltinTypeSpec.Type.Double || t.BuiltinType == BuiltinTypeSpec.Type.Float;
650                 }
651
652                 //
653                 // Returns a stringified representation of the Operator
654                 //
655                 public static string OperName (Operator oper)
656                 {
657                         switch (oper) {
658                         case Operator.UnaryPlus:
659                                 return "+";
660                         case Operator.UnaryNegation:
661                                 return "-";
662                         case Operator.LogicalNot:
663                                 return "!";
664                         case Operator.OnesComplement:
665                                 return "~";
666                         case Operator.AddressOf:
667                                 return "&";
668                         }
669
670                         throw new NotImplementedException (oper.ToString ());
671                 }
672
673                 public override SLE.Expression MakeExpression (BuilderContext ctx)
674                 {
675                         var expr = Expr.MakeExpression (ctx);
676                         bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
677
678                         switch (Oper) {
679                         case Operator.UnaryNegation:
680                                 return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
681                         case Operator.LogicalNot:
682                                 return SLE.Expression.Not (expr);
683 #if NET_4_0 || MOBILE_DYNAMIC
684                         case Operator.OnesComplement:
685                                 return SLE.Expression.OnesComplement (expr);
686 #endif
687                         default:
688                                 throw new NotImplementedException (Oper.ToString ());
689                         }
690                 }
691
692                 Expression ResolveAddressOf (ResolveContext ec)
693                 {
694                         if (!ec.IsUnsafe)
695                                 UnsafeError (ec, loc);
696
697                         Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
698                         if (Expr == null || Expr.eclass != ExprClass.Variable) {
699                                 ec.Report.Error (211, loc, "Cannot take the address of the given expression");
700                                 return null;
701                         }
702
703                         if (!TypeManager.VerifyUnmanaged (ec.Module, Expr.Type, loc)) {
704                                 return null;
705                         }
706
707                         IVariableReference vr = Expr as IVariableReference;
708                         bool is_fixed;
709                         if (vr != null) {
710                                 is_fixed = vr.IsFixed;
711                                 vr.SetHasAddressTaken ();
712
713                                 if (vr.IsHoisted) {
714                                         AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
715                                 }
716                         } else {
717                                 IFixedExpression fe = Expr as IFixedExpression;
718                                 is_fixed = fe != null && fe.IsFixed;
719                         }
720
721                         if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
722                                 ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
723                         }
724
725                         type = PointerContainer.MakeType (ec.Module, Expr.Type);
726                         eclass = ExprClass.Value;
727                         return this;
728                 }
729
730                 Expression ResolvePrimitivePredefinedType (ResolveContext rc, Expression expr, TypeSpec[] predefined)
731                 {
732                         expr = DoNumericPromotion (rc, Oper, expr);
733                         TypeSpec expr_type = expr.Type;
734                         foreach (TypeSpec t in predefined) {
735                                 if (t == expr_type)
736                                         return expr;
737                         }
738                         return null;
739                 }
740
741                 //
742                 // Perform user-operator overload resolution
743                 //
744                 protected virtual Expression ResolveUserOperator (ResolveContext ec, Expression expr)
745                 {
746                         CSharp.Operator.OpType op_type;
747                         switch (Oper) {
748                         case Operator.LogicalNot:
749                                 op_type = CSharp.Operator.OpType.LogicalNot; break;
750                         case Operator.OnesComplement:
751                                 op_type = CSharp.Operator.OpType.OnesComplement; break;
752                         case Operator.UnaryNegation:
753                                 op_type = CSharp.Operator.OpType.UnaryNegation; break;
754                         case Operator.UnaryPlus:
755                                 op_type = CSharp.Operator.OpType.UnaryPlus; break;
756                         default:
757                                 throw new InternalErrorException (Oper.ToString ());
758                         }
759
760                         var methods = MemberCache.GetUserOperator (expr.Type, op_type, false);
761                         if (methods == null)
762                                 return null;
763
764                         Arguments args = new Arguments (1);
765                         args.Add (new Argument (expr));
766
767                         var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
768                         var oper = res.ResolveOperator (ec, ref args);
769
770                         if (oper == null)
771                                 return null;
772
773                         Expr = args [0].Expr;
774                         return new UserOperatorCall (oper, args, CreateExpressionTree, expr.Location);
775                 }
776
777                 //
778                 // Unary user type overload resolution
779                 //
780                 Expression ResolveUserType (ResolveContext ec, Expression expr, TypeSpec[] predefined)
781                 {
782                         Expression best_expr = ResolveUserOperator (ec, expr);
783                         if (best_expr != null)
784                                 return best_expr;
785
786                         foreach (TypeSpec t in predefined) {
787                                 Expression oper_expr = Convert.ImplicitUserConversion (ec, expr, t, expr.Location);
788                                 if (oper_expr == null)
789                                         continue;
790
791                                 if (oper_expr == ErrorExpression.Instance)
792                                         return oper_expr;
793
794                                 //
795                                 // decimal type is predefined but has user-operators
796                                 //
797                                 if (oper_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal)
798                                         oper_expr = ResolveUserType (ec, oper_expr, predefined);
799                                 else
800                                         oper_expr = ResolvePrimitivePredefinedType (ec, oper_expr, predefined);
801
802                                 if (oper_expr == null)
803                                         continue;
804
805                                 if (best_expr == null) {
806                                         best_expr = oper_expr;
807                                         continue;
808                                 }
809
810                                 int result = OverloadResolver.BetterTypeConversion (ec, best_expr.Type, t);
811                                 if (result == 0) {
812                                         if ((oper_expr is UserOperatorCall || oper_expr is UserCast) && (best_expr is UserOperatorCall || best_expr is UserCast)) {
813                                                 Error_Ambiguous (ec, OperName (Oper), expr.Type, loc);
814                                         } else {
815                                                 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), expr.Type);
816                                         }
817
818                                         break;
819                                 }
820
821                                 if (result == 2)
822                                         best_expr = oper_expr;
823                         }
824                         
825                         if (best_expr == null)
826                                 return null;
827                         
828                         //
829                         // HACK: Decimal user-operator is included in standard operators
830                         //
831                         if (best_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal)
832                                 return best_expr;
833
834                         Expr = best_expr;
835                         type = best_expr.Type;
836                         return this;                    
837                 }
838
839                 protected override void CloneTo (CloneContext clonectx, Expression t)
840                 {
841                         Unary target = (Unary) t;
842
843                         target.Expr = Expr.Clone (clonectx);
844                 }
845                 
846                 public override object Accept (StructuralVisitor visitor)
847                 {
848                         return visitor.Visit (this);
849                 }
850
851         }
852
853         //
854         // Unary operators are turned into Indirection expressions
855         // after semantic analysis (this is so we can take the address
856         // of an indirection).
857         //
858         public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
859                 Expression expr;
860                 LocalTemporary temporary;
861                 bool prepared;
862                 
863                 public Indirection (Expression expr, Location l)
864                 {
865                         this.expr = expr;
866                         loc = l;
867                 }
868
869                 public Expression Expr {
870                         get {
871                                 return expr;
872                         }
873                 }
874
875                 public bool IsFixed {
876                         get { return true; }
877                 }
878
879                 public override Location StartLocation {
880                         get {
881                                 return expr.StartLocation;
882                         }
883                 }
884
885                 protected override void CloneTo (CloneContext clonectx, Expression t)
886                 {
887                         Indirection target = (Indirection) t;
888                         target.expr = expr.Clone (clonectx);
889                 }
890
891                 public override bool ContainsEmitWithAwait ()
892                 {
893                         throw new NotImplementedException ();
894                 }
895
896                 public override Expression CreateExpressionTree (ResolveContext ec)
897                 {
898                         Error_PointerInsideExpressionTree (ec);
899                         return null;
900                 }
901                 
902                 public override void Emit (EmitContext ec)
903                 {
904                         if (!prepared)
905                                 expr.Emit (ec);
906                         
907                         ec.EmitLoadFromPtr (Type);
908                 }
909
910                 public void Emit (EmitContext ec, bool leave_copy)
911                 {
912                         Emit (ec);
913                         if (leave_copy) {
914                                 ec.Emit (OpCodes.Dup);
915                                 temporary = new LocalTemporary (expr.Type);
916                                 temporary.Store (ec);
917                         }
918                 }
919                 
920                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
921                 {
922                         prepared = isCompound;
923                         
924                         expr.Emit (ec);
925
926                         if (isCompound)
927                                 ec.Emit (OpCodes.Dup);
928                         
929                         source.Emit (ec);
930                         if (leave_copy) {
931                                 ec.Emit (OpCodes.Dup);
932                                 temporary = new LocalTemporary (source.Type);
933                                 temporary.Store (ec);
934                         }
935                         
936                         ec.EmitStoreFromPtr (type);
937                         
938                         if (temporary != null) {
939                                 temporary.Emit (ec);
940                                 temporary.Release (ec);
941                         }
942                 }
943                 
944                 public void AddressOf (EmitContext ec, AddressOp Mode)
945                 {
946                         expr.Emit (ec);
947                 }
948
949                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
950                 {
951                         return DoResolve (ec);
952                 }
953
954                 protected override Expression DoResolve (ResolveContext ec)
955                 {
956                         expr = expr.Resolve (ec);
957                         if (expr == null)
958                                 return null;
959
960                         if (!ec.IsUnsafe)
961                                 UnsafeError (ec, loc);
962
963                         var pc = expr.Type as PointerContainer;
964
965                         if (pc == null) {
966                                 ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
967                                 return null;
968                         }
969
970                         type = pc.Element;
971
972                         if (type.Kind == MemberKind.Void) {
973                                 Error_VoidPointerOperation (ec);
974                                 return null;
975                         }
976
977                         eclass = ExprClass.Variable;
978                         return this;
979                 }
980
981                 public override object Accept (StructuralVisitor visitor)
982                 {
983                         return visitor.Visit (this);
984                 }
985         }
986         
987         /// <summary>
988         ///   Unary Mutator expressions (pre and post ++ and --)
989         /// </summary>
990         ///
991         /// <remarks>
992         ///   UnaryMutator implements ++ and -- expressions.   It derives from
993         ///   ExpressionStatement becuase the pre/post increment/decrement
994         ///   operators can be used in a statement context.
995         ///
996         /// FIXME: Idea, we could split this up in two classes, one simpler
997         /// for the common case, and one with the extra fields for more complex
998         /// classes (indexers require temporary access;  overloaded require method)
999         ///
1000         /// </remarks>
1001         public class UnaryMutator : ExpressionStatement
1002         {
1003                 class DynamicPostMutator : Expression, IAssignMethod
1004                 {
1005                         LocalTemporary temp;
1006                         Expression expr;
1007
1008                         public DynamicPostMutator (Expression expr)
1009                         {
1010                                 this.expr = expr;
1011                                 this.type = expr.Type;
1012                                 this.loc = expr.Location;
1013                         }
1014
1015                         public override Expression CreateExpressionTree (ResolveContext ec)
1016                         {
1017                                 throw new NotImplementedException ("ET");
1018                         }
1019
1020                         protected override Expression DoResolve (ResolveContext rc)
1021                         {
1022                                 eclass = expr.eclass;
1023                                 return this;
1024                         }
1025
1026                         public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
1027                         {
1028                                 expr.DoResolveLValue (ec, right_side);
1029                                 return DoResolve (ec);
1030                         }
1031
1032                         public override void Emit (EmitContext ec)
1033                         {
1034                                 temp.Emit (ec);
1035                         }
1036
1037                         public void Emit (EmitContext ec, bool leave_copy)
1038                         {
1039                                 throw new NotImplementedException ();
1040                         }
1041
1042                         //
1043                         // Emits target assignment using unmodified source value
1044                         //
1045                         public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
1046                         {
1047                                 //
1048                                 // Allocate temporary variable to keep original value before it's modified
1049                                 //
1050                                 temp = new LocalTemporary (type);
1051                                 expr.Emit (ec);
1052                                 temp.Store (ec);
1053
1054                                 ((IAssignMethod) expr).EmitAssign (ec, source, false, isCompound);
1055
1056                                 if (leave_copy)
1057                                         Emit (ec);
1058
1059                                 temp.Release (ec);
1060                                 temp = null;
1061                         }
1062                 }
1063
1064                 [Flags]
1065                 public enum Mode : byte {
1066                         IsIncrement    = 0,
1067                         IsDecrement    = 1,
1068                         IsPre          = 0,
1069                         IsPost         = 2,
1070                         
1071                         PreIncrement   = 0,
1072                         PreDecrement   = IsDecrement,
1073                         PostIncrement  = IsPost,
1074                         PostDecrement  = IsPost | IsDecrement
1075                 }
1076
1077                 Mode mode;
1078                 bool is_expr, recurse;
1079
1080                 protected Expression expr;
1081
1082                 // Holds the real operation
1083                 Expression operation;
1084
1085                 public UnaryMutator (Mode m, Expression e, Location loc)
1086                 {
1087                         mode = m;
1088                         this.loc = loc;
1089                         expr = e;
1090                 }
1091
1092                 public Mode UnaryMutatorMode {
1093                         get {
1094                                 return mode;
1095                         }
1096                 }
1097                 
1098                 public Expression Expr {
1099                         get {
1100                                 return expr;
1101                         }
1102                 }
1103
1104                 public override Location StartLocation {
1105                         get {
1106                                 return (mode & Mode.IsPost) != 0 ? expr.Location : loc;
1107                         }
1108                 }
1109
1110                 public override bool ContainsEmitWithAwait ()
1111                 {
1112                         return expr.ContainsEmitWithAwait ();
1113                 }
1114
1115                 public override Expression CreateExpressionTree (ResolveContext ec)
1116                 {
1117                         return new SimpleAssign (this, this).CreateExpressionTree (ec);
1118                 }
1119
1120                 public static TypeSpec[] CreatePredefinedOperatorsTable (BuiltinTypes types)
1121                 {
1122                         //
1123                         // Predefined ++ and -- operators exist for the following types: 
1124                         // sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal
1125                         //
1126                         return new TypeSpec[] {
1127                                 types.Int,
1128                                 types.Long,
1129
1130                                 types.SByte,
1131                                 types.Byte,
1132                                 types.Short,
1133                                 types.UInt,
1134                                 types.ULong,
1135                                 types.Char,
1136                                 types.Float,
1137                                 types.Double,
1138                                 types.Decimal
1139                         };
1140                 }
1141
1142                 protected override Expression DoResolve (ResolveContext ec)
1143                 {
1144                         expr = expr.Resolve (ec);
1145                         
1146                         if (expr == null)
1147                                 return null;
1148
1149                         if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1150                                 //
1151                                 // Handle postfix unary operators using local
1152                                 // temporary variable
1153                                 //
1154                                 if ((mode & Mode.IsPost) != 0)
1155                                         expr = new DynamicPostMutator (expr);
1156
1157                                 Arguments args = new Arguments (1);
1158                                 args.Add (new Argument (expr));
1159                                 return new SimpleAssign (expr, new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc)).Resolve (ec);
1160                         }
1161
1162                         if (expr.Type.IsNullableType)
1163                                 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
1164
1165                         return DoResolveOperation (ec);
1166                 }
1167
1168                 protected Expression DoResolveOperation (ResolveContext ec)
1169                 {
1170                         eclass = ExprClass.Value;
1171                         type = expr.Type;
1172
1173                         if (expr is RuntimeValueExpression) {
1174                                 operation = expr;
1175                         } else {
1176                                 // Use itself at the top of the stack
1177                                 operation = new EmptyExpression (type);
1178                         }
1179
1180                         //
1181                         // The operand of the prefix/postfix increment decrement operators
1182                         // should be an expression that is classified as a variable,
1183                         // a property access or an indexer access
1184                         //
1185                         // TODO: Move to parser, expr is ATypeNameExpression
1186                         if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
1187                                 expr = expr.ResolveLValue (ec, expr);
1188                         } else {
1189                                 ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
1190                         }
1191
1192                         //
1193                         // Step 1: Try to find a user operator, it has priority over predefined ones
1194                         //
1195                         var user_op = IsDecrement ? Operator.OpType.Decrement : Operator.OpType.Increment;
1196                         var methods = MemberCache.GetUserOperator (type, user_op, false);
1197
1198                         if (methods != null) {
1199                                 Arguments args = new Arguments (1);
1200                                 args.Add (new Argument (expr));
1201
1202                                 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
1203                                 var method = res.ResolveOperator (ec, ref args);
1204                                 if (method == null)
1205                                         return null;
1206
1207                                 args[0].Expr = operation;
1208                                 operation = new UserOperatorCall (method, args, null, loc);
1209                                 operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
1210                                 return this;
1211                         }
1212
1213                         //
1214                         // Step 2: Try predefined types
1215                         //
1216
1217                         Expression source = null;
1218                         bool primitive_type;
1219
1220                         //
1221                         // Predefined without user conversion first for speed-up
1222                         //
1223                         // Predefined ++ and -- operators exist for the following types: 
1224                         // sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal
1225                         //
1226                         switch (type.BuiltinType) {
1227                         case BuiltinTypeSpec.Type.Byte:
1228                         case BuiltinTypeSpec.Type.SByte:
1229                         case BuiltinTypeSpec.Type.Short:
1230                         case BuiltinTypeSpec.Type.UShort:
1231                         case BuiltinTypeSpec.Type.Int:
1232                         case BuiltinTypeSpec.Type.UInt:
1233                         case BuiltinTypeSpec.Type.Long:
1234                         case BuiltinTypeSpec.Type.ULong:
1235                         case BuiltinTypeSpec.Type.Char:
1236                         case BuiltinTypeSpec.Type.Float:
1237                         case BuiltinTypeSpec.Type.Double:
1238                         case BuiltinTypeSpec.Type.Decimal:
1239                                 source = operation;
1240                                 primitive_type = true;
1241                                 break;
1242                         default:
1243                                 primitive_type = false;
1244
1245                                 // ++/-- on pointer variables of all types except void*
1246                                 if (type.IsPointer) {
1247                                         if (((PointerContainer) type).Element.Kind == MemberKind.Void) {
1248                                                 Error_VoidPointerOperation (ec);
1249                                                 return null;
1250                                         }
1251
1252                                         source = operation;
1253                                 } else {
1254                                         Expression best_source = null;
1255                                         foreach (var t in ec.BuiltinTypes.OperatorsUnaryMutator) {
1256                                                 source = Convert.ImplicitUserConversion (ec, operation, t, loc);
1257
1258                                                 // LAMESPEC: It should error on ambiguous operators but that would make us incompatible
1259                                                 if (source == null)
1260                                                         continue;
1261
1262                                                 if (best_source == null) {
1263                                                         best_source = source;
1264                                                         continue;
1265                                                 }
1266
1267                                                 var better = OverloadResolver.BetterTypeConversion (ec, best_source.Type, source.Type);
1268                                                 if (better == 1)
1269                                                         continue;
1270
1271                                                 if (better == 2) {
1272                                                         best_source = source;
1273                                                         continue;
1274                                                 }
1275
1276                                                 Unary.Error_Ambiguous (ec, OperName (mode), type, loc);
1277                                                 break;
1278                                         }
1279
1280                                         source = best_source;
1281                                 }
1282
1283                                 // ++/-- on enum types
1284                                 if (source == null && type.IsEnum)
1285                                         source = operation;
1286
1287                                 if (source == null) {
1288                                         expr.Error_OperatorCannotBeApplied (ec, loc, Operator.GetName (user_op), type);
1289                                         return null;
1290                                 }
1291
1292                                 break;
1293                         }
1294
1295                         var one = new IntConstant (ec.BuiltinTypes, 1, loc);
1296                         var op = IsDecrement ? Binary.Operator.Subtraction : Binary.Operator.Addition;
1297                         operation = new Binary (op, source, one);
1298                         operation = operation.Resolve (ec);
1299                         if (operation == null)
1300                                 throw new NotImplementedException ("should not be reached");
1301
1302                         if (operation.Type != type) {
1303                                 if (primitive_type)
1304                                         operation = Convert.ExplicitNumericConversion (ec, operation, type);
1305                                 else
1306                                         operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
1307                         }
1308
1309                         return this;
1310                 }
1311
1312                 void EmitCode (EmitContext ec, bool is_expr)
1313                 {
1314                         recurse = true;
1315                         this.is_expr = is_expr;
1316                         ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1317                 }
1318
1319                 public override void Emit (EmitContext ec)
1320                 {
1321                         //
1322                         // We use recurse to allow ourselfs to be the source
1323                         // of an assignment. This little hack prevents us from
1324                         // having to allocate another expression
1325                         //
1326                         if (recurse) {
1327                                 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1328
1329                                 EmitOperation (ec);
1330
1331                                 recurse = false;
1332                                 return;
1333                         }
1334
1335                         EmitCode (ec, true);
1336                 }
1337
1338                 protected virtual void EmitOperation (EmitContext ec)
1339                 {
1340                         operation.Emit (ec);
1341                 }
1342
1343                 public override void EmitStatement (EmitContext ec)
1344                 {
1345                         EmitCode (ec, false);
1346                 }
1347
1348                 public override void FlowAnalysis (FlowAnalysisContext fc)
1349                 {
1350                         expr.FlowAnalysis (fc);
1351                 }
1352
1353                 //
1354                 // Converts operator to System.Linq.Expressions.ExpressionType enum name
1355                 //
1356                 string GetOperatorExpressionTypeName ()
1357                 {
1358                         return IsDecrement ? "Decrement" : "Increment";
1359                 }
1360
1361                 bool IsDecrement {
1362                         get { return (mode & Mode.IsDecrement) != 0; }
1363                 }
1364
1365
1366 #if NET_4_0 || MOBILE_DYNAMIC
1367                 public override SLE.Expression MakeExpression (BuilderContext ctx)
1368                 {
1369                         var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
1370                         var source = SLE.Expression.Convert (operation.MakeExpression (ctx), target.Type);
1371                         return SLE.Expression.Assign (target, source);
1372                 }
1373 #endif
1374
1375                 public static string OperName (Mode oper)
1376                 {
1377                         return (oper & Mode.IsDecrement) != 0 ? "--" : "++";
1378                 }
1379
1380                 protected override void CloneTo (CloneContext clonectx, Expression t)
1381                 {
1382                         UnaryMutator target = (UnaryMutator) t;
1383
1384                         target.expr = expr.Clone (clonectx);
1385                 }
1386
1387                 public override object Accept (StructuralVisitor visitor)
1388                 {
1389                         return visitor.Visit (this);
1390                 }
1391
1392         }
1393
1394         //
1395         // Base class for the `is' and `as' operators
1396         //
1397         public abstract class Probe : Expression
1398         {
1399                 public Expression ProbeType;
1400                 protected Expression expr;
1401                 protected TypeSpec probe_type_expr;
1402                 
1403                 protected Probe (Expression expr, Expression probe_type, Location l)
1404                 {
1405                         ProbeType = probe_type;
1406                         loc = l;
1407                         this.expr = expr;
1408                 }
1409
1410                 public Expression Expr {
1411                         get {
1412                                 return expr;
1413                         }
1414                 }
1415
1416                 public override bool ContainsEmitWithAwait ()
1417                 {
1418                         return expr.ContainsEmitWithAwait ();
1419                 }
1420
1421                 protected override Expression DoResolve (ResolveContext ec)
1422                 {
1423                         probe_type_expr = ProbeType.ResolveAsType (ec);
1424                         if (probe_type_expr == null)
1425                                 return null;
1426
1427                         expr = expr.Resolve (ec);
1428                         if (expr == null)
1429                                 return null;
1430
1431                         if (probe_type_expr.IsStatic) {
1432                                 ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
1433                                         OperatorName);
1434                         }
1435                         
1436                         if (expr.Type.IsPointer || probe_type_expr.IsPointer) {
1437                                 ec.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
1438                                         OperatorName);
1439                                 return null;
1440                         }
1441
1442                         if (expr.Type == InternalType.AnonymousMethod) {
1443                                 ec.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
1444                                         OperatorName);
1445                                 return null;
1446                         }
1447
1448                         return this;
1449                 }
1450
1451                 public override void FlowAnalysis (FlowAnalysisContext fc)
1452                 {
1453                         expr.FlowAnalysis (fc);
1454                 }
1455
1456                 protected abstract string OperatorName { get; }
1457
1458                 protected override void CloneTo (CloneContext clonectx, Expression t)
1459                 {
1460                         Probe target = (Probe) t;
1461
1462                         target.expr = expr.Clone (clonectx);
1463                         target.ProbeType = ProbeType.Clone (clonectx);
1464                 }
1465
1466         }
1467
1468         /// <summary>
1469         ///   Implementation of the `is' operator.
1470         /// </summary>
1471         public class Is : Probe
1472         {
1473                 Nullable.Unwrap expr_unwrap;
1474
1475                 public Is (Expression expr, Expression probe_type, Location l)
1476                         : base (expr, probe_type, l)
1477                 {
1478                 }
1479
1480                 protected override string OperatorName {
1481                         get { return "is"; }
1482                 }
1483
1484                 public override Expression CreateExpressionTree (ResolveContext ec)
1485                 {
1486                         Arguments args = Arguments.CreateForExpressionTree (ec, null,
1487                                 expr.CreateExpressionTree (ec),
1488                                 new TypeOf (probe_type_expr, loc));
1489
1490                         return CreateExpressionFactoryCall (ec, "TypeIs", args);
1491                 }
1492                 
1493                 public override void Emit (EmitContext ec)
1494                 {
1495                         if (expr_unwrap != null) {
1496                                 expr_unwrap.EmitCheck (ec);
1497                                 return;
1498                         }
1499
1500                         expr.Emit (ec);
1501
1502                         // Only to make verifier happy
1503                         if (probe_type_expr.IsGenericParameter && TypeSpec.IsValueType (expr.Type))
1504                                 ec.Emit (OpCodes.Box, expr.Type);
1505
1506                         ec.Emit (OpCodes.Isinst, probe_type_expr);
1507                         ec.EmitNull ();
1508                         ec.Emit (OpCodes.Cgt_Un);
1509                 }
1510
1511                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
1512                 {
1513                         if (expr_unwrap != null) {
1514                                 expr_unwrap.EmitCheck (ec);
1515                         } else {
1516                                 expr.Emit (ec);
1517                                 ec.Emit (OpCodes.Isinst, probe_type_expr);
1518                         }                       
1519                         ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1520                 }
1521                 
1522                 Expression CreateConstantResult (ResolveContext ec, bool result)
1523                 {
1524                         if (result)
1525                                 ec.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
1526                                         probe_type_expr.GetSignatureForError ());
1527                         else
1528                                 ec.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
1529                                         probe_type_expr.GetSignatureForError ());
1530
1531                         return ReducedExpression.Create (new BoolConstant (ec.BuiltinTypes, result, loc), this);
1532                 }
1533
1534                 protected override Expression DoResolve (ResolveContext ec)
1535                 {
1536                         if (base.DoResolve (ec) == null)
1537                                 return null;
1538
1539                         TypeSpec d = expr.Type;
1540                         bool d_is_nullable = false;
1541
1542                         //
1543                         // If E is a method group or the null literal, or if the type of E is a reference
1544                         // type or a nullable type and the value of E is null, the result is false
1545                         //
1546                         if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
1547                                 return CreateConstantResult (ec, false);
1548
1549                         if (d.IsNullableType) {
1550                                 var ut = Nullable.NullableInfo.GetUnderlyingType (d);
1551                                 if (!ut.IsGenericParameter) {
1552                                         d = ut;
1553                                         d_is_nullable = true;
1554                                 }
1555                         }
1556
1557                         type = ec.BuiltinTypes.Bool;
1558                         eclass = ExprClass.Value;
1559                         TypeSpec t = probe_type_expr;
1560                         bool t_is_nullable = false;
1561                         if (t.IsNullableType) {
1562                                 var ut = Nullable.NullableInfo.GetUnderlyingType (t);
1563                                 if (!ut.IsGenericParameter) {
1564                                         t = ut;
1565                                         t_is_nullable = true;
1566                                 }
1567                         }
1568
1569                         if (t.IsStruct) {
1570                                 if (d == t) {
1571                                         //
1572                                         // D and T are the same value types but D can be null
1573                                         //
1574                                         if (d_is_nullable && !t_is_nullable) {
1575                                                 expr_unwrap = Nullable.Unwrap.Create (expr, false);
1576                                                 return this;
1577                                         }
1578                                         
1579                                         //
1580                                         // The result is true if D and T are the same value types
1581                                         //
1582                                         return CreateConstantResult (ec, true);
1583                                 }
1584
1585                                 var tp = d as TypeParameterSpec;
1586                                 if (tp != null)
1587                                         return ResolveGenericParameter (ec, t, tp);
1588
1589                                 //
1590                                 // An unboxing conversion exists
1591                                 //
1592                                 if (Convert.ExplicitReferenceConversionExists (d, t))
1593                                         return this;
1594
1595                                 //
1596                                 // open generic type
1597                                 //
1598                                 if (d is InflatedTypeSpec && InflatedTypeSpec.ContainsTypeParameter (d))
1599                                         return this;
1600                         } else {
1601                                 var tps = t as TypeParameterSpec;
1602                                 if (tps != null)
1603                                         return ResolveGenericParameter (ec, d, tps);
1604
1605                                 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1606                                         ec.Report.Warning (1981, 3, loc,
1607                                                 "Using `{0}' to test compatibility with `{1}' is identical to testing compatibility with `object'",
1608                                                 OperatorName, t.GetSignatureForError ());
1609                                 }
1610
1611                                 if (TypeManager.IsGenericParameter (d))
1612                                         return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
1613
1614                                 if (TypeSpec.IsValueType (d)) {
1615                                         if (Convert.ImplicitBoxingConversion (null, d, t) != null) {
1616                                                 if (d_is_nullable && !t_is_nullable) {
1617                                                         expr_unwrap = Nullable.Unwrap.Create (expr, false);
1618                                                         return this;
1619                                                 }
1620
1621                                                 return CreateConstantResult (ec, true);
1622                                         }
1623                                 } else {
1624                                         if (Convert.ImplicitReferenceConversionExists (d, t)) {
1625                                                 var c = expr as Constant;
1626                                                 if (c != null)
1627                                                         return CreateConstantResult (ec, !c.IsNull);
1628
1629                                                 //
1630                                                 // Do not optimize for imported type or dynamic type
1631                                                 //
1632                                                 if (d.MemberDefinition.IsImported && d.BuiltinType != BuiltinTypeSpec.Type.None &&
1633                                                         d.MemberDefinition.DeclaringAssembly != t.MemberDefinition.DeclaringAssembly) {
1634                                                         return this;
1635                                                 }
1636
1637                                                 if (d.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1638                                                         return this;
1639                                                 
1640                                                 //
1641                                                 // Turn is check into simple null check for implicitly convertible reference types
1642                                                 //
1643                                                 return ReducedExpression.Create (
1644                                                         new Binary (Binary.Operator.Inequality, expr, new NullLiteral (loc)).Resolve (ec),
1645                                                         this).Resolve (ec);
1646                                         }
1647
1648                                         if (Convert.ExplicitReferenceConversionExists (d, t))
1649                                                 return this;
1650
1651                                         //
1652                                         // open generic type
1653                                         //
1654                                         if ((d is InflatedTypeSpec || d.IsArray) && InflatedTypeSpec.ContainsTypeParameter (d))
1655                                                 return this;
1656                                 }
1657                         }
1658
1659                         return CreateConstantResult (ec, false);
1660                 }
1661
1662                 Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
1663                 {
1664                         if (t.IsReferenceType) {
1665                                 if (d.IsStruct)
1666                                         return CreateConstantResult (ec, false);
1667                         }
1668
1669                         if (expr.Type.IsGenericParameter) {
1670                                 if (expr.Type == d && TypeSpec.IsValueType (t) && TypeSpec.IsValueType (d))
1671                                         return CreateConstantResult (ec, true);
1672
1673                                 expr = new BoxedCast (expr, d);
1674                         }
1675
1676                         return this;
1677                 }
1678                 
1679                 public override object Accept (StructuralVisitor visitor)
1680                 {
1681                         return visitor.Visit (this);
1682                 }
1683         }
1684
1685         /// <summary>
1686         ///   Implementation of the `as' operator.
1687         /// </summary>
1688         public class As : Probe {
1689                 Expression resolved_type;
1690                 
1691                 public As (Expression expr, Expression probe_type, Location l)
1692                         : base (expr, probe_type, l)
1693                 {
1694                 }
1695
1696                 protected override string OperatorName {
1697                         get { return "as"; }
1698                 }
1699
1700                 public override Expression CreateExpressionTree (ResolveContext ec)
1701                 {
1702                         Arguments args = Arguments.CreateForExpressionTree (ec, null,
1703                                 expr.CreateExpressionTree (ec),
1704                                 new TypeOf (probe_type_expr, loc));
1705
1706                         return CreateExpressionFactoryCall (ec, "TypeAs", args);
1707                 }
1708
1709                 public override void Emit (EmitContext ec)
1710                 {
1711                         expr.Emit (ec);
1712
1713                         ec.Emit (OpCodes.Isinst, type);
1714
1715                         if (TypeManager.IsGenericParameter (type) || type.IsNullableType)
1716                                 ec.Emit (OpCodes.Unbox_Any, type);
1717                 }
1718
1719                 protected override Expression DoResolve (ResolveContext ec)
1720                 {
1721                         if (resolved_type == null) {
1722                                 resolved_type = base.DoResolve (ec);
1723
1724                                 if (resolved_type == null)
1725                                         return null;
1726                         }
1727
1728                         type = probe_type_expr;
1729                         eclass = ExprClass.Value;
1730                         TypeSpec etype = expr.Type;
1731
1732                         if (!TypeSpec.IsReferenceType (type) && !type.IsNullableType) {
1733                                 if (TypeManager.IsGenericParameter (type)) {
1734                                         ec.Report.Error (413, loc,
1735                                                 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1736                                                 probe_type_expr.GetSignatureForError ());
1737                                 } else {
1738                                         ec.Report.Error (77, loc,
1739                                                 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1740                                                 type.GetSignatureForError ());
1741                                 }
1742                                 return null;
1743                         }
1744
1745                         if (expr.IsNull && type.IsNullableType) {
1746                                 return Nullable.LiftedNull.CreateFromExpression (ec, this);
1747                         }
1748
1749                         // If the compile-time type of E is dynamic, unlike the cast operator the as operator is not dynamically bound
1750                         if (etype.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1751                                 return this;
1752                         }
1753                         
1754                         Expression e = Convert.ImplicitConversionStandard (ec, expr, type, loc);
1755                         if (e != null) {
1756                                 e = EmptyCast.Create (e, type);
1757                                 return ReducedExpression.Create (e, this).Resolve (ec);
1758                         }
1759
1760                         if (Convert.ExplicitReferenceConversionExists (etype, type)){
1761                                 if (TypeManager.IsGenericParameter (etype))
1762                                         expr = new BoxedCast (expr, etype);
1763
1764                                 return this;
1765                         }
1766
1767                         if (InflatedTypeSpec.ContainsTypeParameter (etype) || InflatedTypeSpec.ContainsTypeParameter (type)) {
1768                                 expr = new BoxedCast (expr, etype);
1769                                 return this;
1770                         }
1771
1772                         if (etype != InternalType.ErrorType) {
1773                                 ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1774                                         etype.GetSignatureForError (), type.GetSignatureForError ());
1775                         }
1776
1777                         return null;
1778                 }
1779
1780                 public override object Accept (StructuralVisitor visitor)
1781                 {
1782                         return visitor.Visit (this);
1783                 }
1784         }
1785         
1786         //
1787         // This represents a typecast in the source language.
1788         //
1789         public class Cast : ShimExpression {
1790                 Expression target_type;
1791
1792                 public Cast (Expression cast_type, Expression expr, Location loc)
1793                         : base (expr)
1794                 {
1795                         this.target_type = cast_type;
1796                         this.loc = loc;
1797                 }
1798
1799                 public Expression TargetType {
1800                         get { return target_type; }
1801                 }
1802
1803                 protected override Expression DoResolve (ResolveContext ec)
1804                 {
1805                         expr = expr.Resolve (ec);
1806                         if (expr == null)
1807                                 return null;
1808
1809                         type = target_type.ResolveAsType (ec);
1810                         if (type == null)
1811                                 return null;
1812
1813                         if (type.IsStatic) {
1814                                 ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", type.GetSignatureForError ());
1815                                 return null;
1816                         }
1817
1818                         if (type.IsPointer && !ec.IsUnsafe) {
1819                                 UnsafeError (ec, loc);
1820                         }
1821
1822                         eclass = ExprClass.Value;
1823                         
1824                         Constant c = expr as Constant;
1825                         if (c != null) {
1826                                 c = c.Reduce (ec, type);
1827                                 if (c != null)
1828                                         return c;
1829                         }
1830
1831                         var res = Convert.ExplicitConversion (ec, expr, type, loc);
1832                         if (res == expr)
1833                                 return EmptyCast.Create (res, type);
1834
1835                         return res;
1836                 }
1837                 
1838                 protected override void CloneTo (CloneContext clonectx, Expression t)
1839                 {
1840                         Cast target = (Cast) t;
1841
1842                         target.target_type = target_type.Clone (clonectx);
1843                         target.expr = expr.Clone (clonectx);
1844                 }
1845
1846                 public override object Accept (StructuralVisitor visitor)
1847                 {
1848                         return visitor.Visit (this);
1849                 }
1850         }
1851
1852         public class ImplicitCast : ShimExpression
1853         {
1854                 bool arrayAccess;
1855
1856                 public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
1857                         : base (expr)
1858                 {
1859                         this.loc = expr.Location;
1860                         this.type = target;
1861                         this.arrayAccess = arrayAccess;
1862                 }
1863
1864                 protected override Expression DoResolve (ResolveContext ec)
1865                 {
1866                         expr = expr.Resolve (ec);
1867                         if (expr == null)
1868                                 return null;
1869
1870                         if (arrayAccess)
1871                                 expr = ConvertExpressionToArrayIndex (ec, expr);
1872                         else
1873                                 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
1874
1875                         return expr;
1876                 }
1877         }
1878         
1879         //
1880         // C# 2.0 Default value expression
1881         //
1882         public class DefaultValueExpression : Expression
1883         {
1884                 Expression expr;
1885
1886                 public DefaultValueExpression (Expression expr, Location loc)
1887                 {
1888                         this.expr = expr;
1889                         this.loc = loc;
1890                 }
1891
1892                 public Expression Expr {
1893                         get {
1894                                 return this.expr; 
1895                         }
1896                 }
1897
1898                 public override bool IsSideEffectFree {
1899                         get {
1900                                 return true;
1901                         }
1902                 }
1903
1904                 public override bool ContainsEmitWithAwait ()
1905                 {
1906                         return false;
1907                 }
1908
1909                 public override Expression CreateExpressionTree (ResolveContext ec)
1910                 {
1911                         Arguments args = new Arguments (2);
1912                         args.Add (new Argument (this));
1913                         args.Add (new Argument (new TypeOf (type, loc)));
1914                         return CreateExpressionFactoryCall (ec, "Constant", args);
1915                 }
1916
1917                 protected override Expression DoResolve (ResolveContext ec)
1918                 {
1919                         type = expr.ResolveAsType (ec);
1920                         if (type == null)
1921                                 return null;
1922
1923                         if (type.IsStatic) {
1924                                 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1925                         }
1926
1927                         if (type.IsPointer)
1928                                 return new NullLiteral (Location).ConvertImplicitly (type);
1929
1930                         if (TypeSpec.IsReferenceType (type))
1931                                 return new NullConstant (type, loc);
1932
1933                         Constant c = New.Constantify (type, expr.Location);
1934                         if (c != null)
1935                                 return c;
1936
1937                         eclass = ExprClass.Variable;
1938                         return this;
1939                 }
1940
1941                 public override void Emit (EmitContext ec)
1942                 {
1943                         LocalTemporary temp_storage = new LocalTemporary(type);
1944
1945                         temp_storage.AddressOf(ec, AddressOp.LoadStore);
1946                         ec.Emit(OpCodes.Initobj, type);
1947                         temp_storage.Emit(ec);
1948                         temp_storage.Release (ec);
1949                 }
1950
1951 #if (NET_4_0 || MOBILE_DYNAMIC) && !STATIC
1952                 public override SLE.Expression MakeExpression (BuilderContext ctx)
1953                 {
1954                         return SLE.Expression.Default (type.GetMetaInfo ());
1955                 }
1956 #endif
1957
1958                 protected override void CloneTo (CloneContext clonectx, Expression t)
1959                 {
1960                         DefaultValueExpression target = (DefaultValueExpression) t;
1961                         
1962                         target.expr = expr.Clone (clonectx);
1963                 }
1964                 
1965                 public override object Accept (StructuralVisitor visitor)
1966                 {
1967                         return visitor.Visit (this);
1968                 }
1969         }
1970
1971         /// <summary>
1972         ///   Binary operators
1973         /// </summary>
1974         public class Binary : Expression, IDynamicBinder
1975         {
1976                 public class PredefinedOperator
1977                 {
1978                         protected readonly TypeSpec left;
1979                         protected readonly TypeSpec right;
1980                         protected readonly TypeSpec left_unwrap;
1981                         protected readonly TypeSpec right_unwrap;
1982                         public readonly Operator OperatorsMask;
1983                         public TypeSpec ReturnType;
1984
1985                         public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1986                                 : this (ltype, rtype, op_mask, ltype)
1987                         {
1988                         }
1989
1990                         public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1991                                 : this (type, type, op_mask, return_type)
1992                         {
1993                         }
1994
1995                         public PredefinedOperator (TypeSpec type, Operator op_mask)
1996                                 : this (type, type, op_mask, type)
1997                         {
1998                         }
1999
2000                         public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
2001                         {
2002                                 if ((op_mask & Operator.ValuesOnlyMask) != 0)
2003                                         throw new InternalErrorException ("Only masked values can be used");
2004
2005                                 if ((op_mask & Operator.NullableMask) != 0) {
2006                                         left_unwrap = Nullable.NullableInfo.GetUnderlyingType (ltype);
2007                                         right_unwrap = Nullable.NullableInfo.GetUnderlyingType (rtype);
2008                                 } else {
2009                                         left_unwrap = ltype;
2010                                         right_unwrap = rtype;
2011                                 }
2012
2013                                 this.left = ltype;
2014                                 this.right = rtype;
2015                                 this.OperatorsMask = op_mask;
2016                                 this.ReturnType = return_type;
2017                         }
2018
2019                         public bool IsLifted {
2020                                 get {
2021                                         return (OperatorsMask & Operator.NullableMask) != 0;
2022                                 }
2023                         }
2024
2025                         public virtual Expression ConvertResult (ResolveContext rc, Binary b)
2026                         {
2027                                 Constant c;
2028
2029                                 var left_expr = b.left;
2030                                 var right_expr = b.right;
2031
2032                                 b.type = ReturnType;
2033
2034                                 if (IsLifted) {
2035                                         if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
2036                                                 b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2037                                                 b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2038                                         }
2039
2040                                         if (right_expr.IsNull) {
2041                                                 if ((b.oper & Operator.EqualityMask) != 0) {
2042                                                         if (!left_expr.Type.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (left_expr.Type))
2043                                                                 return b.CreateLiftedValueTypeResult (rc, left_expr.Type);
2044                                                 } else if ((b.oper & Operator.BitwiseMask) != 0) {
2045                                                         if (left_unwrap.BuiltinType != BuiltinTypeSpec.Type.Bool)
2046                                                                 return Nullable.LiftedNull.CreateFromExpression (rc, b);
2047                                                 } else {
2048                                                         b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2049                                                         b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2050
2051                                                         if ((b.Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
2052                                                                 return Nullable.LiftedNull.CreateFromExpression (rc, b);
2053
2054                                                         return b.CreateLiftedValueTypeResult (rc, left);
2055                                                 }
2056                                         } else if (left_expr.IsNull) {
2057                                                 if ((b.oper & Operator.EqualityMask) != 0) {
2058                                                         if (!right_expr.Type.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (right_expr.Type))
2059                                                                 return b.CreateLiftedValueTypeResult (rc, right_expr.Type);
2060                                                 } else if ((b.oper & Operator.BitwiseMask) != 0) {
2061                                                         if (right_unwrap.BuiltinType != BuiltinTypeSpec.Type.Bool)
2062                                                                 return Nullable.LiftedNull.CreateFromExpression (rc, b);
2063                                                 } else {
2064                                                         b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2065                                                         b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2066
2067                                                         if ((b.Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
2068                                                                 return Nullable.LiftedNull.CreateFromExpression (rc, b);
2069
2070                                                         return b.CreateLiftedValueTypeResult (rc, right);
2071                                                 }
2072                                         }
2073                                 }
2074
2075                                 //
2076                                 // A user operators does not support multiple user conversions, but decimal type
2077                                 // is considered to be predefined type therefore we apply predefined operators rules
2078                                 // and then look for decimal user-operator implementation
2079                                 //
2080                                 if (left.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
2081                                         b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2082                                         b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2083
2084                                         return b.ResolveUserOperator (rc, b.left, b.right);
2085                                 }
2086
2087                                 c = right_expr as Constant;
2088                                 if (c != null) {
2089                                         if (c.IsDefaultValue) {
2090                                                 //
2091                                                 // Optimizes
2092                                                 // 
2093                                                 // (expr + 0) to expr
2094                                                 // (expr - 0) to expr
2095                                                 // (bool? | false) to bool?
2096                                                 //
2097                                                 if (b.oper == Operator.Addition || b.oper == Operator.Subtraction ||
2098                                                         (b.oper == Operator.BitwiseOr && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && c is BoolConstant)) {
2099                                                         b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2100                                                         return ReducedExpression.Create (b.left, b).Resolve (rc);
2101                                                 }
2102
2103                                                 //
2104                                                 // Optimizes (value &/&& 0) to 0
2105                                                 //
2106                                                 if ((b.oper == Operator.BitwiseAnd || b.oper == Operator.LogicalAnd) && !IsLifted) {
2107                                                         Constant side_effect = new SideEffectConstant (c, b.left, c.Location);
2108                                                         return ReducedExpression.Create (side_effect, b);
2109                                                 }
2110                                         } else {
2111                                                 //
2112                                                 // Optimizes (bool? & true) to bool?
2113                                                 //
2114                                                 if (IsLifted && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && b.oper == Operator.BitwiseAnd) {
2115                                                         return ReducedExpression.Create (b.left, b).Resolve (rc);
2116                                                 }
2117                                         }
2118
2119                                         if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
2120                                                 return ReducedExpression.Create (b.left, b).Resolve (rc);
2121
2122                                         if ((b.oper & Operator.ShiftMask) != 0 && c is IntConstant) {
2123                                                 b.right = new IntConstant (rc.BuiltinTypes, ((IntConstant) c).Value & GetShiftMask (left_unwrap), b.right.Location);
2124                                         }
2125                                 }
2126
2127                                 c = b.left as Constant;
2128                                 if (c != null) {
2129                                         if (c.IsDefaultValue) {
2130                                                 //
2131                                                 // Optimizes
2132                                                 // 
2133                                                 // (0 + expr) to expr
2134                                                 // (false | bool?) to bool?
2135                                                 //
2136                                                 if (b.oper == Operator.Addition ||
2137                                                         (b.oper == Operator.BitwiseOr && right_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && c is BoolConstant)) {
2138                                                         b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2139                                                         return ReducedExpression.Create (b.right, b).Resolve (rc);
2140                                                 }
2141
2142                                                 //
2143                                                 // Optimizes (false && expr) to false
2144                                                 //
2145                                                 if (b.oper == Operator.LogicalAnd && c.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
2146                                                         // No rhs side-effects
2147                                                         Expression.Warning_UnreachableExpression (rc, b.right.StartLocation);
2148                                                         return ReducedExpression.Create (c, b);
2149                                                 }
2150
2151                                                 //
2152                                                 // Optimizes (0 & value) to 0
2153                                                 //
2154                                                 if (b.oper == Operator.BitwiseAnd && !IsLifted) {
2155                                                         Constant side_effect = new SideEffectConstant (c, b.right, c.Location);
2156                                                         return ReducedExpression.Create (side_effect, b);
2157                                                 }
2158                                         } else {
2159                                                 //
2160                                                 // Optimizes (true & bool?) to bool?
2161                                                 //
2162                                                 if (IsLifted && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && b.oper == Operator.BitwiseAnd) {
2163                                                         return ReducedExpression.Create (b.right, b).Resolve (rc);
2164                                                 }
2165
2166                                                 //
2167                                                 // Optimizes (true || expr) to true
2168                                                 //
2169                                                 if (b.oper == Operator.LogicalOr && c.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
2170                                                         // No rhs side-effects
2171                                                         Expression.Warning_UnreachableExpression (rc, b.right.StartLocation);
2172                                                         return ReducedExpression.Create (c, b);
2173                                                 }
2174                                         }
2175
2176                                         if (b.oper == Operator.Multiply && c.IsOneInteger)
2177                                                 return ReducedExpression.Create (b.right, b).Resolve (rc);
2178                                 }
2179
2180                                 if (IsLifted) {
2181                                         var lifted = new Nullable.LiftedBinaryOperator (b);
2182
2183                                         TypeSpec ltype, rtype;
2184                                         if (b.left.Type.IsNullableType) {
2185                                                 lifted.UnwrapLeft = new Nullable.Unwrap (b.left);
2186                                                 ltype = left_unwrap;
2187                                         } else {
2188                                                 ltype = left;
2189                                         }
2190
2191                                         if (b.right.Type.IsNullableType) {
2192                                                 lifted.UnwrapRight = new Nullable.Unwrap (b.right);
2193                                                 rtype = right_unwrap;
2194                                         } else {
2195                                                 rtype = right;
2196                                         }
2197
2198                                         lifted.Left = b.left.IsNull ?
2199                                                 b.left :
2200                                                 Convert.ImplicitConversion (rc, lifted.UnwrapLeft ?? b.left, ltype, b.left.Location);
2201
2202                                         lifted.Right = b.right.IsNull ?
2203                                                 b.right :
2204                                                 Convert.ImplicitConversion (rc, lifted.UnwrapRight ?? b.right, rtype, b.right.Location);
2205
2206                                         return lifted.Resolve (rc);
2207                                 }
2208
2209                                 b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2210                                 b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2211
2212                                 return b;
2213                         }
2214
2215                         public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
2216                         {
2217                                 //
2218                                 // We are dealing with primitive types only
2219                                 //
2220                                 return left == ltype && ltype == rtype;
2221                         }
2222
2223                         public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
2224                         {
2225                                 // Quick path
2226                                 if (left == lexpr.Type && right == rexpr.Type)
2227                                         return true;
2228
2229                                 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
2230                                         Convert.ImplicitConversionExists (ec, rexpr, right);
2231                         }
2232
2233                         public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
2234                         {
2235                                 if ((OperatorsMask & Operator.DecomposedMask) != 0)
2236                                         return best_operator;
2237
2238                                 if ((best_operator.OperatorsMask & Operator.DecomposedMask) != 0)
2239                                         return this;
2240
2241                                 int result = 0;
2242                                 if (left != null && best_operator.left != null) {
2243                                         result = OverloadResolver.BetterTypeConversion (ec, best_operator.left_unwrap, left_unwrap);
2244                                 }
2245
2246                                 //
2247                                 // When second argument is same as the first one, the result is same
2248                                 //
2249                                 if (right != null && (left != right || best_operator.left != best_operator.right)) {
2250                                         result |= OverloadResolver.BetterTypeConversion (ec, best_operator.right_unwrap, right_unwrap);
2251                                 }
2252
2253                                 if (result == 0 || result > 2)
2254                                         return null;
2255
2256                                 return result == 1 ? best_operator : this;
2257                         }
2258                 }
2259
2260                 sealed class PredefinedStringOperator : PredefinedOperator
2261                 {
2262                         public PredefinedStringOperator (TypeSpec type, Operator op_mask, TypeSpec retType)
2263                                 : base (type, type, op_mask, retType)
2264                         {
2265                         }
2266
2267                         public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
2268                                 : base (ltype, rtype, op_mask, retType)
2269                         {
2270                         }
2271
2272                         public override Expression ConvertResult (ResolveContext ec, Binary b)
2273                         {
2274                                 //
2275                                 // Use original expression for nullable arguments
2276                                 //
2277                                 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
2278                                 if (unwrap != null)
2279                                         b.left = unwrap.Original;
2280
2281                                 unwrap = b.right as Nullable.Unwrap;
2282                                 if (unwrap != null)
2283                                         b.right = unwrap.Original;
2284
2285                                 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
2286                                 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
2287
2288                                 //
2289                                 // Start a new concat expression using converted expression
2290                                 //
2291                                 return StringConcat.Create (ec, b.left, b.right, b.loc);
2292                         }
2293                 }
2294
2295                 sealed class PredefinedEqualityOperator : PredefinedOperator
2296                 {
2297                         MethodSpec equal_method, inequal_method;
2298
2299                         public PredefinedEqualityOperator (TypeSpec arg, TypeSpec retType)
2300                                 : base (arg, arg, Operator.EqualityMask, retType)
2301                         {
2302                         }
2303
2304                         public override Expression ConvertResult (ResolveContext ec, Binary b)
2305                         {
2306                                 b.type = ReturnType;
2307
2308                                 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
2309                                 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
2310
2311                                 Arguments args = new Arguments (2);
2312                                 args.Add (new Argument (b.left));
2313                                 args.Add (new Argument (b.right));
2314
2315                                 MethodSpec method;
2316                                 if (b.oper == Operator.Equality) {
2317                                         if (equal_method == null) {
2318                                                 if (left.BuiltinType == BuiltinTypeSpec.Type.String)
2319                                                         equal_method = ec.Module.PredefinedMembers.StringEqual.Resolve (b.loc);
2320                                                 else if (left.BuiltinType == BuiltinTypeSpec.Type.Delegate)
2321                                                         equal_method = ec.Module.PredefinedMembers.DelegateEqual.Resolve (b.loc);
2322                                                 else
2323                                                         throw new NotImplementedException (left.GetSignatureForError ());
2324                                         }
2325
2326                                         method = equal_method;
2327                                 } else {
2328                                         if (inequal_method == null) {
2329                                                 if (left.BuiltinType == BuiltinTypeSpec.Type.String)
2330                                                         inequal_method = ec.Module.PredefinedMembers.StringInequal.Resolve (b.loc);
2331                                                 else if (left.BuiltinType == BuiltinTypeSpec.Type.Delegate)
2332                                                         inequal_method = ec.Module.PredefinedMembers.DelegateInequal.Resolve (b.loc);
2333                                                 else
2334                                                         throw new NotImplementedException (left.GetSignatureForError ());
2335                                         }
2336
2337                                         method = inequal_method;
2338                                 }
2339
2340                                 return new UserOperatorCall (method, args, b.CreateExpressionTree, b.loc);
2341                         }
2342                 }
2343
2344                 class PredefinedPointerOperator : PredefinedOperator
2345                 {
2346                         public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
2347                                 : base (ltype, rtype, op_mask)
2348                         {
2349                         }
2350
2351                         public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
2352                                 : base (ltype, rtype, op_mask, retType)
2353                         {
2354                         }
2355
2356                         public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
2357                                 : base (type, op_mask, return_type)
2358                         {
2359                         }
2360
2361                         public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
2362                         {
2363                                 if (left == null) {
2364                                         if (!lexpr.Type.IsPointer)
2365                                                 return false;
2366                                 } else {
2367                                         if (!Convert.ImplicitConversionExists (ec, lexpr, left))
2368                                                 return false;
2369                                 }
2370
2371                                 if (right == null) {
2372                                         if (!rexpr.Type.IsPointer)
2373                                                 return false;
2374                                 } else {
2375                                         if (!Convert.ImplicitConversionExists (ec, rexpr, right))
2376                                                 return false;
2377                                 }
2378
2379                                 return true;
2380                         }
2381
2382                         public override Expression ConvertResult (ResolveContext ec, Binary b)
2383                         {
2384                                 if (left != null) {
2385                                         b.left = EmptyCast.Create (b.left, left);
2386                                 } else if (right != null) {
2387                                         b.right = EmptyCast.Create (b.right, right);
2388                                 }
2389
2390                                 TypeSpec r_type = ReturnType;
2391                                 Expression left_arg, right_arg;
2392                                 if (r_type == null) {
2393                                         if (left == null) {
2394                                                 left_arg = b.left;
2395                                                 right_arg = b.right;
2396                                                 r_type = b.left.Type;
2397                                         } else {
2398                                                 left_arg = b.right;
2399                                                 right_arg = b.left;
2400                                                 r_type = b.right.Type;
2401                                         }
2402                                 } else {
2403                                         left_arg = b.left;
2404                                         right_arg = b.right;
2405                                 }
2406
2407                                 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
2408                         }
2409                 }
2410
2411                 [Flags]
2412                 public enum Operator {
2413                         Multiply        = 0 | ArithmeticMask,
2414                         Division        = 1 | ArithmeticMask,
2415                         Modulus         = 2 | ArithmeticMask,
2416                         Addition        = 3 | ArithmeticMask | AdditionMask,
2417                         Subtraction = 4 | ArithmeticMask | SubtractionMask,
2418
2419                         LeftShift       = 5 | ShiftMask,
2420                         RightShift      = 6 | ShiftMask,
2421
2422                         LessThan        = 7 | ComparisonMask | RelationalMask,
2423                         GreaterThan     = 8 | ComparisonMask | RelationalMask,
2424                         LessThanOrEqual         = 9 | ComparisonMask | RelationalMask,
2425                         GreaterThanOrEqual      = 10 | ComparisonMask | RelationalMask,
2426                         Equality        = 11 | ComparisonMask | EqualityMask,
2427                         Inequality      = 12 | ComparisonMask | EqualityMask,
2428
2429                         BitwiseAnd      = 13 | BitwiseMask,
2430                         ExclusiveOr     = 14 | BitwiseMask,
2431                         BitwiseOr       = 15 | BitwiseMask,
2432
2433                         LogicalAnd      = 16 | LogicalMask,
2434                         LogicalOr       = 17 | LogicalMask,
2435
2436                         //
2437                         // Operator masks
2438                         //
2439                         ValuesOnlyMask  = ArithmeticMask - 1,
2440                         ArithmeticMask  = 1 << 5,
2441                         ShiftMask               = 1 << 6,
2442                         ComparisonMask  = 1 << 7,
2443                         EqualityMask    = 1 << 8,
2444                         BitwiseMask             = 1 << 9,
2445                         LogicalMask             = 1 << 10,
2446                         AdditionMask    = 1 << 11,
2447                         SubtractionMask = 1 << 12,
2448                         RelationalMask  = 1 << 13,
2449
2450                         DecomposedMask  = 1 << 19,
2451                         NullableMask    = 1 << 20,
2452                 }
2453
2454                 [Flags]
2455                 enum State : byte
2456                 {
2457                         None = 0,
2458                         Compound = 1 << 1,
2459                 }
2460
2461                 readonly Operator oper;
2462                 Expression left, right;
2463                 State state;
2464                 ConvCast.Mode enum_conversion;
2465
2466                 public Binary (Operator oper, Expression left, Expression right, bool isCompound)
2467                         : this (oper, left, right)
2468                 {
2469                         if (isCompound)
2470                                 state |= State.Compound;
2471                 }
2472
2473                 public Binary (Operator oper, Expression left, Expression right)
2474                 {
2475                         this.oper = oper;
2476                         this.left = left;
2477                         this.right = right;
2478                         this.loc = left.Location;
2479                 }
2480
2481                 #region Properties
2482
2483                 public bool IsCompound {
2484                         get {
2485                                 return (state & State.Compound) != 0;
2486                         }
2487                 }
2488
2489                 public Operator Oper {
2490                         get {
2491                                 return oper;
2492                         }
2493                 }
2494
2495                 public Expression Left {
2496                         get {
2497                                 return this.left;
2498                         }
2499                 }
2500
2501                 public Expression Right {
2502                         get {
2503                                 return this.right;
2504                         }
2505                 }
2506
2507                 public override Location StartLocation {
2508                         get {
2509                                 return left.StartLocation;
2510                         }
2511                 }
2512
2513                 #endregion
2514
2515                 /// <summary>
2516                 ///   Returns a stringified representation of the Operator
2517                 /// </summary>
2518                 string OperName (Operator oper)
2519                 {
2520                         string s;
2521                         switch (oper){
2522                         case Operator.Multiply:
2523                                 s = "*";
2524                                 break;
2525                         case Operator.Division:
2526                                 s = "/";
2527                                 break;
2528                         case Operator.Modulus:
2529                                 s = "%";
2530                                 break;
2531                         case Operator.Addition:
2532                                 s = "+";
2533                                 break;
2534                         case Operator.Subtraction:
2535                                 s = "-";
2536                                 break;
2537                         case Operator.LeftShift:
2538                                 s = "<<";
2539                                 break;
2540                         case Operator.RightShift:
2541                                 s = ">>";
2542                                 break;
2543                         case Operator.LessThan:
2544                                 s = "<";
2545                                 break;
2546                         case Operator.GreaterThan:
2547                                 s = ">";
2548                                 break;
2549                         case Operator.LessThanOrEqual:
2550                                 s = "<=";
2551                                 break;
2552                         case Operator.GreaterThanOrEqual:
2553                                 s = ">=";
2554                                 break;
2555                         case Operator.Equality:
2556                                 s = "==";
2557                                 break;
2558                         case Operator.Inequality:
2559                                 s = "!=";
2560                                 break;
2561                         case Operator.BitwiseAnd:
2562                                 s = "&";
2563                                 break;
2564                         case Operator.BitwiseOr:
2565                                 s = "|";
2566                                 break;
2567                         case Operator.ExclusiveOr:
2568                                 s = "^";
2569                                 break;
2570                         case Operator.LogicalOr:
2571                                 s = "||";
2572                                 break;
2573                         case Operator.LogicalAnd:
2574                                 s = "&&";
2575                                 break;
2576                         default:
2577                                 s = oper.ToString ();
2578                                 break;
2579                         }
2580
2581                         if (IsCompound)
2582                                 return s + "=";
2583
2584                         return s;
2585                 }
2586
2587                 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
2588                 {
2589                         new Binary (oper, left, right).Error_OperatorCannotBeApplied (ec, left, right);
2590                 }
2591
2592                 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
2593                 {
2594                         if (left.Type == InternalType.ErrorType || right.Type == InternalType.ErrorType)
2595                                 return;
2596
2597                         string l, r;
2598                         l = left.Type.GetSignatureForError ();
2599                         r = right.Type.GetSignatureForError ();
2600
2601                         ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2602                                 oper, l, r);
2603                 }
2604                 
2605                 void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
2606                 {
2607                         Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
2608                 }
2609
2610                 public override void FlowAnalysis (FlowAnalysisContext fc)
2611                 {
2612                         if ((oper & Operator.LogicalMask) == 0) {
2613                                 var fc_ontrue = fc.DefiniteAssignmentOnTrue;
2614                                 var fc_onfalse = fc.DefiniteAssignmentOnFalse;
2615                                 fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment;
2616                                 left.FlowAnalysis (fc);
2617                                 fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment;
2618                                 right.FlowAnalysis (fc);
2619                                 fc.DefiniteAssignmentOnTrue = fc_ontrue;
2620                                 fc.DefiniteAssignmentOnFalse = fc_onfalse;
2621                                 return;
2622                         }
2623
2624                         //
2625                         // Optimized version when on-true/on-false data are not needed
2626                         //
2627                         bool set_on_true_false;
2628                         if (fc.DefiniteAssignmentOnTrue == null && fc.DefiniteAssignmentOnFalse == null) {
2629                                 fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignment;
2630                                 set_on_true_false = false;
2631                         } else {
2632                                 set_on_true_false = true;
2633                         }
2634
2635                         left.FlowAnalysis (fc);
2636                         var left_fc = fc.DefiniteAssignment;
2637                         var left_fc_ontrue = fc.DefiniteAssignmentOnTrue;
2638                         var left_fc_onfalse = fc.DefiniteAssignmentOnFalse;
2639
2640                         fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (
2641                                 oper == Operator.LogicalOr ? left_fc_onfalse : left_fc_ontrue);
2642                         right.FlowAnalysis (fc);
2643                         fc.DefiniteAssignment = left_fc;
2644
2645                         if (!set_on_true_false) {
2646                                 fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignmentOnTrue = null;
2647                                 return;
2648                         }
2649
2650                         if (oper == Operator.LogicalOr) {
2651                                 fc.DefiniteAssignmentOnTrue = new DefiniteAssignmentBitSet (left_fc_ontrue);
2652                                 fc.DefiniteAssignmentOnFalse = left_fc_onfalse | fc.DefiniteAssignmentOnFalse;
2653                         } else {
2654                                 fc.DefiniteAssignmentOnTrue = left_fc_ontrue | fc.DefiniteAssignmentOnTrue;
2655                                 fc.DefiniteAssignmentOnFalse = new DefiniteAssignmentBitSet (left_fc_onfalse);
2656                         }
2657                 }
2658
2659                 //
2660                 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2661                 //
2662                 string GetOperatorExpressionTypeName ()
2663                 {
2664                         switch (oper) {
2665                         case Operator.Addition:
2666                                 return IsCompound ? "AddAssign" : "Add";
2667                         case Operator.BitwiseAnd:
2668                                 return IsCompound ? "AndAssign" : "And";
2669                         case Operator.BitwiseOr:
2670                                 return IsCompound ? "OrAssign" : "Or";
2671                         case Operator.Division:
2672                                 return IsCompound ? "DivideAssign" : "Divide";
2673                         case Operator.ExclusiveOr:
2674                                 return IsCompound ? "ExclusiveOrAssign" : "ExclusiveOr";
2675                         case Operator.Equality:
2676                                 return "Equal";
2677                         case Operator.GreaterThan:
2678                                 return "GreaterThan";
2679                         case Operator.GreaterThanOrEqual:
2680                                 return "GreaterThanOrEqual";
2681                         case Operator.Inequality:
2682                                 return "NotEqual";
2683                         case Operator.LeftShift:
2684                                 return IsCompound ? "LeftShiftAssign" : "LeftShift";
2685                         case Operator.LessThan:
2686                                 return "LessThan";
2687                         case Operator.LessThanOrEqual:
2688                                 return "LessThanOrEqual";
2689                         case Operator.LogicalAnd:
2690                                 return "And";
2691                         case Operator.LogicalOr:
2692                                 return "Or";
2693                         case Operator.Modulus:
2694                                 return IsCompound ? "ModuloAssign" : "Modulo";
2695                         case Operator.Multiply:
2696                                 return IsCompound ? "MultiplyAssign" : "Multiply";
2697                         case Operator.RightShift:
2698                                 return IsCompound ? "RightShiftAssign" : "RightShift";
2699                         case Operator.Subtraction:
2700                                 return IsCompound ? "SubtractAssign" : "Subtract";
2701                         default:
2702                                 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2703                         }
2704                 }
2705
2706                 static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
2707                 {
2708                         switch (op) {
2709                         case Operator.Addition:
2710                                 return CSharp.Operator.OpType.Addition;
2711                         case Operator.BitwiseAnd:
2712                         case Operator.LogicalAnd:
2713                                 return CSharp.Operator.OpType.BitwiseAnd;
2714                         case Operator.BitwiseOr:
2715                         case Operator.LogicalOr:
2716                                 return CSharp.Operator.OpType.BitwiseOr;
2717                         case Operator.Division:
2718                                 return CSharp.Operator.OpType.Division;
2719                         case Operator.Equality:
2720                                 return CSharp.Operator.OpType.Equality;
2721                         case Operator.ExclusiveOr:
2722                                 return CSharp.Operator.OpType.ExclusiveOr;
2723                         case Operator.GreaterThan:
2724                                 return CSharp.Operator.OpType.GreaterThan;
2725                         case Operator.GreaterThanOrEqual:
2726                                 return CSharp.Operator.OpType.GreaterThanOrEqual;
2727                         case Operator.Inequality:
2728                                 return CSharp.Operator.OpType.Inequality;
2729                         case Operator.LeftShift:
2730                                 return CSharp.Operator.OpType.LeftShift;
2731                         case Operator.LessThan:
2732                                 return CSharp.Operator.OpType.LessThan;
2733                         case Operator.LessThanOrEqual:
2734                                 return CSharp.Operator.OpType.LessThanOrEqual;
2735                         case Operator.Modulus:
2736                                 return CSharp.Operator.OpType.Modulus;
2737                         case Operator.Multiply:
2738                                 return CSharp.Operator.OpType.Multiply;
2739                         case Operator.RightShift:
2740                                 return CSharp.Operator.OpType.RightShift;
2741                         case Operator.Subtraction:
2742                                 return CSharp.Operator.OpType.Subtraction;
2743                         default:
2744                                 throw new InternalErrorException (op.ToString ());
2745                         }
2746                 }
2747
2748                 public override bool ContainsEmitWithAwait ()
2749                 {
2750                         return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
2751                 }
2752
2753                 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l, Expression right)
2754                 {
2755                         OpCode opcode;
2756
2757                         switch (oper){
2758                         case Operator.Multiply:
2759                                 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2760                                         if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
2761                                                 opcode = OpCodes.Mul_Ovf;
2762                                         else if (!IsFloat (l))
2763                                                 opcode = OpCodes.Mul_Ovf_Un;
2764                                         else
2765                                                 opcode = OpCodes.Mul;
2766                                 } else
2767                                         opcode = OpCodes.Mul;
2768                                 
2769                                 break;
2770                                 
2771                         case Operator.Division:
2772                                 if (IsUnsigned (l))
2773                                         opcode = OpCodes.Div_Un;
2774                                 else
2775                                         opcode = OpCodes.Div;
2776                                 break;
2777                                 
2778                         case Operator.Modulus:
2779                                 if (IsUnsigned (l))
2780                                         opcode = OpCodes.Rem_Un;
2781                                 else
2782                                         opcode = OpCodes.Rem;
2783                                 break;
2784
2785                         case Operator.Addition:
2786                                 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2787                                         if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
2788                                                 opcode = OpCodes.Add_Ovf;
2789                                         else if (!IsFloat (l))
2790                                                 opcode = OpCodes.Add_Ovf_Un;
2791                                         else
2792                                                 opcode = OpCodes.Add;
2793                                 } else
2794                                         opcode = OpCodes.Add;
2795                                 break;
2796
2797                         case Operator.Subtraction:
2798                                 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2799                                         if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
2800                                                 opcode = OpCodes.Sub_Ovf;
2801                                         else if (!IsFloat (l))
2802                                                 opcode = OpCodes.Sub_Ovf_Un;
2803                                         else
2804                                                 opcode = OpCodes.Sub;
2805                                 } else
2806                                         opcode = OpCodes.Sub;
2807                                 break;
2808
2809                         case Operator.RightShift:
2810                                 if (!(right is IntConstant)) {
2811                                         ec.EmitInt (GetShiftMask (l));
2812                                         ec.Emit (OpCodes.And);
2813                                 }
2814
2815                                 if (IsUnsigned (l))
2816                                         opcode = OpCodes.Shr_Un;
2817                                 else
2818                                         opcode = OpCodes.Shr;
2819                                 break;
2820                                 
2821                         case Operator.LeftShift:
2822                                 if (!(right is IntConstant)) {
2823                                         ec.EmitInt (GetShiftMask (l));
2824                                         ec.Emit (OpCodes.And);
2825                                 }
2826
2827                                 opcode = OpCodes.Shl;
2828                                 break;
2829
2830                         case Operator.Equality:
2831                                 opcode = OpCodes.Ceq;
2832                                 break;
2833
2834                         case Operator.Inequality:
2835                                 ec.Emit (OpCodes.Ceq);
2836                                 ec.EmitInt (0);
2837                                 
2838                                 opcode = OpCodes.Ceq;
2839                                 break;
2840
2841                         case Operator.LessThan:
2842                                 if (IsUnsigned (l))
2843                                         opcode = OpCodes.Clt_Un;
2844                                 else
2845                                         opcode = OpCodes.Clt;
2846                                 break;
2847
2848                         case Operator.GreaterThan:
2849                                 if (IsUnsigned (l))
2850                                         opcode = OpCodes.Cgt_Un;
2851                                 else
2852                                         opcode = OpCodes.Cgt;
2853                                 break;
2854
2855                         case Operator.LessThanOrEqual:
2856                                 if (IsUnsigned (l) || IsFloat (l))
2857                                         ec.Emit (OpCodes.Cgt_Un);
2858                                 else
2859                                         ec.Emit (OpCodes.Cgt);
2860                                 ec.EmitInt (0);
2861                                 
2862                                 opcode = OpCodes.Ceq;
2863                                 break;
2864
2865                         case Operator.GreaterThanOrEqual:
2866                                 if (IsUnsigned (l) || IsFloat (l))
2867                                         ec.Emit (OpCodes.Clt_Un);
2868                                 else
2869                                         ec.Emit (OpCodes.Clt);
2870                                 
2871                                 ec.EmitInt (0);
2872                                 
2873                                 opcode = OpCodes.Ceq;
2874                                 break;
2875
2876                         case Operator.BitwiseOr:
2877                                 opcode = OpCodes.Or;
2878                                 break;
2879
2880                         case Operator.BitwiseAnd:
2881                                 opcode = OpCodes.And;
2882                                 break;
2883
2884                         case Operator.ExclusiveOr:
2885                                 opcode = OpCodes.Xor;
2886                                 break;
2887
2888                         default:
2889                                 throw new InternalErrorException (oper.ToString ());
2890                         }
2891
2892                         ec.Emit (opcode);
2893                 }
2894
2895                 static int GetShiftMask (TypeSpec type)
2896                 {
2897                         return type.BuiltinType == BuiltinTypeSpec.Type.Int || type.BuiltinType == BuiltinTypeSpec.Type.UInt ? 0x1f : 0x3f;
2898                 }
2899
2900                 static bool IsUnsigned (TypeSpec t)
2901                 {
2902                         switch (t.BuiltinType) {
2903                         case BuiltinTypeSpec.Type.Char:
2904                         case BuiltinTypeSpec.Type.UInt:
2905                         case BuiltinTypeSpec.Type.ULong:
2906                         case BuiltinTypeSpec.Type.UShort:
2907                         case BuiltinTypeSpec.Type.Byte:
2908                                 return true;
2909                         }
2910
2911                         return t.IsPointer;
2912                 }
2913
2914                 static bool IsFloat (TypeSpec t)
2915                 {
2916                         return t.BuiltinType == BuiltinTypeSpec.Type.Float || t.BuiltinType == BuiltinTypeSpec.Type.Double;
2917                 }
2918
2919                 public Expression ResolveOperator (ResolveContext rc)
2920                 {
2921                         eclass = ExprClass.Value;
2922
2923                         TypeSpec l = left.Type;
2924                         TypeSpec r = right.Type;
2925                         Expression expr;
2926                         bool primitives_only = false;
2927
2928                         //
2929                         // Handles predefined primitive types
2930                         //
2931                         if ((BuiltinTypeSpec.IsPrimitiveType (l) || (l.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (Nullable.NullableInfo.GetUnderlyingType (l)))) &&
2932                                 (BuiltinTypeSpec.IsPrimitiveType (r) || (r.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (Nullable.NullableInfo.GetUnderlyingType (r))))) {
2933                                 if ((oper & Operator.ShiftMask) == 0) {
2934                                         if (!DoBinaryOperatorPromotion (rc))
2935                                                 return null;
2936
2937                                         primitives_only = BuiltinTypeSpec.IsPrimitiveType (l) && BuiltinTypeSpec.IsPrimitiveType (r);
2938                                 }
2939                         } else {
2940                                 // Pointers
2941                                 if (l.IsPointer || r.IsPointer)
2942                                         return ResolveOperatorPointer (rc, l, r);
2943
2944                                 // User operators
2945                                 expr = ResolveUserOperator (rc, left, right);
2946                                 if (expr != null)
2947                                         return expr;
2948
2949
2950                                 bool lenum = l.IsEnum;
2951                                 bool renum = r.IsEnum;
2952                                 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
2953                                         //
2954                                         // Enumerations
2955                                         //
2956                                         if (IsEnumOrNullableEnum (l) || IsEnumOrNullableEnum (r)) {
2957                                                 expr = ResolveSingleEnumOperators (rc, lenum, renum, l, r);
2958
2959                                                 if (expr == null)
2960                                                         return null;
2961
2962                                                 if ((oper & Operator.BitwiseMask) != 0) {
2963                                                         expr = EmptyCast.Create (expr, type);
2964                                                         AddEnumResultCast (type);
2965
2966                                                         if (oper == Operator.BitwiseAnd && left.Type.IsEnum && right.Type.IsEnum) {
2967                                                                 expr = OptimizeAndOperation (expr);
2968                                                         }
2969                                                 }
2970
2971                                                 left = ConvertEnumOperandToUnderlyingType (rc, left, r.IsNullableType);
2972                                                 right = ConvertEnumOperandToUnderlyingType (rc, right, l.IsNullableType);
2973                                                 return expr;
2974                                         }
2975                                 } else if ((oper == Operator.Addition || oper == Operator.Subtraction)) {
2976                                         if (IsEnumOrNullableEnum (l) || IsEnumOrNullableEnum (r)) {
2977                                                 //
2978                                                 // Enumerations
2979                                                 //
2980                                                 expr = ResolveEnumOperators (rc, lenum, renum, l, r);
2981
2982                                                 //
2983                                                 // We cannot break here there is also Enum + String possible match
2984                                                 // which is not ambiguous with predefined enum operators
2985                                                 //
2986                                                 if (expr != null) {
2987                                                         left = ConvertEnumOperandToUnderlyingType (rc, left, false);
2988                                                         right = ConvertEnumOperandToUnderlyingType (rc, right, false);
2989
2990                                                         return expr;
2991                                                 }
2992                                         } else if (l.IsDelegate || r.IsDelegate) {
2993                                                 //
2994                                                 // Delegates
2995                                                 //
2996                                                 expr = ResolveOperatorDelegate (rc, l, r);
2997
2998                                                 // TODO: Can this be ambiguous
2999                                                 if (expr != null)
3000                                                         return expr;
3001                                         }
3002                                 }
3003                         }
3004                         
3005                         //
3006                         // Equality operators are more complicated
3007                         //
3008                         if ((oper & Operator.EqualityMask) != 0) {
3009                                 return ResolveEquality (rc, l, r, primitives_only);
3010                         }
3011
3012                         expr = ResolveOperatorPredefined (rc, rc.BuiltinTypes.OperatorsBinaryStandard, primitives_only);
3013                         if (expr != null)
3014                                 return expr;
3015
3016                         if (primitives_only)
3017                                 return null;
3018
3019                         //
3020                         // Lifted operators have lower priority
3021                         //
3022                         return ResolveOperatorPredefined (rc, rc.Module.OperatorsBinaryLifted, false);
3023                 }
3024
3025                 static bool IsEnumOrNullableEnum (TypeSpec type)
3026                 {
3027                         return type.IsEnum || (type.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (type).IsEnum);
3028                 }
3029
3030
3031                 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
3032                 // if 'left' is not an enumeration constant, create one from the type of 'right'
3033                 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right)
3034                 {
3035                         switch (oper) {
3036                         case Operator.BitwiseOr:
3037                         case Operator.BitwiseAnd:
3038                         case Operator.ExclusiveOr:
3039                         case Operator.Equality:
3040                         case Operator.Inequality:
3041                         case Operator.LessThan:
3042                         case Operator.LessThanOrEqual:
3043                         case Operator.GreaterThan:
3044                         case Operator.GreaterThanOrEqual:
3045                                 if (left.Type.IsEnum)
3046                                         return left;
3047                                 
3048                                 if (left.IsZeroInteger)
3049                                         return left.Reduce (ec, right.Type);
3050                                 
3051                                 break;
3052                                 
3053                         case Operator.Addition:
3054                         case Operator.Subtraction:
3055                                 return left;
3056                                 
3057                         case Operator.Multiply:
3058                         case Operator.Division:
3059                         case Operator.Modulus:
3060                         case Operator.LeftShift:
3061                         case Operator.RightShift:
3062                                 if (right.Type.IsEnum || left.Type.IsEnum)
3063                                         break;
3064                                 return left;
3065                         }
3066
3067                         return null;
3068                 }
3069
3070                 //
3071                 // The `|' operator used on types which were extended is dangerous
3072                 //
3073                 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
3074                 {
3075                         OpcodeCast lcast = left as OpcodeCast;
3076                         if (lcast != null) {
3077                                 if (IsUnsigned (lcast.UnderlyingType))
3078                                         lcast = null;
3079                         }
3080
3081                         OpcodeCast rcast = right as OpcodeCast;
3082                         if (rcast != null) {
3083                                 if (IsUnsigned (rcast.UnderlyingType))
3084                                         rcast = null;
3085                         }
3086
3087                         if (lcast == null && rcast == null)
3088                                 return;
3089
3090                         // FIXME: consider constants
3091
3092                         var ltype = lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType;
3093                         ec.Report.Warning (675, 3, loc,
3094                                 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
3095                                 ltype.GetSignatureForError ());
3096                 }
3097
3098                 public static PredefinedOperator[] CreatePointerOperatorsTable (BuiltinTypes types)
3099                 {
3100                         return new PredefinedOperator[] {
3101                                 //
3102                                 // Pointer arithmetic:
3103                                 //
3104                                 // T* operator + (T* x, int y);         T* operator - (T* x, int y);
3105                                 // T* operator + (T* x, uint y);        T* operator - (T* x, uint y);
3106                                 // T* operator + (T* x, long y);        T* operator - (T* x, long y);
3107                                 // T* operator + (T* x, ulong y);       T* operator - (T* x, ulong y);
3108                                 //
3109                                 new PredefinedPointerOperator (null, types.Int, Operator.AdditionMask | Operator.SubtractionMask),
3110                                 new PredefinedPointerOperator (null, types.UInt, Operator.AdditionMask | Operator.SubtractionMask),
3111                                 new PredefinedPointerOperator (null, types.Long, Operator.AdditionMask | Operator.SubtractionMask),
3112                                 new PredefinedPointerOperator (null, types.ULong, Operator.AdditionMask | Operator.SubtractionMask),
3113
3114                                 //
3115                                 // T* operator + (int y,   T* x);
3116                                 // T* operator + (uint y,  T *x);
3117                                 // T* operator + (long y,  T *x);
3118                                 // T* operator + (ulong y, T *x);
3119                                 //
3120                                 new PredefinedPointerOperator (types.Int, null, Operator.AdditionMask, null),
3121                                 new PredefinedPointerOperator (types.UInt, null, Operator.AdditionMask, null),
3122                                 new PredefinedPointerOperator (types.Long, null, Operator.AdditionMask, null),
3123                                 new PredefinedPointerOperator (types.ULong, null, Operator.AdditionMask, null),
3124
3125                                 //
3126                                 // long operator - (T* x, T *y)
3127                                 //
3128                                 new PredefinedPointerOperator (null, Operator.SubtractionMask, types.Long)
3129                         };
3130                 }
3131
3132                 public static PredefinedOperator[] CreateStandardOperatorsTable (BuiltinTypes types)
3133                 {
3134                         TypeSpec bool_type = types.Bool;
3135
3136                         return new [] {
3137                                 new PredefinedOperator (types.Int, Operator.ArithmeticMask | Operator.BitwiseMask | Operator.ShiftMask),
3138                                 new PredefinedOperator (types.UInt, Operator.ArithmeticMask | Operator.BitwiseMask),
3139                                 new PredefinedOperator (types.Long, Operator.ArithmeticMask | Operator.BitwiseMask),
3140                                 new PredefinedOperator (types.ULong, Operator.ArithmeticMask | Operator.BitwiseMask),
3141                                 new PredefinedOperator (types.Float, Operator.ArithmeticMask),
3142                                 new PredefinedOperator (types.Double, Operator.ArithmeticMask),
3143                                 new PredefinedOperator (types.Decimal, Operator.ArithmeticMask),
3144
3145                                 new PredefinedOperator (types.Int, Operator.ComparisonMask, bool_type),
3146                                 new PredefinedOperator (types.UInt, Operator.ComparisonMask, bool_type),
3147                                 new PredefinedOperator (types.Long, Operator.ComparisonMask, bool_type),
3148                                 new PredefinedOperator (types.ULong, Operator.ComparisonMask, bool_type),
3149                                 new PredefinedOperator (types.Float, Operator.ComparisonMask, bool_type),
3150                                 new PredefinedOperator (types.Double, Operator.ComparisonMask, bool_type),
3151                                 new PredefinedOperator (types.Decimal, Operator.ComparisonMask, bool_type),
3152
3153                                 new PredefinedStringOperator (types.String, Operator.AdditionMask, types.String),
3154                                 // Remaining string operators are in lifted tables
3155
3156                                 new PredefinedOperator (bool_type, Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type),
3157
3158                                 new PredefinedOperator (types.UInt, types.Int, Operator.ShiftMask),
3159                                 new PredefinedOperator (types.Long, types.Int, Operator.ShiftMask),
3160                                 new PredefinedOperator (types.ULong, types.Int, Operator.ShiftMask)
3161                         };
3162
3163                 }
3164                 public static PredefinedOperator[] CreateStandardLiftedOperatorsTable (ModuleContainer module)
3165                 {
3166                         var nullable = module.PredefinedTypes.Nullable.TypeSpec;
3167                         if (nullable == null)
3168                                 return new PredefinedOperator [0];
3169
3170                         var types = module.Compiler.BuiltinTypes;
3171                         var bool_type = types.Bool;
3172
3173                         var nullable_bool = nullable.MakeGenericType (module, new[] { bool_type });
3174                         var nullable_int = nullable.MakeGenericType (module, new[] { types.Int });
3175                         var nullable_uint = nullable.MakeGenericType (module, new[] { types.UInt });
3176                         var nullable_long = nullable.MakeGenericType (module, new[] { types.Long });
3177                         var nullable_ulong = nullable.MakeGenericType (module, new[] { types.ULong });
3178                         var nullable_float = nullable.MakeGenericType (module, new[] { types.Float });
3179                         var nullable_double = nullable.MakeGenericType (module, new[] { types.Double });
3180                         var nullable_decimal = nullable.MakeGenericType (module, new[] { types.Decimal });
3181
3182                         return new[] {
3183                                 new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask | Operator.ShiftMask),
3184                                 new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
3185                                 new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
3186                                 new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
3187                                 new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.ArithmeticMask),
3188                                 new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.ArithmeticMask),
3189                                 new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.ArithmeticMask),
3190
3191                                 new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3192                                 new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3193                                 new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3194                                 new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3195                                 new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3196                                 new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3197                                 new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3198
3199                                 new PredefinedOperator (nullable_bool, Operator.NullableMask | Operator.BitwiseMask, nullable_bool),
3200
3201                                 new PredefinedOperator (nullable_uint, nullable_int, Operator.NullableMask | Operator.ShiftMask),
3202                                 new PredefinedOperator (nullable_long, nullable_int, Operator.NullableMask | Operator.ShiftMask),
3203                                 new PredefinedOperator (nullable_ulong, nullable_int, Operator.NullableMask | Operator.ShiftMask),
3204
3205                                 //
3206                                 // Not strictly lifted but need to be in second group otherwise expressions like
3207                                 // int + null would resolve to +(object, string) instead of +(int?, int?)
3208                                 //
3209                                 new PredefinedStringOperator (types.String, types.Object, Operator.AdditionMask, types.String),
3210                                 new PredefinedStringOperator (types.Object, types.String, Operator.AdditionMask, types.String),
3211
3212                         };
3213                 }
3214
3215                 public static PredefinedOperator[] CreateEqualityOperatorsTable (BuiltinTypes types)
3216                 {
3217                         TypeSpec bool_type = types.Bool;
3218
3219                         return new[] {
3220                                 new PredefinedEqualityOperator (types.String, bool_type),
3221                                 new PredefinedEqualityOperator (types.Delegate, bool_type),
3222                                 new PredefinedOperator (bool_type, Operator.EqualityMask, bool_type),
3223                                 new PredefinedOperator (types.Int, Operator.EqualityMask, bool_type),
3224                                 new PredefinedOperator (types.UInt, Operator.EqualityMask, bool_type),
3225                                 new PredefinedOperator (types.Long, Operator.EqualityMask, bool_type),
3226                                 new PredefinedOperator (types.ULong, Operator.EqualityMask, bool_type),
3227                                 new PredefinedOperator (types.Float, Operator.EqualityMask, bool_type),
3228                                 new PredefinedOperator (types.Double, Operator.EqualityMask, bool_type),
3229                                 new PredefinedOperator (types.Decimal, Operator.EqualityMask, bool_type),
3230                         };
3231                 }
3232
3233                 public static PredefinedOperator[] CreateEqualityLiftedOperatorsTable (ModuleContainer module)
3234                 {
3235                         var nullable = module.PredefinedTypes.Nullable.TypeSpec;
3236
3237                         if (nullable == null)
3238                                 return new PredefinedOperator [0];
3239
3240                         var types = module.Compiler.BuiltinTypes;
3241                         var bool_type = types.Bool;
3242                         var nullable_bool = nullable.MakeGenericType (module, new [] { bool_type });
3243                         var nullable_int = nullable.MakeGenericType (module, new[] { types.Int });
3244                         var nullable_uint = nullable.MakeGenericType (module, new[] { types.UInt });
3245                         var nullable_long = nullable.MakeGenericType (module, new[] { types.Long });
3246                         var nullable_ulong = nullable.MakeGenericType (module, new[] { types.ULong });
3247                         var nullable_float = nullable.MakeGenericType (module, new[] { types.Float });
3248                         var nullable_double = nullable.MakeGenericType (module, new[] { types.Double });
3249                         var nullable_decimal = nullable.MakeGenericType (module, new[] { types.Decimal });
3250
3251                         return new [] {
3252                                 new PredefinedOperator (nullable_bool, Operator.NullableMask | Operator.EqualityMask, bool_type),
3253                                 new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.EqualityMask, bool_type),
3254                                 new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.EqualityMask, bool_type),
3255                                 new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.EqualityMask, bool_type),
3256                                 new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.EqualityMask, bool_type),
3257                                 new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.EqualityMask, bool_type),
3258                                 new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.EqualityMask, bool_type),
3259                                 new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.EqualityMask, bool_type)
3260                         };
3261                 }
3262
3263                 //
3264                 // 7.2.6.2 Binary numeric promotions
3265                 //
3266                 bool DoBinaryOperatorPromotion (ResolveContext rc)
3267                 {
3268                         TypeSpec ltype = left.Type;
3269                         if (ltype.IsNullableType) {
3270                                 ltype = Nullable.NullableInfo.GetUnderlyingType (ltype);
3271                         }
3272
3273                         //
3274                         // This is numeric promotion code only
3275                         //
3276                         if (ltype.BuiltinType == BuiltinTypeSpec.Type.Bool)
3277                                 return true;
3278
3279                         TypeSpec rtype = right.Type;
3280                         if (rtype.IsNullableType) {
3281                                 rtype = Nullable.NullableInfo.GetUnderlyingType (rtype);
3282                         }
3283
3284                         var lb = ltype.BuiltinType;
3285                         var rb = rtype.BuiltinType;
3286                         TypeSpec type;
3287                         Expression expr;
3288
3289                         if (lb == BuiltinTypeSpec.Type.Decimal || rb == BuiltinTypeSpec.Type.Decimal) {
3290                                 type = rc.BuiltinTypes.Decimal;
3291                         } else if (lb == BuiltinTypeSpec.Type.Double || rb == BuiltinTypeSpec.Type.Double) {
3292                                 type = rc.BuiltinTypes.Double;
3293                         } else if (lb == BuiltinTypeSpec.Type.Float || rb == BuiltinTypeSpec.Type.Float) {
3294                                 type = rc.BuiltinTypes.Float;
3295                         } else if (lb == BuiltinTypeSpec.Type.ULong || rb == BuiltinTypeSpec.Type.ULong) {
3296                                 type = rc.BuiltinTypes.ULong;
3297
3298                                 if (IsSignedType (lb)) {
3299                                         expr = ConvertSignedConstant (left, type);
3300                                         if (expr == null)
3301                                                 return false;
3302                                         left = expr;
3303                                 } else if (IsSignedType (rb)) {
3304                                         expr = ConvertSignedConstant (right, type);
3305                                         if (expr == null)
3306                                                 return false;
3307                                         right = expr;
3308                                 }
3309
3310                         } else if (lb == BuiltinTypeSpec.Type.Long || rb == BuiltinTypeSpec.Type.Long) {
3311                                 type = rc.BuiltinTypes.Long;
3312                         } else if (lb == BuiltinTypeSpec.Type.UInt || rb == BuiltinTypeSpec.Type.UInt) {
3313                                 type = rc.BuiltinTypes.UInt;
3314
3315                                 if (IsSignedType (lb)) {
3316                                         expr = ConvertSignedConstant (left, type);
3317                                         if (expr == null)
3318                                                 type = rc.BuiltinTypes.Long;
3319                                 } else if (IsSignedType (rb)) {
3320                                         expr = ConvertSignedConstant (right, type);
3321                                         if (expr == null)
3322                                                 type = rc.BuiltinTypes.Long;
3323                                 }
3324                         } else {
3325                                 type = rc.BuiltinTypes.Int;
3326                         }
3327
3328                         if (ltype != type) {
3329                                 expr = PromoteExpression (rc, left, type);
3330                                 if (expr == null)
3331                                         return false;
3332
3333                                 left = expr;
3334                         }
3335
3336                         if (rtype != type) {
3337                                 expr = PromoteExpression (rc, right, type);
3338                                 if (expr == null)
3339                                         return false;
3340
3341                                 right = expr;
3342                         }
3343
3344                         return true;
3345                 }
3346
3347                 static bool IsSignedType (BuiltinTypeSpec.Type type)
3348                 {
3349                         switch (type) {
3350                         case BuiltinTypeSpec.Type.Int:
3351                         case BuiltinTypeSpec.Type.Short:
3352                         case BuiltinTypeSpec.Type.SByte:
3353                         case BuiltinTypeSpec.Type.Long:
3354                                 return true;
3355                         default:
3356                                 return false;
3357                         }
3358                 }
3359
3360                 static Expression ConvertSignedConstant (Expression expr, TypeSpec type)
3361                 {
3362                         var c = expr as Constant;
3363                         if (c == null)
3364                                 return null;
3365
3366                         return c.ConvertImplicitly (type);
3367                 }
3368
3369                 static Expression PromoteExpression (ResolveContext rc, Expression expr, TypeSpec type)
3370                 {
3371                         if (expr.Type.IsNullableType) {
3372                                 return Convert.ImplicitConversionStandard (rc, expr,
3373                                         rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc, new[] { type }), expr.Location);
3374                         }
3375
3376                         var c = expr as Constant;
3377                         if (c != null)
3378                                 return c.ConvertImplicitly (type);
3379
3380                         return Convert.ImplicitNumericConversion (expr, type);
3381                 }
3382
3383                 protected override Expression DoResolve (ResolveContext ec)
3384                 {
3385                         if (left == null)
3386                                 return null;
3387
3388                         if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
3389                                 left = ((ParenthesizedExpression) left).Expr;
3390                                 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
3391                                 if (left == null)
3392                                         return null;
3393
3394                                 if (left.eclass == ExprClass.Type) {
3395                                         ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
3396                                         return null;
3397                                 }
3398                         } else
3399                                 left = left.Resolve (ec);
3400
3401                         if (left == null)
3402                                 return null;
3403
3404                         right = right.Resolve (ec);
3405                         if (right == null)
3406                                 return null;
3407
3408                         Constant lc = left as Constant;
3409                         Constant rc = right as Constant;
3410
3411                         // The conversion rules are ignored in enum context but why
3412                         if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (left.Type.IsEnum || right.Type.IsEnum)) {
3413                                 lc = EnumLiftUp (ec, lc, rc);
3414                                 if (lc != null)
3415                                         rc = EnumLiftUp (ec, rc, lc);
3416                         }
3417
3418                         if (rc != null && lc != null) {
3419                                 int prev_e = ec.Report.Errors;
3420                                 Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
3421                                 if (e != null || ec.Report.Errors != prev_e)
3422                                         return e;
3423                         }
3424
3425                         // Comparison warnings
3426                         if ((oper & Operator.ComparisonMask) != 0) {
3427                                 if (left.Equals (right)) {
3428                                         ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
3429                                 }
3430                                 CheckOutOfRangeComparison (ec, lc, right.Type);
3431                                 CheckOutOfRangeComparison (ec, rc, left.Type);
3432                         }
3433
3434                         if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic || right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3435                                 return DoResolveDynamic (ec);
3436
3437                         return DoResolveCore (ec, left, right);
3438                 }
3439
3440                 Expression DoResolveDynamic (ResolveContext rc)
3441                 {
3442                         var lt = left.Type;
3443                         var rt = right.Type;
3444                         if (lt.Kind == MemberKind.Void || lt == InternalType.MethodGroup || lt == InternalType.AnonymousMethod ||
3445                                 rt.Kind == MemberKind.Void || rt == InternalType.MethodGroup || rt == InternalType.AnonymousMethod) {
3446                                 Error_OperatorCannotBeApplied (rc, left, right);
3447                                 return null;
3448                         }
3449
3450                         Arguments args;
3451
3452                         //
3453                         // Special handling for logical boolean operators which require rhs not to be
3454                         // evaluated based on lhs value
3455                         //
3456                         if ((oper & Operator.LogicalMask) != 0) {
3457                                 Expression cond_left, cond_right, expr;
3458
3459                                 args = new Arguments (2);
3460
3461                                 if (lt.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3462                                         LocalVariable temp = LocalVariable.CreateCompilerGenerated (lt, rc.CurrentBlock, loc);
3463
3464                                         var cond_args = new Arguments (1);
3465                                         cond_args.Add (new Argument (new SimpleAssign (temp.CreateReferenceExpression (rc, loc), left).Resolve (rc)));
3466
3467                                         //
3468                                         // dynamic && bool => IsFalse (temp = left) ? temp : temp && right;
3469                                         // dynamic || bool => IsTrue (temp = left) ? temp : temp || right;
3470                                         //
3471                                         left = temp.CreateReferenceExpression (rc, loc);
3472                                         if (oper == Operator.LogicalAnd) {
3473                                                 expr = DynamicUnaryConversion.CreateIsFalse (rc, cond_args, loc);
3474                                                 cond_left = left;
3475                                         } else {
3476                                                 expr = DynamicUnaryConversion.CreateIsTrue (rc, cond_args, loc);
3477                                                 cond_left = left;
3478                                         }
3479
3480                                         args.Add (new Argument (left));
3481                                         args.Add (new Argument (right));
3482                                         cond_right = new DynamicExpressionStatement (this, args, loc);
3483                                 } else {
3484                                         LocalVariable temp = LocalVariable.CreateCompilerGenerated (rc.BuiltinTypes.Bool, rc.CurrentBlock, loc);
3485
3486                                         args.Add (new Argument (temp.CreateReferenceExpression (rc, loc).Resolve (rc)));
3487                                         args.Add (new Argument (right));
3488                                         right = new DynamicExpressionStatement (this, args, loc);
3489
3490                                         //
3491                                         // bool && dynamic => (temp = left) ? temp && right : temp;
3492                                         // bool || dynamic => (temp = left) ? temp : temp || right;
3493                                         //
3494                                         if (oper == Operator.LogicalAnd) {
3495                                                 cond_left = right;
3496                                                 cond_right = temp.CreateReferenceExpression (rc, loc);
3497                                         } else {
3498                                                 cond_left = temp.CreateReferenceExpression (rc, loc);
3499                                                 cond_right = right;
3500                                         }
3501
3502                                         expr = new BooleanExpression (new SimpleAssign (temp.CreateReferenceExpression (rc, loc), left));
3503                                 }
3504
3505                                 return new Conditional (expr, cond_left, cond_right, loc).Resolve (rc);
3506                         }
3507
3508                         args = new Arguments (2);
3509                         args.Add (new Argument (left));
3510                         args.Add (new Argument (right));
3511                         return new DynamicExpressionStatement (this, args, loc).Resolve (rc);
3512                 }
3513
3514                 Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
3515                 {
3516                         Expression expr = ResolveOperator (ec);
3517                         if (expr == null)
3518                                 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
3519
3520                         if (left == null || right == null)
3521                                 throw new InternalErrorException ("Invalid conversion");
3522
3523                         if (oper == Operator.BitwiseOr)
3524                                 CheckBitwiseOrOnSignExtended (ec);
3525
3526                         return expr;
3527                 }
3528
3529                 public override SLE.Expression MakeExpression (BuilderContext ctx)
3530                 {
3531                         return MakeExpression (ctx, left, right);
3532                 }
3533
3534                 public SLE.Expression MakeExpression (BuilderContext ctx, Expression left, Expression right)
3535                 {
3536                         var le = left.MakeExpression (ctx);
3537                         var re = right.MakeExpression (ctx);
3538                         bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
3539
3540                         switch (oper) {
3541                         case Operator.Addition:
3542                                 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
3543                         case Operator.BitwiseAnd:
3544                                 return SLE.Expression.And (le, re);
3545                         case Operator.BitwiseOr:
3546                                 return SLE.Expression.Or (le, re);
3547                         case Operator.Division:
3548                                 return SLE.Expression.Divide (le, re);
3549                         case Operator.Equality:
3550                                 return SLE.Expression.Equal (le, re);
3551                         case Operator.ExclusiveOr:
3552                                 return SLE.Expression.ExclusiveOr (le, re);
3553                         case Operator.GreaterThan:
3554                                 return SLE.Expression.GreaterThan (le, re);
3555                         case Operator.GreaterThanOrEqual:
3556                                 return SLE.Expression.GreaterThanOrEqual (le, re);
3557                         case Operator.Inequality:
3558                                 return SLE.Expression.NotEqual (le, re);
3559                         case Operator.LeftShift:
3560                                 return SLE.Expression.LeftShift (le, re);
3561                         case Operator.LessThan:
3562                                 return SLE.Expression.LessThan (le, re);
3563                         case Operator.LessThanOrEqual:
3564                                 return SLE.Expression.LessThanOrEqual (le, re);
3565                         case Operator.LogicalAnd:
3566                                 return SLE.Expression.AndAlso (le, re);
3567                         case Operator.LogicalOr:
3568                                 return SLE.Expression.OrElse (le, re);
3569                         case Operator.Modulus:
3570                                 return SLE.Expression.Modulo (le, re);
3571                         case Operator.Multiply:
3572                                 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
3573                         case Operator.RightShift:
3574                                 return SLE.Expression.RightShift (le, re);
3575                         case Operator.Subtraction:
3576                                 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
3577                         default:
3578                                 throw new NotImplementedException (oper.ToString ());
3579                         }
3580                 }
3581
3582                 //
3583                 // D operator + (D x, D y)
3584                 // D operator - (D x, D y)
3585                 //
3586                 Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
3587                 {
3588                         if (l != r && !TypeSpecComparer.Variant.IsEqual (r, l)) {
3589                                 Expression tmp;
3590                                 if (right.eclass == ExprClass.MethodGroup || r == InternalType.AnonymousMethod || r == InternalType.NullLiteral) {
3591                                         tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
3592                                         if (tmp == null)
3593                                                 return null;
3594                                         right = tmp;
3595                                         r = right.Type;
3596                                 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod || l == InternalType.NullLiteral)) {
3597                                         tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
3598                                         if (tmp == null)
3599                                                 return null;
3600                                         left = tmp;
3601                                         l = left.Type;
3602                                 } else {
3603                                         return null;
3604                                 }
3605                         }
3606
3607                         MethodSpec method = null;
3608                         Arguments args = new Arguments (2);
3609                         args.Add (new Argument (left));
3610                         args.Add (new Argument (right));
3611
3612                         if (oper == Operator.Addition) {
3613                                 method = ec.Module.PredefinedMembers.DelegateCombine.Resolve (loc);
3614                         } else if (oper == Operator.Subtraction) {
3615                                 method = ec.Module.PredefinedMembers.DelegateRemove.Resolve (loc);
3616                         }
3617
3618                         if (method == null)
3619                                 return new EmptyExpression (ec.BuiltinTypes.Decimal);
3620
3621                         Expression expr = new UserOperatorCall (method, args, CreateExpressionTree, loc);
3622                         return new ClassCast (expr, l);
3623                 }
3624
3625                 //
3626                 // Resolves enumeration operators where only single predefined overload exists, handles lifted versions too
3627                 //
3628                 Expression ResolveSingleEnumOperators (ResolveContext rc, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
3629                 {
3630                         //
3631                         // bool operator == (E x, E y);
3632                         // bool operator != (E x, E y);
3633                         // bool operator < (E x, E y);
3634                         // bool operator > (E x, E y);
3635                         // bool operator <= (E x, E y);
3636                         // bool operator >= (E x, E y);
3637                         //
3638                         // E operator & (E x, E y);
3639                         // E operator | (E x, E y);
3640                         // E operator ^ (E x, E y);
3641                         //
3642                         Expression expr;
3643                         if ((oper & Operator.ComparisonMask) != 0) {
3644                                 type = rc.BuiltinTypes.Bool;
3645                         } else {
3646                                 if (lenum)
3647                                         type = ltype;
3648                                 else if (renum)
3649                                         type = rtype;
3650                                 else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum)
3651                                         type = ltype;
3652                                 else
3653                                         type = rtype;
3654                         }
3655
3656                         if (ltype == rtype) {
3657                                 if (lenum || renum)
3658                                         return this;
3659
3660                                 var lifted = new Nullable.LiftedBinaryOperator (this);
3661                                 lifted.Left = left;
3662                                 lifted.Right = right;
3663                                 return lifted.Resolve (rc);
3664                         }
3665
3666                         if (renum && !ltype.IsNullableType) {
3667                                 expr = Convert.ImplicitConversion (rc, left, rtype, loc);
3668                                 if (expr != null) {
3669                                         left = expr;
3670                                         return this;
3671                                 }
3672                         } else if (lenum && !rtype.IsNullableType) {
3673                                 expr = Convert.ImplicitConversion (rc, right, ltype, loc);
3674                                 if (expr != null) {
3675                                         right = expr;
3676                                         return this;
3677                                 }
3678                         }
3679
3680                         //
3681                         // Now try lifted version of predefined operator
3682                         //
3683                         var nullable_type = rc.Module.PredefinedTypes.Nullable.TypeSpec;
3684                         if (nullable_type != null) {
3685                                 if (renum && !ltype.IsNullableType) {
3686                                         var lifted_type = nullable_type.MakeGenericType (rc.Module, new[] { rtype });
3687
3688                                         expr = Convert.ImplicitConversion (rc, left, lifted_type, loc);
3689                                         if (expr != null) {
3690                                                 left = expr;
3691                                                 right = Convert.ImplicitConversion (rc, right, lifted_type, loc);
3692                                         }
3693
3694                                         if ((oper & Operator.BitwiseMask) != 0)
3695                                                 type = lifted_type;
3696
3697                                         if (left.IsNull) {
3698                                                 if ((oper & Operator.BitwiseMask) != 0)
3699                                                         return Nullable.LiftedNull.CreateFromExpression (rc, this);
3700
3701                                                 return CreateLiftedValueTypeResult (rc, rtype);
3702                                         }
3703
3704                                         if (expr != null) {
3705                                                 var lifted = new Nullable.LiftedBinaryOperator (this);
3706                                                 lifted.Left = expr;
3707                                                 lifted.Right = right;
3708                                                 return lifted.Resolve (rc);
3709                                         }
3710                                 } else if (lenum && !rtype.IsNullableType) {
3711                                         var lifted_type = nullable_type.MakeGenericType (rc.Module, new[] { ltype });
3712
3713                                         expr = Convert.ImplicitConversion (rc, right, lifted_type, loc);
3714                                         if (expr != null) {
3715                                                 right = expr;
3716                                                 left = Convert.ImplicitConversion (rc, left, lifted_type, loc);
3717                                         }
3718
3719                                         if ((oper & Operator.BitwiseMask) != 0)
3720                                                 type = lifted_type;
3721
3722                                         if (right.IsNull) {
3723                                                 if ((oper & Operator.BitwiseMask) != 0)
3724                                                         return Nullable.LiftedNull.CreateFromExpression (rc, this);
3725
3726                                                 return CreateLiftedValueTypeResult (rc, ltype);
3727                                         }
3728
3729                                         if (expr != null) {
3730                                                 var lifted = new Nullable.LiftedBinaryOperator (this);
3731                                                 lifted.Left = left;
3732                                                 lifted.Right = expr;
3733                                                 return lifted.Resolve (rc);
3734                                         }
3735                                 } else if (rtype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (rtype).IsEnum) {
3736                                         if (left.IsNull) {
3737                                                 if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
3738                                                         left = Convert.ImplicitConversion (rc, left, rtype, left.Location);
3739
3740                                                 if ((oper & Operator.RelationalMask) != 0)
3741                                                         return CreateLiftedValueTypeResult (rc, rtype);
3742
3743                                                 if ((oper & Operator.BitwiseMask) != 0)
3744                                                         return Nullable.LiftedNull.CreateFromExpression (rc, this);
3745
3746                                                 // Equality operators are valid between E? and null
3747                                                 expr = left;
3748                                         } else {
3749                                                 expr = Convert.ImplicitConversion (rc, left, Nullable.NullableInfo.GetUnderlyingType (rtype), loc);
3750                                                 if (expr == null)
3751                                                         return null;
3752                                         }
3753
3754                                         if (expr != null) {
3755                                                 var lifted = new Nullable.LiftedBinaryOperator (this);
3756                                                 lifted.Left = expr;
3757                                                 lifted.Right = right;
3758                                                 return lifted.Resolve (rc);
3759                                         }
3760                                 } else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum) {
3761                                         if (right.IsNull) {
3762                                                 if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
3763                                                         right = Convert.ImplicitConversion (rc, right, ltype, right.Location);
3764
3765                                                 if ((oper & Operator.RelationalMask) != 0)
3766                                                         return CreateLiftedValueTypeResult (rc, ltype);
3767
3768                                                 if ((oper & Operator.BitwiseMask) != 0)
3769                                                         return Nullable.LiftedNull.CreateFromExpression (rc, this);
3770
3771                                                 // Equality operators are valid between E? and null
3772                                                 expr = right;
3773                                         } else {
3774                                                 expr = Convert.ImplicitConversion (rc, right, Nullable.NullableInfo.GetUnderlyingType (ltype), loc);
3775                                                 if (expr == null)
3776                                                         return null;
3777                                         }
3778
3779                                         if (expr != null) {
3780                                                 var lifted = new Nullable.LiftedBinaryOperator (this);
3781                                                 lifted.Left = left;
3782                                                 lifted.Right = expr;
3783                                                 return lifted.Resolve (rc);
3784                                         }
3785                                 }
3786                         }
3787
3788                         return null;
3789                 }
3790
3791                 static Expression ConvertEnumOperandToUnderlyingType (ResolveContext rc, Expression expr, bool liftType)
3792                 {
3793                         TypeSpec underlying_type;
3794                         if (expr.Type.IsNullableType) {
3795                                 var nt = Nullable.NullableInfo.GetUnderlyingType (expr.Type);
3796                                 if (nt.IsEnum)
3797                                         underlying_type = EnumSpec.GetUnderlyingType (nt);
3798                                 else
3799                                         underlying_type = nt;
3800                         } else if (expr.Type.IsEnum) {
3801                                 underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
3802                         } else {
3803                                 underlying_type = expr.Type;
3804                         }
3805
3806                         switch (underlying_type.BuiltinType) {
3807                         case BuiltinTypeSpec.Type.SByte:
3808                         case BuiltinTypeSpec.Type.Byte:
3809                         case BuiltinTypeSpec.Type.Short:
3810                         case BuiltinTypeSpec.Type.UShort:
3811                                 underlying_type = rc.BuiltinTypes.Int;
3812                                 break;
3813                         }
3814
3815                         if (expr.Type.IsNullableType || liftType)
3816                                 underlying_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { underlying_type });
3817
3818                         if (expr.Type == underlying_type)
3819                                 return expr;
3820
3821                         return EmptyCast.Create (expr, underlying_type);
3822                 }
3823
3824                 Expression ResolveEnumOperators (ResolveContext rc, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
3825                 {
3826                         //
3827                         // U operator - (E e, E f)
3828                         // E operator - (E e, U x)  // Internal decomposition operator
3829                         // E operator - (U x, E e)      // Internal decomposition operator
3830                         //
3831                         // E operator + (E e, U x)
3832                         // E operator + (U x, E e)
3833                         //
3834
3835                         TypeSpec enum_type;
3836
3837                         if (lenum)
3838                                 enum_type = ltype;
3839                         else if (renum)
3840                                 enum_type = rtype;
3841                         else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum)
3842                                 enum_type = ltype;
3843                         else
3844                                 enum_type = rtype;
3845
3846                         Expression expr;
3847                         if (!enum_type.IsNullableType) {
3848                                 expr = ResolveOperatorPredefined (rc, rc.Module.GetPredefinedEnumAritmeticOperators (enum_type, false), false);
3849                                 if (expr != null) {
3850                                         if (oper == Operator.Subtraction)
3851                                                 expr = ConvertEnumSubtractionResult (rc, expr);
3852                                         else
3853                                                 expr = ConvertEnumAdditionalResult (expr, enum_type);
3854
3855                                         AddEnumResultCast (expr.Type);
3856
3857                                         return expr;
3858                                 }
3859
3860                                 enum_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { enum_type });
3861                         }
3862
3863                         expr = ResolveOperatorPredefined (rc, rc.Module.GetPredefinedEnumAritmeticOperators (enum_type, true), false);
3864                         if (expr != null) {
3865                                 if (oper == Operator.Subtraction)
3866                                         expr = ConvertEnumSubtractionResult (rc, expr);
3867                                 else
3868                                         expr = ConvertEnumAdditionalResult (expr, enum_type);
3869
3870                                 AddEnumResultCast (expr.Type);
3871                         }
3872
3873                         return expr;
3874                 }
3875
3876                 static Expression ConvertEnumAdditionalResult (Expression expr, TypeSpec enumType)
3877                 {
3878                         return EmptyCast.Create (expr, enumType);
3879                 }
3880
3881                 Expression ConvertEnumSubtractionResult (ResolveContext rc, Expression expr)
3882                 {
3883                         //
3884                         // Enumeration subtraction has different result type based on
3885                         // best overload
3886                         //
3887                         TypeSpec result_type;
3888                         if (left.Type == right.Type) {
3889                                 var c = right as EnumConstant;
3890                                 if (c != null && c.IsZeroInteger && !right.Type.IsEnum) {
3891                                         //
3892                                         // LAMESPEC: This is quite unexpected for expression E - 0 the return type is
3893                                         // E which is not what expressions E - 1 or 0 - E return
3894                                         //
3895                                         result_type = left.Type;
3896                                 } else {
3897                                         result_type = left.Type.IsNullableType ?
3898                                                 Nullable.NullableInfo.GetEnumUnderlyingType (rc.Module, left.Type) :
3899                                                 EnumSpec.GetUnderlyingType (left.Type);
3900                                 }
3901                         } else {
3902                                 if (IsEnumOrNullableEnum (left.Type)) {
3903                                         result_type = left.Type;
3904                                 } else {
3905                                         result_type = right.Type;
3906                                 }
3907
3908                                 if (expr is Nullable.LiftedBinaryOperator && !result_type.IsNullableType)
3909                                         result_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { result_type });
3910                         }
3911
3912                         return EmptyCast.Create (expr, result_type);
3913                 }
3914
3915                 void AddEnumResultCast (TypeSpec type)
3916                 {
3917                         if (type.IsNullableType)
3918                                 type = Nullable.NullableInfo.GetUnderlyingType (type);
3919
3920                         if (type.IsEnum)
3921                                 type = EnumSpec.GetUnderlyingType (type);
3922
3923                         switch (type.BuiltinType) {
3924                         case BuiltinTypeSpec.Type.SByte:
3925                                 enum_conversion = ConvCast.Mode.I4_I1;
3926                                 break;
3927                         case BuiltinTypeSpec.Type.Byte:
3928                                 enum_conversion = ConvCast.Mode.I4_U1;
3929                                 break;
3930                         case BuiltinTypeSpec.Type.Short:
3931                                 enum_conversion = ConvCast.Mode.I4_I2;
3932                                 break;
3933                         case BuiltinTypeSpec.Type.UShort:
3934                                 enum_conversion = ConvCast.Mode.I4_U2;
3935                                 break;
3936                         }
3937                 }
3938
3939                 //
3940                 // Equality operators rules
3941                 //
3942                 Expression ResolveEquality (ResolveContext ec, TypeSpec l, TypeSpec r, bool primitives_only)
3943                 {
3944                         Expression result;
3945                         type = ec.BuiltinTypes.Bool;
3946                         bool no_arg_conv = false;
3947
3948                         if (!primitives_only) {
3949
3950                                 //
3951                                 // a, Both operands are reference-type values or the value null
3952                                 // b, One operand is a value of type T where T is a type-parameter and
3953                                 // the other operand is the value null. Furthermore T does not have the
3954                                 // value type constraint
3955                                 //
3956                                 // LAMESPEC: Very confusing details in the specification, basically any
3957                                 // reference like type-parameter is allowed
3958                                 //
3959                                 var tparam_l = l as TypeParameterSpec;
3960                                 var tparam_r = r as TypeParameterSpec;
3961                                 if (tparam_l != null) {
3962                                         if (right is NullLiteral) {
3963                                                 if (tparam_l.GetEffectiveBase ().BuiltinType == BuiltinTypeSpec.Type.ValueType)
3964                                                         return null;
3965
3966                                                 left = new BoxedCast (left, ec.BuiltinTypes.Object);
3967                                                 return this;
3968                                         }
3969
3970                                         if (!tparam_l.IsReferenceType)
3971                                                 return null;
3972
3973                                         l = tparam_l.GetEffectiveBase ();
3974                                         left = new BoxedCast (left, l);
3975                                 } else if (left is NullLiteral && tparam_r == null) {
3976                                         if (TypeSpec.IsReferenceType (r))
3977                                                 return this;
3978
3979                                         if (r.Kind == MemberKind.InternalCompilerType)
3980                                                 return null;
3981                                 }
3982
3983                                 if (tparam_r != null) {
3984                                         if (left is NullLiteral) {
3985                                                 if (tparam_r.GetEffectiveBase ().BuiltinType == BuiltinTypeSpec.Type.ValueType)
3986                                                         return null;
3987
3988                                                 right = new BoxedCast (right, ec.BuiltinTypes.Object);
3989                                                 return this;
3990                                         }
3991
3992                                         if (!tparam_r.IsReferenceType)
3993                                                 return null;
3994
3995                                         r = tparam_r.GetEffectiveBase ();
3996                                         right = new BoxedCast (right, r);
3997                                 } else if (right is NullLiteral) {
3998                                         if (TypeSpec.IsReferenceType (l))
3999                                                 return this;
4000
4001                                         if (l.Kind == MemberKind.InternalCompilerType)
4002                                                 return null;
4003                                 }
4004
4005                                 //
4006                                 // LAMESPEC: method groups can be compared when they convert to other side delegate
4007                                 //
4008                                 if (l.IsDelegate) {
4009                                         if (right.eclass == ExprClass.MethodGroup) {
4010                                                 result = Convert.ImplicitConversion (ec, right, l, loc);
4011                                                 if (result == null)
4012                                                         return null;
4013
4014                                                 right = result;
4015                                                 r = l;
4016                                         } else if (r.IsDelegate && l != r) {
4017                                                 return null;
4018                                         }
4019                                 } else if (left.eclass == ExprClass.MethodGroup && r.IsDelegate) {
4020                                         result = Convert.ImplicitConversionRequired (ec, left, r, loc);
4021                                         if (result == null)
4022                                                 return null;
4023
4024                                         left = result;
4025                                         l = r;
4026                                 } else {
4027                                         no_arg_conv = l == r && !l.IsStruct;
4028                                 }
4029                         }
4030
4031                         //
4032                         // bool operator != (string a, string b)
4033                         // bool operator == (string a, string b)
4034                         //
4035                         // bool operator != (Delegate a, Delegate b)
4036                         // bool operator == (Delegate a, Delegate b)
4037                         //
4038                         // bool operator != (bool a, bool b)
4039                         // bool operator == (bool a, bool b)
4040                         //
4041                         // LAMESPEC: Reference equality comparison can apply to value/reference types when
4042                         // they implement an implicit conversion to any of types above. This does
4043                         // not apply when both operands are of same reference type
4044                         //
4045                         if (r.BuiltinType != BuiltinTypeSpec.Type.Object && l.BuiltinType != BuiltinTypeSpec.Type.Object) {
4046                                 result = ResolveOperatorPredefined (ec, ec.BuiltinTypes.OperatorsBinaryEquality, no_arg_conv);  
4047                                 if (result != null)
4048                                         return result;
4049
4050                                 //
4051                                 // Now try lifted version of predefined operators
4052                                 //
4053                                 if (no_arg_conv && !l.IsNullableType) {
4054                                         //
4055                                         // Optimizes cases which won't match
4056                                         //
4057                                 } else {
4058                                         result = ResolveOperatorPredefined (ec, ec.Module.OperatorsBinaryEqualityLifted, no_arg_conv);
4059                                         if (result != null)
4060                                                 return result;
4061                                 }
4062
4063                                 //
4064                                 // The == and != operators permit one operand to be a value of a nullable
4065                                 // type and the other to be the null literal, even if no predefined or user-defined
4066                                 // operator (in unlifted or lifted form) exists for the operation.
4067                                 //
4068                                 if ((l.IsNullableType && right.IsNull) || (r.IsNullableType && left.IsNull)) {
4069                                         var lifted = new Nullable.LiftedBinaryOperator (this);
4070                                         lifted.Left = left;
4071                                         lifted.Right = right;
4072                                         return lifted.Resolve (ec);
4073                                 }
4074                         }
4075
4076                         //
4077                         // bool operator != (object a, object b)
4078                         // bool operator == (object a, object b)
4079                         //
4080                         // An explicit reference conversion exists from the
4081                         // type of either operand to the type of the other operand.
4082                         //
4083
4084                         // Optimize common path
4085                         if (l == r) {
4086                                 return l.Kind == MemberKind.InternalCompilerType || l.Kind == MemberKind.Struct ? null : this;
4087                         }
4088
4089                         if (!Convert.ExplicitReferenceConversionExists (l, r) &&
4090                                 !Convert.ExplicitReferenceConversionExists (r, l))
4091                                 return null;
4092
4093                         // Reject allowed explicit conversions like int->object
4094                         if (!TypeSpec.IsReferenceType (l) || !TypeSpec.IsReferenceType (r))
4095                                 return null;
4096
4097                         if (l.BuiltinType == BuiltinTypeSpec.Type.String || l.BuiltinType == BuiltinTypeSpec.Type.Delegate || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
4098                                 ec.Report.Warning (253, 2, loc,
4099                                         "Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
4100                                         l.GetSignatureForError ());
4101
4102                         if (r.BuiltinType == BuiltinTypeSpec.Type.String || r.BuiltinType == BuiltinTypeSpec.Type.Delegate || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
4103                                 ec.Report.Warning (252, 2, loc,
4104                                         "Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
4105                                         r.GetSignatureForError ());
4106
4107                         return this;
4108                 }
4109
4110
4111                 Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
4112                 {
4113                         //
4114                         // bool operator == (void* x, void* y);
4115                         // bool operator != (void* x, void* y);
4116                         // bool operator < (void* x, void* y);
4117                         // bool operator > (void* x, void* y);
4118                         // bool operator <= (void* x, void* y);
4119                         // bool operator >= (void* x, void* y);
4120                         //
4121                         if ((oper & Operator.ComparisonMask) != 0) {
4122                                 Expression temp;
4123                                 if (!l.IsPointer) {
4124                                         temp = Convert.ImplicitConversion (ec, left, r, left.Location);
4125                                         if (temp == null)
4126                                                 return null;
4127                                         left = temp;
4128                                 }
4129
4130                                 if (!r.IsPointer) {
4131                                         temp = Convert.ImplicitConversion (ec, right, l, right.Location);
4132                                         if (temp == null)
4133                                                 return null;
4134                                         right = temp;
4135                                 }
4136
4137                                 type = ec.BuiltinTypes.Bool;
4138                                 return this;
4139                         }
4140
4141                         return ResolveOperatorPredefined (ec, ec.BuiltinTypes.OperatorsBinaryUnsafe, false);
4142                 }
4143
4144                 //
4145                 // Build-in operators method overloading
4146                 //
4147                 Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only)
4148                 {
4149                         PredefinedOperator best_operator = null;
4150                         TypeSpec l = left.Type;
4151                         TypeSpec r = right.Type;
4152                         Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
4153
4154                         foreach (PredefinedOperator po in operators) {
4155                                 if ((po.OperatorsMask & oper_mask) == 0)
4156                                         continue;
4157
4158                                 if (primitives_only) {
4159                                         if (!po.IsPrimitiveApplicable (l, r))
4160                                                 continue;
4161                                 } else {
4162                                         if (!po.IsApplicable (ec, left, right))
4163                                                 continue;
4164                                 }
4165
4166                                 if (best_operator == null) {
4167                                         best_operator = po;
4168                                         if (primitives_only)
4169                                                 break;
4170
4171                                         continue;
4172                                 }
4173
4174                                 best_operator = po.ResolveBetterOperator (ec, best_operator);
4175
4176                                 if (best_operator == null) {
4177                                         ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
4178                                                 OperName (oper), l.GetSignatureForError (), r.GetSignatureForError ());
4179
4180                                         best_operator = po;
4181                                         break;
4182                                 }
4183                         }
4184
4185                         if (best_operator == null)
4186                                 return null;
4187
4188                         return best_operator.ConvertResult (ec, this);
4189                 }
4190
4191                 //
4192                 // Optimize & constant expressions with 0 value
4193                 //
4194                 Expression OptimizeAndOperation (Expression expr)
4195                 {
4196                         Constant rc = right as Constant;
4197                         Constant lc = left as Constant;
4198                         if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
4199                                 //
4200                                 // The result is a constant with side-effect
4201                                 //
4202                                 Constant side_effect = rc == null ?
4203                                         new SideEffectConstant (lc, right, loc) :
4204                                         new SideEffectConstant (rc, left, loc);
4205
4206                                 return ReducedExpression.Create (side_effect, expr);
4207                         }
4208
4209                         return expr;
4210                 }
4211
4212                 //
4213                 // Value types can be compared with the null literal because of the lifting
4214                 // language rules. However the result is always true or false.
4215                 //
4216                 public Expression CreateLiftedValueTypeResult (ResolveContext rc, TypeSpec valueType)
4217                 {
4218                         if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
4219                                 type = rc.BuiltinTypes.Bool;
4220                                 return this;
4221                         }
4222
4223                         // FIXME: Handle side effect constants
4224                         Constant c = new BoolConstant (rc.BuiltinTypes, Oper == Operator.Inequality, loc);
4225
4226                         if ((Oper & Operator.EqualityMask) != 0) {
4227                                 rc.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is always `{1}'",
4228                                         valueType.GetSignatureForError (), c.GetValueAsLiteral ());
4229                         } else {
4230                                 rc.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
4231                                         valueType.GetSignatureForError (), c.GetValueAsLiteral ());
4232                         }
4233
4234                         return c;
4235                 }
4236
4237                 //
4238                 // Performs user-operator overloading
4239                 //
4240                 Expression ResolveUserOperator (ResolveContext rc, Expression left, Expression right)
4241                 {
4242                         Expression oper_expr;
4243
4244                         var op = ConvertBinaryToUserOperator (oper);
4245                         var l = left.Type;
4246                         if (l.IsNullableType)
4247                                 l = Nullable.NullableInfo.GetUnderlyingType (l);
4248                         var r = right.Type;
4249                         if (r.IsNullableType)
4250                                 r = Nullable.NullableInfo.GetUnderlyingType (r);
4251
4252                         IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
4253                         IList<MemberSpec> right_operators = null;
4254
4255                         if (l != r) {
4256                                 right_operators = MemberCache.GetUserOperator (r, op, false);
4257                                 if (right_operators == null && left_operators == null)
4258                                         return null;
4259                         } else if (left_operators == null) {
4260                                 return null;
4261                         }
4262
4263                         Arguments args = new Arguments (2);
4264                         Argument larg = new Argument (left);
4265                         args.Add (larg);        
4266                         Argument rarg = new Argument (right);
4267                         args.Add (rarg);
4268
4269                         //
4270                         // User-defined operator implementations always take precedence
4271                         // over predefined operator implementations
4272                         //
4273                         if (left_operators != null && right_operators != null) {
4274                                 left_operators = CombineUserOperators (left_operators, right_operators);
4275                         } else if (right_operators != null) {
4276                                 left_operators = right_operators;
4277                         }
4278
4279                         const OverloadResolver.Restrictions restr = OverloadResolver.Restrictions.ProbingOnly |
4280                                 OverloadResolver.Restrictions.NoBaseMembers | OverloadResolver.Restrictions.BaseMembersIncluded;
4281
4282                         var res = new OverloadResolver (left_operators, restr, loc);
4283
4284                         var oper_method = res.ResolveOperator (rc, ref args);
4285                         if (oper_method == null) {
4286                                 //
4287                                 // Logical && and || cannot be lifted
4288                                 //
4289                                 if ((oper & Operator.LogicalMask) != 0)
4290                                         return null;
4291
4292                                 //
4293                                 // Apply lifted user operators only for liftable types. Implicit conversion
4294                                 // to nullable types is not allowed
4295                                 //
4296                                 if (!IsLiftedOperatorApplicable ())
4297                                         return null;
4298
4299                                 // TODO: Cache the result in module container
4300                                 var lifted_methods = CreateLiftedOperators (rc, left_operators);
4301                                 if (lifted_methods == null)
4302                                         return null;
4303
4304                                 res = new OverloadResolver (lifted_methods, restr | OverloadResolver.Restrictions.ProbingOnly, loc);
4305
4306                                 oper_method = res.ResolveOperator (rc, ref args);
4307                                 if (oper_method == null)
4308                                         return null;
4309
4310                                 MethodSpec best_original = null;
4311                                 foreach (MethodSpec ms in left_operators) {
4312                                         if (ms.MemberDefinition == oper_method.MemberDefinition) {
4313                                                 best_original = ms;
4314                                                 break;
4315                                         }
4316                                 }
4317
4318                                 if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
4319                                         //
4320                                         // Expression trees use lifted notation in this case
4321                                         //
4322                                         this.left = Convert.ImplicitConversion (rc, left, oper_method.Parameters.Types[0], left.Location);
4323                                         this.right = Convert.ImplicitConversion (rc, right, oper_method.Parameters.Types[1], left.Location);
4324                                 }
4325
4326                                 var ptypes = best_original.Parameters.Types;
4327
4328                                 if (left.IsNull || right.IsNull) {
4329                                         //
4330                                         // The lifted operator produces the value false if one or both operands are null for
4331                                         // relational operators.
4332                                         //
4333                                         if ((oper & Operator.ComparisonMask) != 0) {
4334                                                 //
4335                                                 // CSC BUG: This should be different warning, csc reports CS0458 with bool? which is wrong
4336                                                 // because return type is actually bool
4337                                                 //
4338                                                 // For some reason CSC does not report this warning for equality operators
4339                                                 //
4340                                                 return CreateLiftedValueTypeResult (rc, left.IsNull ? ptypes [1] : ptypes [0]);
4341                                         }
4342
4343                                         // The lifted operator produces a null value if one or both operands are null
4344                                         //
4345                                         if ((oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) {
4346                                                 type = oper_method.ReturnType;
4347                                                 return Nullable.LiftedNull.CreateFromExpression (rc, this);
4348                                         }
4349                                 }
4350
4351                                 type = oper_method.ReturnType;
4352                                 var lifted = new Nullable.LiftedBinaryOperator (this);
4353                                 lifted.UserOperator = best_original;
4354
4355                                 if (left.Type.IsNullableType && !ptypes[0].IsNullableType) {
4356                                         lifted.UnwrapLeft = new Nullable.Unwrap (left);
4357                                 }
4358
4359                                 if (right.Type.IsNullableType && !ptypes[1].IsNullableType) {
4360                                         lifted.UnwrapRight = new Nullable.Unwrap (right);
4361                                 }
4362
4363                                 lifted.Left = Convert.ImplicitConversion (rc, lifted.UnwrapLeft ?? left, ptypes[0], left.Location);
4364                                 lifted.Right = Convert.ImplicitConversion (rc, lifted.UnwrapRight ?? right, ptypes[1], right.Location);
4365
4366                                 return lifted.Resolve (rc);
4367                         }
4368                         
4369                         if ((oper & Operator.LogicalMask) != 0) {
4370                                 // TODO: CreateExpressionTree is allocated every time           
4371                                 oper_expr = new ConditionalLogicalOperator (oper_method, args, CreateExpressionTree,
4372                                         oper == Operator.LogicalAnd, loc).Resolve (rc);
4373                         } else {
4374                                 oper_expr = new UserOperatorCall (oper_method, args, CreateExpressionTree, loc);
4375                         }
4376
4377                         this.left = larg.Expr;
4378                         this.right = rarg.Expr;
4379
4380                         return oper_expr;
4381                 }
4382
4383                 bool IsLiftedOperatorApplicable ()
4384                 {
4385                         if (left.Type.IsNullableType) {
4386                                 if ((oper & Operator.EqualityMask) != 0)
4387                                         return !right.IsNull;
4388
4389                                 return true;
4390                         }
4391
4392                         if (right.Type.IsNullableType) {
4393                                 if ((oper & Operator.EqualityMask) != 0)
4394                                         return !left.IsNull;
4395
4396                                 return true;
4397                         }
4398
4399                         if (TypeSpec.IsValueType (left.Type))
4400                                 return right.IsNull;
4401
4402                         if (TypeSpec.IsValueType (right.Type))
4403                                 return left.IsNull;
4404
4405                         return false;
4406                 }
4407
4408                 List<MemberSpec> CreateLiftedOperators (ResolveContext rc, IList<MemberSpec> operators)
4409                 {
4410                         var nullable_type = rc.Module.PredefinedTypes.Nullable.TypeSpec;
4411                         if (nullable_type == null)
4412                                 return null;
4413
4414                         //
4415                         // Lifted operators permit predefined and user-defined operators that operate
4416                         // on non-nullable value types to also be used with nullable forms of those types.
4417                         // Lifted operators are constructed from predefined and user-defined operators
4418                         // that meet certain requirements
4419                         //
4420                         List<MemberSpec> lifted = null;
4421                         foreach (MethodSpec oper in operators) {
4422                                 TypeSpec rt;
4423                                 if ((Oper & Operator.ComparisonMask) != 0) {
4424                                         //
4425                                         // Result type must be of type bool for lifted comparison operators
4426                                         //
4427                                         rt = oper.ReturnType;
4428                                         if (rt.BuiltinType != BuiltinTypeSpec.Type.Bool)
4429                                                 continue;
4430                                 } else {
4431                                         if (!TypeSpec.IsNonNullableValueType (oper.ReturnType))
4432                                                 continue;
4433
4434                                         rt = null;
4435                                 }
4436
4437                                 var ptypes = oper.Parameters.Types;
4438                                 if (!TypeSpec.IsNonNullableValueType (ptypes [0]) || !TypeSpec.IsNonNullableValueType (ptypes [1]))
4439                                         continue;
4440
4441                                 //
4442                                 // LAMESPEC: I am not sure why but for equality operators to be lifted
4443                                 // both types have to match
4444                                 //
4445                                 if ((Oper & Operator.EqualityMask) != 0 && ptypes [0] != ptypes [1])
4446                                         continue;
4447
4448                                 if (lifted == null)
4449                                         lifted = new List<MemberSpec> ();
4450
4451                                 //
4452                                 // The lifted form is constructed by adding a single ? modifier to each operand and
4453                                 // result type except for comparison operators where return type is bool
4454                                 //
4455                                 if (rt == null)
4456                                         rt = nullable_type.MakeGenericType (rc.Module, new[] { oper.ReturnType });
4457
4458                                 var parameters = ParametersCompiled.CreateFullyResolved (
4459                                         nullable_type.MakeGenericType (rc.Module, new [] { ptypes[0] }),
4460                                         nullable_type.MakeGenericType (rc.Module, new [] { ptypes[1] }));
4461
4462                                 var lifted_op = new MethodSpec (oper.Kind, oper.DeclaringType, oper.MemberDefinition,
4463                                         rt, parameters, oper.Modifiers);
4464
4465                                 lifted.Add (lifted_op);
4466                         }
4467
4468                         return lifted;
4469                 }
4470
4471                 //
4472                 // Merge two sets of user operators into one, they are mostly distinguish
4473                 // except when they share base type and it contains an operator
4474                 //
4475                 static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
4476                 {
4477                         var combined = new List<MemberSpec> (left.Count + right.Count);
4478                         combined.AddRange (left);
4479                         foreach (var r in right) {
4480                                 bool same = false;
4481                                 foreach (var l in left) {
4482                                         if (l.DeclaringType == r.DeclaringType) {
4483                                                 same = true;
4484                                                 break;
4485                                         }
4486                                 }
4487
4488                                 if (!same)
4489                                         combined.Add (r);
4490                         }
4491
4492                         return combined;
4493                 }
4494
4495                 void CheckOutOfRangeComparison (ResolveContext ec, Constant c, TypeSpec type)
4496                 {
4497                         if (c is IntegralConstant || c is CharConstant) {
4498                                 try {
4499                                         c.ConvertExplicitly (true, type);
4500                                 } catch (OverflowException) {
4501                                         ec.Report.Warning (652, 2, loc,
4502                                                 "A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
4503                                                 type.GetSignatureForError ());
4504                                 }
4505                         }
4506                 }
4507
4508                 /// <remarks>
4509                 ///   EmitBranchable is called from Statement.EmitBoolExpression in the
4510                 ///   context of a conditional bool expression.  This function will return
4511                 ///   false if it is was possible to use EmitBranchable, or true if it was.
4512                 ///
4513                 ///   The expression's code is generated, and we will generate a branch to `target'
4514                 ///   if the resulting expression value is equal to isTrue
4515                 /// </remarks>
4516                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
4517                 {
4518                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && right.ContainsEmitWithAwait ()) {
4519                                 left = left.EmitToField (ec);
4520
4521                                 if ((oper & Operator.LogicalMask) == 0) {
4522                                         right = right.EmitToField (ec);
4523                                 }
4524                         }
4525
4526                         //
4527                         // This is more complicated than it looks, but its just to avoid
4528                         // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
4529                         // but on top of that we want for == and != to use a special path
4530                         // if we are comparing against null
4531                         //
4532                         if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
4533                                 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
4534                                 
4535                                 //
4536                                 // put the constant on the rhs, for simplicity
4537                                 //
4538                                 if (left is Constant) {
4539                                         Expression swap = right;
4540                                         right = left;
4541                                         left = swap;
4542                                 }
4543                                 
4544                                 //
4545                                 // brtrue/brfalse works with native int only
4546                                 //
4547                                 if (((Constant) right).IsZeroInteger && right.Type.BuiltinType != BuiltinTypeSpec.Type.Long && right.Type.BuiltinType != BuiltinTypeSpec.Type.ULong) {
4548                                         left.EmitBranchable (ec, target, my_on_true);
4549                                         return;
4550                                 }
4551                                 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
4552                                         // right is a boolean, and it's not 'false' => it is 'true'
4553                                         left.EmitBranchable (ec, target, !my_on_true);
4554                                         return;
4555                                 }
4556
4557                         } else if (oper == Operator.LogicalAnd) {
4558
4559                                 if (on_true) {
4560                                         Label tests_end = ec.DefineLabel ();
4561                                         
4562                                         left.EmitBranchable (ec, tests_end, false);
4563                                         right.EmitBranchable (ec, target, true);
4564                                         ec.MarkLabel (tests_end);                                       
4565                                 } else {
4566                                         //
4567                                         // This optimizes code like this 
4568                                         // if (true && i > 4)
4569                                         //
4570                                         if (!(left is Constant))
4571                                                 left.EmitBranchable (ec, target, false);
4572
4573                                         if (!(right is Constant)) 
4574                                                 right.EmitBranchable (ec, target, false);
4575                                 }
4576                                 
4577                                 return;
4578                                 
4579                         } else if (oper == Operator.LogicalOr){
4580                                 if (on_true) {
4581                                         left.EmitBranchable (ec, target, true);
4582                                         right.EmitBranchable (ec, target, true);
4583                                         
4584                                 } else {
4585                                         Label tests_end = ec.DefineLabel ();
4586                                         left.EmitBranchable (ec, tests_end, true);
4587                                         right.EmitBranchable (ec, target, false);
4588                                         ec.MarkLabel (tests_end);
4589                                 }
4590                                 
4591                                 return;
4592
4593                         } else if ((oper & Operator.ComparisonMask) == 0) {
4594                                 base.EmitBranchable (ec, target, on_true);
4595                                 return;
4596                         }
4597                         
4598                         left.Emit (ec);
4599                         right.Emit (ec);
4600
4601                         TypeSpec t = left.Type;
4602                         bool is_float = IsFloat (t);
4603                         bool is_unsigned = is_float || IsUnsigned (t);
4604                         
4605                         switch (oper){
4606                         case Operator.Equality:
4607                                 if (on_true)
4608                                         ec.Emit (OpCodes.Beq, target);
4609                                 else
4610                                         ec.Emit (OpCodes.Bne_Un, target);
4611                                 break;
4612
4613                         case Operator.Inequality:
4614                                 if (on_true)
4615                                         ec.Emit (OpCodes.Bne_Un, target);
4616                                 else
4617                                         ec.Emit (OpCodes.Beq, target);
4618                                 break;
4619
4620                         case Operator.LessThan:
4621                                 if (on_true)
4622                                         if (is_unsigned && !is_float)
4623                                                 ec.Emit (OpCodes.Blt_Un, target);
4624                                         else
4625                                                 ec.Emit (OpCodes.Blt, target);
4626                                 else
4627                                         if (is_unsigned)
4628                                                 ec.Emit (OpCodes.Bge_Un, target);
4629                                         else
4630                                                 ec.Emit (OpCodes.Bge, target);
4631                                 break;
4632
4633                         case Operator.GreaterThan:
4634                                 if (on_true)
4635                                         if (is_unsigned && !is_float)
4636                                                 ec.Emit (OpCodes.Bgt_Un, target);
4637                                         else
4638                                                 ec.Emit (OpCodes.Bgt, target);
4639                                 else
4640                                         if (is_unsigned)
4641                                                 ec.Emit (OpCodes.Ble_Un, target);
4642                                         else
4643                                                 ec.Emit (OpCodes.Ble, target);
4644                                 break;
4645
4646                         case Operator.LessThanOrEqual:
4647                                 if (on_true)
4648                                         if (is_unsigned && !is_float)
4649                                                 ec.Emit (OpCodes.Ble_Un, target);
4650                                         else
4651                                                 ec.Emit (OpCodes.Ble, target);
4652                                 else
4653                                         if (is_unsigned)
4654                                                 ec.Emit (OpCodes.Bgt_Un, target);
4655                                         else
4656                                                 ec.Emit (OpCodes.Bgt, target);
4657                                 break;
4658
4659
4660                         case Operator.GreaterThanOrEqual:
4661                                 if (on_true)
4662                                         if (is_unsigned && !is_float)
4663                                                 ec.Emit (OpCodes.Bge_Un, target);
4664                                         else
4665                                                 ec.Emit (OpCodes.Bge, target);
4666                                 else
4667                                         if (is_unsigned)
4668                                                 ec.Emit (OpCodes.Blt_Un, target);
4669                                         else
4670                                                 ec.Emit (OpCodes.Blt, target);
4671                                 break;
4672                         default:
4673                                 throw new InternalErrorException (oper.ToString ());
4674                         }
4675                 }
4676                 
4677                 public override void Emit (EmitContext ec)
4678                 {
4679                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && right.ContainsEmitWithAwait ()) {
4680                                 left = left.EmitToField (ec);
4681
4682                                 if ((oper & Operator.LogicalMask) == 0) {
4683                                         right = right.EmitToField (ec);
4684                                 }
4685                         }
4686
4687                         //
4688                         // Handle short-circuit operators differently
4689                         // than the rest
4690                         //
4691                         if ((oper & Operator.LogicalMask) != 0) {
4692                                 Label load_result = ec.DefineLabel ();
4693                                 Label end = ec.DefineLabel ();
4694
4695                                 bool is_or = oper == Operator.LogicalOr;
4696                                 left.EmitBranchable (ec, load_result, is_or);
4697                                 right.Emit (ec);
4698                                 ec.Emit (OpCodes.Br_S, end);
4699                                 
4700                                 ec.MarkLabel (load_result);
4701                                 ec.EmitInt (is_or ? 1 : 0);
4702                                 ec.MarkLabel (end);
4703                                 return;
4704                         }
4705
4706                         //
4707                         // Optimize zero-based operations which cannot be optimized at expression level
4708                         //
4709                         if (oper == Operator.Subtraction) {
4710                                 var lc = left as IntegralConstant;
4711                                 if (lc != null && lc.IsDefaultValue) {
4712                                         right.Emit (ec);
4713                                         ec.Emit (OpCodes.Neg);
4714                                         return;
4715                                 }
4716                         }
4717
4718                         EmitOperator (ec, left, right);
4719                 }
4720
4721                 public void EmitOperator (EmitContext ec, Expression left, Expression right)
4722                 {
4723                         left.Emit (ec);
4724                         right.Emit (ec);
4725
4726                         EmitOperatorOpcode (ec, oper, left.Type, right);
4727
4728                         //
4729                         // Emit result enumerable conversion this way because it's quite complicated get it
4730                         // to resolved tree because expression tree cannot see it.
4731                         //
4732                         if (enum_conversion != 0)
4733                                 ConvCast.Emit (ec, enum_conversion);
4734                 }
4735
4736                 public override void EmitSideEffect (EmitContext ec)
4737                 {
4738                         if ((oper & Operator.LogicalMask) != 0 ||
4739                                 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
4740                                 base.EmitSideEffect (ec);
4741                         } else {
4742                                 left.EmitSideEffect (ec);
4743                                 right.EmitSideEffect (ec);
4744                         }
4745                 }
4746
4747                 public override Expression EmitToField (EmitContext ec)
4748                 {
4749                         if ((oper & Operator.LogicalMask) == 0) {
4750                                 var await_expr = left as Await;
4751                                 if (await_expr != null && right.IsSideEffectFree) {
4752                                         await_expr.Statement.EmitPrologue (ec);
4753                                         left = await_expr.Statement.GetResultExpression (ec);
4754                                         return this;
4755                                 }
4756
4757                                 await_expr = right as Await;
4758                                 if (await_expr != null && left.IsSideEffectFree) {
4759                                         await_expr.Statement.EmitPrologue (ec);
4760                                         right = await_expr.Statement.GetResultExpression (ec);
4761                                         return this;
4762                                 }
4763                         }
4764
4765                         return base.EmitToField (ec);
4766                 }
4767
4768                 protected override void CloneTo (CloneContext clonectx, Expression t)
4769                 {
4770                         Binary target = (Binary) t;
4771
4772                         target.left = left.Clone (clonectx);
4773                         target.right = right.Clone (clonectx);
4774                 }
4775
4776                 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
4777                 {
4778                         Arguments binder_args = new Arguments (4);
4779
4780                         MemberAccess sle = new MemberAccess (new MemberAccess (
4781                                 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
4782
4783                         CSharpBinderFlags flags = 0;
4784                         if (ec.HasSet (ResolveContext.Options.CheckedScope))
4785                                 flags = CSharpBinderFlags.CheckedContext;
4786
4787                         if ((oper & Operator.LogicalMask) != 0)
4788                                 flags |= CSharpBinderFlags.BinaryOperationLogical;
4789
4790                         binder_args.Add (new Argument (new EnumConstant (new IntLiteral (ec.BuiltinTypes, (int) flags, loc), ec.Module.PredefinedTypes.BinderFlags.Resolve ())));
4791                         binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
4792                         binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));                                                                      
4793                         binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
4794
4795                         return new Invocation (new MemberAccess (new TypeExpression (ec.Module.PredefinedTypes.Binder.TypeSpec, loc), "BinaryOperation", loc), binder_args);
4796                 }
4797                 
4798                 public override Expression CreateExpressionTree (ResolveContext ec)
4799                 {
4800                         return CreateExpressionTree (ec, null);
4801                 }
4802
4803                 public Expression CreateExpressionTree (ResolveContext ec, Expression method)           
4804                 {
4805                         string method_name;
4806                         bool lift_arg = false;
4807                         
4808                         switch (oper) {
4809                         case Operator.Addition:
4810                                 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
4811                                         method_name = "AddChecked";
4812                                 else
4813                                         method_name = "Add";
4814                                 break;
4815                         case Operator.BitwiseAnd:
4816                                 method_name = "And";
4817                                 break;
4818                         case Operator.BitwiseOr:
4819                                 method_name = "Or";
4820                                 break;
4821                         case Operator.Division:
4822                                 method_name = "Divide";
4823                                 break;
4824                         case Operator.Equality:
4825                                 method_name = "Equal";
4826                                 lift_arg = true;
4827                                 break;
4828                         case Operator.ExclusiveOr:
4829                                 method_name = "ExclusiveOr";
4830                                 break;                          
4831                         case Operator.GreaterThan:
4832                                 method_name = "GreaterThan";
4833                                 lift_arg = true;
4834                                 break;
4835                         case Operator.GreaterThanOrEqual:
4836                                 method_name = "GreaterThanOrEqual";
4837                                 lift_arg = true;
4838                                 break;
4839                         case Operator.Inequality:
4840                                 method_name = "NotEqual";
4841                                 lift_arg = true;
4842                                 break;
4843                         case Operator.LeftShift:
4844                                 method_name = "LeftShift";
4845                                 break;
4846                         case Operator.LessThan:
4847                                 method_name = "LessThan";
4848                                 lift_arg = true;
4849                                 break;
4850                         case Operator.LessThanOrEqual:
4851                                 method_name = "LessThanOrEqual";
4852                                 lift_arg = true;
4853                                 break;
4854                         case Operator.LogicalAnd:
4855                                 method_name = "AndAlso";
4856                                 break;
4857                         case Operator.LogicalOr:
4858                                 method_name = "OrElse";
4859                                 break;
4860                         case Operator.Modulus:
4861                                 method_name = "Modulo";
4862                                 break;
4863                         case Operator.Multiply:
4864                                 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
4865                                         method_name = "MultiplyChecked";
4866                                 else
4867                                         method_name = "Multiply";
4868                                 break;
4869                         case Operator.RightShift:
4870                                 method_name = "RightShift";
4871                                 break;
4872                         case Operator.Subtraction:
4873                                 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
4874                                         method_name = "SubtractChecked";
4875                                 else
4876                                         method_name = "Subtract";
4877                                 break;
4878
4879                         default:
4880                                 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
4881                         }
4882
4883                         Arguments args = new Arguments (2);
4884                         args.Add (new Argument (left.CreateExpressionTree (ec)));
4885                         args.Add (new Argument (right.CreateExpressionTree (ec)));
4886                         if (method != null) {
4887                                 if (lift_arg)
4888                                         args.Add (new Argument (new BoolLiteral (ec.BuiltinTypes, false, loc)));
4889
4890                                 args.Add (new Argument (method));
4891                         }
4892                         
4893                         return CreateExpressionFactoryCall (ec, method_name, args);
4894                 }
4895                 
4896                 public override object Accept (StructuralVisitor visitor)
4897                 {
4898                         return visitor.Visit (this);
4899                 }
4900
4901         }
4902         
4903         //
4904         // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
4905         // b, c, d... may be strings or objects.
4906         //
4907         public class StringConcat : Expression
4908         {
4909                 Arguments arguments;
4910                 
4911                 StringConcat (Location loc)
4912                 {
4913                         this.loc = loc;
4914                         arguments = new Arguments (2);
4915                 }
4916
4917                 public override bool ContainsEmitWithAwait ()
4918                 {
4919                         return arguments.ContainsEmitWithAwait ();
4920                 }
4921
4922                 public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
4923                 {
4924                         if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
4925                                 throw new ArgumentException ();
4926
4927                         var s = new StringConcat (loc);
4928                         s.type = rc.BuiltinTypes.String;
4929                         s.eclass = ExprClass.Value;
4930
4931                         s.Append (rc, left);
4932                         s.Append (rc, right);
4933                         return s;
4934                 }
4935
4936                 public override Expression CreateExpressionTree (ResolveContext ec)
4937                 {
4938                         Argument arg = arguments [0];
4939                         return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
4940                 }
4941
4942                 //
4943                 // Creates nested calls tree from an array of arguments used for IL emit
4944                 //
4945                 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
4946                 {
4947                         Arguments concat_args = new Arguments (2);
4948                         Arguments add_args = new Arguments (3);
4949
4950                         concat_args.Add (left);
4951                         add_args.Add (new Argument (left_etree));
4952
4953                         concat_args.Add (arguments [pos]);
4954                         add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
4955
4956                         var methods = GetConcatMethodCandidates ();
4957                         if (methods == null)
4958                                 return null;
4959
4960                         var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
4961                         var method = res.ResolveMember<MethodSpec> (ec, ref concat_args);
4962                         if (method == null)
4963                                 return null;
4964
4965                         add_args.Add (new Argument (new TypeOfMethod (method, loc)));
4966
4967                         Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
4968                         if (++pos == arguments.Count)
4969                                 return expr;
4970
4971                         left = new Argument (new EmptyExpression (method.ReturnType));
4972                         return CreateExpressionAddCall (ec, left, expr, pos);
4973                 }
4974
4975                 protected override Expression DoResolve (ResolveContext ec)
4976                 {
4977                         return this;
4978                 }
4979                 
4980                 void Append (ResolveContext rc, Expression operand)
4981                 {
4982                         //
4983                         // Constant folding
4984                         //
4985                         StringConstant sc = operand as StringConstant;
4986                         if (sc != null) {
4987                                 if (arguments.Count != 0) {
4988                                         Argument last_argument = arguments [arguments.Count - 1];
4989                                         StringConstant last_expr_constant = last_argument.Expr as StringConstant;
4990                                         if (last_expr_constant != null) {
4991                                                 last_argument.Expr = new StringConstant (rc.BuiltinTypes, last_expr_constant.Value + sc.Value, sc.Location);
4992                                                 return;
4993                                         }
4994                                 }
4995                         } else {
4996                                 //
4997                                 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
4998                                 //
4999                                 StringConcat concat_oper = operand as StringConcat;
5000                                 if (concat_oper != null) {
5001                                         arguments.AddRange (concat_oper.arguments);
5002                                         return;
5003                                 }
5004                         }
5005
5006                         arguments.Add (new Argument (operand));
5007                 }
5008
5009                 IList<MemberSpec> GetConcatMethodCandidates ()
5010                 {
5011                         return MemberCache.FindMembers (type, "Concat", true);
5012                 }
5013
5014                 public override void Emit (EmitContext ec)
5015                 {
5016                         // Optimize by removing any extra null arguments, they are no-op
5017                         for (int i = 0; i < arguments.Count; ++i) {
5018                                 if (arguments[i].Expr is NullConstant)
5019                                         arguments.RemoveAt (i--);
5020                         }
5021
5022                         var members = GetConcatMethodCandidates ();
5023                         var res = new OverloadResolver (members, OverloadResolver.Restrictions.NoBaseMembers, loc);
5024                         var method = res.ResolveMember<MethodSpec> (new ResolveContext (ec.MemberContext), ref arguments);
5025                         if (method != null) {
5026                                 var call = new CallEmitter ();
5027                                 call.EmitPredefined (ec, method, arguments);
5028                         }
5029                 }
5030
5031                 public override void FlowAnalysis (FlowAnalysisContext fc)
5032                 {
5033                         arguments.FlowAnalysis (fc);
5034                 }
5035
5036                 public override SLE.Expression MakeExpression (BuilderContext ctx)
5037                 {
5038                         if (arguments.Count != 2)
5039                                 throw new NotImplementedException ("arguments.Count != 2");
5040
5041                         var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
5042                         return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
5043                 }
5044         }
5045
5046         //
5047         // User-defined conditional logical operator
5048         //
5049         public class ConditionalLogicalOperator : UserOperatorCall
5050         {
5051                 readonly bool is_and;
5052                 Expression oper_expr;
5053
5054                 public ConditionalLogicalOperator (MethodSpec oper, Arguments arguments, Func<ResolveContext, Expression, Expression> expr_tree, bool is_and, Location loc)
5055                         : base (oper, arguments, expr_tree, loc)
5056                 {
5057                         this.is_and = is_and;
5058                         eclass = ExprClass.Unresolved;
5059                 }
5060                 
5061                 protected override Expression DoResolve (ResolveContext ec)
5062                 {
5063                         AParametersCollection pd = oper.Parameters;
5064                         if (!TypeSpecComparer.IsEqual (type, pd.Types[0]) || !TypeSpecComparer.IsEqual (type, pd.Types[1])) {
5065                                 ec.Report.Error (217, loc,
5066                                         "A user-defined operator `{0}' must have each parameter type and return type of the same type in order to be applicable as a short circuit operator",
5067                                         oper.GetSignatureForError ());
5068                                 return null;
5069                         }
5070
5071                         Expression left_dup = new EmptyExpression (type);
5072                         Expression op_true = GetOperatorTrue (ec, left_dup, loc);
5073                         Expression op_false = GetOperatorFalse (ec, left_dup, loc);
5074                         if (op_true == null || op_false == null) {
5075                                 ec.Report.Error (218, loc,
5076                                         "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
5077                                         type.GetSignatureForError (), oper.GetSignatureForError ());
5078                                 return null;
5079                         }
5080
5081                         oper_expr = is_and ? op_false : op_true;
5082                         eclass = ExprClass.Value;
5083                         return this;
5084                 }
5085
5086                 public override void Emit (EmitContext ec)
5087                 {
5088                         Label end_target = ec.DefineLabel ();
5089
5090                         //
5091                         // Emit and duplicate left argument
5092                         //
5093                         bool right_contains_await = ec.HasSet (BuilderContext.Options.AsyncBody) && arguments[1].Expr.ContainsEmitWithAwait ();
5094                         if (right_contains_await) {
5095                                 arguments[0] = arguments[0].EmitToField (ec, false);
5096                                 arguments[0].Expr.Emit (ec);
5097                         } else {
5098                                 arguments[0].Expr.Emit (ec);
5099                                 ec.Emit (OpCodes.Dup);
5100                                 arguments.RemoveAt (0);
5101                         }
5102
5103                         oper_expr.EmitBranchable (ec, end_target, true);
5104
5105                         base.Emit (ec);
5106
5107                         if (right_contains_await) {
5108                                 //
5109                                 // Special handling when right expression contains await and left argument
5110                                 // could not be left on stack before logical branch
5111                                 //
5112                                 Label skip_left_load = ec.DefineLabel ();
5113                                 ec.Emit (OpCodes.Br_S, skip_left_load);
5114                                 ec.MarkLabel (end_target);
5115                                 arguments[0].Expr.Emit (ec);
5116                                 ec.MarkLabel (skip_left_load);
5117                         } else {
5118                                 ec.MarkLabel (end_target);
5119                         }
5120                 }
5121         }
5122
5123         public class PointerArithmetic : Expression {
5124                 Expression left, right;
5125                 readonly Binary.Operator op;
5126
5127                 //
5128                 // We assume that `l' is always a pointer
5129                 //
5130                 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
5131                 {
5132                         type = t;
5133                         this.loc = loc;
5134                         left = l;
5135                         right = r;
5136                         this.op = op;
5137                 }
5138
5139                 public override bool ContainsEmitWithAwait ()
5140                 {
5141                         throw new NotImplementedException ();
5142                 }
5143
5144                 public override Expression CreateExpressionTree (ResolveContext ec)
5145                 {
5146                         Error_PointerInsideExpressionTree (ec);
5147                         return null;
5148                 }
5149
5150                 protected override Expression DoResolve (ResolveContext ec)
5151                 {
5152                         eclass = ExprClass.Variable;
5153
5154                         var pc = left.Type as PointerContainer;
5155                         if (pc != null && pc.Element.Kind == MemberKind.Void) {
5156                                 Error_VoidPointerOperation (ec);
5157                                 return null;
5158                         }
5159                         
5160                         return this;
5161                 }
5162
5163                 public override void Emit (EmitContext ec)
5164                 {
5165                         TypeSpec op_type = left.Type;
5166                         
5167                         // It must be either array or fixed buffer
5168                         TypeSpec element;
5169                         if (TypeManager.HasElementType (op_type)) {
5170                                 element = TypeManager.GetElementType (op_type);
5171                         } else {
5172                                 FieldExpr fe = left as FieldExpr;
5173                                 if (fe != null)
5174                                         element = ((FixedFieldSpec) (fe.Spec)).ElementType;
5175                                 else
5176                                         element = op_type;
5177                         }
5178
5179                         int size = BuiltinTypeSpec.GetSize(element);
5180                         TypeSpec rtype = right.Type;
5181                         
5182                         if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
5183                                 //
5184                                 // handle (pointer - pointer)
5185                                 //
5186                                 left.Emit (ec);
5187                                 right.Emit (ec);
5188                                 ec.Emit (OpCodes.Sub);
5189
5190                                 if (size != 1){
5191                                         if (size == 0)
5192                                                 ec.Emit (OpCodes.Sizeof, element);
5193                                         else 
5194                                                 ec.EmitInt (size);
5195                                         ec.Emit (OpCodes.Div);
5196                                 }
5197                                 ec.Emit (OpCodes.Conv_I8);
5198                         } else {
5199                                 //
5200                                 // handle + and - on (pointer op int)
5201                                 //
5202                                 Constant left_const = left as Constant;
5203                                 if (left_const != null) {
5204                                         //
5205                                         // Optimize ((T*)null) pointer operations
5206                                         //
5207                                         if (left_const.IsDefaultValue) {
5208                                                 left = EmptyExpression.Null;
5209                                         } else {
5210                                                 left_const = null;
5211                                         }
5212                                 }
5213
5214                                 left.Emit (ec);
5215
5216                                 var right_const = right as Constant;
5217                                 if (right_const != null) {
5218                                         //
5219                                         // Optimize 0-based arithmetic
5220                                         //
5221                                         if (right_const.IsDefaultValue)
5222                                                 return;
5223
5224                                         if (size != 0)
5225                                                 right = new IntConstant (ec.BuiltinTypes, size, right.Location);
5226                                         else
5227                                                 right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
5228                                         
5229                                         // TODO: Should be the checks resolve context sensitive?
5230                                         ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
5231                                         right = new Binary (Binary.Operator.Multiply, right, right_const).Resolve (rc);
5232                                         if (right == null)
5233                                                 return;
5234                                 }
5235
5236                                 right.Emit (ec);
5237                                 switch (rtype.BuiltinType) {
5238                                 case BuiltinTypeSpec.Type.SByte:
5239                                 case BuiltinTypeSpec.Type.Byte:
5240                                 case BuiltinTypeSpec.Type.Short:
5241                                 case BuiltinTypeSpec.Type.UShort:
5242                                         ec.Emit (OpCodes.Conv_I);
5243                                         break;
5244                                 case BuiltinTypeSpec.Type.UInt:
5245                                         ec.Emit (OpCodes.Conv_U);
5246                                         break;
5247                                 }
5248
5249                                 if (right_const == null && size != 1){
5250                                         if (size == 0)
5251                                                 ec.Emit (OpCodes.Sizeof, element);
5252                                         else 
5253                                                 ec.EmitInt (size);
5254                                         if (rtype.BuiltinType == BuiltinTypeSpec.Type.Long || rtype.BuiltinType == BuiltinTypeSpec.Type.ULong)
5255                                                 ec.Emit (OpCodes.Conv_I8);
5256
5257                                         Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype, right);
5258                                 }
5259
5260                                 if (left_const == null) {
5261                                         if (rtype.BuiltinType == BuiltinTypeSpec.Type.Long)
5262                                                 ec.Emit (OpCodes.Conv_I);
5263                                         else if (rtype.BuiltinType == BuiltinTypeSpec.Type.ULong)
5264                                                 ec.Emit (OpCodes.Conv_U);
5265
5266                                         Binary.EmitOperatorOpcode (ec, op, op_type, right);
5267                                 }
5268                         }
5269                 }
5270         }
5271
5272         //
5273         // A boolean-expression is an expression that yields a result
5274         // of type bool
5275         //
5276         public class BooleanExpression : ShimExpression
5277         {
5278                 public BooleanExpression (Expression expr)
5279                         : base (expr)
5280                 {
5281                         this.loc = expr.Location;
5282                 }
5283
5284                 public override Expression CreateExpressionTree (ResolveContext ec)
5285                 {
5286                         // TODO: We should emit IsTrue (v4) instead of direct user operator
5287                         // call but that would break csc compatibility
5288                         return base.CreateExpressionTree (ec);
5289                 }
5290
5291                 protected override Expression DoResolve (ResolveContext ec)
5292                 {
5293                         // A boolean-expression is required to be of a type
5294                         // that can be implicitly converted to bool or of
5295                         // a type that implements operator true
5296
5297                         expr = expr.Resolve (ec);
5298                         if (expr == null)
5299                                 return null;
5300
5301                         Assign ass = expr as Assign;
5302                         if (ass != null && ass.Source is Constant) {
5303                                 ec.Report.Warning (665, 3, loc,
5304                                         "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
5305                         }
5306
5307                         if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Bool)
5308                                 return expr;
5309
5310                         if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
5311                                 Arguments args = new Arguments (1);
5312                                 args.Add (new Argument (expr));
5313                                 return DynamicUnaryConversion.CreateIsTrue (ec, args, loc).Resolve (ec);
5314                         }
5315
5316                         type = ec.BuiltinTypes.Bool;
5317                         Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
5318                         if (converted != null)
5319                                 return converted;
5320
5321                         //
5322                         // If no implicit conversion to bool exists, try using `operator true'
5323                         //
5324                         converted = GetOperatorTrue (ec, expr, loc);
5325                         if (converted == null) {
5326                                 expr.Error_ValueCannotBeConverted (ec, type, false);
5327                                 return null;
5328                         }
5329
5330                         return converted;
5331                 }
5332                 
5333                 public override object Accept (StructuralVisitor visitor)
5334                 {
5335                         return visitor.Visit (this);
5336                 }
5337         }
5338
5339         public class BooleanExpressionFalse : Unary
5340         {
5341                 public BooleanExpressionFalse (Expression expr)
5342                         : base (Operator.LogicalNot, expr, expr.Location)
5343                 {
5344                 }
5345
5346                 protected override Expression ResolveOperator (ResolveContext ec, Expression expr)
5347                 {
5348                         return GetOperatorFalse (ec, expr, loc) ?? base.ResolveOperator (ec, expr);
5349                 }
5350         }
5351         
5352         /// <summary>
5353         ///   Implements the ternary conditional operator (?:)
5354         /// </summary>
5355         public class Conditional : Expression {
5356                 Expression expr, true_expr, false_expr;
5357
5358                 public Conditional (Expression expr, Expression true_expr, Expression false_expr, Location loc)
5359                 {
5360                         this.expr = expr;
5361                         this.true_expr = true_expr;
5362                         this.false_expr = false_expr;
5363                         this.loc = loc;
5364                 }
5365
5366                 #region Properties
5367
5368                 public Expression Expr {
5369                         get {
5370                                 return expr;
5371                         }
5372                 }
5373
5374                 public Expression TrueExpr {
5375                         get {
5376                                 return true_expr;
5377                         }
5378                 }
5379
5380                 public Expression FalseExpr {
5381                         get {
5382                                 return false_expr;
5383                         }
5384                 }
5385
5386                 #endregion
5387
5388                 public override bool ContainsEmitWithAwait ()
5389                 {
5390                         return Expr.ContainsEmitWithAwait () || true_expr.ContainsEmitWithAwait () || false_expr.ContainsEmitWithAwait ();
5391                 }
5392
5393                 public override Expression CreateExpressionTree (ResolveContext ec)
5394                 {
5395                         Arguments args = new Arguments (3);
5396                         args.Add (new Argument (expr.CreateExpressionTree (ec)));
5397                         args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
5398                         args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
5399                         return CreateExpressionFactoryCall (ec, "Condition", args);
5400                 }
5401
5402                 protected override Expression DoResolve (ResolveContext ec)
5403                 {
5404                         expr = expr.Resolve (ec);
5405                         true_expr = true_expr.Resolve (ec);
5406                         false_expr = false_expr.Resolve (ec);
5407
5408                         if (true_expr == null || false_expr == null || expr == null)
5409                                 return null;
5410
5411                         eclass = ExprClass.Value;
5412                         TypeSpec true_type = true_expr.Type;
5413                         TypeSpec false_type = false_expr.Type;
5414                         type = true_type;
5415
5416                         //
5417                         // First, if an implicit conversion exists from true_expr
5418                         // to false_expr, then the result type is of type false_expr.Type
5419                         //
5420                         if (!TypeSpecComparer.IsEqual (true_type, false_type)) {
5421                                 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
5422                                 if (conv != null && true_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
5423                                         //
5424                                         // Check if both can convert implicitly to each other's type
5425                                         //
5426                                         type = false_type;
5427
5428                                         if (false_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
5429                                                 var conv_false_expr = Convert.ImplicitConversion (ec, false_expr, true_type, loc);
5430                                                 //
5431                                                 // LAMESPEC: There seems to be hardcoded promotition to int type when
5432                                                 // both sides are numeric constants and one side is int constant and
5433                                                 // other side is numeric constant convertible to int.
5434                                                 //
5435                                                 // var res = condition ? (short)1 : 1;
5436                                                 //
5437                                                 // Type of res is int even if according to the spec the conversion is
5438                                                 // ambiguous because 1 literal can be converted to short.
5439                                                 //
5440                                                 if (conv_false_expr != null) {
5441                                                         if (conv_false_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Int && conv is Constant) {
5442                                                                 type = true_type;
5443                                                                 conv_false_expr = null;
5444                                                         } else if (type.BuiltinType == BuiltinTypeSpec.Type.Int && conv_false_expr is Constant) {
5445                                                                 conv_false_expr = null;
5446                                                         }
5447                                                 }
5448
5449                                                 if (conv_false_expr != null) {
5450                                                         ec.Report.Error (172, true_expr.Location,
5451                                                                 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
5452                                                                         true_type.GetSignatureForError (), false_type.GetSignatureForError ());
5453                                                 }
5454                                         }
5455
5456                                         true_expr = conv;
5457                                         if (true_expr.Type != type)
5458                                                 true_expr = EmptyCast.Create (true_expr, type);
5459                                 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
5460                                         false_expr = conv;
5461                                 } else {
5462                                         ec.Report.Error (173, true_expr.Location,
5463                                                 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
5464                                                 true_type.GetSignatureForError (), false_type.GetSignatureForError ());
5465                                         return null;
5466                                 }
5467                         }
5468
5469                         Constant c = expr as Constant;
5470                         if (c != null) {
5471                                 bool is_false = c.IsDefaultValue;
5472
5473                                 //
5474                                 // Don't issue the warning for constant expressions
5475                                 //
5476                                 if (!(is_false ? true_expr is Constant : false_expr is Constant)) {
5477                                         // CSC: Missing warning
5478                                         Warning_UnreachableExpression (ec, is_false ? true_expr.Location : false_expr.Location);
5479                                 }
5480
5481                                 return ReducedExpression.Create (
5482                                         is_false ? false_expr : true_expr, this,
5483                                         false_expr is Constant && true_expr is Constant).Resolve (ec);
5484                         }
5485
5486                         return this;
5487                 }
5488
5489                 public override void Emit (EmitContext ec)
5490                 {
5491                         Label false_target = ec.DefineLabel ();
5492                         Label end_target = ec.DefineLabel ();
5493
5494                         expr.EmitBranchable (ec, false_target, false);
5495                         true_expr.Emit (ec);
5496
5497                         //
5498                         // Verifier doesn't support interface merging. When there are two types on
5499                         // the stack without common type hint and the common type is an interface.
5500                         // Use temporary local to give verifier hint on what type to unify the stack
5501                         //
5502                         if (type.IsInterface && true_expr is EmptyCast && false_expr is EmptyCast) {
5503                                 var temp = ec.GetTemporaryLocal (type);
5504                                 ec.Emit (OpCodes.Stloc, temp);
5505                                 ec.Emit (OpCodes.Ldloc, temp);
5506                                 ec.FreeTemporaryLocal (temp, type);
5507                         }
5508
5509                         ec.Emit (OpCodes.Br, end_target);
5510                         ec.MarkLabel (false_target);
5511                         false_expr.Emit (ec);
5512                         ec.MarkLabel (end_target);
5513                 }
5514
5515                 public override void FlowAnalysis (FlowAnalysisContext fc)
5516                 {
5517                         fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment;
5518
5519                         expr.FlowAnalysis (fc);
5520                         var da_true = fc.DefiniteAssignmentOnTrue;
5521                         var da_false = fc.DefiniteAssignmentOnFalse;
5522
5523                         fc.DefiniteAssignment = new DefiniteAssignmentBitSet (da_true);
5524                         true_expr.FlowAnalysis (fc);
5525                         var true_fc = fc.DefiniteAssignment;
5526
5527                         fc.DefiniteAssignment = new DefiniteAssignmentBitSet (da_false);
5528                         false_expr.FlowAnalysis (fc);
5529
5530                         fc.DefiniteAssignment &= true_fc;
5531                         if (fc.DefiniteAssignmentOnTrue != null)
5532                                 fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignment;
5533                         if (fc.DefiniteAssignmentOnFalse != null)
5534                                 fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment;
5535                 }
5536
5537                 protected override void CloneTo (CloneContext clonectx, Expression t)
5538                 {
5539                         Conditional target = (Conditional) t;
5540
5541                         target.expr = expr.Clone (clonectx);
5542                         target.true_expr = true_expr.Clone (clonectx);
5543                         target.false_expr = false_expr.Clone (clonectx);
5544                 }
5545         }
5546
5547         public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference
5548         {
5549                 LocalTemporary temp;
5550
5551                 #region Abstract
5552                 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
5553                 public abstract void SetHasAddressTaken ();
5554
5555                 public abstract bool IsLockedByStatement { get; set; }
5556
5557                 public abstract bool IsFixed { get; }
5558                 public abstract bool IsRef { get; }
5559                 public abstract string Name { get; }
5560
5561                 //
5562                 // Variable IL data, it has to be protected to encapsulate hoisted variables
5563                 //
5564                 protected abstract ILocalVariable Variable { get; }
5565                 
5566                 //
5567                 // Variable flow-analysis data
5568                 //
5569                 public abstract VariableInfo VariableInfo { get; }
5570                 #endregion
5571
5572                 public virtual void AddressOf (EmitContext ec, AddressOp mode)
5573                 {
5574                         HoistedVariable hv = GetHoistedVariable (ec);
5575                         if (hv != null) {
5576                                 hv.AddressOf (ec, mode);
5577                                 return;
5578                         }
5579
5580                         Variable.EmitAddressOf (ec);
5581                 }
5582
5583                 public override bool ContainsEmitWithAwait ()
5584                 {
5585                         return false;
5586                 }
5587
5588                 public override Expression CreateExpressionTree (ResolveContext ec)
5589                 {
5590                         HoistedVariable hv = GetHoistedVariable (ec);
5591                         if (hv != null)
5592                                 return hv.CreateExpressionTree ();
5593
5594                         Arguments arg = new Arguments (1);
5595                         arg.Add (new Argument (this));
5596                         return CreateExpressionFactoryCall (ec, "Constant", arg);
5597                 }
5598
5599                 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
5600                 {
5601                         if (IsLockedByStatement) {
5602                                 rc.Report.Warning (728, 2, loc,
5603                                         "Possibly incorrect assignment to `{0}' which is the argument to a using or lock statement",
5604                                         Name);
5605                         }
5606
5607                         return this;
5608                 }
5609
5610                 public override void Emit (EmitContext ec)
5611                 {
5612                         Emit (ec, false);
5613                 }
5614
5615                 public override void EmitSideEffect (EmitContext ec)
5616                 {
5617                         // do nothing
5618                 }
5619
5620                 //
5621                 // This method is used by parameters that are references, that are
5622                 // being passed as references:  we only want to pass the pointer (that
5623                 // is already stored in the parameter, not the address of the pointer,
5624                 // and not the value of the variable).
5625                 //
5626                 public void EmitLoad (EmitContext ec)
5627                 {
5628                         Variable.Emit (ec);
5629                 }
5630
5631                 public void Emit (EmitContext ec, bool leave_copy)
5632                 {
5633                         HoistedVariable hv = GetHoistedVariable (ec);
5634                         if (hv != null) {
5635                                 hv.Emit (ec, leave_copy);
5636                                 return;
5637                         }
5638
5639                         EmitLoad (ec);
5640
5641                         if (IsRef) {
5642                                 //
5643                                 // If we are a reference, we loaded on the stack a pointer
5644                                 // Now lets load the real value
5645                                 //
5646                                 ec.EmitLoadFromPtr (type);
5647                         }
5648
5649                         if (leave_copy) {
5650                                 ec.Emit (OpCodes.Dup);
5651
5652                                 if (IsRef) {
5653                                         temp = new LocalTemporary (Type);
5654                                         temp.Store (ec);
5655                                 }
5656                         }
5657                 }
5658
5659                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
5660                                         bool prepare_for_load)
5661                 {
5662                         HoistedVariable hv = GetHoistedVariable (ec);
5663                         if (hv != null) {
5664                                 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
5665                                 return;
5666                         }
5667
5668                         New n_source = source as New;
5669                         if (n_source != null) {
5670                                 if (!n_source.Emit (ec, this)) {
5671                                         if (leave_copy) {
5672                                                 EmitLoad (ec);
5673                                                 if (IsRef)
5674                                                         ec.EmitLoadFromPtr (type);
5675                                         }
5676                                         return;
5677                                 }
5678                         } else {
5679                                 if (IsRef)
5680                                         EmitLoad (ec);
5681
5682                                 source.Emit (ec);
5683                         }
5684
5685                         if (leave_copy) {
5686                                 ec.Emit (OpCodes.Dup);
5687                                 if (IsRef) {
5688                                         temp = new LocalTemporary (Type);
5689                                         temp.Store (ec);
5690                                 }
5691                         }
5692
5693                         if (IsRef)
5694                                 ec.EmitStoreFromPtr (type);
5695                         else
5696                                 Variable.EmitAssign (ec);
5697
5698                         if (temp != null) {
5699                                 temp.Emit (ec);
5700                                 temp.Release (ec);
5701                         }
5702                 }
5703
5704                 public override Expression EmitToField (EmitContext ec)
5705                 {
5706                         HoistedVariable hv = GetHoistedVariable (ec);
5707                         if (hv != null) {
5708                                 return hv.EmitToField (ec);
5709                         }
5710
5711                         return base.EmitToField (ec);
5712                 }
5713
5714                 public HoistedVariable GetHoistedVariable (ResolveContext rc)
5715                 {
5716                         return GetHoistedVariable (rc.CurrentAnonymousMethod);
5717                 }
5718
5719                 public HoistedVariable GetHoistedVariable (EmitContext ec)
5720                 {
5721                         return GetHoistedVariable (ec.CurrentAnonymousMethod);
5722                 }
5723
5724                 public override string GetSignatureForError ()
5725                 {
5726                         return Name;
5727                 }
5728
5729                 public bool IsHoisted {
5730                         get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
5731                 }
5732         }
5733
5734         //
5735         // Resolved reference to a local variable
5736         //
5737         public class LocalVariableReference : VariableReference
5738         {
5739                 public LocalVariable local_info;
5740
5741                 public LocalVariableReference (LocalVariable li, Location l)
5742                 {
5743                         this.local_info = li;
5744                         loc = l;
5745                 }
5746
5747                 public override VariableInfo VariableInfo {
5748                         get { return local_info.VariableInfo; }
5749                 }
5750
5751                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
5752                 {
5753                         return local_info.HoistedVariant;
5754                 }
5755
5756                 #region Properties
5757
5758                 //              
5759                 // A local variable is always fixed
5760                 //
5761                 public override bool IsFixed {
5762                         get {
5763                                 return true;
5764                         }
5765                 }
5766
5767                 public override bool IsLockedByStatement {
5768                         get {
5769                                 return local_info.IsLocked;
5770                         }
5771                         set {
5772                                 local_info.IsLocked = value;
5773                         }
5774                 }
5775
5776                 public override bool IsRef {
5777                         get { return false; }
5778                 }
5779
5780                 public override string Name {
5781                         get { return local_info.Name; }
5782                 }
5783
5784                 #endregion
5785
5786                 public override void FlowAnalysis (FlowAnalysisContext fc)
5787                 {
5788                         VariableInfo variable_info = VariableInfo;
5789                         if (variable_info == null)
5790                                 return;
5791
5792                         if (fc.IsDefinitelyAssigned (variable_info))
5793                                 return;
5794
5795                         fc.Report.Error (165, loc, "Use of unassigned local variable `{0}'", Name);
5796                         variable_info.SetAssigned (fc.DefiniteAssignment, true);
5797                 }
5798
5799                 public override void SetHasAddressTaken ()
5800                 {
5801                         local_info.SetHasAddressTaken ();
5802                 }
5803
5804                 void DoResolveBase (ResolveContext ec)
5805                 {
5806                         //
5807                         // If we are referencing a variable from the external block
5808                         // flag it for capturing
5809                         //
5810                         if (ec.MustCaptureVariable (local_info)) {
5811                                 if (local_info.AddressTaken) {
5812                                         AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
5813                                 } else if (local_info.IsFixed) {
5814                                         ec.Report.Error (1764, loc,
5815                                                 "Cannot use fixed local `{0}' inside an anonymous method, lambda expression or query expression",
5816                                                 GetSignatureForError ());
5817                                 }
5818
5819                                 if (ec.IsVariableCapturingRequired) {
5820                                         AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
5821                                         storey.CaptureLocalVariable (ec, local_info);
5822                                 }
5823                         }
5824
5825                         eclass = ExprClass.Variable;
5826                         type = local_info.Type;
5827                 }
5828
5829                 protected override Expression DoResolve (ResolveContext ec)
5830                 {
5831                         local_info.SetIsUsed ();
5832
5833                         DoResolveBase (ec);
5834                         return this;
5835                 }
5836
5837                 public override Expression DoResolveLValue (ResolveContext ec, Expression rhs)
5838                 {
5839                         //
5840                         // Don't be too pedantic when variable is used as out param or for some broken code
5841                         // which uses property/indexer access to run some initialization
5842                         //
5843                         if (rhs == EmptyExpression.OutAccess || rhs.eclass == ExprClass.PropertyAccess || rhs.eclass == ExprClass.IndexerAccess)
5844                                 local_info.SetIsUsed ();
5845
5846                         if (local_info.IsReadonly && !ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.UsingInitializerScope)) {
5847                                 if (rhs == EmptyExpression.LValueMemberAccess) {
5848                                         // CS1654 already reported
5849                                 } else {
5850                                         int code;
5851                                         string msg;
5852                                         if (rhs == EmptyExpression.OutAccess) {
5853                                                 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
5854                                         } else if (rhs == EmptyExpression.LValueMemberOutAccess) {
5855                                                 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
5856                                         } else if (rhs == EmptyExpression.UnaryAddress) {
5857                                                 code = 459; msg = "Cannot take the address of {1} `{0}'";
5858                                         } else {
5859                                                 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
5860                                         }
5861                                         ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
5862                                 }
5863                         }
5864
5865                         if (eclass == ExprClass.Unresolved)
5866                                 DoResolveBase (ec);
5867
5868                         return base.DoResolveLValue (ec, rhs);
5869                 }
5870
5871                 public override int GetHashCode ()
5872                 {
5873                         return local_info.GetHashCode ();
5874                 }
5875
5876                 public override bool Equals (object obj)
5877                 {
5878                         LocalVariableReference lvr = obj as LocalVariableReference;
5879                         if (lvr == null)
5880                                 return false;
5881
5882                         return local_info == lvr.local_info;
5883                 }
5884
5885                 protected override ILocalVariable Variable {
5886                         get { return local_info; }
5887                 }
5888
5889                 public override string ToString ()
5890                 {
5891                         return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
5892                 }
5893
5894                 protected override void CloneTo (CloneContext clonectx, Expression t)
5895                 {
5896                         // Nothing
5897                 }
5898         }
5899
5900         /// <summary>
5901         ///   This represents a reference to a parameter in the intermediate
5902         ///   representation.
5903         /// </summary>
5904         public class ParameterReference : VariableReference
5905         {
5906                 protected ParametersBlock.ParameterInfo pi;
5907
5908                 public ParameterReference (ParametersBlock.ParameterInfo pi, Location loc)
5909                 {
5910                         this.pi = pi;
5911                         this.loc = loc;
5912                 }
5913
5914                 #region Properties
5915
5916                 public override bool IsLockedByStatement {
5917                         get {
5918                                 return pi.IsLocked;
5919                         }
5920                         set     {
5921                                 pi.IsLocked = value;
5922                         }
5923                 }
5924
5925                 public override bool IsRef {
5926                         get { return (pi.Parameter.ModFlags & Parameter.Modifier.RefOutMask) != 0; }
5927                 }
5928
5929                 bool HasOutModifier {
5930                         get { return (pi.Parameter.ModFlags & Parameter.Modifier.OUT) != 0; }
5931                 }
5932
5933                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
5934                 {
5935                         return pi.Parameter.HoistedVariant;
5936                 }
5937
5938                 //
5939                 // A ref or out parameter is classified as a moveable variable, even 
5940                 // if the argument given for the parameter is a fixed variable
5941                 //              
5942                 public override bool IsFixed {
5943                         get { return !IsRef; }
5944                 }
5945
5946                 public override string Name {
5947                         get { return Parameter.Name; }
5948                 }
5949
5950                 public Parameter Parameter {
5951                         get { return pi.Parameter; }
5952                 }
5953
5954                 public override VariableInfo VariableInfo {
5955                         get { return pi.VariableInfo; }
5956                 }
5957
5958                 protected override ILocalVariable Variable {
5959                         get { return Parameter; }
5960                 }
5961
5962                 #endregion
5963
5964                 public override void AddressOf (EmitContext ec, AddressOp mode)
5965                 {
5966                         //
5967                         // ParameterReferences might already be a reference
5968                         //
5969                         if (IsRef) {
5970                                 EmitLoad (ec);
5971                                 return;
5972                         }
5973
5974                         base.AddressOf (ec, mode);
5975                 }
5976
5977                 public override void SetHasAddressTaken ()
5978                 {
5979                         Parameter.HasAddressTaken = true;
5980                 }
5981
5982                 bool DoResolveBase (ResolveContext ec)
5983                 {
5984                         if (eclass != ExprClass.Unresolved)
5985                                 return true;
5986
5987                         type = pi.ParameterType;
5988                         eclass = ExprClass.Variable;
5989
5990                         //
5991                         // If we are referencing a parameter from the external block
5992                         // flag it for capturing
5993                         //
5994                         if (ec.MustCaptureVariable (pi)) {
5995                                 if (Parameter.HasAddressTaken)
5996                                         AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
5997
5998                                 if (IsRef) {
5999                                         ec.Report.Error (1628, loc,
6000                                                 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
6001                                                 Name, ec.CurrentAnonymousMethod.ContainerType);
6002                                 }
6003
6004                                 if (ec.IsVariableCapturingRequired && !pi.Block.ParametersBlock.IsExpressionTree) {
6005                                         AnonymousMethodStorey storey = pi.Block.Explicit.CreateAnonymousMethodStorey (ec);
6006                                         storey.CaptureParameter (ec, pi, this);
6007                                 }
6008                         }
6009
6010                         return true;
6011                 }
6012
6013                 public override int GetHashCode ()
6014                 {
6015                         return Name.GetHashCode ();
6016                 }
6017
6018                 public override bool Equals (object obj)
6019                 {
6020                         ParameterReference pr = obj as ParameterReference;
6021                         if (pr == null)
6022                                 return false;
6023
6024                         return Name == pr.Name;
6025                 }
6026         
6027                 protected override void CloneTo (CloneContext clonectx, Expression target)
6028                 {
6029                         // Nothing to clone
6030                         return;
6031                 }
6032
6033                 public override Expression CreateExpressionTree (ResolveContext ec)
6034                 {
6035                         HoistedVariable hv = GetHoistedVariable (ec);
6036                         if (hv != null)
6037                                 return hv.CreateExpressionTree ();
6038
6039                         return Parameter.ExpressionTreeVariableReference ();
6040                 }
6041
6042                 protected override Expression DoResolve (ResolveContext ec)
6043                 {
6044                         if (!DoResolveBase (ec))
6045                                 return null;
6046
6047                         return this;
6048                 }
6049
6050                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6051                 {
6052                         if (!DoResolveBase (ec))
6053                                 return null;
6054
6055                         if (Parameter.HoistedVariant != null)
6056                                 Parameter.HoistedVariant.IsAssigned = true;
6057
6058                         return base.DoResolveLValue (ec, right_side);
6059                 }
6060
6061                 public override void FlowAnalysis (FlowAnalysisContext fc)
6062                 {
6063                         VariableInfo variable_info = VariableInfo;
6064                         if (variable_info == null)
6065                                 return;
6066
6067                         if (fc.IsDefinitelyAssigned (variable_info))
6068                                 return;
6069
6070                         fc.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
6071                         fc.SetVariableAssigned (variable_info);
6072                 }
6073         }
6074         
6075         /// <summary>
6076         ///   Invocation of methods or delegates.
6077         /// </summary>
6078         public class Invocation : ExpressionStatement
6079         {
6080                 protected Arguments arguments;
6081                 protected Expression expr;
6082                 protected MethodGroupExpr mg;
6083                 
6084                 public Invocation (Expression expr, Arguments arguments)
6085                 {
6086                         this.expr = expr;               
6087                         this.arguments = arguments;
6088                         if (expr != null) {
6089                                 loc = expr.Location;
6090                         }
6091                 }
6092
6093                 #region Properties
6094                 public Arguments Arguments {
6095                         get {
6096                                 return arguments;
6097                         }
6098                 }
6099                 
6100                 public Expression Exp {
6101                         get {
6102                                 return expr;
6103                         }
6104                 }
6105
6106                 public MethodGroupExpr MethodGroup {
6107                         get {
6108                                 return mg;
6109                         }
6110                 }
6111
6112                 public override Location StartLocation {
6113                         get {
6114                                 return expr.StartLocation;
6115                         }
6116                 }
6117
6118                 #endregion
6119
6120                 public override MethodGroupExpr CanReduceLambda (AnonymousMethodBody body)
6121                 {
6122                         if (MethodGroup == null)
6123                                 return null;
6124
6125                         var candidate = MethodGroup.BestCandidate;
6126                         if (candidate == null || !(candidate.IsStatic || Exp is This))
6127                                 return null;
6128
6129                         var args_count = arguments == null ? 0 : arguments.Count;
6130                         if (args_count != body.Parameters.Count)
6131                                 return null;
6132
6133                         var lambda_parameters = body.Block.Parameters.FixedParameters;
6134                         for (int i = 0; i < args_count; ++i) {
6135                                 var pr = arguments[i].Expr as ParameterReference;
6136                                 if (pr == null)
6137                                         return null;
6138
6139                                 if (lambda_parameters[i] != pr.Parameter)
6140                                         return null;
6141
6142                                 if ((lambda_parameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (pr.Parameter.ModFlags & Parameter.Modifier.RefOutMask))
6143                                         return null;
6144                         }
6145
6146                         var emg = MethodGroup as ExtensionMethodGroupExpr;
6147                         if (emg != null) {
6148                                 var mg = MethodGroupExpr.CreatePredefined (candidate, candidate.DeclaringType, MethodGroup.Location);
6149                                 if (candidate.IsGeneric) {
6150                                         var targs = new TypeExpression [candidate.Arity];
6151                                         for (int i = 0; i < targs.Length; ++i) {
6152                                                 targs[i] = new TypeExpression (candidate.TypeArguments[i], MethodGroup.Location);
6153                                         }
6154
6155                                         mg.SetTypeArguments (null, new TypeArguments (targs));
6156                                 }
6157
6158                                 return mg;
6159                         }
6160
6161                         return MethodGroup;
6162                 }
6163
6164                 protected override void CloneTo (CloneContext clonectx, Expression t)
6165                 {
6166                         Invocation target = (Invocation) t;
6167
6168                         if (arguments != null)
6169                                 target.arguments = arguments.Clone (clonectx);
6170
6171                         target.expr = expr.Clone (clonectx);
6172                 }
6173
6174                 public override bool ContainsEmitWithAwait ()
6175                 {
6176                         if (arguments != null && arguments.ContainsEmitWithAwait ())
6177                                 return true;
6178
6179                         return mg.ContainsEmitWithAwait ();
6180                 }
6181
6182                 public override Expression CreateExpressionTree (ResolveContext ec)
6183                 {
6184                         Expression instance = mg.IsInstance ?
6185                                 mg.InstanceExpression.CreateExpressionTree (ec) :
6186                                 new NullLiteral (loc);
6187
6188                         var args = Arguments.CreateForExpressionTree (ec, arguments,
6189                                 instance,
6190                                 mg.CreateExpressionTree (ec));
6191
6192                         return CreateExpressionFactoryCall (ec, "Call", args);
6193                 }
6194
6195                 protected override Expression DoResolve (ResolveContext ec)
6196                 {
6197                         Expression member_expr;
6198                         var atn = expr as ATypeNameExpression;
6199                         if (atn != null) {
6200                                 member_expr = atn.LookupNameExpression (ec, MemberLookupRestrictions.InvocableOnly | MemberLookupRestrictions.ReadAccess);
6201                                 if (member_expr != null)
6202                                         member_expr = member_expr.Resolve (ec);
6203                         } else {
6204                                 member_expr = expr.Resolve (ec);
6205                         }
6206
6207                         if (member_expr == null)
6208                                 return null;
6209
6210                         //
6211                         // Next, evaluate all the expressions in the argument list
6212                         //
6213                         bool dynamic_arg = false;
6214                         if (arguments != null)
6215                                 arguments.Resolve (ec, out dynamic_arg);
6216
6217                         TypeSpec expr_type = member_expr.Type;
6218                         if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
6219                                 return DoResolveDynamic (ec, member_expr);
6220
6221                         mg = member_expr as MethodGroupExpr;
6222                         Expression invoke = null;
6223
6224                         if (mg == null) {
6225                                 if (expr_type != null && expr_type.IsDelegate) {
6226                                         invoke = new DelegateInvocation (member_expr, arguments, loc);
6227                                         invoke = invoke.Resolve (ec);
6228                                         if (invoke == null || !dynamic_arg)
6229                                                 return invoke;
6230                                 } else {
6231                                         if (member_expr is RuntimeValueExpression) {
6232                                                 ec.Report.Error (Report.RuntimeErrorId, loc, "Cannot invoke a non-delegate type `{0}'",
6233                                                         member_expr.Type.GetSignatureForError ());
6234                                                 return null;
6235                                         }
6236
6237                                         MemberExpr me = member_expr as MemberExpr;
6238                                         if (me == null) {
6239                                                 member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
6240                                                 return null;
6241                                         }
6242
6243                                         ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
6244                                                         member_expr.GetSignatureForError ());
6245                                         return null;
6246                                 }
6247                         }
6248
6249                         if (invoke == null) {
6250                                 mg = DoResolveOverload (ec);
6251                                 if (mg == null)
6252                                         return null;
6253                         }
6254
6255                         if (dynamic_arg)
6256                                 return DoResolveDynamic (ec, member_expr);
6257
6258                         var method = mg.BestCandidate;
6259                         type = mg.BestCandidateReturnType;
6260                 
6261                         if (arguments == null && method.DeclaringType.BuiltinType == BuiltinTypeSpec.Type.Object && method.Name == Destructor.MetadataName) {
6262                                 if (mg.IsBase)
6263                                         ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
6264                                 else
6265                                         ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
6266                                 return null;
6267                         }
6268
6269                         IsSpecialMethodInvocation (ec, method, loc);
6270                         
6271                         eclass = ExprClass.Value;
6272                         return this;
6273                 }
6274
6275                 protected virtual Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
6276                 {
6277                         Arguments args;
6278                         DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
6279                         if (dmb != null) {
6280                                 args = dmb.Arguments;
6281                                 if (arguments != null)
6282                                         args.AddRange (arguments);
6283                         } else if (mg == null) {
6284                                 if (arguments == null)
6285                                         args = new Arguments (1);
6286                                 else
6287                                         args = arguments;
6288
6289                                 args.Insert (0, new Argument (memberExpr));
6290                                 this.expr = null;
6291                         } else {
6292                                 if (mg.IsBase) {
6293                                         ec.Report.Error (1971, loc,
6294                                                 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
6295                                                 mg.Name);
6296                                         return null;
6297                                 }
6298
6299                                 if (arguments == null)
6300                                         args = new Arguments (1);
6301                                 else
6302                                         args = arguments;
6303
6304                                 MemberAccess ma = expr as MemberAccess;
6305                                 if (ma != null) {
6306                                         var left_type = ma.LeftExpression as TypeExpr;
6307                                         if (left_type != null) {
6308                                                 args.Insert (0, new Argument (new TypeOf (left_type.Type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
6309                                         } else {
6310                                                 //
6311                                                 // Any value type has to be pass as by-ref to get back the same
6312                                                 // instance on which the member was called
6313                                                 //
6314                                                 var mod = ma.LeftExpression is IMemoryLocation && TypeSpec.IsValueType (ma.LeftExpression.Type) ?
6315                                                         Argument.AType.Ref : Argument.AType.None;
6316                                                 args.Insert (0, new Argument (ma.LeftExpression.Resolve (ec), mod));
6317                                         }
6318                                 } else {        // is SimpleName
6319                                         if (ec.IsStatic) {
6320                                                 args.Insert (0, new Argument (new TypeOf (ec.CurrentType, loc).Resolve (ec), Argument.AType.DynamicTypeName));
6321                                         } else {
6322                                                 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
6323                                         }
6324                                 }
6325                         }
6326
6327                         return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
6328                 }
6329
6330                 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
6331                 {
6332                         return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.None);
6333                 }
6334
6335                 public override void FlowAnalysis (FlowAnalysisContext fc)
6336                 {
6337                         if (mg.IsConditionallyExcluded)
6338                                 return;
6339
6340                         mg.FlowAnalysis (fc);
6341
6342                         if (arguments != null)
6343                                 arguments.FlowAnalysis (fc);
6344                 }
6345
6346                 public override string GetSignatureForError ()
6347                 {
6348                         return mg.GetSignatureForError ();
6349                 }
6350
6351                 //
6352                 // If a member is a method or event, or if it is a constant, field or property of either a delegate type
6353                 // or the type dynamic, then the member is invocable
6354                 //
6355                 public static bool IsMemberInvocable (MemberSpec member)
6356                 {
6357                         switch (member.Kind) {
6358                         case MemberKind.Event:
6359                                 return true;
6360                         case MemberKind.Field:
6361                         case MemberKind.Property:
6362                                 var m = member as IInterfaceMemberSpec;
6363                                 return m.MemberType.IsDelegate || m.MemberType.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
6364                         default:
6365                                 return false;
6366                         }
6367                 }
6368
6369                 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
6370                 {
6371                         if (!method.IsReservedMethod)
6372                                 return false;
6373
6374                         if (ec.HasSet (ResolveContext.Options.InvokeSpecialName) || ec.CurrentMemberDefinition.IsCompilerGenerated)
6375                                 return false;
6376
6377                         ec.Report.SymbolRelatedToPreviousError (method);
6378                         ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
6379                                 method.GetSignatureForError ());
6380         
6381                         return true;
6382                 }
6383
6384                 public override void Emit (EmitContext ec)
6385                 {
6386                         if (mg.IsConditionallyExcluded)
6387                                 return;
6388
6389                         mg.EmitCall (ec, arguments);
6390                 }
6391                 
6392                 public override void EmitStatement (EmitContext ec)
6393                 {
6394                         Emit (ec);
6395
6396                         // 
6397                         // Pop the return value if there is one
6398                         //
6399                         if (type.Kind != MemberKind.Void)
6400                                 ec.Emit (OpCodes.Pop);
6401                 }
6402
6403                 public override SLE.Expression MakeExpression (BuilderContext ctx)
6404                 {
6405                         return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
6406                 }
6407
6408                 public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
6409                 {
6410 #if STATIC
6411                         throw new NotSupportedException ();
6412 #else
6413                         var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
6414                         return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
6415 #endif
6416                 }
6417
6418                 public override object Accept (StructuralVisitor visitor)
6419                 {
6420                         return visitor.Visit (this);
6421                 }
6422         }
6423
6424         //
6425         // Implements simple new expression 
6426         //
6427         public class New : ExpressionStatement, IMemoryLocation
6428         {
6429                 protected Arguments arguments;
6430
6431                 //
6432                 // During bootstrap, it contains the RequestedType,
6433                 // but if `type' is not null, it *might* contain a NewDelegate
6434                 // (because of field multi-initialization)
6435                 //
6436                 protected Expression RequestedType;
6437
6438                 protected MethodSpec method;
6439
6440                 public New (Expression requested_type, Arguments arguments, Location l)
6441                 {
6442                         RequestedType = requested_type;
6443                         this.arguments = arguments;
6444                         loc = l;
6445                 }
6446
6447                 #region Properties
6448                 public Arguments Arguments {
6449                         get {
6450                                 return arguments;
6451                         }
6452                 }
6453
6454                 //
6455                 // Returns true for resolved `new S()'
6456                 //
6457                 public bool IsDefaultStruct {
6458                         get {
6459                                 return arguments == null && type.IsStruct && GetType () == typeof (New);
6460                         }
6461                 }
6462
6463                 public Expression TypeExpression {
6464                         get {
6465                                 return RequestedType;
6466                         }
6467                 }
6468
6469                 #endregion
6470
6471                 /// <summary>
6472                 /// Converts complex core type syntax like 'new int ()' to simple constant
6473                 /// </summary>
6474                 public static Constant Constantify (TypeSpec t, Location loc)
6475                 {
6476                         switch (t.BuiltinType) {
6477                         case BuiltinTypeSpec.Type.Int:
6478                                 return new IntConstant (t, 0, loc);
6479                         case BuiltinTypeSpec.Type.UInt:
6480                                 return new UIntConstant (t, 0, loc);
6481                         case BuiltinTypeSpec.Type.Long:
6482                                 return new LongConstant (t, 0, loc);
6483                         case BuiltinTypeSpec.Type.ULong:
6484                                 return new ULongConstant (t, 0, loc);
6485                         case BuiltinTypeSpec.Type.Float:
6486                                 return new FloatConstant (t, 0, loc);
6487                         case BuiltinTypeSpec.Type.Double:
6488                                 return new DoubleConstant (t, 0, loc);
6489                         case BuiltinTypeSpec.Type.Short:
6490                                 return new ShortConstant (t, 0, loc);
6491                         case BuiltinTypeSpec.Type.UShort:
6492                                 return new UShortConstant (t, 0, loc);
6493                         case BuiltinTypeSpec.Type.SByte:
6494                                 return new SByteConstant (t, 0, loc);
6495                         case BuiltinTypeSpec.Type.Byte:
6496                                 return new ByteConstant (t, 0, loc);
6497                         case BuiltinTypeSpec.Type.Char:
6498                                 return new CharConstant (t, '\0', loc);
6499                         case BuiltinTypeSpec.Type.Bool:
6500                                 return new BoolConstant (t, false, loc);
6501                         case BuiltinTypeSpec.Type.Decimal:
6502                                 return new DecimalConstant (t, 0, loc);
6503                         }
6504
6505                         if (t.IsEnum)
6506                                 return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t), loc), t);
6507
6508                         if (t.IsNullableType)
6509                                 return Nullable.LiftedNull.Create (t, loc);
6510
6511                         return null;
6512                 }
6513
6514                 public override bool ContainsEmitWithAwait ()
6515                 {
6516                         return arguments != null && arguments.ContainsEmitWithAwait ();
6517                 }
6518
6519                 //
6520                 // Checks whether the type is an interface that has the
6521                 // [ComImport, CoClass] attributes and must be treated
6522                 // specially
6523                 //
6524                 public Expression CheckComImport (ResolveContext ec)
6525                 {
6526                         if (!type.IsInterface)
6527                                 return null;
6528
6529                         //
6530                         // Turn the call into:
6531                         // (the-interface-stated) (new class-referenced-in-coclassattribute ())
6532                         //
6533                         var real_class = type.MemberDefinition.GetAttributeCoClass ();
6534                         if (real_class == null)
6535                                 return null;
6536
6537                         New proxy = new New (new TypeExpression (real_class, loc), arguments, loc);
6538                         Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
6539                         return cast.Resolve (ec);
6540                 }
6541
6542                 public override Expression CreateExpressionTree (ResolveContext ec)
6543                 {
6544                         Arguments args;
6545                         if (method == null) {
6546                                 args = new Arguments (1);
6547                                 args.Add (new Argument (new TypeOf (type, loc)));
6548                         } else {
6549                                 args = Arguments.CreateForExpressionTree (ec,
6550                                         arguments, new TypeOfMethod (method, loc));
6551                         }
6552
6553                         return CreateExpressionFactoryCall (ec, "New", args);
6554                 }
6555                 
6556                 protected override Expression DoResolve (ResolveContext ec)
6557                 {
6558                         type = RequestedType.ResolveAsType (ec);
6559                         if (type == null)
6560                                 return null;
6561
6562                         eclass = ExprClass.Value;
6563
6564                         if (type.IsPointer) {
6565                                 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
6566                                         type.GetSignatureForError ());
6567                                 return null;
6568                         }
6569
6570                         if (arguments == null) {
6571                                 Constant c = Constantify (type, RequestedType.Location);
6572                                 if (c != null)
6573                                         return ReducedExpression.Create (c, this);
6574                         }
6575
6576                         if (type.IsDelegate) {
6577                                 return (new NewDelegate (type, arguments, loc)).Resolve (ec);
6578                         }
6579
6580                         var tparam = type as TypeParameterSpec;
6581                         if (tparam != null) {
6582                                 //
6583                                 // Check whether the type of type parameter can be constructed. BaseType can be a struct for method overrides
6584                                 // where type parameter constraint is inflated to struct
6585                                 //
6586                                 if ((tparam.SpecialConstraint & (SpecialConstraint.Struct | SpecialConstraint.Constructor)) == 0 && !TypeSpec.IsValueType (tparam)) {
6587                                         ec.Report.Error (304, loc,
6588                                                 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
6589                                                 type.GetSignatureForError ());
6590                                 }
6591
6592                                 if ((arguments != null) && (arguments.Count != 0)) {
6593                                         ec.Report.Error (417, loc,
6594                                                 "`{0}': cannot provide arguments when creating an instance of a variable type",
6595                                                 type.GetSignatureForError ());
6596                                 }
6597
6598                                 return this;
6599                         }
6600
6601                         if (type.IsStatic) {
6602                                 ec.Report.SymbolRelatedToPreviousError (type);
6603                                 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", type.GetSignatureForError ());
6604                                 return null;
6605                         }
6606
6607                         if (type.IsInterface || type.IsAbstract){
6608                                 if (!TypeManager.IsGenericType (type)) {
6609                                         RequestedType = CheckComImport (ec);
6610                                         if (RequestedType != null)
6611                                                 return RequestedType;
6612                                 }
6613                                 
6614                                 ec.Report.SymbolRelatedToPreviousError (type);
6615                                 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", type.GetSignatureForError ());
6616                                 return null;
6617                         }
6618
6619                         //
6620                         // Any struct always defines parameterless constructor
6621                         //
6622                         if (type.IsStruct && arguments == null)
6623                                 return this;
6624
6625                         bool dynamic;
6626                         if (arguments != null) {
6627                                 arguments.Resolve (ec, out dynamic);
6628                         } else {
6629                                 dynamic = false;
6630                         }
6631
6632                         method = ConstructorLookup (ec, type, ref arguments, loc);
6633
6634                         if (dynamic) {
6635                                 arguments.Insert (0, new Argument (new TypeOf (type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
6636                                 return new DynamicConstructorBinder (type, arguments, loc).Resolve (ec);
6637                         }
6638
6639                         return this;
6640                 }
6641
6642                 bool DoEmitTypeParameter (EmitContext ec)
6643                 {
6644                         var m = ec.Module.PredefinedMembers.ActivatorCreateInstance.Resolve (loc);
6645                         if (m == null)
6646                                 return true;
6647
6648                         var ctor_factory = m.MakeGenericMethod (ec.MemberContext, type);
6649                         var tparam = (TypeParameterSpec) type;
6650
6651                         if (tparam.IsReferenceType) {
6652                                 ec.Emit (OpCodes.Call, ctor_factory);
6653                                 return true;
6654                         }
6655
6656                         // Allow DoEmit() to be called multiple times.
6657                         // We need to create a new LocalTemporary each time since
6658                         // you can't share LocalBuilders among ILGeneators.
6659                         LocalTemporary temp = new LocalTemporary (type);
6660
6661                         Label label_activator = ec.DefineLabel ();
6662                         Label label_end = ec.DefineLabel ();
6663
6664                         temp.AddressOf (ec, AddressOp.Store);
6665                         ec.Emit (OpCodes.Initobj, type);
6666
6667                         temp.Emit (ec);
6668                         ec.Emit (OpCodes.Box, type);
6669                         ec.Emit (OpCodes.Brfalse, label_activator);
6670
6671                         temp.AddressOf (ec, AddressOp.Store);
6672                         ec.Emit (OpCodes.Initobj, type);
6673                         temp.Emit (ec);
6674                         temp.Release (ec);
6675                         ec.Emit (OpCodes.Br_S, label_end);
6676
6677                         ec.MarkLabel (label_activator);
6678
6679                         ec.Emit (OpCodes.Call, ctor_factory);
6680                         ec.MarkLabel (label_end);
6681                         return true;
6682                 }
6683
6684                 //
6685                 // This Emit can be invoked in two contexts:
6686                 //    * As a mechanism that will leave a value on the stack (new object)
6687                 //    * As one that wont (init struct)
6688                 //
6689                 // If we are dealing with a ValueType, we have a few
6690                 // situations to deal with:
6691                 //
6692                 //    * The target is a ValueType, and we have been provided
6693                 //      the instance (this is easy, we are being assigned).
6694                 //
6695                 //    * The target of New is being passed as an argument,
6696                 //      to a boxing operation or a function that takes a
6697                 //      ValueType.
6698                 //
6699                 //      In this case, we need to create a temporary variable
6700                 //      that is the argument of New.
6701                 //
6702                 // Returns whether a value is left on the stack
6703                 //
6704                 // *** Implementation note ***
6705                 //
6706                 // To benefit from this optimization, each assignable expression
6707                 // has to manually cast to New and call this Emit.
6708                 //
6709                 // TODO: It's worth to implement it for arrays and fields
6710                 //
6711                 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
6712                 {
6713                         bool is_value_type = TypeSpec.IsValueType (type);
6714                         VariableReference vr = target as VariableReference;
6715
6716                         if (target != null && is_value_type && (vr != null || method == null)) {
6717                                 target.AddressOf (ec, AddressOp.Store);
6718                         } else if (vr != null && vr.IsRef) {
6719                                 vr.EmitLoad (ec);
6720                         }
6721
6722                         if (arguments != null) {
6723                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && (arguments.Count > (this is NewInitialize ? 0 : 1)) && arguments.ContainsEmitWithAwait ())
6724                                         arguments = arguments.Emit (ec, false, true);
6725
6726                                 arguments.Emit (ec);
6727                         }
6728
6729                         if (is_value_type) {
6730                                 if (method == null) {
6731                                         ec.Emit (OpCodes.Initobj, type);
6732                                         return false;
6733                                 }
6734
6735                                 if (vr != null) {
6736                                         ec.MarkCallEntry (loc);
6737                                         ec.Emit (OpCodes.Call, method);
6738                                         return false;
6739                                 }
6740                         }
6741                         
6742                         if (type is TypeParameterSpec)
6743                                 return DoEmitTypeParameter (ec);
6744
6745                         ec.MarkCallEntry (loc);
6746                         ec.Emit (OpCodes.Newobj, method);
6747                         return true;
6748                 }
6749
6750                 public override void Emit (EmitContext ec)
6751                 {
6752                         LocalTemporary v = null;
6753                         if (method == null && TypeSpec.IsValueType (type)) {
6754                                 // TODO: Use temporary variable from pool
6755                                 v = new LocalTemporary (type);
6756                         }
6757
6758                         if (!Emit (ec, v))
6759                                 v.Emit (ec);
6760                 }
6761                 
6762                 public override void EmitStatement (EmitContext ec)
6763                 {
6764                         LocalTemporary v = null;
6765                         if (method == null && TypeSpec.IsValueType (type)) {
6766                                 // TODO: Use temporary variable from pool
6767                                 v = new LocalTemporary (type);
6768                         }
6769
6770                         if (Emit (ec, v))
6771                                 ec.Emit (OpCodes.Pop);
6772                 }
6773
6774                 public override void FlowAnalysis (FlowAnalysisContext fc)
6775                 {
6776                         if (arguments != null)
6777                                 arguments.FlowAnalysis (fc);
6778                 }
6779
6780                 public void AddressOf (EmitContext ec, AddressOp mode)
6781                 {
6782                         EmitAddressOf (ec, mode);
6783                 }
6784
6785                 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
6786                 {
6787                         LocalTemporary value_target = new LocalTemporary (type);
6788
6789                         if (type is TypeParameterSpec) {
6790                                 DoEmitTypeParameter (ec);
6791                                 value_target.Store (ec);
6792                                 value_target.AddressOf (ec, mode);
6793                                 return value_target;
6794                         }
6795
6796                         value_target.AddressOf (ec, AddressOp.Store);
6797
6798                         if (method == null) {
6799                                 ec.Emit (OpCodes.Initobj, type);
6800                         } else {
6801                                 if (arguments != null)
6802                                         arguments.Emit (ec);
6803
6804                                 ec.Emit (OpCodes.Call, method);
6805                         }
6806                         
6807                         value_target.AddressOf (ec, mode);
6808                         return value_target;
6809                 }
6810
6811                 protected override void CloneTo (CloneContext clonectx, Expression t)
6812                 {
6813                         New target = (New) t;
6814
6815                         target.RequestedType = RequestedType.Clone (clonectx);
6816                         if (arguments != null){
6817                                 target.arguments = arguments.Clone (clonectx);
6818                         }
6819                 }
6820
6821                 public override SLE.Expression MakeExpression (BuilderContext ctx)
6822                 {
6823 #if STATIC
6824                         return base.MakeExpression (ctx);
6825 #else
6826                         return SLE.Expression.New ((ConstructorInfo) method.GetMetaInfo (), Arguments.MakeExpression (arguments, ctx));
6827 #endif
6828                 }
6829                 
6830                 public override object Accept (StructuralVisitor visitor)
6831                 {
6832                         return visitor.Visit (this);
6833                 }
6834         }
6835
6836         //
6837         // Array initializer expression, the expression is allowed in
6838         // variable or field initialization only which makes it tricky as
6839         // the type has to be infered based on the context either from field
6840         // type or variable type (think of multiple declarators)
6841         //
6842         public class ArrayInitializer : Expression
6843         {
6844                 List<Expression> elements;
6845                 BlockVariable variable;
6846
6847                 public ArrayInitializer (List<Expression> init, Location loc)
6848                 {
6849                         elements = init;
6850                         this.loc = loc;
6851                 }
6852
6853                 public ArrayInitializer (int count, Location loc)
6854                         : this (new List<Expression> (count), loc)
6855                 {
6856                 }
6857
6858                 public ArrayInitializer (Location loc)
6859                         : this (4, loc)
6860                 {
6861                 }
6862
6863                 #region Properties
6864
6865                 public int Count {
6866                         get { return elements.Count; }
6867                 }
6868
6869                 public List<Expression> Elements {
6870                         get {
6871                                 return elements;
6872                         }
6873                 }
6874
6875                 public Expression this [int index] {
6876                         get {
6877                                 return elements [index];
6878                         }
6879                 }
6880
6881                 public BlockVariable VariableDeclaration {
6882                         get {
6883                                 return variable;
6884                         }
6885                         set {
6886                                 variable = value;
6887                         }
6888                 }
6889
6890                 #endregion
6891
6892                 public void Add (Expression expr)
6893                 {
6894                         elements.Add (expr);
6895                 }
6896
6897                 public override bool ContainsEmitWithAwait ()
6898                 {
6899                         throw new NotSupportedException ();
6900                 }
6901
6902                 public override Expression CreateExpressionTree (ResolveContext ec)
6903                 {
6904                         throw new NotSupportedException ("ET");
6905                 }
6906
6907                 protected override void CloneTo (CloneContext clonectx, Expression t)
6908                 {
6909                         var target = (ArrayInitializer) t;
6910
6911                         target.elements = new List<Expression> (elements.Count);
6912                         foreach (var element in elements)
6913                                 target.elements.Add (element.Clone (clonectx));
6914                 }
6915
6916                 protected override Expression DoResolve (ResolveContext rc)
6917                 {
6918                         var current_field = rc.CurrentMemberDefinition as FieldBase;
6919                         TypeExpression type;
6920                         if (current_field != null && rc.CurrentAnonymousMethod == null) {
6921                                 type = new TypeExpression (current_field.MemberType, current_field.Location);
6922                         } else if (variable != null) {
6923                                 if (variable.TypeExpression is VarExpr) {
6924                                         rc.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
6925                                         return EmptyExpression.Null;
6926                                 }
6927
6928                                 type = new TypeExpression (variable.Variable.Type, variable.Variable.Location);
6929                         } else {
6930                                 throw new NotImplementedException ("Unexpected array initializer context");
6931                         }
6932
6933                         return new ArrayCreation (type, this).Resolve (rc);
6934                 }
6935
6936                 public override void Emit (EmitContext ec)
6937                 {
6938                         throw new InternalErrorException ("Missing Resolve call");
6939                 }
6940
6941                 public override void FlowAnalysis (FlowAnalysisContext fc)
6942                 {
6943                         throw new InternalErrorException ("Missing Resolve call");
6944                 }
6945                 
6946                 public override object Accept (StructuralVisitor visitor)
6947                 {
6948                         return visitor.Visit (this);
6949                 }
6950         }
6951
6952         /// <summary>
6953         ///   14.5.10.2: Represents an array creation expression.
6954         /// </summary>
6955         ///
6956         /// <remarks>
6957         ///   There are two possible scenarios here: one is an array creation
6958         ///   expression that specifies the dimensions and optionally the
6959         ///   initialization data and the other which does not need dimensions
6960         ///   specified but where initialization data is mandatory.
6961         /// </remarks>
6962         public class ArrayCreation : Expression
6963         {
6964                 FullNamedExpression requested_base_type;
6965                 ArrayInitializer initializers;
6966
6967                 //
6968                 // The list of Argument types.
6969                 // This is used to construct the `newarray' or constructor signature
6970                 //
6971                 protected List<Expression> arguments;
6972                 
6973                 protected TypeSpec array_element_type;
6974                 int num_arguments;
6975                 protected int dimensions;
6976                 protected readonly ComposedTypeSpecifier rank;
6977                 Expression first_emit;
6978                 LocalTemporary first_emit_temp;
6979
6980                 protected List<Expression> array_data;
6981
6982                 Dictionary<int, int> bounds;
6983
6984 #if STATIC
6985                 // The number of constants in array initializers
6986                 int const_initializers_count;
6987                 bool only_constant_initializers;
6988 #endif
6989                 public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
6990                         : this (requested_base_type, rank, initializers, l)
6991                 {
6992                         arguments = new List<Expression> (exprs);
6993                         num_arguments = arguments.Count;
6994                 }
6995
6996                 //
6997                 // For expressions like int[] foo = new int[] { 1, 2, 3 };
6998                 //
6999                 public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
7000                 {
7001                         this.requested_base_type = requested_base_type;
7002                         this.rank = rank;
7003                         this.initializers = initializers;
7004                         this.loc = loc;
7005
7006                         if (rank != null)
7007                                 num_arguments = rank.Dimension;
7008                 }
7009
7010                 //
7011                 // For compiler generated single dimensional arrays only
7012                 //
7013                 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
7014                         : this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
7015                 {
7016                 }
7017
7018                 //
7019                 // For expressions like int[] foo = { 1, 2, 3 };
7020                 //
7021                 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
7022                         : this (requested_base_type, null, initializers, initializers.Location)
7023                 {
7024                 }
7025
7026                 public ComposedTypeSpecifier Rank {
7027                         get {
7028                                 return this.rank;
7029                         }
7030                 }
7031                 
7032                 public FullNamedExpression TypeExpression {
7033                         get {
7034                                 return this.requested_base_type;
7035                         }
7036                 }
7037                 
7038                 public ArrayInitializer Initializers {
7039                         get {
7040                                 return this.initializers;
7041                         }
7042                 }
7043
7044                 bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
7045                 {
7046                         if (initializers != null && bounds == null) {
7047                                 //
7048                                 // We use this to store all the data values in the order in which we
7049                                 // will need to store them in the byte blob later
7050                                 //
7051                                 array_data = new List<Expression> (probe.Count);
7052                                 bounds = new Dictionary<int, int> ();
7053                         }
7054
7055                         if (specified_dims) { 
7056                                 Expression a = arguments [idx];
7057                                 a = a.Resolve (ec);
7058                                 if (a == null)
7059                                         return false;
7060
7061                                 a = ConvertExpressionToArrayIndex (ec, a);
7062                                 if (a == null)
7063                                         return false;
7064
7065                                 arguments[idx] = a;
7066
7067                                 if (initializers != null) {
7068                                         Constant c = a as Constant;
7069                                         if (c == null && a is ArrayIndexCast)
7070                                                 c = ((ArrayIndexCast) a).Child as Constant;
7071
7072                                         if (c == null) {
7073                                                 ec.Report.Error (150, a.Location, "A constant value is expected");
7074                                                 return false;
7075                                         }
7076
7077                                         int value;
7078                                         try {
7079                                                 value = System.Convert.ToInt32 (c.GetValue ());
7080                                         } catch {
7081                                                 ec.Report.Error (150, a.Location, "A constant value is expected");
7082                                                 return false;
7083                                         }
7084
7085                                         // TODO: probe.Count does not fit ulong in
7086                                         if (value != probe.Count) {
7087                                                 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
7088                                                 return false;
7089                                         }
7090
7091                                         bounds[idx] = value;
7092                                 }
7093                         }
7094
7095                         if (initializers == null)
7096                                 return true;
7097
7098                         for (int i = 0; i < probe.Count; ++i) {
7099                                 var o = probe [i];
7100                                 if (o is ArrayInitializer) {
7101                                         var sub_probe = o as ArrayInitializer;
7102                                         if (idx + 1 >= dimensions){
7103                                                 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
7104                                                 return false;
7105                                         }
7106
7107                                         // When we don't have explicitly specified dimensions, record whatever dimension we first encounter at each level
7108                                         if (!bounds.ContainsKey(idx + 1))
7109                                                 bounds[idx + 1] = sub_probe.Count;
7110
7111                                         if (bounds[idx + 1] != sub_probe.Count) {
7112                                                 ec.Report.Error(847, sub_probe.Location, "An array initializer of length `{0}' was expected", bounds[idx + 1].ToString());
7113                                                 return false;
7114                                         }
7115
7116                                         bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
7117                                         if (!ret)
7118                                                 return false;
7119                                 } else if (child_bounds > 1) {
7120                                         ec.Report.Error (846, o.Location, "A nested array initializer was expected");
7121                                 } else {
7122                                         Expression element = ResolveArrayElement (ec, o);
7123                                         if (element == null)
7124                                                 continue;
7125 #if STATIC
7126                                         // Initializers with the default values can be ignored
7127                                         Constant c = element as Constant;
7128                                         if (c != null) {
7129                                                 if (!c.IsDefaultInitializer (array_element_type)) {
7130                                                         ++const_initializers_count;
7131                                                 }
7132                                         } else {
7133                                                 only_constant_initializers = false;
7134                                         }
7135 #endif                                  
7136                                         array_data.Add (element);
7137                                 }
7138                         }
7139
7140                         return true;
7141                 }
7142
7143                 public override bool ContainsEmitWithAwait ()
7144                 {
7145                         foreach (var arg in arguments) {
7146                                 if (arg.ContainsEmitWithAwait ())
7147                                         return true;
7148                         }
7149
7150                         return InitializersContainAwait ();
7151                 }
7152
7153                 public override Expression CreateExpressionTree (ResolveContext ec)
7154                 {
7155                         Arguments args;
7156
7157                         if (array_data == null) {
7158                                 args = new Arguments (arguments.Count + 1);
7159                                 args.Add (new Argument (new TypeOf (array_element_type, loc)));
7160                                 foreach (Expression a in arguments)
7161                                         args.Add (new Argument (a.CreateExpressionTree (ec)));
7162
7163                                 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
7164                         }
7165
7166                         if (dimensions > 1) {
7167                                 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
7168                                 return null;
7169                         }
7170
7171                         args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
7172                         args.Add (new Argument (new TypeOf (array_element_type, loc)));
7173                         if (array_data != null) {
7174                                 for (int i = 0; i < array_data.Count; ++i) {
7175                                         Expression e = array_data [i];
7176                                         args.Add (new Argument (e.CreateExpressionTree (ec)));
7177                                 }
7178                         }
7179
7180                         return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
7181                 }               
7182                 
7183                 void UpdateIndices (ResolveContext rc)
7184                 {
7185                         int i = 0;
7186                         for (var probe = initializers; probe != null;) {
7187                                 Expression e = new IntConstant (rc.BuiltinTypes, probe.Count, Location.Null);
7188                                 arguments.Add (e);
7189                                 bounds[i++] = probe.Count;
7190
7191                                 if (probe.Count > 0 && probe [0] is ArrayInitializer) {
7192                                         probe = (ArrayInitializer) probe[0];
7193                                 } else if (dimensions > i) {
7194                                         continue;
7195                                 } else {
7196                                         return;
7197                                 }
7198                         }
7199                 }
7200
7201                 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
7202                 {
7203                         ec.Report.Error (248, loc, "Cannot create an array with a negative size");
7204                 }
7205
7206                 public override void FlowAnalysis (FlowAnalysisContext fc)
7207                 {
7208                         foreach (var arg in arguments)
7209                                 arg.FlowAnalysis (fc);
7210
7211                         if (array_data != null) {
7212                                 foreach (var ad in array_data)
7213                                         ad.FlowAnalysis (fc);
7214                         }
7215                 }
7216
7217                 bool InitializersContainAwait ()
7218                 {
7219                         if (array_data == null)
7220                                 return false;
7221
7222                         foreach (var expr in array_data) {
7223                                 if (expr.ContainsEmitWithAwait ())
7224                                         return true;
7225                         }
7226
7227                         return false;
7228                 }
7229
7230                 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
7231                 {
7232                         element = element.Resolve (ec);
7233                         if (element == null)
7234                                 return null;
7235
7236                         if (element is CompoundAssign.TargetExpression) {
7237                                 if (first_emit != null)
7238                                         throw new InternalErrorException ("Can only handle one mutator at a time");
7239                                 first_emit = element;
7240                                 element = first_emit_temp = new LocalTemporary (element.Type);
7241                         }
7242
7243                         return Convert.ImplicitConversionRequired (
7244                                 ec, element, array_element_type, loc);
7245                 }
7246
7247                 protected bool ResolveInitializers (ResolveContext ec)
7248                 {
7249 #if STATIC
7250                         only_constant_initializers = true;
7251 #endif
7252
7253                         if (arguments != null) {
7254                                 bool res = true;
7255                                 for (int i = 0; i < arguments.Count; ++i) {
7256                                         res &= CheckIndices (ec, initializers, i, true, dimensions);
7257                                         if (initializers != null)
7258                                                 break;
7259                                 }
7260
7261                                 return res;
7262                         }
7263
7264                         arguments = new List<Expression> ();
7265
7266                         if (!CheckIndices (ec, initializers, 0, false, dimensions))
7267                                 return false;
7268                                 
7269                         UpdateIndices (ec);
7270                                 
7271                         return true;
7272                 }
7273
7274                 //
7275                 // Resolved the type of the array
7276                 //
7277                 bool ResolveArrayType (ResolveContext ec)
7278                 {
7279                         //
7280                         // Lookup the type
7281                         //
7282                         FullNamedExpression array_type_expr;
7283                         if (num_arguments > 0) {
7284                                 array_type_expr = new ComposedCast (requested_base_type, rank);
7285                         } else {
7286                                 array_type_expr = requested_base_type;
7287                         }
7288
7289                         type = array_type_expr.ResolveAsType (ec);
7290                         if (array_type_expr == null)
7291                                 return false;
7292
7293                         var ac = type as ArrayContainer;
7294                         if (ac == null) {
7295                                 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
7296                                 return false;
7297                         }
7298
7299                         array_element_type = ac.Element;
7300                         dimensions = ac.Rank;
7301
7302                         return true;
7303                 }
7304
7305                 protected override Expression DoResolve (ResolveContext ec)
7306                 {
7307                         if (type != null)
7308                                 return this;
7309
7310                         if (!ResolveArrayType (ec))
7311                                 return null;
7312
7313                         //
7314                         // validate the initializers and fill in any missing bits
7315                         //
7316                         if (!ResolveInitializers (ec))
7317                                 return null;
7318
7319                         eclass = ExprClass.Value;
7320                         return this;
7321                 }
7322
7323                 byte [] MakeByteBlob ()
7324                 {
7325                         int factor;
7326                         byte [] data;
7327                         byte [] element;
7328                         int count = array_data.Count;
7329
7330                         TypeSpec element_type = array_element_type;
7331                         if (element_type.IsEnum)
7332                                 element_type = EnumSpec.GetUnderlyingType (element_type);
7333
7334                         factor = BuiltinTypeSpec.GetSize (element_type);
7335                         if (factor == 0)
7336                                 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
7337
7338                         data = new byte [(count * factor + 3) & ~3];
7339                         int idx = 0;
7340
7341                         for (int i = 0; i < count; ++i) {
7342                                 var c = array_data[i] as Constant;
7343                                 if (c == null) {
7344                                         idx += factor;
7345                                         continue;
7346                                 }
7347
7348                                 object v = c.GetValue ();
7349
7350                                 switch (element_type.BuiltinType) {
7351                                 case BuiltinTypeSpec.Type.Long:
7352                                         long lval = (long) v;
7353
7354                                         for (int j = 0; j < factor; ++j) {
7355                                                 data[idx + j] = (byte) (lval & 0xFF);
7356                                                 lval = (lval >> 8);
7357                                         }
7358                                         break;
7359                                 case BuiltinTypeSpec.Type.ULong:
7360                                         ulong ulval = (ulong) v;
7361
7362                                         for (int j = 0; j < factor; ++j) {
7363                                                 data[idx + j] = (byte) (ulval & 0xFF);
7364                                                 ulval = (ulval >> 8);
7365                                         }
7366                                         break;
7367                                 case BuiltinTypeSpec.Type.Float:
7368                                         var fval = SingleConverter.SingleToInt32Bits((float) v);
7369
7370                                         data[idx] = (byte) (fval & 0xff);
7371                                         data[idx + 1] = (byte) ((fval >> 8) & 0xff);
7372                                         data[idx + 2] = (byte) ((fval >> 16) & 0xff);
7373                                         data[idx + 3] = (byte) (fval >> 24);
7374                                         break;
7375                                 case BuiltinTypeSpec.Type.Double:
7376                                         element = BitConverter.GetBytes ((double) v);
7377
7378                                         for (int j = 0; j < factor; ++j)
7379                                                 data[idx + j] = element[j];
7380
7381                                         // FIXME: Handle the ARM float format.
7382                                         if (!BitConverter.IsLittleEndian)
7383                                                 System.Array.Reverse (data, idx, 8);
7384                                         break;
7385                                 case BuiltinTypeSpec.Type.Char:
7386                                         int chval = (int) ((char) v);
7387
7388                                         data[idx] = (byte) (chval & 0xff);
7389                                         data[idx + 1] = (byte) (chval >> 8);
7390                                         break;
7391                                 case BuiltinTypeSpec.Type.Short:
7392                                         int sval = (int) ((short) v);
7393
7394                                         data[idx] = (byte) (sval & 0xff);
7395                                         data[idx + 1] = (byte) (sval >> 8);
7396                                         break;
7397                                 case BuiltinTypeSpec.Type.UShort:
7398                                         int usval = (int) ((ushort) v);
7399
7400                                         data[idx] = (byte) (usval & 0xff);
7401                                         data[idx + 1] = (byte) (usval >> 8);
7402                                         break;
7403                                 case BuiltinTypeSpec.Type.Int:
7404                                         int val = (int) v;
7405
7406                                         data[idx] = (byte) (val & 0xff);
7407                                         data[idx + 1] = (byte) ((val >> 8) & 0xff);
7408                                         data[idx + 2] = (byte) ((val >> 16) & 0xff);
7409                                         data[idx + 3] = (byte) (val >> 24);
7410                                         break;
7411                                 case BuiltinTypeSpec.Type.UInt:
7412                                         uint uval = (uint) v;
7413
7414                                         data[idx] = (byte) (uval & 0xff);
7415                                         data[idx + 1] = (byte) ((uval >> 8) & 0xff);
7416                                         data[idx + 2] = (byte) ((uval >> 16) & 0xff);
7417                                         data[idx + 3] = (byte) (uval >> 24);
7418                                         break;
7419                                 case BuiltinTypeSpec.Type.SByte:
7420                                         data[idx] = (byte) (sbyte) v;
7421                                         break;
7422                                 case BuiltinTypeSpec.Type.Byte:
7423                                         data[idx] = (byte) v;
7424                                         break;
7425                                 case BuiltinTypeSpec.Type.Bool:
7426                                         data[idx] = (byte) ((bool) v ? 1 : 0);
7427                                         break;
7428                                 case BuiltinTypeSpec.Type.Decimal:
7429                                         int[] bits = Decimal.GetBits ((decimal) v);
7430                                         int p = idx;
7431
7432                                         // FIXME: For some reason, this doesn't work on the MS runtime.
7433                                         int[] nbits = new int[4];
7434                                         nbits[0] = bits[3];
7435                                         nbits[1] = bits[2];
7436                                         nbits[2] = bits[0];
7437                                         nbits[3] = bits[1];
7438
7439                                         for (int j = 0; j < 4; j++) {
7440                                                 data[p++] = (byte) (nbits[j] & 0xff);
7441                                                 data[p++] = (byte) ((nbits[j] >> 8) & 0xff);
7442                                                 data[p++] = (byte) ((nbits[j] >> 16) & 0xff);
7443                                                 data[p++] = (byte) (nbits[j] >> 24);
7444                                         }
7445                                         break;
7446                                 default:
7447                                         throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
7448                                 }
7449
7450                                 idx += factor;
7451                         }
7452
7453                         return data;
7454                 }
7455
7456 #if NET_4_0 || MOBILE_DYNAMIC
7457                 public override SLE.Expression MakeExpression (BuilderContext ctx)
7458                 {
7459 #if STATIC
7460                         return base.MakeExpression (ctx);
7461 #else
7462                         var initializers = new SLE.Expression [array_data.Count];
7463                         for (var i = 0; i < initializers.Length; i++) {
7464                                 if (array_data [i] == null)
7465                                         initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
7466                                 else
7467                                         initializers [i] = array_data [i].MakeExpression (ctx);
7468                         }
7469
7470                         return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
7471 #endif
7472                 }
7473 #endif
7474 #if STATIC
7475                 //
7476                 // Emits the initializers for the array
7477                 //
7478                 void EmitStaticInitializers (EmitContext ec, FieldExpr stackArray)
7479                 {
7480                         var m = ec.Module.PredefinedMembers.RuntimeHelpersInitializeArray.Resolve (loc);
7481                         if (m == null)
7482                                 return;
7483
7484                         //
7485                         // First, the static data
7486                         //
7487                         byte [] data = MakeByteBlob ();
7488                         var fb = ec.CurrentTypeDefinition.Module.MakeStaticData (data, loc);
7489
7490                         if (stackArray == null) {
7491                                 ec.Emit (OpCodes.Dup);
7492                         } else {
7493                                 stackArray.Emit (ec);
7494                         }
7495
7496                         ec.Emit (OpCodes.Ldtoken, fb);
7497                         ec.Emit (OpCodes.Call, m);
7498                 }
7499 #endif
7500
7501                 //
7502                 // Emits pieces of the array that can not be computed at compile
7503                 // time (variables and string locations).
7504                 //
7505                 // This always expect the top value on the stack to be the array
7506                 //
7507                 void EmitDynamicInitializers (EmitContext ec, bool emitConstants, StackFieldExpr stackArray)
7508                 {
7509                         int dims = bounds.Count;
7510                         var current_pos = new int [dims];
7511
7512                         for (int i = 0; i < array_data.Count; i++){
7513
7514                                 Expression e = array_data [i];
7515                                 var c = e as Constant;
7516
7517                                 // Constant can be initialized via StaticInitializer
7518                                 if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
7519
7520                                         var etype = e.Type;
7521
7522                                         if (stackArray != null) {
7523                                                 if (e.ContainsEmitWithAwait ()) {
7524                                                         e = e.EmitToField (ec);
7525                                                 }
7526
7527                                                 stackArray.EmitLoad (ec);
7528                                         } else {
7529                                                 ec.Emit (OpCodes.Dup);
7530                                         }
7531
7532                                         for (int idx = 0; idx < dims; idx++) 
7533                                                 ec.EmitInt (current_pos [idx]);
7534
7535                                         //
7536                                         // If we are dealing with a struct, get the
7537                                         // address of it, so we can store it.
7538                                         //
7539                                         if (dims == 1 && etype.IsStruct && !BuiltinTypeSpec.IsPrimitiveType (etype))
7540                                                 ec.Emit (OpCodes.Ldelema, etype);
7541
7542                                         e.Emit (ec);
7543
7544                                         ec.EmitArrayStore ((ArrayContainer) type);
7545                                 }
7546                                 
7547                                 //
7548                                 // Advance counter
7549                                 //
7550                                 for (int j = dims - 1; j >= 0; j--){
7551                                         current_pos [j]++;
7552                                         if (current_pos [j] < bounds [j])
7553                                                 break;
7554                                         current_pos [j] = 0;
7555                                 }
7556                         }
7557
7558                         if (stackArray != null)
7559                                 stackArray.PrepareCleanup (ec);
7560                 }
7561
7562                 public override void Emit (EmitContext ec)
7563                 {
7564                         EmitToFieldSource (ec);
7565                 }
7566
7567                 protected sealed override FieldExpr EmitToFieldSource (EmitContext ec)
7568                 {
7569                         if (first_emit != null) {
7570                                 first_emit.Emit (ec);
7571                                 first_emit_temp.Store (ec);
7572                         }
7573
7574                         StackFieldExpr await_stack_field;
7575                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && InitializersContainAwait ()) {
7576                                 await_stack_field = ec.GetTemporaryField (type);
7577                                 ec.EmitThis ();
7578                         } else {
7579                                 await_stack_field = null;
7580                         }
7581
7582                         EmitExpressionsList (ec, arguments);
7583
7584                         ec.EmitArrayNew ((ArrayContainer) type);
7585                         
7586                         if (initializers == null)
7587                                 return await_stack_field;
7588
7589                         if (await_stack_field != null)
7590                                 await_stack_field.EmitAssignFromStack (ec);
7591
7592 #if STATIC
7593                         //
7594                         // Emit static initializer for arrays which contain more than 2 items and
7595                         // the static initializer will initialize at least 25% of array values or there
7596                         // is more than 10 items to be initialized
7597                         //
7598                         // NOTE: const_initializers_count does not contain default constant values.
7599                         //
7600                         if (const_initializers_count > 2 && (array_data.Count > 10 || const_initializers_count * 4 > (array_data.Count)) &&
7601                                 (BuiltinTypeSpec.IsPrimitiveType (array_element_type) || array_element_type.IsEnum)) {
7602                                 EmitStaticInitializers (ec, await_stack_field);
7603
7604                                 if (!only_constant_initializers)
7605                                         EmitDynamicInitializers (ec, false, await_stack_field);
7606                         } else
7607 #endif
7608                         {
7609                                 EmitDynamicInitializers (ec, true, await_stack_field);
7610                         }
7611
7612                         if (first_emit_temp != null)
7613                                 first_emit_temp.Release (ec);
7614
7615                         return await_stack_field;
7616                 }
7617
7618                 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
7619                 {
7620                         // no multi dimensional or jagged arrays
7621                         if (arguments.Count != 1 || array_element_type.IsArray) {
7622                                 base.EncodeAttributeValue (rc, enc, targetType);
7623                                 return;
7624                         }
7625
7626                         // No array covariance, except for array -> object
7627                         if (type != targetType) {
7628                                 if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) {
7629                                         base.EncodeAttributeValue (rc, enc, targetType);
7630                                         return;
7631                                 }
7632
7633                                 if (enc.Encode (type) == AttributeEncoder.EncodedTypeProperties.DynamicType) {
7634                                         Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
7635                                         return;
7636                                 }
7637                         }
7638
7639                         // Single dimensional array of 0 size
7640                         if (array_data == null) {
7641                                 IntConstant ic = arguments[0] as IntConstant;
7642                                 if (ic == null || !ic.IsDefaultValue) {
7643                                         base.EncodeAttributeValue (rc, enc, targetType);
7644                                 } else {
7645                                         enc.Encode (0);
7646                                 }
7647
7648                                 return;
7649                         }
7650
7651                         enc.Encode (array_data.Count);
7652                         foreach (var element in array_data) {
7653                                 element.EncodeAttributeValue (rc, enc, array_element_type);
7654                         }
7655                 }
7656                 
7657                 protected override void CloneTo (CloneContext clonectx, Expression t)
7658                 {
7659                         ArrayCreation target = (ArrayCreation) t;
7660
7661                         if (requested_base_type != null)
7662                                 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
7663
7664                         if (arguments != null){
7665                                 target.arguments = new List<Expression> (arguments.Count);
7666                                 foreach (Expression e in arguments)
7667                                         target.arguments.Add (e.Clone (clonectx));
7668                         }
7669
7670                         if (initializers != null)
7671                                 target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
7672                 }
7673                 
7674                 public override object Accept (StructuralVisitor visitor)
7675                 {
7676                         return visitor.Visit (this);
7677                 }
7678         }
7679         
7680         //
7681         // Represents an implicitly typed array epxression
7682         //
7683         class ImplicitlyTypedArrayCreation : ArrayCreation
7684         {
7685                 TypeInferenceContext best_type_inference;
7686
7687                 public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
7688                         : base (null, rank, initializers, loc)
7689                 {                       
7690                 }
7691
7692                 public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
7693                         : base (null, initializers, loc)
7694                 {
7695                 }
7696
7697                 protected override Expression DoResolve (ResolveContext ec)
7698                 {
7699                         if (type != null)
7700                                 return this;
7701
7702                         dimensions = rank.Dimension;
7703
7704                         best_type_inference = new TypeInferenceContext ();
7705
7706                         if (!ResolveInitializers (ec))
7707                                 return null;
7708
7709                         best_type_inference.FixAllTypes (ec);
7710                         array_element_type = best_type_inference.InferredTypeArguments[0];
7711                         best_type_inference = null;
7712
7713                         if (array_element_type == null ||
7714                                 array_element_type == InternalType.NullLiteral || array_element_type == InternalType.MethodGroup || array_element_type == InternalType.AnonymousMethod ||
7715                                 arguments.Count != rank.Dimension) {
7716                                 ec.Report.Error (826, loc,
7717                                         "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
7718                                 return null;
7719                         }
7720
7721                         //
7722                         // At this point we found common base type for all initializer elements
7723                         // but we have to be sure that all static initializer elements are of
7724                         // same type
7725                         //
7726                         UnifyInitializerElement (ec);
7727
7728                         type = ArrayContainer.MakeType (ec.Module, array_element_type, dimensions);
7729                         eclass = ExprClass.Value;
7730                         return this;
7731                 }
7732
7733                 //
7734                 // Converts static initializer only
7735                 //
7736                 void UnifyInitializerElement (ResolveContext ec)
7737                 {
7738                         for (int i = 0; i < array_data.Count; ++i) {
7739                                 Expression e = array_data[i];
7740                                 if (e != null)
7741                                         array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
7742                         }
7743                 }
7744
7745                 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
7746                 {
7747                         element = element.Resolve (ec);
7748                         if (element != null)
7749                                 best_type_inference.AddCommonTypeBound (element.Type);
7750
7751                         return element;
7752                 }
7753         }       
7754         
7755         sealed class CompilerGeneratedThis : This
7756         {
7757                 public CompilerGeneratedThis (TypeSpec type, Location loc)
7758                         : base (loc)
7759                 {
7760                         this.type = type;
7761                         eclass = ExprClass.Variable;
7762                 }
7763
7764                 protected override Expression DoResolve (ResolveContext ec)
7765                 {
7766                         return this;
7767                 }
7768
7769                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
7770                 {
7771                         return null;
7772                 }
7773         }
7774         
7775         /// <summary>
7776         ///   Represents the `this' construct
7777         /// </summary>
7778
7779         public class This : VariableReference
7780         {
7781                 sealed class ThisVariable : ILocalVariable
7782                 {
7783                         public static readonly ILocalVariable Instance = new ThisVariable ();
7784
7785                         public void Emit (EmitContext ec)
7786                         {
7787                                 ec.EmitThis ();
7788                         }
7789
7790                         public void EmitAssign (EmitContext ec)
7791                         {
7792                                 throw new InvalidOperationException ();
7793                         }
7794
7795                         public void EmitAddressOf (EmitContext ec)
7796                         {
7797                                 ec.EmitThis ();
7798                         }
7799                 }
7800
7801                 VariableInfo variable_info;
7802
7803                 public This (Location loc)
7804                 {
7805                         this.loc = loc;
7806                 }
7807
7808                 #region Properties
7809
7810                 public override string Name {
7811                         get { return "this"; }
7812                 }
7813
7814                 public override bool IsLockedByStatement {
7815                         get {
7816                                 return false;
7817                         }
7818                         set {
7819                         }
7820                 }
7821
7822                 public override bool IsRef {
7823                         get { return type.IsStruct; }
7824                 }
7825
7826                 public override bool IsSideEffectFree {
7827                         get {
7828                                 return true;
7829                         }
7830                 }
7831
7832                 protected override ILocalVariable Variable {
7833                         get { return ThisVariable.Instance; }
7834                 }
7835
7836                 public override VariableInfo VariableInfo {
7837                         get { return variable_info; }
7838                 }
7839
7840                 public override bool IsFixed {
7841                         get { return false; }
7842                 }
7843
7844                 #endregion
7845
7846                 void CheckStructThisDefiniteAssignment (FlowAnalysisContext fc)
7847                 {
7848                         //
7849                         // It's null for all cases when we don't need to check `this'
7850                         // definitive assignment
7851                         //
7852                         if (variable_info == null)
7853                                 return;
7854
7855                         if (fc.IsDefinitelyAssigned (variable_info))
7856                                 return;
7857
7858                         fc.Report.Error (188, loc, "The `this' object cannot be used before all of its fields are assigned to");
7859                 }
7860
7861                 protected virtual void Error_ThisNotAvailable (ResolveContext ec)
7862                 {
7863                         if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
7864                                 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
7865                         } else if (ec.CurrentAnonymousMethod != null) {
7866                                 ec.Report.Error (1673, loc,
7867                                         "Anonymous methods inside structs cannot access instance members of `this'. " +
7868                                         "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
7869                         } else {
7870                                 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
7871                         }
7872                 }
7873
7874                 public override void FlowAnalysis (FlowAnalysisContext fc)
7875                 {
7876                         CheckStructThisDefiniteAssignment (fc);
7877                 }
7878
7879                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
7880                 {
7881                         if (ae == null)
7882                                 return null;
7883
7884                         AnonymousMethodStorey storey = ae.Storey;
7885                         return storey != null ? storey.HoistedThis : null;
7886                 }
7887
7888                 public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
7889                 {
7890                         if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
7891                                 return false;
7892
7893                         if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
7894                                 return true;
7895
7896                         if (ec.CurrentType.IsStruct && !(ec.CurrentAnonymousMethod is StateMachineInitializer))
7897                                 return false;
7898
7899                         return true;
7900                 }
7901
7902                 public virtual void ResolveBase (ResolveContext ec)
7903                 {
7904                         eclass = ExprClass.Variable;
7905                         type = ec.CurrentType;
7906
7907                         if (!IsThisAvailable (ec, false)) {
7908                                 Error_ThisNotAvailable (ec);
7909                                 return;
7910                         }
7911
7912                         var block = ec.CurrentBlock;
7913                         if (block != null) {
7914                                 var top = block.ParametersBlock.TopBlock;
7915                                 if (top.ThisVariable != null)
7916                                         variable_info = top.ThisVariable.VariableInfo;
7917
7918                                 AnonymousExpression am = ec.CurrentAnonymousMethod;
7919                                 if (am != null && ec.IsVariableCapturingRequired && !block.Explicit.HasCapturedThis) {
7920                                         //
7921                                         // Hoisted this is almost like hoisted variable but not exactly. When
7922                                         // there is no variable hoisted we can simply emit an instance method
7923                                         // without lifting this into a storey. Unfotunatelly this complicates
7924                                         // things in other cases because we don't know where this will be hoisted
7925                                         // until top-level block is fully resolved
7926                                         //
7927                                         top.AddThisReferenceFromChildrenBlock (block.Explicit);
7928                                         am.SetHasThisAccess ();
7929                                 }
7930                         }
7931                 }
7932
7933                 protected override Expression DoResolve (ResolveContext ec)
7934                 {
7935                         ResolveBase (ec);
7936                         return this;
7937                 }
7938
7939                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7940                 {
7941                         if (eclass == ExprClass.Unresolved)
7942                                 ResolveBase (ec);
7943
7944                         if (type.IsClass){
7945                                 if (right_side == EmptyExpression.UnaryAddress)
7946                                         ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
7947                                 else if (right_side == EmptyExpression.OutAccess)
7948                                         ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
7949                                 else
7950                                         ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
7951                         }
7952
7953                         return this;
7954                 }
7955
7956                 public override int GetHashCode()
7957                 {
7958                         throw new NotImplementedException ();
7959                 }
7960
7961                 public override bool Equals (object obj)
7962                 {
7963                         This t = obj as This;
7964                         if (t == null)
7965                                 return false;
7966
7967                         return true;
7968                 }
7969
7970                 protected override void CloneTo (CloneContext clonectx, Expression t)
7971                 {
7972                         // Nothing
7973                 }
7974
7975                 public override void SetHasAddressTaken ()
7976                 {
7977                         // Nothing
7978                 }
7979                 
7980                 public override object Accept (StructuralVisitor visitor)
7981                 {
7982                         return visitor.Visit (this);
7983                 }
7984         }
7985
7986         /// <summary>
7987         ///   Represents the `__arglist' construct
7988         /// </summary>
7989         public class ArglistAccess : Expression
7990         {
7991                 public ArglistAccess (Location loc)
7992                 {
7993                         this.loc = loc;
7994                 }
7995
7996                 protected override void CloneTo (CloneContext clonectx, Expression target)
7997                 {
7998                         // nothing.
7999                 }
8000
8001                 public override bool ContainsEmitWithAwait ()
8002                 {
8003                         return false;
8004                 }
8005
8006                 public override Expression CreateExpressionTree (ResolveContext ec)
8007                 {
8008                         throw new NotSupportedException ("ET");
8009                 }
8010
8011                 protected override Expression DoResolve (ResolveContext ec)
8012                 {
8013                         eclass = ExprClass.Variable;
8014                         type = ec.Module.PredefinedTypes.RuntimeArgumentHandle.Resolve ();
8015
8016                         if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.ParametersBlock.Parameters.HasArglist) {
8017                                 ec.Report.Error (190, loc,
8018                                         "The __arglist construct is valid only within a variable argument method");
8019                         }
8020
8021                         return this;
8022                 }
8023
8024                 public override void Emit (EmitContext ec)
8025                 {
8026                         ec.Emit (OpCodes.Arglist);
8027                 }
8028
8029                 public override object Accept (StructuralVisitor visitor)
8030                 {
8031                         return visitor.Visit (this);
8032                 }
8033         }
8034
8035         /// <summary>
8036         ///   Represents the `__arglist (....)' construct
8037         /// </summary>
8038         public class Arglist : Expression
8039         {
8040                 Arguments arguments;
8041
8042                 public Arglist (Location loc)
8043                         : this (null, loc)
8044                 {
8045                 }
8046
8047                 public Arglist (Arguments args, Location l)
8048                 {
8049                         arguments = args;
8050                         loc = l;
8051                 }
8052
8053                 public Arguments Arguments {
8054                         get {
8055                                 return arguments;
8056                         }
8057                 }
8058
8059                 public MetaType[] ArgumentTypes {
8060                     get {
8061                                 if (arguments == null)
8062                                         return MetaType.EmptyTypes;
8063
8064                                 var retval = new MetaType[arguments.Count];
8065                                 for (int i = 0; i < retval.Length; i++)
8066                                         retval[i] = arguments[i].Expr.Type.GetMetaInfo ();
8067
8068                         return retval;
8069                     }
8070                 }
8071
8072                 public override bool ContainsEmitWithAwait ()
8073                 {
8074                         throw new NotImplementedException ();
8075                 }
8076                 
8077                 public override Expression CreateExpressionTree (ResolveContext ec)
8078                 {
8079                         ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
8080                         return null;
8081                 }
8082
8083                 protected override Expression DoResolve (ResolveContext ec)
8084                 {
8085                         eclass = ExprClass.Variable;
8086                         type = InternalType.Arglist;
8087                         if (arguments != null) {
8088                                 bool dynamic;   // Can be ignored as there is always only 1 overload
8089                                 arguments.Resolve (ec, out dynamic);
8090                         }
8091
8092                         return this;
8093                 }
8094
8095                 public override void Emit (EmitContext ec)
8096                 {
8097                         if (arguments != null)
8098                                 arguments.Emit (ec);
8099                 }
8100
8101                 protected override void CloneTo (CloneContext clonectx, Expression t)
8102                 {
8103                         Arglist target = (Arglist) t;
8104
8105                         if (arguments != null)
8106                                 target.arguments = arguments.Clone (clonectx);
8107                 }
8108
8109                 public override object Accept (StructuralVisitor visitor)
8110                 {
8111                         return visitor.Visit (this);
8112                 }
8113         }
8114
8115         public class RefValueExpr : ShimExpression, IAssignMethod
8116         {
8117                 FullNamedExpression texpr;
8118
8119                 public RefValueExpr (Expression expr, FullNamedExpression texpr, Location loc)
8120                         : base (expr)
8121                 {
8122                         this.texpr = texpr;
8123                         this.loc = loc;
8124                 }
8125
8126                 public FullNamedExpression TypeExpression {
8127                         get {
8128                                 return texpr;
8129                         }
8130                 }
8131
8132                 public override bool ContainsEmitWithAwait ()
8133                 {
8134                         return false;
8135                 }
8136
8137                 protected override Expression DoResolve (ResolveContext rc)
8138                 {
8139                         expr = expr.Resolve (rc);
8140                         type = texpr.ResolveAsType (rc);
8141                         if (expr == null || type == null)
8142                                 return null;
8143
8144                         expr = Convert.ImplicitConversionRequired (rc, expr, rc.Module.PredefinedTypes.TypedReference.Resolve (), loc);
8145                         eclass = ExprClass.Value;
8146                         return this;
8147                 }
8148
8149                 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
8150                 {
8151                         return DoResolve (rc);
8152                 }
8153
8154                 public override void Emit (EmitContext ec)
8155                 {
8156                         expr.Emit (ec);
8157                         ec.Emit (OpCodes.Refanyval, type);
8158                         ec.EmitLoadFromPtr (type);
8159                 }
8160
8161                 public void Emit (EmitContext ec, bool leave_copy)
8162                 {
8163                         throw new NotImplementedException ();
8164                 }
8165
8166                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
8167                 {
8168                         expr.Emit (ec);
8169                         ec.Emit (OpCodes.Refanyval, type);
8170                         source.Emit (ec);
8171
8172                         LocalTemporary temporary = null;
8173                         if (leave_copy) {
8174                                 ec.Emit (OpCodes.Dup);
8175                                 temporary = new LocalTemporary (source.Type);
8176                                 temporary.Store (ec);
8177                         }
8178
8179                         ec.EmitStoreFromPtr (type);
8180
8181                         if (temporary != null) {
8182                                 temporary.Emit (ec);
8183                                 temporary.Release (ec);
8184                         }
8185                 }
8186
8187                 public override object Accept (StructuralVisitor visitor)
8188                 {
8189                         return visitor.Visit (this);
8190                 }
8191         }
8192
8193         public class RefTypeExpr : ShimExpression
8194         {
8195                 public RefTypeExpr (Expression expr, Location loc)
8196                         : base (expr)
8197                 {
8198                         this.loc = loc;
8199                 }
8200
8201                 protected override Expression DoResolve (ResolveContext rc)
8202                 {
8203                         expr = expr.Resolve (rc);
8204                         if (expr == null)
8205                                 return null;
8206
8207                         expr = Convert.ImplicitConversionRequired (rc, expr, rc.Module.PredefinedTypes.TypedReference.Resolve (), loc);
8208                         if (expr == null)
8209                                 return null;
8210
8211                         type = rc.BuiltinTypes.Type;
8212                         eclass = ExprClass.Value;
8213                         return this;
8214                 }
8215
8216                 public override void Emit (EmitContext ec)
8217                 {
8218                         expr.Emit (ec);
8219                         ec.Emit (OpCodes.Refanytype);
8220                         var m = ec.Module.PredefinedMembers.TypeGetTypeFromHandle.Resolve (loc);
8221                         if (m != null)
8222                                 ec.Emit (OpCodes.Call, m);
8223                 }
8224                 
8225                 public override object Accept (StructuralVisitor visitor)
8226                 {
8227                         return visitor.Visit (this);
8228                 }
8229         }
8230
8231         public class MakeRefExpr : ShimExpression
8232         {
8233                 public MakeRefExpr (Expression expr, Location loc)
8234                         : base (expr)
8235                 {
8236                         this.loc = loc;
8237                 }
8238
8239                 public override bool ContainsEmitWithAwait ()
8240                 {
8241                         throw new NotImplementedException ();
8242                 }
8243
8244                 protected override Expression DoResolve (ResolveContext rc)
8245                 {
8246                         expr = expr.ResolveLValue (rc, EmptyExpression.LValueMemberAccess);
8247                         type = rc.Module.PredefinedTypes.TypedReference.Resolve ();
8248                         eclass = ExprClass.Value;
8249                         return this;
8250                 }
8251
8252                 public override void Emit (EmitContext ec)
8253                 {
8254                         ((IMemoryLocation) expr).AddressOf (ec, AddressOp.Load);
8255                         ec.Emit (OpCodes.Mkrefany, expr.Type);
8256                 }
8257                 
8258                 public override object Accept (StructuralVisitor visitor)
8259                 {
8260                         return visitor.Visit (this);
8261                 }
8262         }
8263
8264         /// <summary>
8265         ///   Implements the typeof operator
8266         /// </summary>
8267         public class TypeOf : Expression {
8268                 FullNamedExpression QueriedType;
8269                 TypeSpec typearg;
8270
8271                 public TypeOf (FullNamedExpression queried_type, Location l)
8272                 {
8273                         QueriedType = queried_type;
8274                         loc = l;
8275                 }
8276
8277                 //
8278                 // Use this constructor for any compiler generated typeof expression
8279                 //
8280                 public TypeOf (TypeSpec type, Location loc)
8281                 {
8282                         this.typearg = type;
8283                         this.loc = loc;
8284                 }
8285
8286                 #region Properties
8287
8288                 public override bool IsSideEffectFree {
8289                         get {
8290                                 return true;
8291                         }
8292                 }
8293
8294                 public TypeSpec TypeArgument {
8295                         get {
8296                                 return typearg;
8297                         }
8298                 }
8299
8300                 public FullNamedExpression TypeExpression {
8301                         get {
8302                                 return QueriedType;
8303                         }
8304                 }
8305
8306                 #endregion
8307
8308
8309                 protected override void CloneTo (CloneContext clonectx, Expression t)
8310                 {
8311                         TypeOf target = (TypeOf) t;
8312                         if (QueriedType != null)
8313                                 target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
8314                 }
8315
8316                 public override bool ContainsEmitWithAwait ()
8317                 {
8318                         return false;
8319                 }
8320
8321                 public override Expression CreateExpressionTree (ResolveContext ec)
8322                 {
8323                         Arguments args = new Arguments (2);
8324                         args.Add (new Argument (this));
8325                         args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
8326                         return CreateExpressionFactoryCall (ec, "Constant", args);
8327                 }
8328
8329                 protected override Expression DoResolve (ResolveContext ec)
8330                 {
8331                         if (eclass != ExprClass.Unresolved)
8332                                 return this;
8333
8334                         if (typearg == null) {
8335                                 //
8336                                 // Pointer types are allowed without explicit unsafe, they are just tokens
8337                                 //
8338                                 using (ec.Set (ResolveContext.Options.UnsafeScope)) {
8339                                         typearg = QueriedType.ResolveAsType (ec);
8340                                 }
8341
8342                                 if (typearg == null)
8343                                         return null;
8344
8345                                 if (typearg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
8346                                         ec.Report.Error (1962, QueriedType.Location,
8347                                                 "The typeof operator cannot be used on the dynamic type");
8348                                 }
8349                         }
8350
8351                         type = ec.BuiltinTypes.Type;
8352
8353                         // Even though what is returned is a type object, it's treated as a value by the compiler.
8354                         // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
8355                         eclass = ExprClass.Value;
8356                         return this;
8357                 }
8358
8359                 static bool ContainsDynamicType (TypeSpec type)
8360                 {
8361                         if (type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
8362                                 return true;
8363
8364                         var element_container = type as ElementTypeSpec;
8365                         if (element_container != null)
8366                                 return ContainsDynamicType (element_container.Element);
8367
8368                         foreach (var t in type.TypeArguments) {
8369                                 if (ContainsDynamicType (t)) {
8370                                         return true;
8371                                 }
8372                         }
8373
8374                         return false;
8375                 }
8376
8377                 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
8378                 {
8379                         // Target type is not System.Type therefore must be object
8380                         // and we need to use different encoding sequence
8381                         if (targetType != type)
8382                                 enc.Encode (type);
8383
8384                         if (typearg is InflatedTypeSpec) {
8385                                 var gt = typearg;
8386                                 do {
8387                                         if (InflatedTypeSpec.ContainsTypeParameter (gt)) {
8388                                                 rc.Module.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
8389                                                         typearg.GetSignatureForError ());
8390                                                 return;
8391                                         }
8392
8393                                         gt = gt.DeclaringType;
8394                                 } while (gt != null);
8395                         }
8396
8397                         if (ContainsDynamicType (typearg)) {
8398                                 Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
8399                                 return;
8400                         }
8401
8402                         enc.EncodeTypeName (typearg);
8403                 }
8404
8405                 public override void Emit (EmitContext ec)
8406                 {
8407                         ec.Emit (OpCodes.Ldtoken, typearg);
8408                         var m = ec.Module.PredefinedMembers.TypeGetTypeFromHandle.Resolve (loc);
8409                         if (m != null)
8410                                 ec.Emit (OpCodes.Call, m);
8411                 }
8412                 
8413                 public override object Accept (StructuralVisitor visitor)
8414                 {
8415                         return visitor.Visit (this);
8416                 }
8417         }
8418
8419         sealed class TypeOfMethod : TypeOfMember<MethodSpec>
8420         {
8421                 public TypeOfMethod (MethodSpec method, Location loc)
8422                         : base (method, loc)
8423                 {
8424                 }
8425
8426                 protected override Expression DoResolve (ResolveContext ec)
8427                 {
8428                         if (member.IsConstructor) {
8429                                 type = ec.Module.PredefinedTypes.ConstructorInfo.Resolve ();
8430                         } else {
8431                                 type = ec.Module.PredefinedTypes.MethodInfo.Resolve ();
8432                         }
8433
8434                         if (type == null)
8435                                 return null;
8436
8437                         return base.DoResolve (ec);
8438                 }
8439
8440                 public override void Emit (EmitContext ec)
8441                 {
8442                         ec.Emit (OpCodes.Ldtoken, member);
8443
8444                         base.Emit (ec);
8445                         ec.Emit (OpCodes.Castclass, type);
8446                 }
8447
8448                 protected override PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec)
8449                 {
8450                         return ec.Module.PredefinedMembers.MethodInfoGetMethodFromHandle;
8451                 }
8452
8453                 protected override PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec)
8454                 {
8455                         return ec.Module.PredefinedMembers.MethodInfoGetMethodFromHandle2;
8456                 }
8457         }
8458
8459         abstract class TypeOfMember<T> : Expression where T : MemberSpec
8460         {
8461                 protected readonly T member;
8462
8463                 protected TypeOfMember (T member, Location loc)
8464                 {
8465                         this.member = member;
8466                         this.loc = loc;
8467                 }
8468
8469                 public override bool IsSideEffectFree {
8470                         get {
8471                                 return true;
8472                         }
8473                 }
8474
8475                 public override bool ContainsEmitWithAwait ()
8476                 {
8477                         return false;
8478                 }
8479
8480                 public override Expression CreateExpressionTree (ResolveContext ec)
8481                 {
8482                         Arguments args = new Arguments (2);
8483                         args.Add (new Argument (this));
8484                         args.Add (new Argument (new TypeOf (type, loc)));
8485                         return CreateExpressionFactoryCall (ec, "Constant", args);
8486                 }
8487
8488                 protected override Expression DoResolve (ResolveContext ec)
8489                 {
8490                         eclass = ExprClass.Value;
8491                         return this;
8492                 }
8493
8494                 public override void Emit (EmitContext ec)
8495                 {
8496                         bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
8497                         PredefinedMember<MethodSpec> p;
8498                         if (is_generic) {
8499                                 p = GetTypeFromHandleGeneric (ec);
8500                                 ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
8501                         } else {
8502                                 p = GetTypeFromHandle (ec);
8503                         }
8504
8505                         var mi = p.Resolve (loc);
8506                         if (mi != null)
8507                                 ec.Emit (OpCodes.Call, mi);
8508                 }
8509
8510                 protected abstract PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec);
8511                 protected abstract PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec);
8512         }
8513
8514         sealed class TypeOfField : TypeOfMember<FieldSpec>
8515         {
8516                 public TypeOfField (FieldSpec field, Location loc)
8517                         : base (field, loc)
8518                 {
8519                 }
8520
8521                 protected override Expression DoResolve (ResolveContext ec)
8522                 {
8523                         type = ec.Module.PredefinedTypes.FieldInfo.Resolve ();
8524                         if (type == null)
8525                                 return null;
8526
8527                         return base.DoResolve (ec);
8528                 }
8529
8530                 public override void Emit (EmitContext ec)
8531                 {
8532                         ec.Emit (OpCodes.Ldtoken, member);
8533                         base.Emit (ec);
8534                 }
8535
8536                 protected override PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec)
8537                 {
8538                         return ec.Module.PredefinedMembers.FieldInfoGetFieldFromHandle;
8539                 }
8540
8541                 protected override PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec)
8542                 {
8543                         return ec.Module.PredefinedMembers.FieldInfoGetFieldFromHandle2;
8544                 }
8545         }
8546
8547         /// <summary>
8548         ///   Implements the sizeof expression
8549         /// </summary>
8550         public class SizeOf : Expression {
8551                 readonly Expression texpr;
8552                 TypeSpec type_queried;
8553                 
8554                 public SizeOf (Expression queried_type, Location l)
8555                 {
8556                         this.texpr = queried_type;
8557                         loc = l;
8558                 }
8559
8560                 public override bool IsSideEffectFree {
8561                         get {
8562                                 return true;
8563                         }
8564                 }
8565
8566                 public Expression TypeExpression {
8567                         get {
8568                                 return texpr;
8569                         }
8570                 }
8571
8572                 public override bool ContainsEmitWithAwait ()
8573                 {
8574                         return false;
8575                 }
8576
8577                 public override Expression CreateExpressionTree (ResolveContext ec)
8578                 {
8579                         Error_PointerInsideExpressionTree (ec);
8580                         return null;
8581                 }
8582
8583                 protected override Expression DoResolve (ResolveContext ec)
8584                 {
8585                         type_queried = texpr.ResolveAsType (ec);
8586                         if (type_queried == null)
8587                                 return null;
8588
8589                         if (type_queried.IsEnum)
8590                                 type_queried = EnumSpec.GetUnderlyingType (type_queried);
8591
8592                         int size_of = BuiltinTypeSpec.GetSize (type_queried);
8593                         if (size_of > 0) {
8594                                 return new IntConstant (ec.BuiltinTypes, size_of, loc);
8595                         }
8596
8597                         if (!TypeManager.VerifyUnmanaged (ec.Module, type_queried, loc)){
8598                                 return null;
8599                         }
8600
8601                         if (!ec.IsUnsafe) {
8602                                 ec.Report.Error (233, loc,
8603                                         "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
8604                                         type_queried.GetSignatureForError ());
8605                         }
8606                         
8607                         type = ec.BuiltinTypes.Int;
8608                         eclass = ExprClass.Value;
8609                         return this;
8610                 }
8611
8612                 public override void Emit (EmitContext ec)
8613                 {
8614                         ec.Emit (OpCodes.Sizeof, type_queried);
8615                 }
8616
8617                 protected override void CloneTo (CloneContext clonectx, Expression t)
8618                 {
8619                 }
8620                 
8621                 public override object Accept (StructuralVisitor visitor)
8622                 {
8623                         return visitor.Visit (this);
8624                 }
8625         }
8626
8627         /// <summary>
8628         ///   Implements the qualified-alias-member (::) expression.
8629         /// </summary>
8630         public class QualifiedAliasMember : MemberAccess
8631         {
8632                 readonly string alias;
8633                 public static readonly string GlobalAlias = "global";
8634
8635                 public QualifiedAliasMember (string alias, string identifier, Location l)
8636                         : base (null, identifier, l)
8637                 {
8638                         this.alias = alias;
8639                 }
8640
8641                 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
8642                         : base (null, identifier, targs, l)
8643                 {
8644                         this.alias = alias;
8645                 }
8646
8647                 public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
8648                         : base (null, identifier, arity, l)
8649                 {
8650                         this.alias = alias;
8651                 }
8652
8653                 public string Alias {
8654                         get {
8655                                 return alias;
8656                         }
8657                 }
8658
8659                 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
8660                 {
8661                         if (alias == GlobalAlias) {
8662                                 expr = new NamespaceExpression (ec.Module.GlobalRootNamespace, loc);
8663                                 return base.ResolveAsTypeOrNamespace (ec);
8664                         }
8665
8666                         int errors = ec.Module.Compiler.Report.Errors;
8667                         expr = ec.LookupNamespaceAlias (alias);
8668                         if (expr == null) {
8669                                 if (errors == ec.Module.Compiler.Report.Errors)
8670                                         ec.Module.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
8671                                 return null;
8672                         }
8673                         
8674                         return base.ResolveAsTypeOrNamespace (ec);
8675                 }
8676
8677                 protected override Expression DoResolve (ResolveContext ec)
8678                 {
8679                         return ResolveAsTypeOrNamespace (ec);
8680                 }
8681
8682                 public override string GetSignatureForError ()
8683                 {
8684                         string name = Name;
8685                         if (targs != null) {
8686                                 name = Name + "<" + targs.GetSignatureForError () + ">";
8687                         }
8688
8689                         return alias + "::" + name;
8690                 }
8691
8692                 public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
8693                 {
8694                         if ((restrictions & MemberLookupRestrictions.InvocableOnly) != 0) {
8695                                 rc.Module.Compiler.Report.Error (687, loc,
8696                                         "The namespace alias qualifier `::' cannot be used to invoke a method. Consider using `.' instead",
8697                                         GetSignatureForError ());
8698
8699                                 return null;
8700                         }
8701
8702                         return DoResolve (rc);
8703                 }
8704
8705                 protected override void CloneTo (CloneContext clonectx, Expression t)
8706                 {
8707                         // Nothing 
8708                 }
8709                 
8710                 public override object Accept (StructuralVisitor visitor)
8711                 {
8712                         return visitor.Visit (this);
8713                 }
8714         }
8715
8716         /// <summary>
8717         ///   Implements the member access expression
8718         /// </summary>
8719         public class MemberAccess : ATypeNameExpression
8720         {
8721                 protected Expression expr;
8722
8723                 public MemberAccess (Expression expr, string id)
8724                         : base (id, expr.Location)
8725                 {
8726                         this.expr = expr;
8727                 }
8728
8729                 public MemberAccess (Expression expr, string identifier, Location loc)
8730                         : base (identifier, loc)
8731                 {
8732                         this.expr = expr;
8733                 }
8734
8735                 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
8736                         : base (identifier, args, loc)
8737                 {
8738                         this.expr = expr;
8739                 }
8740
8741                 public MemberAccess (Expression expr, string identifier, int arity, Location loc)
8742                         : base (identifier, arity, loc)
8743                 {
8744                         this.expr = expr;
8745                 }
8746
8747                 public Expression LeftExpression {
8748                         get {
8749                                 return expr;
8750                         }
8751                 }
8752
8753                 public override Location StartLocation {
8754                         get {
8755                                 return expr == null ? loc : expr.StartLocation;
8756                         }
8757                 }
8758
8759                 protected override Expression DoResolve (ResolveContext rc)
8760                 {
8761                         var e = LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess);
8762                         if (e != null)
8763                                 e = e.Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.Type | ResolveFlags.MethodGroup);
8764
8765                         return e;
8766                 }
8767
8768                 public override Expression DoResolveLValue (ResolveContext rc, Expression rhs)
8769                 {
8770                         var e = LookupNameExpression (rc, MemberLookupRestrictions.None);
8771
8772                         if (e is TypeExpr) {
8773                                 e.Error_UnexpectedKind (rc, ResolveFlags.VariableOrValue, loc);
8774                                 return null;
8775                         }
8776
8777                         if (e != null)
8778                                 e = e.ResolveLValue (rc, rhs);
8779
8780                         return e;
8781                 }
8782
8783                 protected virtual void Error_OperatorCannotBeApplied (ResolveContext rc, TypeSpec type)
8784                 {
8785                         if (type == InternalType.NullLiteral && rc.IsRuntimeBinder)
8786                                 rc.Report.Error (Report.RuntimeErrorId, loc, "Cannot perform member binding on `null' value");
8787                         else
8788                                 expr.Error_OperatorCannotBeApplied (rc, loc, ".", type);
8789                 }
8790
8791                 public static bool IsValidDotExpression (TypeSpec type)
8792                 {
8793                         const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
8794                                 MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
8795
8796                         return (type.Kind & dot_kinds) != 0 || type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
8797                 }
8798
8799                 public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
8800                 {
8801                         var sn = expr as SimpleName;
8802                         const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
8803
8804                         if (sn != null) {
8805                                 expr = sn.LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);
8806
8807                                 //
8808                                 // Resolve expression which does have type set as we need expression type
8809                                 // with disable flow analysis as we don't know whether left side expression
8810                                 // is used as variable or type
8811                                 //
8812                                 if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess) {
8813                                         expr = expr.Resolve (rc);
8814                                 } else if (expr is TypeParameterExpr) {
8815                                         expr.Error_UnexpectedKind (rc, flags, sn.Location);
8816                                         expr = null;
8817                                 }
8818                         } else {
8819                                 expr = expr.Resolve (rc, flags);
8820                         }
8821
8822                         if (expr == null)
8823                                 return null;
8824
8825                         var ns = expr as NamespaceExpression;
8826                         if (ns != null) {
8827                                 var retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc);
8828
8829                                 if (retval == null) {
8830                                         ns.Error_NamespaceDoesNotExist (rc, Name, Arity);
8831                                         return null;
8832                                 }
8833
8834                                 if (HasTypeArguments)
8835                                         return new GenericTypeExpr (retval.Type, targs, loc);
8836
8837                                 return retval;
8838                         }
8839
8840                         MemberExpr me;
8841                         TypeSpec expr_type = expr.Type;
8842                         if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
8843                                 me = expr as MemberExpr;
8844                                 if (me != null)
8845                                         me.ResolveInstanceExpression (rc, null);
8846
8847                                 Arguments args = new Arguments (1);
8848                                 args.Add (new Argument (expr));
8849                                 return new DynamicMemberBinder (Name, args, loc);
8850                         }
8851
8852                         if (!IsValidDotExpression (expr_type)) {
8853                                 Error_OperatorCannotBeApplied (rc, expr_type);
8854                                 return null;
8855                         }
8856
8857                         var lookup_arity = Arity;
8858                         bool errorMode = false;
8859                         Expression member_lookup;
8860                         while (true) {
8861                                 member_lookup = MemberLookup (rc, errorMode, expr_type, Name, lookup_arity, restrictions, loc);
8862                                 if (member_lookup == null) {
8863                                         //
8864                                         // Try to look for extension method when member lookup failed
8865                                         //
8866                                         if (MethodGroupExpr.IsExtensionMethodArgument (expr)) {
8867                                                 var methods = rc.LookupExtensionMethod (expr_type, Name, lookup_arity);
8868                                                 if (methods != null) {
8869                                                         var emg = new ExtensionMethodGroupExpr (methods, expr, loc);
8870                                                         if (HasTypeArguments) {
8871                                                                 if (!targs.Resolve (rc))
8872                                                                         return null;
8873
8874                                                                 emg.SetTypeArguments (rc, targs);
8875                                                         }
8876
8877                                                         // TODO: it should really skip the checks bellow
8878                                                         return emg.Resolve (rc);
8879                                                 }
8880                                         }
8881                                 }
8882
8883                                 if (errorMode) {
8884                                         if (member_lookup == null) {
8885                                                 var dep = expr_type.GetMissingDependencies ();
8886                                                 if (dep != null) {
8887                                                         ImportedTypeDefinition.Error_MissingDependency (rc, dep, loc);
8888                                                 } else if (expr is TypeExpr) {
8889                                                         base.Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
8890                                                 } else {
8891                                                         Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
8892                                                 }
8893
8894                                                 return null;
8895                                         }
8896
8897                                         if (member_lookup is MethodGroupExpr || member_lookup is PropertyExpr) {
8898                                                 // Leave it to overload resolution to report correct error
8899                                         } else if (!(member_lookup is TypeExpr)) {
8900                                                 // TODO: rc.SymbolRelatedToPreviousError
8901                                                 ErrorIsInaccesible (rc, member_lookup.GetSignatureForError (), loc);
8902                                         }
8903                                         break;
8904                                 }
8905
8906                                 if (member_lookup != null)
8907                                         break;
8908
8909                                 lookup_arity = 0;
8910                                 restrictions &= ~MemberLookupRestrictions.InvocableOnly;
8911                                 errorMode = true;
8912                         }
8913
8914                         TypeExpr texpr = member_lookup as TypeExpr;
8915                         if (texpr != null) {
8916                                 if (!(expr is TypeExpr) && (sn == null || expr.ProbeIdenticalTypeName (rc, expr, sn) == expr)) {
8917                                         rc.Report.Error (572, loc, "`{0}': cannot reference a type through an expression. Consider using `{1}' instead",
8918                                                 Name, texpr.GetSignatureForError ());
8919                                 }
8920
8921                                 if (!texpr.Type.IsAccessible (rc)) {
8922                                         rc.Report.SymbolRelatedToPreviousError (member_lookup.Type);
8923                                         ErrorIsInaccesible (rc, member_lookup.Type.GetSignatureForError (), loc);
8924                                         return null;
8925                                 }
8926
8927                                 if (HasTypeArguments) {
8928                                         return new GenericTypeExpr (member_lookup.Type, targs, loc);
8929                                 }
8930
8931                                 return member_lookup;
8932                         }
8933
8934                         me = member_lookup as MemberExpr;
8935
8936                         if (sn != null && me.IsStatic && (expr = me.ProbeIdenticalTypeName (rc, expr, sn)) != expr) {
8937                                 sn = null;
8938                         }
8939
8940                         me = me.ResolveMemberAccess (rc, expr, sn);
8941
8942                         if (Arity > 0) {
8943                                 if (!targs.Resolve (rc))
8944                                         return null;
8945
8946                                 me.SetTypeArguments (rc, targs);
8947                         }
8948
8949                         return me;
8950                 }
8951
8952                 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext rc)
8953                 {
8954                         FullNamedExpression fexpr = expr as FullNamedExpression;
8955                         if (fexpr == null) {
8956                                 expr.ResolveAsType (rc);
8957                                 return null;
8958                         }
8959
8960                         FullNamedExpression expr_resolved = fexpr.ResolveAsTypeOrNamespace (rc);
8961
8962                         if (expr_resolved == null)
8963                                 return null;
8964
8965                         var ns = expr_resolved as NamespaceExpression;
8966                         if (ns != null) {
8967                                 FullNamedExpression retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc);
8968
8969                                 if (retval == null) {
8970                                         ns.Error_NamespaceDoesNotExist (rc, Name, Arity);
8971                                 } else if (HasTypeArguments) {
8972                                         retval = new GenericTypeExpr (retval.Type, targs, loc);
8973                                         if (retval.ResolveAsType (rc) == null)
8974                                                 return null;
8975                                 }
8976
8977                                 return retval;
8978                         }
8979
8980                         var tnew_expr = expr_resolved.ResolveAsType (rc);
8981                         if (tnew_expr == null)
8982                                 return null;
8983
8984                         TypeSpec expr_type = tnew_expr;
8985                         if (TypeManager.IsGenericParameter (expr_type)) {
8986                                 rc.Module.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
8987                                         tnew_expr.GetSignatureForError ());
8988                                 return null;
8989                         }
8990
8991                         var qam = this as QualifiedAliasMember;
8992                         if (qam != null) {
8993                                 rc.Module.Compiler.Report.Error (431, loc,
8994                                         "Alias `{0}' cannot be used with `::' since it denotes a type. Consider replacing `::' with `.'",
8995                                         qam.Alias);
8996
8997                         }
8998
8999                         TypeSpec nested = null;
9000                         while (expr_type != null) {
9001                                 nested = MemberCache.FindNestedType (expr_type, Name, Arity);
9002                                 if (nested == null) {
9003                                         if (expr_type == tnew_expr) {
9004                                                 Error_IdentifierNotFound (rc, expr_type, Name);
9005                                                 return null;
9006                                         }
9007
9008                                         expr_type = tnew_expr;
9009                                         nested = MemberCache.FindNestedType (expr_type, Name, Arity);
9010                                         ErrorIsInaccesible (rc, nested.GetSignatureForError (), loc);
9011                                         break;
9012                                 }
9013
9014                                 if (nested.IsAccessible (rc))
9015                                         break;
9016
9017                                 //
9018                                 // Keep looking after inaccessible candidate but only if
9019                                 // we are not in same context as the definition itself
9020                                 //
9021                                 if (expr_type.MemberDefinition == rc.CurrentMemberDefinition)
9022                                         break;
9023
9024                                 expr_type = expr_type.BaseType;
9025                         }
9026                         
9027                         TypeExpr texpr;
9028                         if (Arity > 0) {
9029                                 if (HasTypeArguments) {
9030                                         texpr = new GenericTypeExpr (nested, targs, loc);
9031                                 } else {
9032                                         texpr = new GenericOpenTypeExpr (nested, loc);
9033                                 }
9034                         } else {
9035                                 texpr = new TypeExpression (nested, loc);
9036                         }
9037
9038                         if (texpr.ResolveAsType (rc) == null)
9039                                 return null;
9040
9041                         return texpr;
9042                 }
9043
9044                 protected virtual void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
9045                 {
9046                         var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
9047
9048                         if (nested != null) {
9049                                 Error_TypeArgumentsCannotBeUsed (rc, nested, expr.Location);
9050                                 return;
9051                         }
9052
9053                         var any_other_member = MemberLookup (rc, false, expr_type, Name, 0, MemberLookupRestrictions.None, loc);
9054                         if (any_other_member != null) {
9055                                 Error_UnexpectedKind (rc, any_other_member, "type", any_other_member.ExprClassName, loc);
9056                                 return;
9057                         }
9058
9059                         rc.Module.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
9060                                 Name, expr_type.GetSignatureForError ());
9061                 }
9062
9063                 protected override void Error_InvalidExpressionStatement (Report report, Location loc)
9064                 {
9065                         base.Error_InvalidExpressionStatement (report, LeftExpression.Location);
9066                 }
9067
9068                 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
9069                 {
9070                         if (ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2 && !ec.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
9071                                 ec.Report.SymbolRelatedToPreviousError (type);
9072
9073                                 var cand = ec.Module.GlobalRootNamespace.FindExtensionMethodNamespaces (ec, name, Arity);
9074                                 string missing;
9075                                 // a using directive or an assembly reference
9076                                 if (cand != null) {
9077                                         missing = "`" + string.Join ("' or `", cand.ToArray ()) + "' using directive";
9078                                 } else {
9079                                         missing = "an assembly reference";
9080                                 }
9081
9082                                 ec.Report.Error (1061, loc,
9083                                         "Type `{0}' does not contain a definition for `{1}' and no extension method `{1}' of type `{0}' could be found. Are you missing {2}?",
9084                                         type.GetSignatureForError (), name, missing);
9085                                 return;
9086                         }
9087
9088                         base.Error_TypeDoesNotContainDefinition (ec, type, name);
9089                 }
9090
9091                 public override string GetSignatureForError ()
9092                 {
9093                         return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
9094                 }
9095
9096                 protected override void CloneTo (CloneContext clonectx, Expression t)
9097                 {
9098                         MemberAccess target = (MemberAccess) t;
9099
9100                         target.expr = expr.Clone (clonectx);
9101                 }
9102                 
9103                 public override object Accept (StructuralVisitor visitor)
9104                 {
9105                         return visitor.Visit (this);
9106                 }
9107         }
9108
9109         /// <summary>
9110         ///   Implements checked expressions
9111         /// </summary>
9112         public class CheckedExpr : Expression {
9113
9114                 public Expression Expr;
9115
9116                 public CheckedExpr (Expression e, Location l)
9117                 {
9118                         Expr = e;
9119                         loc = l;
9120                 }
9121
9122                 public override bool ContainsEmitWithAwait ()
9123                 {
9124                         return Expr.ContainsEmitWithAwait ();
9125                 }
9126                 
9127                 public override Expression CreateExpressionTree (ResolveContext ec)
9128                 {
9129                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
9130                                 return Expr.CreateExpressionTree (ec);
9131                 }
9132
9133                 protected override Expression DoResolve (ResolveContext ec)
9134                 {
9135                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
9136                                 Expr = Expr.Resolve (ec);
9137                         
9138                         if (Expr == null)
9139                                 return null;
9140
9141                         if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
9142                                 return Expr;
9143                         
9144                         eclass = Expr.eclass;
9145                         type = Expr.Type;
9146                         return this;
9147                 }
9148
9149                 public override void Emit (EmitContext ec)
9150                 {
9151                         using (ec.With (EmitContext.Options.CheckedScope, true))
9152                                 Expr.Emit (ec);
9153                 }
9154
9155                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
9156                 {
9157                         using (ec.With (EmitContext.Options.CheckedScope, true))
9158                                 Expr.EmitBranchable (ec, target, on_true);
9159                 }
9160
9161                 public override void FlowAnalysis (FlowAnalysisContext fc)
9162                 {
9163                         Expr.FlowAnalysis (fc);
9164                 }
9165
9166                 public override SLE.Expression MakeExpression (BuilderContext ctx)
9167                 {
9168                         using (ctx.With (BuilderContext.Options.CheckedScope, true)) {
9169                                 return Expr.MakeExpression (ctx);
9170                         }
9171                 }
9172
9173                 protected override void CloneTo (CloneContext clonectx, Expression t)
9174                 {
9175                         CheckedExpr target = (CheckedExpr) t;
9176
9177                         target.Expr = Expr.Clone (clonectx);
9178                 }
9179
9180                 public override object Accept (StructuralVisitor visitor)
9181                 {
9182                         return visitor.Visit (this);
9183                 }
9184         }
9185
9186         /// <summary>
9187         ///   Implements the unchecked expression
9188         /// </summary>
9189         public class UnCheckedExpr : Expression {
9190
9191                 public Expression Expr;
9192
9193                 public UnCheckedExpr (Expression e, Location l)
9194                 {
9195                         Expr = e;
9196                         loc = l;
9197                 }
9198
9199                 public override bool ContainsEmitWithAwait ()
9200                 {
9201                         return Expr.ContainsEmitWithAwait ();
9202                 }
9203                 
9204                 public override Expression CreateExpressionTree (ResolveContext ec)
9205                 {
9206                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
9207                                 return Expr.CreateExpressionTree (ec);
9208                 }
9209
9210                 protected override Expression DoResolve (ResolveContext ec)
9211                 {
9212                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
9213                                 Expr = Expr.Resolve (ec);
9214
9215                         if (Expr == null)
9216                                 return null;
9217
9218                         if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
9219                                 return Expr;
9220                         
9221                         eclass = Expr.eclass;
9222                         type = Expr.Type;
9223                         return this;
9224                 }
9225
9226                 public override void Emit (EmitContext ec)
9227                 {
9228                         using (ec.With (EmitContext.Options.CheckedScope, false))
9229                                 Expr.Emit (ec);
9230                 }
9231
9232                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
9233                 {
9234                         using (ec.With (EmitContext.Options.CheckedScope, false))
9235                                 Expr.EmitBranchable (ec, target, on_true);
9236                 }
9237
9238                 public override void FlowAnalysis (FlowAnalysisContext fc)
9239                 {
9240                         Expr.FlowAnalysis (fc);
9241                 }
9242
9243                 protected override void CloneTo (CloneContext clonectx, Expression t)
9244                 {
9245                         UnCheckedExpr target = (UnCheckedExpr) t;
9246
9247                         target.Expr = Expr.Clone (clonectx);
9248                 }
9249
9250                 public override object Accept (StructuralVisitor visitor)
9251                 {
9252                         return visitor.Visit (this);
9253                 }
9254         }
9255
9256         /// <summary>
9257         ///   An Element Access expression.
9258         ///
9259         ///   During semantic analysis these are transformed into 
9260         ///   IndexerAccess, ArrayAccess or a PointerArithmetic.
9261         /// </summary>
9262         public class ElementAccess : Expression
9263         {
9264                 public Arguments Arguments;
9265                 public Expression Expr;
9266
9267                 public ElementAccess (Expression e, Arguments args, Location loc)
9268                 {
9269                         Expr = e;
9270                         this.loc = loc;
9271                         this.Arguments = args;
9272                 }
9273
9274                 public override Location StartLocation {
9275                         get {
9276                                 return Expr.StartLocation;
9277                         }
9278                 }
9279
9280                 public override bool ContainsEmitWithAwait ()
9281                 {
9282                         return Expr.ContainsEmitWithAwait () || Arguments.ContainsEmitWithAwait ();
9283                 }
9284
9285                 //
9286                 // We perform some simple tests, and then to "split" the emit and store
9287                 // code we create an instance of a different class, and return that.
9288                 //
9289                 Expression CreateAccessExpression (ResolveContext ec)
9290                 {
9291                         if (type.IsArray)
9292                                 return (new ArrayAccess (this, loc));
9293
9294                         if (type.IsPointer)
9295                                 return MakePointerAccess (ec, type);
9296
9297                         FieldExpr fe = Expr as FieldExpr;
9298                         if (fe != null) {
9299                                 var ff = fe.Spec as FixedFieldSpec;
9300                                 if (ff != null) {
9301                                         return MakePointerAccess (ec, ff.ElementType);
9302                                 }
9303                         }
9304
9305                         var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
9306                         if (indexers != null || type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
9307                                 return new IndexerExpr (indexers, type, this);
9308                         }
9309
9310                         if (type != InternalType.ErrorType) {
9311                                 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
9312                                         type.GetSignatureForError ());
9313                         }
9314
9315                         return null;
9316                 }
9317
9318                 public override Expression CreateExpressionTree (ResolveContext ec)
9319                 {
9320                         Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
9321                                 Expr.CreateExpressionTree (ec));
9322
9323                         return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
9324                 }
9325
9326                 Expression MakePointerAccess (ResolveContext rc, TypeSpec type)
9327                 {
9328                         if (Arguments.Count != 1){
9329                                 rc.Report.Error (196, loc, "A pointer must be indexed by only one value");
9330                                 return null;
9331                         }
9332
9333                         var arg = Arguments[0];
9334                         if (arg is NamedArgument)
9335                                 Error_NamedArgument ((NamedArgument) arg, rc.Report);
9336
9337                         var index = arg.Expr.Resolve (rc);
9338                         if (index == null)
9339                                 return null;
9340
9341                         index = ConvertExpressionToArrayIndex (rc, index, true);
9342
9343                         Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, index, type, loc);
9344                         return new Indirection (p, loc);
9345                 }
9346                 
9347                 protected override Expression DoResolve (ResolveContext ec)
9348                 {
9349                         Expr = Expr.Resolve (ec);
9350                         if (Expr == null)
9351                                 return null;
9352
9353                         type = Expr.Type;
9354
9355                         // TODO: Create 1 result for Resolve and ResolveLValue ?
9356                         var res = CreateAccessExpression (ec);
9357                         if (res == null)
9358                                 return null;
9359
9360                         return res.Resolve (ec);
9361                 }
9362
9363                 public override Expression DoResolveLValue (ResolveContext ec, Expression rhs)
9364                 {
9365                         Expr = Expr.Resolve (ec);
9366                         if (Expr == null)
9367                                 return null;
9368
9369                         type = Expr.Type;
9370
9371                         var res = CreateAccessExpression (ec);
9372                         if (res == null)
9373                                 return null;
9374
9375                         return res.ResolveLValue (ec, rhs);
9376                 }
9377                 
9378                 public override void Emit (EmitContext ec)
9379                 {
9380                         throw new Exception ("Should never be reached");
9381                 }
9382
9383                 public static void Error_NamedArgument (NamedArgument na, Report Report)
9384                 {
9385                         Report.Error (1742, na.Location, "An element access expression cannot use named argument");
9386                 }
9387
9388                 public override void FlowAnalysis (FlowAnalysisContext fc)
9389                 {
9390                         Expr.FlowAnalysis (fc);
9391                         Arguments.FlowAnalysis (fc);
9392                 }
9393
9394                 public override string GetSignatureForError ()
9395                 {
9396                         return Expr.GetSignatureForError ();
9397                 }
9398
9399                 protected override void CloneTo (CloneContext clonectx, Expression t)
9400                 {
9401                         ElementAccess target = (ElementAccess) t;
9402
9403                         target.Expr = Expr.Clone (clonectx);
9404                         if (Arguments != null)
9405                                 target.Arguments = Arguments.Clone (clonectx);
9406                 }
9407                 
9408                 public override object Accept (StructuralVisitor visitor)
9409                 {
9410                         return visitor.Visit (this);
9411                 }
9412         }
9413
9414         /// <summary>
9415         ///   Implements array access 
9416         /// </summary>
9417         public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
9418                 //
9419                 // Points to our "data" repository
9420                 //
9421                 ElementAccess ea;
9422
9423                 LocalTemporary temp;
9424                 bool prepared;
9425                 bool? has_await_args;
9426                 
9427                 public ArrayAccess (ElementAccess ea_data, Location l)
9428                 {
9429                         ea = ea_data;
9430                         loc = l;
9431                 }
9432
9433                 public void AddressOf (EmitContext ec, AddressOp mode)
9434                 {
9435                         var ac = (ArrayContainer) ea.Expr.Type;
9436
9437                         LoadInstanceAndArguments (ec, false, false);
9438
9439                         if (ac.Element.IsGenericParameter && mode == AddressOp.Load)
9440                                 ec.Emit (OpCodes.Readonly);
9441
9442                         ec.EmitArrayAddress (ac);
9443                 }
9444
9445                 public override Expression CreateExpressionTree (ResolveContext ec)
9446                 {
9447                         return ea.CreateExpressionTree (ec);
9448                 }
9449
9450                 public override bool ContainsEmitWithAwait ()
9451                 {
9452                         return ea.ContainsEmitWithAwait ();
9453                 }
9454
9455                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
9456                 {
9457                         return DoResolve (ec);
9458                 }
9459
9460                 protected override Expression DoResolve (ResolveContext ec)
9461                 {
9462                         // dynamic is used per argument in ConvertExpressionToArrayIndex case
9463                         bool dynamic;
9464                         ea.Arguments.Resolve (ec, out dynamic);
9465
9466                         var ac = ea.Expr.Type as ArrayContainer;
9467                         int rank = ea.Arguments.Count;
9468                         if (ac.Rank != rank) {
9469                                 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
9470                                           rank.ToString (), ac.Rank.ToString ());
9471                                 return null;
9472                         }
9473
9474                         type = ac.Element;
9475                         if (type.IsPointer && !ec.IsUnsafe) {
9476                                 UnsafeError (ec, ea.Location);
9477                         }
9478
9479                         foreach (Argument a in ea.Arguments) {
9480                                 if (a is NamedArgument)
9481                                         ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
9482
9483                                 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
9484                         }
9485                         
9486                         eclass = ExprClass.Variable;
9487
9488                         return this;
9489                 }
9490
9491                 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
9492                 {
9493                         ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
9494                 }
9495
9496                 public override void FlowAnalysis (FlowAnalysisContext fc)
9497                 {
9498                         ea.FlowAnalysis (fc);
9499                 }
9500
9501                 //
9502                 // Load the array arguments into the stack.
9503                 //
9504                 void LoadInstanceAndArguments (EmitContext ec, bool duplicateArguments, bool prepareAwait)
9505                 {
9506                         if (prepareAwait) {
9507                                 ea.Expr = ea.Expr.EmitToField (ec);
9508                         } else if (duplicateArguments) {
9509                                 ea.Expr.Emit (ec);
9510                                 ec.Emit (OpCodes.Dup);
9511
9512                                 var copy = new LocalTemporary (ea.Expr.Type);
9513                                 copy.Store (ec);
9514                                 ea.Expr = copy;
9515                         } else {
9516                                 ea.Expr.Emit (ec);
9517                         }
9518
9519                         var dup_args = ea.Arguments.Emit (ec, duplicateArguments, prepareAwait);
9520                         if (dup_args != null)
9521                                 ea.Arguments = dup_args;
9522                 }
9523
9524                 public void Emit (EmitContext ec, bool leave_copy)
9525                 {
9526                         var ac = ea.Expr.Type as ArrayContainer;
9527
9528                         if (prepared) {
9529                                 ec.EmitLoadFromPtr (type);
9530                         } else {
9531                                 if (!has_await_args.HasValue && ec.HasSet (BuilderContext.Options.AsyncBody) && ea.Arguments.ContainsEmitWithAwait ()) {
9532                                         LoadInstanceAndArguments (ec, false, true);
9533                                 }
9534
9535                                 LoadInstanceAndArguments (ec, false, false);
9536                                 ec.EmitArrayLoad (ac);
9537                         }       
9538
9539                         if (leave_copy) {
9540                                 ec.Emit (OpCodes.Dup);
9541                                 temp = new LocalTemporary (this.type);
9542                                 temp.Store (ec);
9543                         }
9544                 }
9545                 
9546                 public override void Emit (EmitContext ec)
9547                 {
9548                         Emit (ec, false);
9549                 }
9550
9551                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
9552                 {
9553                         var ac = (ArrayContainer) ea.Expr.Type;
9554                         TypeSpec t = source.Type;
9555
9556                         has_await_args = ec.HasSet (BuilderContext.Options.AsyncBody) && (ea.Arguments.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ());
9557
9558                         //
9559                         // When we are dealing with a struct, get the address of it to avoid value copy
9560                         // Same cannot be done for reference type because array covariance and the
9561                         // check in ldelema requires to specify the type of array element stored at the index
9562                         //
9563                         if (t.IsStruct && ((isCompound && !(source is DynamicExpressionStatement)) || !BuiltinTypeSpec.IsPrimitiveType (t))) {
9564                                 LoadInstanceAndArguments (ec, false, has_await_args.Value);
9565
9566                                 if (has_await_args.Value) {
9567                                         if (source.ContainsEmitWithAwait ()) {
9568                                                 source = source.EmitToField (ec);
9569                                                 isCompound = false;
9570                                                 prepared = true;
9571                                         }
9572
9573                                         LoadInstanceAndArguments (ec, isCompound, false);
9574                                 } else {
9575                                         prepared = true;
9576                                 }
9577
9578                                 ec.EmitArrayAddress (ac);
9579
9580                                 if (isCompound) {
9581                                         ec.Emit (OpCodes.Dup);
9582                                         prepared = true;
9583                                 }
9584                         } else {
9585                                 LoadInstanceAndArguments (ec, isCompound, has_await_args.Value);
9586
9587                                 if (has_await_args.Value) {
9588                                         if (source.ContainsEmitWithAwait ())
9589                                                 source = source.EmitToField (ec);
9590
9591                                         LoadInstanceAndArguments (ec, false, false);
9592                                 }
9593                         }
9594
9595                         source.Emit (ec);
9596
9597                         if (isCompound) {
9598                                 var lt = ea.Expr as LocalTemporary;
9599                                 if (lt != null)
9600                                         lt.Release (ec);
9601                         }
9602
9603                         if (leave_copy) {
9604                                 ec.Emit (OpCodes.Dup);
9605                                 temp = new LocalTemporary (this.type);
9606                                 temp.Store (ec);
9607                         }
9608
9609                         if (prepared) {
9610                                 ec.EmitStoreFromPtr (t);
9611                         } else {
9612                                 ec.EmitArrayStore (ac);
9613                         }
9614                         
9615                         if (temp != null) {
9616                                 temp.Emit (ec);
9617                                 temp.Release (ec);
9618                         }
9619                 }
9620
9621                 public override Expression EmitToField (EmitContext ec)
9622                 {
9623                         //
9624                         // Have to be specialized for arrays to get access to
9625                         // underlying element. Instead of another result copy we
9626                         // need direct access to element 
9627                         //
9628                         // Consider:
9629                         //
9630                         // CallRef (ref a[await Task.Factory.StartNew (() => 1)]);
9631                         //
9632                         ea.Expr = ea.Expr.EmitToField (ec);
9633                         return this;
9634                 }
9635
9636                 public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
9637                 {
9638 #if NET_4_0 || MOBILE_DYNAMIC
9639                         return SLE.Expression.ArrayAccess (ea.Expr.MakeExpression (ctx), MakeExpressionArguments (ctx));
9640 #else
9641                         throw new NotImplementedException ();
9642 #endif
9643                 }
9644
9645                 public override SLE.Expression MakeExpression (BuilderContext ctx)
9646                 {
9647                         return SLE.Expression.ArrayIndex (ea.Expr.MakeExpression (ctx), MakeExpressionArguments (ctx));
9648                 }
9649
9650                 SLE.Expression[] MakeExpressionArguments (BuilderContext ctx)
9651                 {
9652                         using (ctx.With (BuilderContext.Options.CheckedScope, true)) {
9653                                 return Arguments.MakeExpression (ea.Arguments, ctx);
9654                         }
9655                 }
9656         }
9657
9658         //
9659         // Indexer access expression
9660         //
9661         sealed class IndexerExpr : PropertyOrIndexerExpr<IndexerSpec>, OverloadResolver.IBaseMembersProvider
9662         {
9663                 IList<MemberSpec> indexers;
9664                 Arguments arguments;
9665                 TypeSpec queried_type;
9666                 
9667                 public IndexerExpr (IList<MemberSpec> indexers, TypeSpec queriedType, ElementAccess ea)
9668                         : base (ea.Location)
9669                 {
9670                         this.indexers = indexers;
9671                         this.queried_type = queriedType;
9672                         this.InstanceExpression = ea.Expr;
9673                         this.arguments = ea.Arguments;
9674                 }
9675
9676                 #region Properties
9677
9678                 protected override Arguments Arguments {
9679                         get {
9680                                 return arguments;
9681                         }
9682                         set {
9683                                 arguments = value;
9684                         }
9685                 }
9686
9687                 protected override TypeSpec DeclaringType {
9688                         get {
9689                                 return best_candidate.DeclaringType;
9690                         }
9691                 }
9692
9693                 public override bool IsInstance {
9694                         get {
9695                                 return true;
9696                         }
9697                 }
9698
9699                 public override bool IsStatic {
9700                         get {
9701                                 return false;
9702                         }
9703                 }
9704
9705                 public override string KindName {
9706                         get { return "indexer"; }
9707                 }
9708
9709                 public override string Name {
9710                         get {
9711                                 return "this";
9712                         }
9713                 }
9714
9715                 #endregion
9716
9717                 public override bool ContainsEmitWithAwait ()
9718                 {
9719                         return base.ContainsEmitWithAwait () || arguments.ContainsEmitWithAwait ();
9720                 }
9721
9722                 public override Expression CreateExpressionTree (ResolveContext ec)
9723                 {
9724                         Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
9725                                 InstanceExpression.CreateExpressionTree (ec),
9726                                 new TypeOfMethod (Getter, loc));
9727
9728                         return CreateExpressionFactoryCall (ec, "Call", args);
9729                 }
9730         
9731                 public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
9732                 {
9733                         LocalTemporary await_source_arg = null;
9734
9735                         if (isCompound) {
9736                                 emitting_compound_assignment = true;
9737                                 if (source is DynamicExpressionStatement) {
9738                                         Emit (ec, false);
9739                                 } else {
9740                                         source.Emit (ec);
9741                                 }
9742                                 emitting_compound_assignment = false;
9743
9744                                 if (has_await_arguments) {
9745                                         await_source_arg = new LocalTemporary (Type);
9746                                         await_source_arg.Store (ec);
9747
9748                                         arguments.Add (new Argument (await_source_arg));
9749
9750                                         if (leave_copy) {
9751                                                 temp = await_source_arg;
9752                                         }
9753
9754                                         has_await_arguments = false;
9755                                 } else {
9756                                         arguments = null;
9757
9758                                         if (leave_copy) {
9759                                                 ec.Emit (OpCodes.Dup);
9760                                                 temp = new LocalTemporary (Type);
9761                                                 temp.Store (ec);
9762                                         }
9763                                 }
9764                         } else {
9765                                 if (leave_copy) {
9766                                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && (arguments.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ())) {
9767                                                 source = source.EmitToField (ec);
9768                                         } else {
9769                                                 temp = new LocalTemporary (Type);
9770                                                 source.Emit (ec);
9771                                                 temp.Store (ec);
9772                                                 source = temp;
9773                                         }
9774                                 }
9775
9776                                 arguments.Add (new Argument (source));
9777                         }
9778
9779                         var call = new CallEmitter ();
9780                         call.InstanceExpression = InstanceExpression;
9781                         if (arguments == null)
9782                                 call.InstanceExpressionOnStack = true;
9783
9784                         call.Emit (ec, Setter, arguments, loc);
9785
9786                         if (temp != null) {
9787                                 temp.Emit (ec);
9788                                 temp.Release (ec);
9789                         } else if (leave_copy) {
9790                                 source.Emit (ec);
9791                         }
9792
9793                         if (await_source_arg != null) {
9794                                 await_source_arg.Release (ec);
9795                         }
9796                 }
9797
9798                 public override void FlowAnalysis (FlowAnalysisContext fc)
9799                 {
9800                         // TODO: Check the order
9801                         base.FlowAnalysis (fc);
9802                         arguments.FlowAnalysis (fc);
9803                 }
9804
9805                 public override string GetSignatureForError ()
9806                 {
9807                         return best_candidate.GetSignatureForError ();
9808                 }
9809                 
9810                 public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
9811                 {
9812 #if STATIC
9813                         throw new NotSupportedException ();
9814 #else
9815                         var value = new[] { source.MakeExpression (ctx) };
9816                         var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
9817 #if NET_4_0 || MOBILE_DYNAMIC
9818                         return SLE.Expression.Block (
9819                                         SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
9820                                         value [0]);
9821 #else
9822                         return args.First ();
9823 #endif
9824 #endif
9825                 }
9826
9827                 public override SLE.Expression MakeExpression (BuilderContext ctx)
9828                 {
9829 #if STATIC
9830                         return base.MakeExpression (ctx);
9831 #else
9832                         var args = Arguments.MakeExpression (arguments, ctx);
9833                         return SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo (), args);
9834 #endif
9835                 }
9836
9837                 protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
9838                 {
9839                         if (best_candidate != null)
9840                                 return this;
9841
9842                         eclass = ExprClass.IndexerAccess;
9843
9844                         bool dynamic;
9845                         arguments.Resolve (rc, out dynamic);
9846
9847                         if (indexers == null && InstanceExpression.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
9848                                 dynamic = true;
9849                         } else {
9850                                 var res = new OverloadResolver (indexers, OverloadResolver.Restrictions.None, loc);
9851                                 res.BaseMembersProvider = this;
9852                                 res.InstanceQualifier = this;
9853
9854                                 // TODO: Do I need 2 argument sets?
9855                                 best_candidate = res.ResolveMember<IndexerSpec> (rc, ref arguments);
9856                                 if (best_candidate != null)
9857                                         type = res.BestCandidateReturnType;
9858                                 else if (!res.BestCandidateIsDynamic)
9859                                         return null;
9860                         }
9861
9862                         //
9863                         // It has dynamic arguments
9864                         //
9865                         if (dynamic) {
9866                                 Arguments args = new Arguments (arguments.Count + 1);
9867                                 if (IsBase) {
9868                                         rc.Report.Error (1972, loc,
9869                                                 "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
9870                                 } else {
9871                                         args.Add (new Argument (InstanceExpression));
9872                                 }
9873                                 args.AddRange (arguments);
9874
9875                                 best_candidate = null;
9876                                 return new DynamicIndexBinder (args, loc);
9877                         }
9878
9879                         //
9880                         // Try to avoid resolving left expression again
9881                         //
9882                         if (right_side != null)
9883                                 ResolveInstanceExpression (rc, right_side);
9884
9885                         return this;
9886                 }
9887
9888                 protected override void CloneTo (CloneContext clonectx, Expression t)
9889                 {
9890                         IndexerExpr target = (IndexerExpr) t;
9891
9892                         if (arguments != null)
9893                                 target.arguments = arguments.Clone (clonectx);
9894                 }
9895
9896                 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
9897                 {
9898                         Error_TypeArgumentsCannotBeUsed (ec, "indexer", GetSignatureForError (), loc);
9899                 }
9900
9901                 #region IBaseMembersProvider Members
9902
9903                 IList<MemberSpec> OverloadResolver.IBaseMembersProvider.GetBaseMembers (TypeSpec baseType)
9904                 {
9905                         return baseType == null ? null : MemberCache.FindMembers (baseType, MemberCache.IndexerNameAlias, false);
9906                 }
9907
9908                 IParametersMember OverloadResolver.IBaseMembersProvider.GetOverrideMemberParameters (MemberSpec member)
9909                 {
9910                         if (queried_type == member.DeclaringType)
9911                                 return null;
9912
9913                         var filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, MemberKind.Indexer, ((IndexerSpec) member).Parameters, null);
9914                         return MemberCache.FindMember (queried_type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as IParametersMember;
9915                 }
9916
9917                 MethodGroupExpr OverloadResolver.IBaseMembersProvider.LookupExtensionMethod (ResolveContext rc)
9918                 {
9919                         return null;
9920                 }
9921
9922                 #endregion
9923         }
9924
9925         //
9926         // A base access expression
9927         //
9928         public class BaseThis : This
9929         {
9930                 public BaseThis (Location loc)
9931                         : base (loc)
9932                 {
9933                 }
9934
9935                 public BaseThis (TypeSpec type, Location loc)
9936                         : base (loc)
9937                 {
9938                         this.type = type;
9939                         eclass = ExprClass.Variable;
9940                 }
9941
9942                 #region Properties
9943
9944                 public override string Name {
9945                         get {
9946                                 return "base";
9947                         }
9948                 }
9949
9950                 #endregion
9951
9952                 public override Expression CreateExpressionTree (ResolveContext ec)
9953                 {
9954                         ec.Report.Error (831, loc, "An expression tree may not contain a base access");
9955                         return base.CreateExpressionTree (ec);
9956                 }
9957
9958                 public override void Emit (EmitContext ec)
9959                 {
9960                         base.Emit (ec);
9961
9962                         if (type == ec.Module.Compiler.BuiltinTypes.ValueType) {
9963                                 var context_type = ec.CurrentType;
9964                                 ec.Emit (OpCodes.Ldobj, context_type);
9965                                 ec.Emit (OpCodes.Box, context_type);
9966                         }
9967                 }
9968
9969                 protected override void Error_ThisNotAvailable (ResolveContext ec)
9970                 {
9971                         if (ec.IsStatic) {
9972                                 ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
9973                         } else {
9974                                 ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
9975                         }
9976                 }
9977
9978                 public override void ResolveBase (ResolveContext ec)
9979                 {
9980                         base.ResolveBase (ec);
9981                         type = ec.CurrentType.BaseType;
9982                 }
9983
9984                 public override object Accept (StructuralVisitor visitor)
9985                 {
9986                         return visitor.Visit (this);
9987                 }
9988         }
9989
9990         /// <summary>
9991         ///   This class exists solely to pass the Type around and to be a dummy
9992         ///   that can be passed to the conversion functions (this is used by
9993         ///   foreach implementation to typecast the object return value from
9994         ///   get_Current into the proper type.  All code has been generated and
9995         ///   we only care about the side effect conversions to be performed
9996         ///
9997         ///   This is also now used as a placeholder where a no-action expression
9998         ///   is needed (the `New' class).
9999         /// </summary>
10000         public class EmptyExpression : Expression
10001         {
10002                 sealed class OutAccessExpression : EmptyExpression
10003                 {
10004                         public OutAccessExpression (TypeSpec t)
10005                                 : base (t)
10006                         {
10007                         }
10008
10009                         public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
10010                         {
10011                                 rc.Report.Error (206, right_side.Location,
10012                                         "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
10013
10014                                 return null;
10015                         }
10016                 }
10017
10018                 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression (InternalType.FakeInternalType);
10019                 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression (InternalType.FakeInternalType);
10020                 public static readonly EmptyExpression UnaryAddress = new EmptyExpression (InternalType.FakeInternalType);
10021                 public static readonly EmptyExpression EventAddition = new EmptyExpression (InternalType.FakeInternalType);
10022                 public static readonly EmptyExpression EventSubtraction = new EmptyExpression (InternalType.FakeInternalType);
10023                 public static readonly EmptyExpression MissingValue = new EmptyExpression (InternalType.FakeInternalType);
10024                 public static readonly Expression Null = new EmptyExpression (InternalType.FakeInternalType);
10025                 public static readonly EmptyExpression OutAccess = new OutAccessExpression (InternalType.FakeInternalType);
10026
10027                 public EmptyExpression (TypeSpec t)
10028                 {
10029                         type = t;
10030                         eclass = ExprClass.Value;
10031                         loc = Location.Null;
10032                 }
10033
10034                 protected override void CloneTo (CloneContext clonectx, Expression target)
10035                 {
10036                 }
10037
10038                 public override bool ContainsEmitWithAwait ()
10039                 {
10040                         return false;
10041                 }
10042
10043                 public override Expression CreateExpressionTree (ResolveContext ec)
10044                 {
10045                         throw new NotSupportedException ("ET");
10046                 }
10047                 
10048                 protected override Expression DoResolve (ResolveContext ec)
10049                 {
10050                         return this;
10051                 }
10052
10053                 public override void Emit (EmitContext ec)
10054                 {
10055                         // nothing, as we only exist to not do anything.
10056                 }
10057
10058                 public override void EmitSideEffect (EmitContext ec)
10059                 {
10060                 }
10061
10062                 public override object Accept (StructuralVisitor visitor)
10063                 {
10064                         return visitor.Visit (this);
10065                 }
10066         }
10067         
10068         sealed class EmptyAwaitExpression : EmptyExpression
10069         {
10070                 public EmptyAwaitExpression (TypeSpec type)
10071                         : base (type)
10072                 {
10073                 }
10074                 
10075                 public override bool ContainsEmitWithAwait ()
10076                 {
10077                         return true;
10078                 }
10079         }
10080         
10081         //
10082         // Empty statement expression
10083         //
10084         public sealed class EmptyExpressionStatement : ExpressionStatement
10085         {
10086                 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
10087
10088                 private EmptyExpressionStatement ()
10089                 {
10090                         loc = Location.Null;
10091                 }
10092
10093                 public override bool ContainsEmitWithAwait ()
10094                 {
10095                         return false;
10096                 }
10097
10098                 public override Expression CreateExpressionTree (ResolveContext ec)
10099                 {
10100                         return null;
10101                 }
10102
10103                 public override void EmitStatement (EmitContext ec)
10104                 {
10105                         // Do nothing
10106                 }
10107
10108                 protected override Expression DoResolve (ResolveContext ec)
10109                 {
10110                         eclass = ExprClass.Value;
10111                         type = ec.BuiltinTypes.Object;
10112                         return this;
10113                 }
10114
10115                 public override void Emit (EmitContext ec)
10116                 {
10117                         // Do nothing
10118                 }
10119                 
10120                 public override object Accept (StructuralVisitor visitor)
10121                 {
10122                         return visitor.Visit (this);
10123                 }
10124         }
10125
10126         public class ErrorExpression : EmptyExpression
10127         {
10128                 public static readonly ErrorExpression Instance = new ErrorExpression ();
10129
10130                 private ErrorExpression ()
10131                         : base (InternalType.ErrorType)
10132                 {
10133                 }
10134
10135                 public override Expression CreateExpressionTree (ResolveContext ec)
10136                 {
10137                         return this;
10138                 }
10139
10140                 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
10141                 {
10142                         return this;
10143                 }
10144
10145                 public override void Error_ValueAssignment (ResolveContext rc, Expression rhs)
10146                 {
10147                 }
10148
10149                 public override void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
10150                 {
10151                 }
10152
10153                 public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
10154                 {
10155                 }
10156
10157                 public override void Error_OperatorCannotBeApplied (ResolveContext rc, Location loc, string oper, TypeSpec t)
10158                 {
10159                 }
10160                 
10161                 public override object Accept (StructuralVisitor visitor)
10162                 {
10163                         return visitor.Visit (this);
10164                 }
10165         }
10166
10167         public class UserCast : Expression {
10168                 MethodSpec method;
10169                 Expression source;
10170                 
10171                 public UserCast (MethodSpec method, Expression source, Location l)
10172                 {
10173                         if (source == null)
10174                                 throw new ArgumentNullException ("source");
10175
10176                         this.method = method;
10177                         this.source = source;
10178                         type = method.ReturnType;
10179                         loc = l;
10180                 }
10181
10182                 public Expression Source {
10183                         get {
10184                                 return source;
10185                         }
10186                 }
10187
10188                 public override bool ContainsEmitWithAwait ()
10189                 {
10190                         return source.ContainsEmitWithAwait ();
10191                 }
10192
10193                 public override Expression CreateExpressionTree (ResolveContext ec)
10194                 {
10195                         Arguments args = new Arguments (3);
10196                         args.Add (new Argument (source.CreateExpressionTree (ec)));
10197                         args.Add (new Argument (new TypeOf (type, loc)));
10198                         args.Add (new Argument (new TypeOfMethod (method, loc)));
10199                         return CreateExpressionFactoryCall (ec, "Convert", args);
10200                 }
10201                         
10202                 protected override Expression DoResolve (ResolveContext ec)
10203                 {
10204                         ObsoleteAttribute oa = method.GetAttributeObsolete ();
10205                         if (oa != null)
10206                                 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
10207
10208                         eclass = ExprClass.Value;
10209                         return this;
10210                 }
10211
10212                 public override void Emit (EmitContext ec)
10213                 {
10214                         source.Emit (ec);
10215                         ec.MarkCallEntry (loc);
10216                         ec.Emit (OpCodes.Call, method);
10217                 }
10218
10219                 public override void FlowAnalysis (FlowAnalysisContext fc)
10220                 {
10221                         source.FlowAnalysis (fc);
10222                 }
10223
10224                 public override string GetSignatureForError ()
10225                 {
10226                         return TypeManager.CSharpSignature (method);
10227                 }
10228
10229                 public override SLE.Expression MakeExpression (BuilderContext ctx)
10230                 {
10231 #if STATIC
10232                         return base.MakeExpression (ctx);
10233 #else
10234                         return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
10235 #endif
10236                 }
10237         }
10238
10239         //
10240         // Holds additional type specifiers like ?, *, []
10241         //
10242         public class ComposedTypeSpecifier
10243         {
10244                 public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
10245
10246                 public readonly int Dimension;
10247                 public readonly Location Location;
10248
10249                 public ComposedTypeSpecifier (int specifier, Location loc)
10250                 {
10251                         this.Dimension = specifier;
10252                         this.Location = loc;
10253                 }
10254
10255                 #region Properties
10256                 public bool IsNullable {
10257                         get {
10258                                 return Dimension == -1;
10259                         }
10260                 }
10261
10262                 public bool IsPointer {
10263                         get {
10264                                 return Dimension == -2;
10265                         }
10266                 }
10267
10268                 public ComposedTypeSpecifier Next { get; set; }
10269
10270                 #endregion
10271
10272                 public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
10273                 {
10274                         return new ComposedTypeSpecifier (dimension, loc);
10275                 }
10276
10277                 public static ComposedTypeSpecifier CreateNullable (Location loc)
10278                 {
10279                         return new ComposedTypeSpecifier (-1, loc);
10280                 }
10281
10282                 public static ComposedTypeSpecifier CreatePointer (Location loc)
10283                 {
10284                         return new ComposedTypeSpecifier (-2, loc);
10285                 }
10286
10287                 public string GetSignatureForError ()
10288                 {
10289                         string s =
10290                                 IsPointer ? "*" :
10291                                 IsNullable ? "?" :
10292                                 ArrayContainer.GetPostfixSignature (Dimension);
10293
10294                         return Next != null ? s + Next.GetSignatureForError () : s;
10295                 }
10296         }
10297
10298         // <summary>
10299         //   This class is used to "construct" the type during a typecast
10300         //   operation.  Since the Type.GetType class in .NET can parse
10301         //   the type specification, we just use this to construct the type
10302         //   one bit at a time.
10303         // </summary>
10304         public class ComposedCast : TypeExpr {
10305                 FullNamedExpression left;
10306                 ComposedTypeSpecifier spec;
10307                 
10308                 public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
10309                 {
10310                         if (spec == null)
10311                                 throw new ArgumentNullException ("spec");
10312
10313                         this.left = left;
10314                         this.spec = spec;
10315                         this.loc = left.Location;
10316                 }
10317
10318                 public override TypeSpec ResolveAsType (IMemberContext ec)
10319                 {
10320                         type = left.ResolveAsType (ec);
10321                         if (type == null)
10322                                 return null;
10323
10324                         eclass = ExprClass.Type;
10325
10326                         var single_spec = spec;
10327
10328                         if (single_spec.IsNullable) {
10329                                 type = new Nullable.NullableType (type, loc).ResolveAsType (ec);
10330                                 if (type == null)
10331                                         return null;
10332
10333                                 single_spec = single_spec.Next;
10334                         } else if (single_spec.IsPointer) {
10335                                 if (!TypeManager.VerifyUnmanaged (ec.Module, type, loc))
10336                                         return null;
10337
10338                                 if (!ec.IsUnsafe) {
10339                                         UnsafeError (ec.Module.Compiler.Report, loc);
10340                                 }
10341
10342                                 do {
10343                                         type = PointerContainer.MakeType (ec.Module, type);
10344                                         single_spec = single_spec.Next;
10345                                 } while (single_spec != null && single_spec.IsPointer);
10346                         }
10347
10348                         if (single_spec != null && single_spec.Dimension > 0) {
10349                                 if (type.IsSpecialRuntimeType) {
10350                                         ec.Module.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
10351                                 } else if (type.IsStatic) {
10352                                         ec.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
10353                                         ec.Module.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
10354                                                 type.GetSignatureForError ());
10355                                 } else {
10356                                         MakeArray (ec.Module, single_spec);
10357                                 }
10358                         }
10359
10360                         return type;
10361                 }
10362
10363                 void MakeArray (ModuleContainer module, ComposedTypeSpecifier spec)
10364                 {
10365                         if (spec.Next != null)
10366                                 MakeArray (module, spec.Next);
10367
10368                         type = ArrayContainer.MakeType (module, type, spec.Dimension);
10369                 }
10370
10371                 public override string GetSignatureForError ()
10372                 {
10373                         return left.GetSignatureForError () + spec.GetSignatureForError ();
10374                 }
10375
10376                 public override object Accept (StructuralVisitor visitor)
10377                 {
10378                         return visitor.Visit (this);
10379                 }
10380         }
10381
10382         class FixedBufferPtr : Expression
10383         {
10384                 readonly Expression array;
10385
10386                 public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
10387                 {
10388                         this.type = array_type;
10389                         this.array = array;
10390                         this.loc = l;
10391                 }
10392
10393                 public override bool ContainsEmitWithAwait ()
10394                 {
10395                         throw new NotImplementedException ();
10396                 }
10397
10398                 public override Expression CreateExpressionTree (ResolveContext ec)
10399                 {
10400                         Error_PointerInsideExpressionTree (ec);
10401                         return null;
10402                 }
10403
10404                 public override void Emit(EmitContext ec)
10405                 {
10406                         array.Emit (ec);
10407                 }
10408
10409                 protected override Expression DoResolve (ResolveContext ec)
10410                 {
10411                         type = PointerContainer.MakeType (ec.Module, type);
10412                         eclass = ExprClass.Value;
10413                         return this;
10414                 }
10415         }
10416
10417
10418         //
10419         // This class is used to represent the address of an array, used
10420         // only by the Fixed statement, this generates "&a [0]" construct
10421         // for fixed (char *pa = a)
10422         //
10423         class ArrayPtr : FixedBufferPtr
10424         {
10425                 public ArrayPtr (Expression array, TypeSpec array_type, Location l):
10426                         base (array, array_type, l)
10427                 {
10428                 }
10429
10430                 public override void Emit (EmitContext ec)
10431                 {
10432                         base.Emit (ec);
10433                         
10434                         ec.EmitInt (0);
10435                         ec.Emit (OpCodes.Ldelema, ((PointerContainer) type).Element);
10436                 }
10437         }
10438
10439         //
10440         // Encapsulates a conversion rules required for array indexes
10441         //
10442         public class ArrayIndexCast : TypeCast
10443         {
10444                 public ArrayIndexCast (Expression expr, TypeSpec returnType)
10445                         : base (expr, returnType)
10446                 {
10447                         if (expr.Type == returnType) // int -> int
10448                                 throw new ArgumentException ("unnecessary array index conversion");
10449                 }
10450
10451                 public override Expression CreateExpressionTree (ResolveContext ec)
10452                 {
10453                         using (ec.Set (ResolveContext.Options.CheckedScope)) {
10454                                 return base.CreateExpressionTree (ec);
10455                         }
10456                 }
10457
10458                 public override void Emit (EmitContext ec)
10459                 {
10460                         child.Emit (ec);
10461
10462                         switch (child.Type.BuiltinType) {
10463                         case BuiltinTypeSpec.Type.UInt:
10464                                 ec.Emit (OpCodes.Conv_U);
10465                                 break;
10466                         case BuiltinTypeSpec.Type.Long:
10467                                 ec.Emit (OpCodes.Conv_Ovf_I);
10468                                 break;
10469                         case BuiltinTypeSpec.Type.ULong:
10470                                 ec.Emit (OpCodes.Conv_Ovf_I_Un);
10471                                 break;
10472                         default:
10473                                 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
10474                         }
10475                 }
10476         }
10477
10478         //
10479         // Implements the `stackalloc' keyword
10480         //
10481         public class StackAlloc : Expression {
10482                 TypeSpec otype;
10483                 Expression t;
10484                 Expression count;
10485                 
10486                 public StackAlloc (Expression type, Expression count, Location l)
10487                 {
10488                         t = type;
10489                         this.count = count;
10490                         loc = l;
10491                 }
10492
10493                 public Expression TypeExpression {
10494                         get {
10495                                 return this.t;
10496                         }
10497                 }
10498
10499                 public Expression CountExpression {
10500                         get {
10501                                 return this.count;
10502                         }
10503                 }
10504
10505                 public override bool ContainsEmitWithAwait ()
10506                 {
10507                         return false;
10508                 }
10509
10510                 public override Expression CreateExpressionTree (ResolveContext ec)
10511                 {
10512                         throw new NotSupportedException ("ET");
10513                 }
10514
10515                 protected override Expression DoResolve (ResolveContext ec)
10516                 {
10517                         count = count.Resolve (ec);
10518                         if (count == null)
10519                                 return null;
10520                         
10521                         if (count.Type.BuiltinType != BuiltinTypeSpec.Type.UInt){
10522                                 count = Convert.ImplicitConversionRequired (ec, count, ec.BuiltinTypes.Int, loc);
10523                                 if (count == null)
10524                                         return null;
10525                         }
10526
10527                         Constant c = count as Constant;
10528                         if (c != null && c.IsNegative) {
10529                                 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
10530                         }
10531
10532                         if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
10533                                 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
10534                         }
10535
10536                         otype = t.ResolveAsType (ec);
10537                         if (otype == null)
10538                                 return null;
10539
10540                         if (!TypeManager.VerifyUnmanaged (ec.Module, otype, loc))
10541                                 return null;
10542
10543                         type = PointerContainer.MakeType (ec.Module, otype);
10544                         eclass = ExprClass.Value;
10545
10546                         return this;
10547                 }
10548
10549                 public override void Emit (EmitContext ec)
10550                 {
10551                         int size = BuiltinTypeSpec.GetSize (otype);
10552
10553                         count.Emit (ec);
10554
10555                         if (size == 0)
10556                                 ec.Emit (OpCodes.Sizeof, otype);
10557                         else
10558                                 ec.EmitInt (size);
10559
10560                         ec.Emit (OpCodes.Mul_Ovf_Un);
10561                         ec.Emit (OpCodes.Localloc);
10562                 }
10563
10564                 protected override void CloneTo (CloneContext clonectx, Expression t)
10565                 {
10566                         StackAlloc target = (StackAlloc) t;
10567                         target.count = count.Clone (clonectx);
10568                         target.t = t.Clone (clonectx);
10569                 }
10570                 
10571                 public override object Accept (StructuralVisitor visitor)
10572                 {
10573                         return visitor.Visit (this);
10574                 }
10575         }
10576
10577         //
10578         // An object initializer expression
10579         //
10580         public class ElementInitializer : Assign
10581         {
10582                 public readonly string Name;
10583
10584                 public ElementInitializer (string name, Expression initializer, Location loc)
10585                         : base (null, initializer, loc)
10586                 {
10587                         this.Name = name;
10588                 }
10589                 
10590                 protected override void CloneTo (CloneContext clonectx, Expression t)
10591                 {
10592                         ElementInitializer target = (ElementInitializer) t;
10593                         target.source = source.Clone (clonectx);
10594                 }
10595
10596                 public override Expression CreateExpressionTree (ResolveContext ec)
10597                 {
10598                         Arguments args = new Arguments (2);
10599                         FieldExpr fe = target as FieldExpr;
10600                         if (fe != null)
10601                                 args.Add (new Argument (fe.CreateTypeOfExpression ()));
10602                         else
10603                                 args.Add (new Argument (((PropertyExpr) target).CreateSetterTypeOfExpression (ec)));
10604
10605                         string mname;
10606                         Expression arg_expr;
10607                         var cinit = source as CollectionOrObjectInitializers;
10608                         if (cinit == null) {
10609                                 mname = "Bind";
10610                                 arg_expr = source.CreateExpressionTree (ec);
10611                         } else {
10612                                 mname = cinit.IsEmpty || cinit.Initializers[0] is ElementInitializer ? "MemberBind" : "ListBind";
10613                                 arg_expr = cinit.CreateExpressionTree (ec, !cinit.IsEmpty);
10614                         }
10615
10616                         args.Add (new Argument (arg_expr));
10617                         return CreateExpressionFactoryCall (ec, mname, args);
10618                 }
10619
10620                 protected override Expression DoResolve (ResolveContext ec)
10621                 {
10622                         if (source == null)
10623                                 return EmptyExpressionStatement.Instance;
10624
10625                         var t = ec.CurrentInitializerVariable.Type;
10626                         if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
10627                                 Arguments args = new Arguments (1);
10628                                 args.Add (new Argument (ec.CurrentInitializerVariable));
10629                                 target = new DynamicMemberBinder (Name, args, loc);
10630                         } else {
10631
10632                                 var member = MemberLookup (ec, false, t, Name, 0, MemberLookupRestrictions.ExactArity, loc);
10633                                 if (member == null) {
10634                                         member = Expression.MemberLookup (ec, true, t, Name, 0, MemberLookupRestrictions.ExactArity, loc);
10635
10636                                         if (member != null) {
10637                                                 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
10638                                                 ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
10639                                                 return null;
10640                                         }
10641                                 }
10642
10643                                 if (member == null) {
10644                                         Error_TypeDoesNotContainDefinition (ec, loc, t, Name);
10645                                         return null;
10646                                 }
10647
10648                                 if (!(member is PropertyExpr || member is FieldExpr)) {
10649                                         ec.Report.Error (1913, loc,
10650                                                 "Member `{0}' cannot be initialized. An object initializer may only be used for fields, or properties",
10651                                                 member.GetSignatureForError ());
10652
10653                                         return null;
10654                                 }
10655
10656                                 var me = member as MemberExpr;
10657                                 if (me.IsStatic) {
10658                                         ec.Report.Error (1914, loc,
10659                                                 "Static field or property `{0}' cannot be assigned in an object initializer",
10660                                                 me.GetSignatureForError ());
10661                                 }
10662
10663                                 target = me;
10664                                 me.InstanceExpression = ec.CurrentInitializerVariable;
10665                         }
10666
10667                         if (source is CollectionOrObjectInitializers) {
10668                                 Expression previous = ec.CurrentInitializerVariable;
10669                                 ec.CurrentInitializerVariable = target;
10670                                 source = source.Resolve (ec);
10671                                 ec.CurrentInitializerVariable = previous;
10672                                 if (source == null)
10673                                         return null;
10674                                         
10675                                 eclass = source.eclass;
10676                                 type = source.Type;
10677                                 return this;
10678                         }
10679
10680                         return base.DoResolve (ec);
10681                 }
10682         
10683                 public override void EmitStatement (EmitContext ec)
10684                 {
10685                         if (source is CollectionOrObjectInitializers)
10686                                 source.Emit (ec);
10687                         else
10688                                 base.EmitStatement (ec);
10689                 }
10690         }
10691         
10692         //
10693         // A collection initializer expression
10694         //
10695         class CollectionElementInitializer : Invocation
10696         {
10697                 public class ElementInitializerArgument : Argument
10698                 {
10699                         public ElementInitializerArgument (Expression e)
10700                                 : base (e)
10701                         {
10702                         }
10703                 }
10704
10705                 sealed class AddMemberAccess : MemberAccess
10706                 {
10707                         public AddMemberAccess (Expression expr, Location loc)
10708                                 : base (expr, "Add", loc)
10709                         {
10710                         }
10711
10712                         protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
10713                         {
10714                                 if (TypeManager.HasElementType (type))
10715                                         return;
10716
10717                                 base.Error_TypeDoesNotContainDefinition (ec, type, name);
10718                         }
10719                 }
10720
10721                 public CollectionElementInitializer (Expression argument)
10722                         : base (null, new Arguments (1))
10723                 {
10724                         base.arguments.Add (new ElementInitializerArgument (argument));
10725                         this.loc = argument.Location;
10726                 }
10727
10728                 public CollectionElementInitializer (List<Expression> arguments, Location loc)
10729                         : base (null, new Arguments (arguments.Count))
10730                 {
10731                         foreach (Expression e in arguments)
10732                                 base.arguments.Add (new ElementInitializerArgument (e));
10733
10734                         this.loc = loc;
10735                 }
10736
10737                 public CollectionElementInitializer (Location loc)
10738                         : base (null, null)
10739                 {
10740                         this.loc = loc;
10741                 }
10742
10743                 public override Expression CreateExpressionTree (ResolveContext ec)
10744                 {
10745                         Arguments args = new Arguments (2);
10746                         args.Add (new Argument (mg.CreateExpressionTree (ec)));
10747
10748                         var expr_initializers = new ArrayInitializer (arguments.Count, loc);
10749                         foreach (Argument a in arguments)
10750                                 expr_initializers.Add (a.CreateExpressionTree (ec));
10751
10752                         args.Add (new Argument (new ArrayCreation (
10753                                 CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
10754                         return CreateExpressionFactoryCall (ec, "ElementInit", args);
10755                 }
10756
10757                 protected override void CloneTo (CloneContext clonectx, Expression t)
10758                 {
10759                         CollectionElementInitializer target = (CollectionElementInitializer) t;
10760                         if (arguments != null)
10761                                 target.arguments = arguments.Clone (clonectx);
10762                 }
10763
10764                 protected override Expression DoResolve (ResolveContext ec)
10765                 {
10766                         base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
10767
10768                         return base.DoResolve (ec);
10769                 }
10770         }
10771         
10772         //
10773         // A block of object or collection initializers
10774         //
10775         public class CollectionOrObjectInitializers : ExpressionStatement
10776         {
10777                 IList<Expression> initializers;
10778                 bool is_collection_initialization;
10779
10780                 public CollectionOrObjectInitializers (Location loc)
10781                         : this (new Expression[0], loc)
10782                 {
10783                 }
10784
10785                 public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
10786                 {
10787                         this.initializers = initializers;
10788                         this.loc = loc;
10789                 }
10790
10791                 public IList<Expression> Initializers {
10792                         get {
10793                                 return initializers;
10794                         }
10795                 }
10796                 
10797                 public bool IsEmpty {
10798                         get {
10799                                 return initializers.Count == 0;
10800                         }
10801                 }
10802
10803                 public bool IsCollectionInitializer {
10804                         get {
10805                                 return is_collection_initialization;
10806                         }
10807                 }
10808
10809                 protected override void CloneTo (CloneContext clonectx, Expression target)
10810                 {
10811                         CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
10812
10813                         t.initializers = new List<Expression> (initializers.Count);
10814                         foreach (var e in initializers)
10815                                 t.initializers.Add (e.Clone (clonectx));
10816                 }
10817
10818                 public override bool ContainsEmitWithAwait ()
10819                 {
10820                         foreach (var e in initializers) {
10821                                 if (e.ContainsEmitWithAwait ())
10822                                         return true;
10823                         }
10824
10825                         return false;
10826                 }
10827
10828                 public override Expression CreateExpressionTree (ResolveContext ec)
10829                 {
10830                         return CreateExpressionTree (ec, false);
10831                 }
10832
10833                 public Expression CreateExpressionTree (ResolveContext ec, bool inferType)
10834                 {
10835                         var expr_initializers = new ArrayInitializer (initializers.Count, loc);
10836                         foreach (Expression e in initializers) {
10837                                 Expression expr = e.CreateExpressionTree (ec);
10838                                 if (expr != null)
10839                                         expr_initializers.Add (expr);
10840                         }
10841
10842                         if (inferType)
10843                                 return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
10844
10845                         return new ArrayCreation (new TypeExpression (ec.Module.PredefinedTypes.MemberBinding.Resolve (), loc), expr_initializers, loc); 
10846                 }
10847                 
10848                 protected override Expression DoResolve (ResolveContext ec)
10849                 {
10850                         List<string> element_names = null;
10851                         for (int i = 0; i < initializers.Count; ++i) {
10852                                 Expression initializer = initializers [i];
10853                                 ElementInitializer element_initializer = initializer as ElementInitializer;
10854
10855                                 if (i == 0) {
10856                                         if (element_initializer != null) {
10857                                                 element_names = new List<string> (initializers.Count);
10858                                                 element_names.Add (element_initializer.Name);
10859                                         } else if (initializer is CompletingExpression){
10860                                                 initializer.Resolve (ec);
10861                                                 throw new InternalErrorException ("This line should never be reached");
10862                                         } else {
10863                                                 var t = ec.CurrentInitializerVariable.Type;
10864                                                 // LAMESPEC: The collection must implement IEnumerable only, no dynamic support
10865                                                 if (!t.ImplementsInterface (ec.BuiltinTypes.IEnumerable, false) && t.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
10866                                                         ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
10867                                                                 "object initializer because type `{1}' does not implement `{2}' interface",
10868                                                                 ec.CurrentInitializerVariable.GetSignatureForError (),
10869                                                                 ec.CurrentInitializerVariable.Type.GetSignatureForError (),
10870                                                                 ec.BuiltinTypes.IEnumerable.GetSignatureForError ());
10871                                                         return null;
10872                                                 }
10873                                                 is_collection_initialization = true;
10874                                         }
10875                                 } else {
10876                                         if (is_collection_initialization != (element_initializer == null)) {
10877                                                 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
10878                                                         is_collection_initialization ? "collection initializer" : "object initializer");
10879                                                 continue;
10880                                         }
10881
10882                                         if (!is_collection_initialization) {
10883                                                 if (element_names.Contains (element_initializer.Name)) {
10884                                                         ec.Report.Error (1912, element_initializer.Location,
10885                                                                 "An object initializer includes more than one member `{0}' initialization",
10886                                                                 element_initializer.Name);
10887                                                 } else {
10888                                                         element_names.Add (element_initializer.Name);
10889                                                 }
10890                                         }
10891                                 }
10892
10893                                 Expression e = initializer.Resolve (ec);
10894                                 if (e == EmptyExpressionStatement.Instance)
10895                                         initializers.RemoveAt (i--);
10896                                 else
10897                                         initializers [i] = e;
10898                         }
10899
10900                         type = ec.CurrentInitializerVariable.Type;
10901                         if (is_collection_initialization) {
10902                                 if (TypeManager.HasElementType (type)) {
10903                                         ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
10904                                                 type.GetSignatureForError ());
10905                                 }
10906                         }
10907
10908                         eclass = ExprClass.Variable;
10909                         return this;
10910                 }
10911
10912                 public override void Emit (EmitContext ec)
10913                 {
10914                         EmitStatement (ec);
10915                 }
10916
10917                 public override void EmitStatement (EmitContext ec)
10918                 {
10919                         foreach (ExpressionStatement e in initializers) {
10920                                 // TODO: need location region
10921                                 ec.Mark (e.Location);
10922                                 e.EmitStatement (ec);
10923                         }
10924                 }
10925
10926                 public override void FlowAnalysis (FlowAnalysisContext fc)
10927                 {
10928                         foreach (var initializer in initializers)
10929                                 initializer.FlowAnalysis (fc);
10930                 }
10931         }
10932         
10933         //
10934         // New expression with element/object initializers
10935         //
10936         public class NewInitialize : New
10937         {
10938                 //
10939                 // This class serves as a proxy for variable initializer target instances.
10940                 // A real variable is assigned later when we resolve left side of an
10941                 // assignment
10942                 //
10943                 sealed class InitializerTargetExpression : Expression, IMemoryLocation
10944                 {
10945                         NewInitialize new_instance;
10946
10947                         public InitializerTargetExpression (NewInitialize newInstance)
10948                         {
10949                                 this.type = newInstance.type;
10950                                 this.loc = newInstance.loc;
10951                                 this.eclass = newInstance.eclass;
10952                                 this.new_instance = newInstance;
10953                         }
10954
10955                         public override bool ContainsEmitWithAwait ()
10956                         {
10957                                 return false;
10958                         }
10959
10960                         public override Expression CreateExpressionTree (ResolveContext ec)
10961                         {
10962                                 // Should not be reached
10963                                 throw new NotSupportedException ("ET");
10964                         }
10965
10966                         protected override Expression DoResolve (ResolveContext ec)
10967                         {
10968                                 return this;
10969                         }
10970
10971                         public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
10972                         {
10973                                 return this;
10974                         }
10975
10976                         public override void Emit (EmitContext ec)
10977                         {
10978                                 Expression e = (Expression) new_instance.instance;
10979                                 e.Emit (ec);
10980                         }
10981
10982                         public override Expression EmitToField (EmitContext ec)
10983                         {
10984                                 return (Expression) new_instance.instance;
10985                         }
10986
10987                         #region IMemoryLocation Members
10988
10989                         public void AddressOf (EmitContext ec, AddressOp mode)
10990                         {
10991                                 new_instance.instance.AddressOf (ec, mode);
10992                         }
10993
10994                         #endregion
10995                 }
10996
10997                 CollectionOrObjectInitializers initializers;
10998                 IMemoryLocation instance;
10999                 DynamicExpressionStatement dynamic;
11000
11001                 public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
11002                         : base (requested_type, arguments, l)
11003                 {
11004                         this.initializers = initializers;
11005                 }
11006
11007                 public CollectionOrObjectInitializers Initializers {
11008                         get {
11009                                 return initializers;
11010                         }
11011                 }
11012
11013                 protected override void CloneTo (CloneContext clonectx, Expression t)
11014                 {
11015                         base.CloneTo (clonectx, t);
11016
11017                         NewInitialize target = (NewInitialize) t;
11018                         target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
11019                 }
11020
11021                 public override bool ContainsEmitWithAwait ()
11022                 {
11023                         return base.ContainsEmitWithAwait () || initializers.ContainsEmitWithAwait ();
11024                 }
11025
11026                 public override Expression CreateExpressionTree (ResolveContext ec)
11027                 {
11028                         Arguments args = new Arguments (2);
11029                         args.Add (new Argument (base.CreateExpressionTree (ec)));
11030                         if (!initializers.IsEmpty)
11031                                 args.Add (new Argument (initializers.CreateExpressionTree (ec, initializers.IsCollectionInitializer)));
11032
11033                         return CreateExpressionFactoryCall (ec,
11034                                 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
11035                                 args);
11036                 }
11037
11038                 protected override Expression DoResolve (ResolveContext ec)
11039                 {
11040                         Expression e = base.DoResolve (ec);
11041                         if (type == null)
11042                                 return null;
11043
11044                         if (type.IsDelegate) {
11045                                 ec.Report.Error (1958, Initializers.Location,
11046                                         "Object and collection initializers cannot be used to instantiate a delegate");
11047                         }
11048
11049                         Expression previous = ec.CurrentInitializerVariable;
11050                         ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
11051                         initializers.Resolve (ec);
11052                         ec.CurrentInitializerVariable = previous;
11053
11054                         dynamic = e as DynamicExpressionStatement;
11055                         if (dynamic != null)
11056                                 return this;
11057
11058                         return e;
11059                 }
11060
11061                 public override bool Emit (EmitContext ec, IMemoryLocation target)
11062                 {
11063                         bool left_on_stack;
11064                         if (dynamic != null) {
11065                                 dynamic.Emit (ec);
11066                                 left_on_stack = true;
11067                         } else {
11068                                 left_on_stack = base.Emit (ec, target);
11069                         }
11070
11071                         if (initializers.IsEmpty)
11072                                 return left_on_stack;
11073
11074                         LocalTemporary temp = null;
11075
11076                         instance = target as LocalTemporary;
11077
11078                         if (instance == null) {
11079                                 if (!left_on_stack) {
11080                                         VariableReference vr = target as VariableReference;
11081
11082                                         // FIXME: This still does not work correctly for pre-set variables
11083                                         if (vr != null && vr.IsRef)
11084                                                 target.AddressOf (ec, AddressOp.Load);
11085
11086                                         ((Expression) target).Emit (ec);
11087                                         left_on_stack = true;
11088                                 }
11089
11090                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && initializers.ContainsEmitWithAwait ()) {
11091                                         instance = new EmptyAwaitExpression (Type).EmitToField (ec) as IMemoryLocation;
11092                                 } else {
11093                                         temp = new LocalTemporary (type);
11094                                         instance = temp;
11095                                 }
11096                         }
11097
11098                         if (left_on_stack && temp != null)
11099                                 temp.Store (ec);
11100
11101                         initializers.Emit (ec);
11102
11103                         if (left_on_stack) {
11104                                 if (temp != null) {
11105                                         temp.Emit (ec);
11106                                         temp.Release (ec);
11107                                 } else {
11108                                         ((Expression) instance).Emit (ec);
11109                                 }
11110                         }
11111
11112                         return left_on_stack;
11113                 }
11114
11115                 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
11116                 {
11117                         instance = base.EmitAddressOf (ec, Mode);
11118
11119                         if (!initializers.IsEmpty)
11120                                 initializers.Emit (ec);
11121
11122                         return instance;
11123                 }
11124
11125                 public override void FlowAnalysis (FlowAnalysisContext fc)
11126                 {
11127                         base.FlowAnalysis (fc);
11128                         initializers.FlowAnalysis (fc);
11129                 }
11130
11131                 public override object Accept (StructuralVisitor visitor)
11132                 {
11133                         return visitor.Visit (this);
11134                 }
11135         }
11136
11137         public class NewAnonymousType : New
11138         {
11139                 static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
11140
11141                 List<AnonymousTypeParameter> parameters;
11142                 readonly TypeContainer parent;
11143                 AnonymousTypeClass anonymous_type;
11144
11145                 public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
11146                          : base (null, null, loc)
11147                 {
11148                         this.parameters = parameters;
11149                         this.parent = parent;
11150                 }
11151
11152                 public List<AnonymousTypeParameter> Parameters {
11153                         get {
11154                                 return this.parameters;
11155                         }
11156                 }
11157
11158                 protected override void CloneTo (CloneContext clonectx, Expression target)
11159                 {
11160                         if (parameters == null)
11161                                 return;
11162
11163                         NewAnonymousType t = (NewAnonymousType) target;
11164                         t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
11165                         foreach (AnonymousTypeParameter atp in parameters)
11166                                 t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
11167                 }
11168
11169                 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
11170                 {
11171                         AnonymousTypeClass type = parent.Module.GetAnonymousType (parameters);
11172                         if (type != null)
11173                                 return type;
11174
11175                         type = AnonymousTypeClass.Create (parent, parameters, loc);
11176                         if (type == null)
11177                                 return null;
11178
11179                         int errors = ec.Report.Errors;
11180                         type.CreateContainer ();
11181                         type.DefineContainer ();
11182                         type.Define ();
11183                         if ((ec.Report.Errors - errors) == 0) {
11184                                 parent.Module.AddAnonymousType (type);
11185                                 type.PrepareEmit ();
11186                         }
11187
11188                         return type;
11189                 }
11190
11191                 public override Expression CreateExpressionTree (ResolveContext ec)
11192                 {
11193                         if (parameters == null)
11194                                 return base.CreateExpressionTree (ec);
11195
11196                         var init = new ArrayInitializer (parameters.Count, loc);
11197                         foreach (var m in anonymous_type.Members) {
11198                                 var p = m as Property;
11199                                 if (p != null)
11200                                         init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
11201                         }
11202
11203                         var ctor_args = new ArrayInitializer (arguments.Count, loc);
11204                         foreach (Argument a in arguments)
11205                                 ctor_args.Add (a.CreateExpressionTree (ec));
11206
11207                         Arguments args = new Arguments (3);
11208                         args.Add (new Argument (new TypeOfMethod (method, loc)));
11209                         args.Add (new Argument (new ArrayCreation (CreateExpressionTypeExpression (ec, loc), ctor_args, loc)));
11210                         args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
11211
11212                         return CreateExpressionFactoryCall (ec, "New", args);
11213                 }
11214
11215                 protected override Expression DoResolve (ResolveContext ec)
11216                 {
11217                         if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
11218                                 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
11219                                 return null;
11220                         }
11221
11222                         if (parameters == null) {
11223                                 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
11224                                 RequestedType = new TypeExpression (anonymous_type.Definition, loc);
11225                                 return base.DoResolve (ec);
11226                         }
11227
11228                         bool error = false;
11229                         arguments = new Arguments (parameters.Count);
11230                         var t_args = new TypeSpec [parameters.Count];
11231                         for (int i = 0; i < parameters.Count; ++i) {
11232                                 Expression e = parameters [i].Resolve (ec);
11233                                 if (e == null) {
11234                                         error = true;
11235                                         continue;
11236                                 }
11237
11238                                 arguments.Add (new Argument (e));
11239                                 t_args [i] = e.Type;
11240                         }
11241
11242                         if (error)
11243                                 return null;
11244
11245                         anonymous_type = CreateAnonymousType (ec, parameters);
11246                         if (anonymous_type == null)
11247                                 return null;
11248
11249                         type = anonymous_type.Definition.MakeGenericType (ec.Module, t_args);
11250                         method = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
11251                         eclass = ExprClass.Value;
11252                         return this;
11253                 }
11254                 
11255                 public override object Accept (StructuralVisitor visitor)
11256                 {
11257                         return visitor.Visit (this);
11258                 }
11259         }
11260
11261         public class AnonymousTypeParameter : ShimExpression
11262         {
11263                 public readonly string Name;
11264
11265                 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
11266                         : base (initializer)
11267                 {
11268                         this.Name = name;
11269                         this.loc = loc;
11270                 }
11271                 
11272                 public AnonymousTypeParameter (Parameter parameter)
11273                         : base (new SimpleName (parameter.Name, parameter.Location))
11274                 {
11275                         this.Name = parameter.Name;
11276                         this.loc = parameter.Location;
11277                 }               
11278
11279                 public override bool Equals (object o)
11280                 {
11281                         AnonymousTypeParameter other = o as AnonymousTypeParameter;
11282                         return other != null && Name == other.Name;
11283                 }
11284
11285                 public override int GetHashCode ()
11286                 {
11287                         return Name.GetHashCode ();
11288                 }
11289
11290                 protected override Expression DoResolve (ResolveContext ec)
11291                 {
11292                         Expression e = expr.Resolve (ec);
11293                         if (e == null)
11294                                 return null;
11295
11296                         if (e.eclass == ExprClass.MethodGroup) {
11297                                 Error_InvalidInitializer (ec, e.ExprClassName);
11298                                 return null;
11299                         }
11300
11301                         type = e.Type;
11302                         if (type.Kind == MemberKind.Void || type == InternalType.NullLiteral || type == InternalType.AnonymousMethod || type.IsPointer) {
11303                                 Error_InvalidInitializer (ec, type.GetSignatureForError ());
11304                                 return null;
11305                         }
11306
11307                         return e;
11308                 }
11309
11310                 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
11311                 {
11312                         ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",
11313                                 Name, initializer);
11314                 }
11315         }
11316
11317         public class CatchFilterExpression : BooleanExpression
11318         {
11319                 public CatchFilterExpression (Expression expr, Location loc)
11320                         : base (expr)
11321                 {
11322                         this.loc = loc;
11323                 }
11324         }
11325 }