Merge pull request #2040 from esdrubal/monoman
[mono.git] / mcs / mcs / codegen.cs
1 //
2 // codegen.cs: The code generator
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2004 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
11 //
12
13 using System;
14 using System.Collections.Generic;
15 using Mono.CompilerServices.SymbolWriter;
16
17 #if STATIC
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
21 #else
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
25 #endif
26
27 namespace Mono.CSharp
28 {
29         /// <summary>
30         ///   An Emit Context is created for each body of code (from methods,
31         ///   properties bodies, indexer bodies or constructor bodies)
32         /// </summary>
33         public class EmitContext : BuilderContext
34         {
35                 // TODO: Has to be private
36                 public readonly ILGenerator ig;
37
38                 /// <summary>
39                 ///   The value that is allowed to be returned or NULL if there is no
40                 ///   return type.
41                 /// </summary>
42                 readonly TypeSpec return_type;
43
44                 /// <summary>
45                 ///   Keeps track of the Type to LocalBuilder temporary storage created
46                 ///   to store structures (used to compute the address of the structure
47                 ///   value on structure method invocations)
48                 /// </summary>
49                 Dictionary<TypeSpec, object> temporary_storage;
50
51                 /// <summary>
52                 ///   The location where we store the return value.
53                 /// </summary>
54                 public LocalBuilder return_value;
55
56
57                 /// <summary>
58                 ///   Current loop begin and end labels.
59                 /// </summary>
60                 public Label LoopBegin, LoopEnd;
61
62                 /// <summary>
63                 ///   Default target in a switch statement.   Only valid if
64                 ///   InSwitch is true
65                 /// </summary>
66                 public Label DefaultTarget;
67
68                 /// <summary>
69                 ///   If this is non-null, points to the current switch statement
70                 /// </summary>
71                 public Switch Switch;
72
73                 /// <summary>
74                 ///  Whether we are inside an anonymous method.
75                 /// </summary>
76                 public AnonymousExpression CurrentAnonymousMethod;
77                 
78                 readonly IMemberContext member_context;
79
80                 readonly SourceMethodBuilder methodSymbols;
81
82                 DynamicSiteClass dynamic_site_container;
83
84                 Label? return_label;
85
86                 List<IExpressionCleanup> epilogue_expressions;
87
88                 public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type, SourceMethodBuilder methodSymbols)
89                 {
90                         this.member_context = rc;
91                         this.ig = ig;
92                         this.return_type = return_type;
93
94                         if (rc.Module.Compiler.Settings.Checked)
95                                 flags |= Options.CheckedScope;
96
97                         if (methodSymbols != null) {
98                                 this.methodSymbols = methodSymbols;
99                                 if (!rc.Module.Compiler.Settings.Optimize)
100                                         flags |= Options.AccurateDebugInfo;
101                         } else {
102                                 flags |= Options.OmitDebugInfo;
103                         }
104
105 #if STATIC
106                         ig.__CleverExceptionBlockAssistance ();
107 #endif
108                 }
109
110                 #region Properties
111
112                 internal AsyncTaskStorey AsyncTaskStorey {
113                         get {
114                                 return CurrentAnonymousMethod.Storey as AsyncTaskStorey;
115                         }
116                 }
117
118                 public BuiltinTypes BuiltinTypes {
119                         get {
120                                 return MemberContext.Module.Compiler.BuiltinTypes;
121                         }
122                 }
123
124                 public ConditionalAccessContext ConditionalAccess { get; set; }
125
126                 public TypeSpec CurrentType {
127                         get { return member_context.CurrentType; }
128                 }
129
130                 public TypeParameters CurrentTypeParameters {
131                     get { return member_context.CurrentTypeParameters; }
132                 }
133
134                 public MemberCore CurrentTypeDefinition {
135                         get { return member_context.CurrentMemberDefinition; }
136                 }
137
138                 public bool EmitAccurateDebugInfo {
139                         get {
140                                 return (flags & Options.AccurateDebugInfo) != 0;
141                         }
142                 }
143
144                 public bool HasMethodSymbolBuilder {
145                         get {
146                                 return methodSymbols != null;
147                         }
148                 }
149
150                 public bool HasReturnLabel {
151                         get {
152                                 return return_label.HasValue;
153                         }
154                 }
155
156                 public bool IsStatic {
157                         get { return member_context.IsStatic; }
158                 }
159
160                 public bool IsStaticConstructor {
161                         get {
162                                 return member_context.IsStatic && (flags & Options.ConstructorScope) != 0;
163                         }
164                 }
165
166                 public bool IsAnonymousStoreyMutateRequired {
167                         get {
168                                 return CurrentAnonymousMethod != null &&
169                                         CurrentAnonymousMethod.Storey != null &&
170                                         CurrentAnonymousMethod.Storey.Mutator != null;
171                         }
172                 }
173
174                 public IMemberContext MemberContext {
175                         get {
176                                 return member_context;
177                         }
178                 }
179
180                 public ModuleContainer Module {
181                         get {
182                                 return member_context.Module;
183                         }
184                 }
185
186                 public bool NotifyEvaluatorOnStore {
187                         get {
188                                 return Module.Evaluator != null && Module.Evaluator.ModificationListener != null;
189                         }
190                 }
191
192                 // Has to be used for specific emitter errors only any
193                 // possible resolver errors have to be reported during Resolve
194                 public Report Report {
195                         get {
196                                 return member_context.Module.Compiler.Report;
197                         }
198                 }
199
200                 public TypeSpec ReturnType {
201                         get {
202                                 return return_type;
203                         }
204                 }
205
206                 //
207                 // The label where we have to jump before leaving the context
208                 //
209                 public Label ReturnLabel {
210                         get {
211                                 return return_label.Value;
212                         }
213                 }
214
215                 public List<IExpressionCleanup> StatementEpilogue {
216                         get {
217                                 return epilogue_expressions;
218                         }
219                 }
220
221                 public LocalVariable AsyncThrowVariable { get; set; }
222
223                 public List<TryFinally> TryFinallyUnwind { get; set; }
224
225                 public Label RecursivePatternLabel { get; set; }
226
227                 #endregion
228
229                 public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
230                 {
231                         if (epilogue_expressions == null) {
232                                 epilogue_expressions = new List<IExpressionCleanup> ();
233                         } else if (epilogue_expressions.Contains (cleanupExpression)) {
234                                 return;
235                         }
236
237                         epilogue_expressions.Add (cleanupExpression);
238                 }
239
240                 public void AssertEmptyStack ()
241                 {
242 #if STATIC
243                         if (ig.__StackHeight != 0)
244                                 throw new InternalErrorException ("Await yields with non-empty stack in `{0}",
245                                         member_context.GetSignatureForError ());
246 #endif
247                 }
248
249                 /// <summary>
250                 ///   This is called immediately before emitting an IL opcode to tell the symbol
251                 ///   writer to which source line this opcode belongs.
252                 /// </summary>
253                 public bool Mark (Location loc)
254                 {
255                         if ((flags & Options.OmitDebugInfo) != 0)
256                                 return false;
257
258                         if (loc.IsNull || methodSymbols == null)
259                                 return false;
260
261                         var sf = loc.SourceFile;
262                         if (sf.IsHiddenLocation (loc))
263                                 return false;
264
265                         methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false);
266                         return true;
267                 }
268
269                 public void MarkCallEntry (Location loc)
270                 {
271                         if (!EmitAccurateDebugInfo)
272                                 return;
273
274                         //
275                         // TODO: This should emit different kind of sequence point to make
276                         // step-over work for statement over multiple lines
277                         //
278                         // Debugging experience for Foo (A () + B ()) where A and B are
279                         // on separate lines is not great
280                         //
281                         Mark (loc);
282                 }
283
284                 public void DefineLocalVariable (string name, LocalBuilder builder)
285                 {
286                         if ((flags & Options.OmitDebugInfo) != 0)
287                                 return;
288
289                         methodSymbols.AddLocal (builder.LocalIndex, name);
290                 }
291
292                 public void BeginCatchBlock (TypeSpec type)
293                 {
294                         if (IsAnonymousStoreyMutateRequired)
295                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
296
297                         ig.BeginCatchBlock (type.GetMetaInfo ());
298                 }
299
300                 public void BeginFilterHandler ()
301                 {
302                         ig.BeginCatchBlock (null);
303                 }
304
305                 public void BeginExceptionBlock ()
306                 {
307                         ig.BeginExceptionBlock ();
308                 }
309
310                 public void BeginExceptionFilterBlock ()
311                 {
312                         ig.BeginExceptFilterBlock ();
313                 }
314
315                 public void BeginFinallyBlock ()
316                 {
317                         ig.BeginFinallyBlock ();
318                 }
319
320                 public void BeginScope ()
321                 {
322                         if ((flags & Options.OmitDebugInfo) != 0)
323                                 return;
324
325                         methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset);
326                 }
327
328                 public void BeginCompilerScope ()
329                 {
330                         if ((flags & Options.OmitDebugInfo) != 0)
331                                 return;
332
333                         methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset);
334                 }
335
336                 public void EndExceptionBlock ()
337                 {
338                         ig.EndExceptionBlock ();
339                 }
340
341                 public void EndScope ()
342                 {
343                         if ((flags & Options.OmitDebugInfo) != 0)
344                                 return;
345
346                         methodSymbols.EndBlock (ig.ILOffset);
347                 }
348
349                 public void CloseConditionalAccess (TypeSpec type)
350                 {
351                         if (type != null)
352                                 Emit (OpCodes.Newobj, Nullable.NullableInfo.GetConstructor (type));
353
354                         MarkLabel (ConditionalAccess.EndLabel);
355                         ConditionalAccess = null;
356                 }
357
358                 //
359                 // Creates a nested container in this context for all dynamic compiler generated stuff
360                 //
361                 internal DynamicSiteClass CreateDynamicSite ()
362                 {
363                         if (dynamic_site_container == null) {
364                                 var mc = member_context.CurrentMemberDefinition as MemberBase;
365                                 dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters);
366
367                                 CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
368                                 dynamic_site_container.CreateContainer ();
369                                 dynamic_site_container.DefineContainer ();
370                                 dynamic_site_container.Define ();
371
372                                 var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
373                                 var inflated = dynamic_site_container.CurrentType.InflateMember (inflator);
374                                 CurrentType.MemberCache.AddMember (inflated);
375                         }
376
377                         return dynamic_site_container;
378                 }
379
380                 public Label CreateReturnLabel ()
381                 {
382                         if (!return_label.HasValue)
383                                 return_label = DefineLabel ();
384
385                         return return_label.Value;
386                 }
387
388                 public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
389                 {
390                         if (IsAnonymousStoreyMutateRequired)
391                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
392
393                         return ig.DeclareLocal (type.GetMetaInfo (), pinned);
394                 }
395
396                 public Label DefineLabel ()
397                 {
398                         return ig.DefineLabel ();
399                 }
400
401                 //
402                 // Creates temporary field in current async storey
403                 //
404                 public StackFieldExpr GetTemporaryField (TypeSpec type, bool initializedFieldRequired = false)
405                 {
406                         var f = AsyncTaskStorey.AddCapturedLocalVariable (type, initializedFieldRequired);
407                         var fexpr = new StackFieldExpr (f);
408                         fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
409                         return fexpr;
410                 }
411
412                 public void MarkLabel (Label label)
413                 {
414                         ig.MarkLabel (label);
415                 }
416
417                 public void Emit (OpCode opcode)
418                 {
419                         ig.Emit (opcode);
420                 }
421
422                 public void Emit (OpCode opcode, LocalBuilder local)
423                 {
424                         ig.Emit (opcode, local);
425                 }
426
427                 public void Emit (OpCode opcode, string arg)
428                 {
429                         ig.Emit (opcode, arg);
430                 }
431
432                 public void Emit (OpCode opcode, double arg)
433                 {
434                         ig.Emit (opcode, arg);
435                 }
436
437                 public void Emit (OpCode opcode, float arg)
438                 {
439                         ig.Emit (opcode, arg);
440                 }
441
442                 public void Emit (OpCode opcode, Label label)
443                 {
444                         ig.Emit (opcode, label);
445                 }
446
447                 public void Emit (OpCode opcode, Label[] labels)
448                 {
449                         ig.Emit (opcode, labels);
450                 }
451
452                 public void Emit (OpCode opcode, TypeSpec type)
453                 {
454                         if (IsAnonymousStoreyMutateRequired)
455                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
456
457                         ig.Emit (opcode, type.GetMetaInfo ());
458                 }
459
460                 public void Emit (OpCode opcode, FieldSpec field)
461                 {
462                         if (IsAnonymousStoreyMutateRequired)
463                                 field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
464
465                         ig.Emit (opcode, field.GetMetaInfo ());
466                 }
467
468                 public void Emit (OpCode opcode, MethodSpec method)
469                 {
470                         if (IsAnonymousStoreyMutateRequired)
471                                 method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
472
473                         if (method.IsConstructor)
474                                 ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
475                         else
476                                 ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
477                 }
478
479                 // TODO: REMOVE breaks mutator
480                 public void Emit (OpCode opcode, MethodInfo method)
481                 {
482                         ig.Emit (opcode, method);
483                 }
484
485                 public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs)
486                 {
487                         // TODO MemberCache: This should mutate too
488                         ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
489                 }
490
491                 public void EmitArrayNew (ArrayContainer ac)
492                 {
493                         if (ac.Rank == 1) {
494                                 var type = IsAnonymousStoreyMutateRequired ?
495                                         CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
496                                         ac.Element;
497
498                                 ig.Emit (OpCodes.Newarr, type.GetMetaInfo ());
499                         } else {
500                                 if (IsAnonymousStoreyMutateRequired)
501                                         ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
502
503                                 ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
504                         }
505                 }
506
507                 public void EmitArrayAddress (ArrayContainer ac)
508                 {
509                         if (ac.Rank > 1) {
510                                 if (IsAnonymousStoreyMutateRequired)
511                                         ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
512
513                                 ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
514                         } else {
515                                 var type = IsAnonymousStoreyMutateRequired ?
516                                         CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
517                                         ac.Element;
518
519                                 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
520                         }
521                 }
522
523                 //
524                 // Emits the right opcode to load from an array
525                 //
526                 public void EmitArrayLoad (ArrayContainer ac)
527                 {
528                         if (ac.Rank > 1) {
529                                 if (IsAnonymousStoreyMutateRequired)
530                                         ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
531
532                                 ig.Emit (OpCodes.Call, ac.GetGetMethod ());
533                                 return;
534                         }
535
536
537                         var type = ac.Element;
538                         if (type.Kind == MemberKind.Enum)
539                                 type = EnumSpec.GetUnderlyingType (type);
540
541                         switch (type.BuiltinType) {
542                         case BuiltinTypeSpec.Type.Bool:
543                                 //
544                                 // bool array can actually store any byte value in underlying byte slot
545                                 // and C# spec does not specify any normalization rule, except the result
546                                 // is undefined
547                                 //
548                         case BuiltinTypeSpec.Type.Byte:
549                                 ig.Emit (OpCodes.Ldelem_U1);
550                                 break;
551                         case BuiltinTypeSpec.Type.SByte:
552                                 ig.Emit (OpCodes.Ldelem_I1);
553                                 break;
554                         case BuiltinTypeSpec.Type.Short:
555                                 ig.Emit (OpCodes.Ldelem_I2);
556                                 break;
557                         case BuiltinTypeSpec.Type.UShort:
558                         case BuiltinTypeSpec.Type.Char:
559                                 ig.Emit (OpCodes.Ldelem_U2);
560                                 break;
561                         case BuiltinTypeSpec.Type.Int:
562                                 ig.Emit (OpCodes.Ldelem_I4);
563                                 break;
564                         case BuiltinTypeSpec.Type.UInt:
565                                 ig.Emit (OpCodes.Ldelem_U4);
566                                 break;
567                         case BuiltinTypeSpec.Type.ULong:
568                         case BuiltinTypeSpec.Type.Long:
569                                 ig.Emit (OpCodes.Ldelem_I8);
570                                 break;
571                         case BuiltinTypeSpec.Type.Float:
572                                 ig.Emit (OpCodes.Ldelem_R4);
573                                 break;
574                         case BuiltinTypeSpec.Type.Double:
575                                 ig.Emit (OpCodes.Ldelem_R8);
576                                 break;
577                         case BuiltinTypeSpec.Type.IntPtr:
578                                 ig.Emit (OpCodes.Ldelem_I);
579                                 break;
580                         default:
581                                 switch (type.Kind) {
582                                 case MemberKind.Struct:
583                                         if (IsAnonymousStoreyMutateRequired)
584                                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
585
586                                         ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
587                                         ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
588                                         break;
589                                 case MemberKind.TypeParameter:
590                                         if (IsAnonymousStoreyMutateRequired)
591                                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
592
593                                         ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ());
594                                         break;
595                                 case MemberKind.PointerType:
596                                         ig.Emit (OpCodes.Ldelem_I);
597                                         break;
598                                 default:
599                                         ig.Emit (OpCodes.Ldelem_Ref);
600                                         break;
601                                 }
602                                 break;
603                         }
604                 }
605
606                 //
607                 // Emits the right opcode to store to an array
608                 //
609                 public void EmitArrayStore (ArrayContainer ac)
610                 {
611                         if (ac.Rank > 1) {
612                                 if (IsAnonymousStoreyMutateRequired)
613                                         ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
614
615                                 ig.Emit (OpCodes.Call, ac.GetSetMethod ());
616                                 return;
617                         }
618
619                         var type = ac.Element;
620
621                         if (type.Kind == MemberKind.Enum)
622                                 type = EnumSpec.GetUnderlyingType (type);
623
624                         switch (type.BuiltinType) {
625                         case BuiltinTypeSpec.Type.Byte:
626                         case BuiltinTypeSpec.Type.SByte:
627                         case BuiltinTypeSpec.Type.Bool:
628                                 Emit (OpCodes.Stelem_I1);
629                                 return;
630                         case BuiltinTypeSpec.Type.Short:
631                         case BuiltinTypeSpec.Type.UShort:
632                         case BuiltinTypeSpec.Type.Char:
633                                 Emit (OpCodes.Stelem_I2);
634                                 return;
635                         case BuiltinTypeSpec.Type.Int:
636                         case BuiltinTypeSpec.Type.UInt:
637                                 Emit (OpCodes.Stelem_I4);
638                                 return;
639                         case BuiltinTypeSpec.Type.Long:
640                         case BuiltinTypeSpec.Type.ULong:
641                                 Emit (OpCodes.Stelem_I8);
642                                 return;
643                         case BuiltinTypeSpec.Type.Float:
644                                 Emit (OpCodes.Stelem_R4);
645                                 return;
646                         case BuiltinTypeSpec.Type.Double:
647                                 Emit (OpCodes.Stelem_R8);
648                                 return;
649                         }
650
651                         switch (type.Kind) {
652                         case MemberKind.Struct:
653                                 Emit (OpCodes.Stobj, type);
654                                 break;
655                         case MemberKind.TypeParameter:
656                                 Emit (OpCodes.Stelem, type);
657                                 break;
658                         case MemberKind.PointerType:
659                                 Emit (OpCodes.Stelem_I);
660                                 break;
661                         default:
662                                 Emit (OpCodes.Stelem_Ref);
663                                 break;
664                         }
665                 }
666
667                 public void EmitInt (int i)
668                 {
669                         EmitIntConstant (i);
670                 }
671
672                 void EmitIntConstant (int i)
673                 {
674                         switch (i) {
675                         case -1:
676                                 ig.Emit (OpCodes.Ldc_I4_M1);
677                                 break;
678
679                         case 0:
680                                 ig.Emit (OpCodes.Ldc_I4_0);
681                                 break;
682
683                         case 1:
684                                 ig.Emit (OpCodes.Ldc_I4_1);
685                                 break;
686
687                         case 2:
688                                 ig.Emit (OpCodes.Ldc_I4_2);
689                                 break;
690
691                         case 3:
692                                 ig.Emit (OpCodes.Ldc_I4_3);
693                                 break;
694
695                         case 4:
696                                 ig.Emit (OpCodes.Ldc_I4_4);
697                                 break;
698
699                         case 5:
700                                 ig.Emit (OpCodes.Ldc_I4_5);
701                                 break;
702
703                         case 6:
704                                 ig.Emit (OpCodes.Ldc_I4_6);
705                                 break;
706
707                         case 7:
708                                 ig.Emit (OpCodes.Ldc_I4_7);
709                                 break;
710
711                         case 8:
712                                 ig.Emit (OpCodes.Ldc_I4_8);
713                                 break;
714
715                         default:
716                                 if (i >= -128 && i <= 127) {
717                                         ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
718                                 } else
719                                         ig.Emit (OpCodes.Ldc_I4, i);
720                                 break;
721                         }
722                 }
723
724                 public void EmitLong (long l)
725                 {
726                         if (l >= int.MinValue && l <= int.MaxValue) {
727                                 EmitIntConstant (unchecked ((int) l));
728                                 ig.Emit (OpCodes.Conv_I8);
729                         } else if (l >= 0 && l <= uint.MaxValue) {
730                                 EmitIntConstant (unchecked ((int) l));
731                                 ig.Emit (OpCodes.Conv_U8);
732                         } else {
733                                 ig.Emit (OpCodes.Ldc_I8, l);
734                         }
735                 }
736
737                 //
738                 // Load the object from the pointer.  
739                 //
740                 public void EmitLoadFromPtr (TypeSpec type)
741                 {
742                         if (type.Kind == MemberKind.Enum)
743                                 type = EnumSpec.GetUnderlyingType (type);
744
745                         switch (type.BuiltinType) {
746                         case BuiltinTypeSpec.Type.Int:
747                                 ig.Emit (OpCodes.Ldind_I4);
748                                 break;
749                         case BuiltinTypeSpec.Type.UInt:
750                                 ig.Emit (OpCodes.Ldind_U4);
751                                 break;
752                         case BuiltinTypeSpec.Type.Short:
753                                 ig.Emit (OpCodes.Ldind_I2);
754                                 break;
755                         case BuiltinTypeSpec.Type.UShort:
756                         case BuiltinTypeSpec.Type.Char:
757                                 ig.Emit (OpCodes.Ldind_U2);
758                                 break;
759                         case BuiltinTypeSpec.Type.Byte:
760                                 ig.Emit (OpCodes.Ldind_U1);
761                                 break;
762                         case BuiltinTypeSpec.Type.SByte:
763                         case BuiltinTypeSpec.Type.Bool:
764                                 ig.Emit (OpCodes.Ldind_I1);
765                                 break;
766                         case BuiltinTypeSpec.Type.ULong:
767                         case BuiltinTypeSpec.Type.Long:
768                                 ig.Emit (OpCodes.Ldind_I8);
769                                 break;
770                         case BuiltinTypeSpec.Type.Float:
771                                 ig.Emit (OpCodes.Ldind_R4);
772                                 break;
773                         case BuiltinTypeSpec.Type.Double:
774                                 ig.Emit (OpCodes.Ldind_R8);
775                                 break;
776                         case BuiltinTypeSpec.Type.IntPtr:
777                                 ig.Emit (OpCodes.Ldind_I);
778                                 break;
779                         default:
780                                 switch (type.Kind) {
781                                 case MemberKind.Struct:
782                                 case MemberKind.TypeParameter:
783                                         if (IsAnonymousStoreyMutateRequired)
784                                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
785
786                                         ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
787                                         break;
788                                 case MemberKind.PointerType:
789                                         ig.Emit (OpCodes.Ldind_I);
790                                         break;
791                                 default:
792                                         ig.Emit (OpCodes.Ldind_Ref);
793                                         break;
794                                 }
795                                 break;
796                         }
797                 }
798
799                 public void EmitNull ()
800                 {
801                         ig.Emit (OpCodes.Ldnull);
802                 }
803
804                 public void EmitArgumentAddress (int pos)
805                 {
806                         if (!IsStatic)
807                                 ++pos;
808
809                         if (pos > byte.MaxValue)
810                                 ig.Emit (OpCodes.Ldarga, pos);
811                         else
812                                 ig.Emit (OpCodes.Ldarga_S, (byte) pos);
813                 }
814
815                 public void EmitArgumentLoad (int pos)
816                 {
817                         if (!IsStatic)
818                                 ++pos;
819
820                         switch (pos) {
821                         case 0: ig.Emit (OpCodes.Ldarg_0); break;
822                         case 1: ig.Emit (OpCodes.Ldarg_1); break;
823                         case 2: ig.Emit (OpCodes.Ldarg_2); break;
824                         case 3: ig.Emit (OpCodes.Ldarg_3); break;
825                         default:
826                                 if (pos > byte.MaxValue)
827                                         ig.Emit (OpCodes.Ldarg, pos);
828                                 else
829                                         ig.Emit (OpCodes.Ldarg_S, (byte) pos);
830                                 break;
831                         }
832                 }
833
834                 public void EmitArgumentStore (int pos)
835                 {
836                         if (!IsStatic)
837                                 ++pos;
838
839                         if (pos > byte.MaxValue)
840                                 ig.Emit (OpCodes.Starg, pos);
841                         else
842                                 ig.Emit (OpCodes.Starg_S, (byte) pos);
843                 }
844
845                 //
846                 // The stack contains the pointer and the value of type `type'
847                 //
848                 public void EmitStoreFromPtr (TypeSpec type)
849                 {
850                         if (type.IsEnum)
851                                 type = EnumSpec.GetUnderlyingType (type);
852
853                         switch (type.BuiltinType) {
854                         case BuiltinTypeSpec.Type.Int:
855                         case BuiltinTypeSpec.Type.UInt:
856                                 ig.Emit (OpCodes.Stind_I4);
857                                 return;
858                         case BuiltinTypeSpec.Type.Long:
859                         case BuiltinTypeSpec.Type.ULong:
860                                 ig.Emit (OpCodes.Stind_I8);
861                                 return;
862                         case BuiltinTypeSpec.Type.Char:
863                         case BuiltinTypeSpec.Type.Short:
864                         case BuiltinTypeSpec.Type.UShort:
865                                 ig.Emit (OpCodes.Stind_I2);
866                                 return;
867                         case BuiltinTypeSpec.Type.Float:
868                                 ig.Emit (OpCodes.Stind_R4);
869                                 return;
870                         case BuiltinTypeSpec.Type.Double:
871                                 ig.Emit (OpCodes.Stind_R8);
872                                 return;
873                         case BuiltinTypeSpec.Type.Byte:
874                         case BuiltinTypeSpec.Type.SByte:
875                         case BuiltinTypeSpec.Type.Bool:
876                                 ig.Emit (OpCodes.Stind_I1);
877                                 return;
878                         case BuiltinTypeSpec.Type.IntPtr:
879                                 ig.Emit (OpCodes.Stind_I);
880                                 return;
881                         }
882
883                         switch (type.Kind) {
884                         case MemberKind.Struct:
885                         case MemberKind.TypeParameter:
886                                 if (IsAnonymousStoreyMutateRequired)
887                                         type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
888
889                                 ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
890                                 break;
891                         case MemberKind.PointerType:
892                                 ig.Emit (OpCodes.Stind_I);
893                                 break;
894                         default:
895                                 ig.Emit (OpCodes.Stind_Ref);
896                                 break;
897                         }
898                 }
899
900                 public void EmitThis ()
901                 {
902                         ig.Emit (OpCodes.Ldarg_0);
903                 }
904
905                 public void EmitEpilogue ()
906                 {
907                         if (epilogue_expressions == null)
908                                 return;
909
910                         foreach (var e in epilogue_expressions)
911                                 e.EmitCleanup (this);
912
913                         epilogue_expressions = null;
914                 }
915
916                 /// <summary>
917                 ///   Returns a temporary storage for a variable of type t as 
918                 ///   a local variable in the current body.
919                 /// </summary>
920                 public LocalBuilder GetTemporaryLocal (TypeSpec t)
921                 {
922                         if (temporary_storage != null) {
923                                 object o;
924                                 if (temporary_storage.TryGetValue (t, out o)) {
925                                         if (o is Stack<LocalBuilder>) {
926                                                 var s = (Stack<LocalBuilder>) o;
927                                                 o = s.Count == 0 ? null : s.Pop ();
928                                         } else {
929                                                 temporary_storage.Remove (t);
930                                         }
931                                 }
932                                 if (o != null)
933                                         return (LocalBuilder) o;
934                         }
935                         return DeclareLocal (t, false);
936                 }
937
938                 public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
939                 {
940                         if (temporary_storage == null) {
941                                 temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
942                                 temporary_storage.Add (t, b);
943                                 return;
944                         }
945                         object o;
946                         
947                         if (!temporary_storage.TryGetValue (t, out o)) {
948                                 temporary_storage.Add (t, b);
949                                 return;
950                         }
951                         var s = o as Stack<LocalBuilder>;
952                         if (s == null) {
953                                 s = new Stack<LocalBuilder> ();
954                                 s.Push ((LocalBuilder)o);
955                                 temporary_storage [t] = s;
956                         }
957                         s.Push (b);
958                 }
959
960                 /// <summary>
961                 ///   ReturnValue creates on demand the LocalBuilder for the
962                 ///   return value from the function.  By default this is not
963                 ///   used.  This is only required when returns are found inside
964                 ///   Try or Catch statements.
965                 ///
966                 ///   This method is typically invoked from the Emit phase, so
967                 ///   we allow the creation of a return label if it was not
968                 ///   requested during the resolution phase.   Could be cleaned
969                 ///   up, but it would replicate a lot of logic in the Emit phase
970                 ///   of the code that uses it.
971                 /// </summary>
972                 public LocalBuilder TemporaryReturn ()
973                 {
974                         if (return_value == null){
975                                 return_value = DeclareLocal (return_type, false);
976                         }
977
978                         return return_value;
979                 }
980         }
981
982         public class ConditionalAccessContext
983         {
984                 public ConditionalAccessContext (TypeSpec type, Label endLabel)
985                 {
986                         Type = type;
987                         EndLabel = endLabel;
988                 }
989
990                 public bool Statement { get; set; }
991                 public Label EndLabel { get; private set; }
992                 public TypeSpec Type { get; private set; }
993         }
994
995         struct CallEmitter
996         {
997                 public Expression InstanceExpression;
998
999                 //
1000                 // When call has to leave an extra copy of all arguments on the stack
1001                 //
1002                 public bool DuplicateArguments;
1003
1004                 //
1005                 // Does not emit InstanceExpression load when InstanceExpressionOnStack
1006                 // is set. Used by compound assignments.
1007                 //
1008                 public bool InstanceExpressionOnStack;
1009
1010                 //
1011                 // Any of arguments contains await expression
1012                 //
1013                 public bool HasAwaitArguments;
1014
1015                 public bool ConditionalAccess;
1016
1017                 //
1018                 // When dealing with await arguments the original arguments are converted
1019                 // into a new set with hoisted stack results
1020                 //
1021                 public Arguments EmittedArguments;
1022
1023                 public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
1024                 {
1025                         EmitPredefined (ec, method, Arguments, false, loc);
1026                 }
1027
1028                 public void EmitStatement (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
1029                 {
1030                         EmitPredefined (ec, method, Arguments, true, loc);
1031                 }
1032
1033                 public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, bool statement = false, Location? loc = null)
1034                 {
1035                         Expression instance_copy = null;
1036
1037                         if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) {
1038                                 HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait ();
1039                                 if (HasAwaitArguments && InstanceExpressionOnStack) {
1040                                         throw new NotSupportedException ();
1041                                 }
1042                         }
1043
1044                         OpCode call_op;
1045                         LocalTemporary lt = null;
1046
1047                         if (method.IsStatic) {
1048                                 call_op = OpCodes.Call;
1049                         } else {
1050                                 call_op = IsVirtualCallRequired (InstanceExpression, method) ? OpCodes.Callvirt : OpCodes.Call;
1051
1052                                 if (HasAwaitArguments) {
1053                                         instance_copy = InstanceExpression.EmitToField (ec);
1054                                         var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType));
1055
1056                                         if (Arguments == null) {
1057                                                 ie.EmitLoad (ec, true);
1058                                         }
1059                                 } else if (!InstanceExpressionOnStack) {
1060                                         var ie = new InstanceEmitter (InstanceExpression, IsAddressCall (InstanceExpression, call_op, method.DeclaringType));
1061                                         ie.Emit (ec, ConditionalAccess);
1062
1063                                         if (DuplicateArguments) {
1064                                                 ec.Emit (OpCodes.Dup);
1065                                                 if (Arguments != null && Arguments.Count != 0) {
1066                                                         lt = new LocalTemporary (ie.GetStackType (ec));
1067                                                         lt.Store (ec);
1068                                                         instance_copy = lt;
1069                                                 }
1070                                         }
1071                                 }
1072                         }
1073
1074                         if (Arguments != null && !InstanceExpressionOnStack) {
1075                                 EmittedArguments = Arguments.Emit (ec, DuplicateArguments, HasAwaitArguments);
1076                                 if (EmittedArguments != null) {
1077                                         if (instance_copy != null) {
1078                                                 var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType));
1079                                                 ie.Emit (ec, ConditionalAccess);
1080
1081                                                 if (lt != null)
1082                                                         lt.Release (ec);
1083                                         }
1084
1085                                         EmittedArguments.Emit (ec);
1086                                 }
1087                         }
1088
1089                         if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStructOrEnum)) {
1090                                 ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
1091                         }
1092
1093                         if (loc != null) {
1094                                 //
1095                                 // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
1096                                 // break at right place when LHS expression can be stepped-into
1097                                 //
1098                                 ec.MarkCallEntry (loc.Value);
1099                         }
1100
1101                         //
1102                         // Set instance expression to actual result expression. When it contains await it can be
1103                         // picked up by caller
1104                         //
1105                         InstanceExpression = instance_copy;
1106
1107                         if (method.Parameters.HasArglist) {
1108                                 var varargs_types = GetVarargsTypes (method, Arguments);
1109                                 ec.Emit (call_op, method, varargs_types);
1110                         } else {
1111                                 //
1112                                 // If you have:
1113                                 // this.DoFoo ();
1114                                 // and DoFoo is not virtual, you can omit the callvirt,
1115                                 // because you don't need the null checking behavior.
1116                                 //
1117                                 ec.Emit (call_op, method);
1118                         }
1119
1120                         // 
1121                         // Pop the return value if there is one and stack should be empty
1122                         //
1123                         if (statement && method.ReturnType.Kind != MemberKind.Void)
1124                                 ec.Emit (OpCodes.Pop);
1125                 }
1126
1127                 static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments)
1128                 {
1129                         AParametersCollection pd = method.Parameters;
1130
1131                         Argument a = arguments[pd.Count - 1];
1132                         Arglist list = (Arglist) a.Expr;
1133
1134                         return list.ArgumentTypes;
1135                 }
1136
1137                 //
1138                 // Used to decide whether call or callvirt is needed
1139                 //
1140                 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
1141                 {
1142                         //
1143                         // There are 2 scenarious where we emit callvirt
1144                         //
1145                         // Case 1: A method is virtual and it's not used to call base
1146                         // Case 2: A method instance expression can be null. In this casen callvirt ensures
1147                         // correct NRE exception when the method is called
1148                         //
1149                         var decl_type = method.DeclaringType;
1150                         if (decl_type.IsStruct || decl_type.IsEnum)
1151                                 return false;
1152
1153                         if (instance is BaseThis)
1154                                 return false;
1155
1156                         //
1157                         // It's non-virtual and will never be null and it can be determined
1158                         // whether it's known value or reference type by verifier
1159                         //
1160                         if (!method.IsVirtual && Expression.IsNeverNull (instance) && !instance.Type.IsGenericParameter)
1161                                 return false;
1162
1163                         return true;
1164                 }
1165
1166                 static bool IsAddressCall (Expression instance, OpCode callOpcode, TypeSpec declaringType)
1167                 {
1168                         var instance_type = instance.Type;
1169                         return (instance_type.IsStructOrEnum && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
1170                                 instance_type.IsGenericParameter || declaringType.IsNullableType;
1171                 }
1172         }
1173
1174         public struct InstanceEmitter
1175         {
1176                 readonly Expression instance;
1177                 readonly bool addressRequired;
1178
1179                 public InstanceEmitter (Expression instance, bool addressLoad)
1180                 {
1181                         this.instance = instance;
1182                         this.addressRequired = addressLoad;
1183                 }
1184
1185                 public void Emit (EmitContext ec, bool conditionalAccess)
1186                 {
1187                         Label NullOperatorLabel;
1188                         Nullable.Unwrap unwrap;
1189
1190                         if (conditionalAccess && Expression.IsNeverNull (instance))
1191                                 conditionalAccess = false;
1192
1193                         if (conditionalAccess) {
1194                                 NullOperatorLabel = ec.DefineLabel ();
1195                                 unwrap = instance as Nullable.Unwrap;
1196                         } else {
1197                                 NullOperatorLabel = new Label ();
1198                                 unwrap = null;
1199                         }
1200
1201                         IMemoryLocation instance_address = null;
1202                         bool conditional_access_dup = false;
1203
1204                         if (unwrap != null) {
1205                                 unwrap.Store (ec);
1206                                 unwrap.EmitCheck (ec);
1207                                 ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel);
1208                         } else {
1209                                 if (conditionalAccess && addressRequired) {
1210                                         //
1211                                         // Don't allocate temp variable when instance load is cheap and load and load-address
1212                                         // operate on same memory
1213                                         //
1214                                         instance_address = instance as VariableReference;
1215                                         if (instance_address == null)
1216                                                 instance_address = instance as LocalTemporary;
1217
1218                                         if (instance_address == null) {
1219                                                 EmitLoad (ec, false);
1220                                                 ec.Emit (OpCodes.Dup);
1221                                                 ec.EmitLoadFromPtr (instance.Type);
1222
1223                                                 conditional_access_dup = true;
1224                                         } else {
1225                                                 instance.Emit (ec);
1226                                         }
1227                                 } else {
1228                                         EmitLoad (ec, !conditionalAccess);
1229
1230                                         if (conditionalAccess) {
1231                                                 conditional_access_dup = !ExpressionAnalyzer.IsInexpensiveLoad (instance);
1232                                                 if (conditional_access_dup)
1233                                                         ec.Emit (OpCodes.Dup);
1234                                         }
1235                                 }
1236
1237                                 if (conditionalAccess) {
1238                                         if (instance.Type.Kind == MemberKind.TypeParameter)
1239                                                 ec.Emit (OpCodes.Box, instance.Type);
1240
1241                                         ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel);
1242
1243                                         if (conditional_access_dup)
1244                                                 ec.Emit (OpCodes.Pop);
1245                                 }
1246                         }
1247
1248                         if (conditionalAccess) {
1249                                 if (!ec.ConditionalAccess.Statement) {
1250                                         if (ec.ConditionalAccess.Type.IsNullableType)
1251                                                 Nullable.LiftedNull.Create (ec.ConditionalAccess.Type, Location.Null).Emit (ec);
1252                                         else
1253                                                 ec.EmitNull ();
1254                                 }
1255
1256                                 ec.Emit (OpCodes.Br, ec.ConditionalAccess.EndLabel);
1257                                 ec.MarkLabel (NullOperatorLabel);
1258
1259                                 if (instance_address != null) {
1260                                         instance_address.AddressOf (ec, AddressOp.Load);
1261                                 } else if (unwrap != null) {
1262                                         unwrap.Emit (ec);
1263                                         if (addressRequired) {
1264                                                 var tmp = ec.GetTemporaryLocal (unwrap.Type);
1265                                                 ec.Emit (OpCodes.Stloc, tmp);
1266                                                 ec.Emit (OpCodes.Ldloca, tmp);
1267                                                 ec.FreeTemporaryLocal (tmp, unwrap.Type);
1268                                         }
1269                                 } else if (!conditional_access_dup) {
1270                                         instance.Emit (ec);
1271                                 }
1272                         }
1273                 }
1274
1275                 public void EmitLoad (EmitContext ec, bool boxInstance)
1276                 {
1277                         var instance_type = instance.Type;
1278
1279                         //
1280                         // Push the instance expression
1281                         //
1282                         if (addressRequired) {
1283                                 //
1284                                 // If the expression implements IMemoryLocation, then
1285                                 // we can optimize and use AddressOf on the
1286                                 // return.
1287                                 //
1288                                 // If not we have to use some temporary storage for
1289                                 // it.
1290                                 var iml = instance as IMemoryLocation;
1291                                 if (iml != null) {
1292                                         iml.AddressOf (ec, AddressOp.Load);
1293                                 } else {
1294                                         LocalTemporary temp = new LocalTemporary (instance_type);
1295                                         instance.Emit (ec);
1296                                         temp.Store (ec);
1297                                         temp.AddressOf (ec, AddressOp.Load);
1298                                 }
1299
1300                                 return;
1301                         }
1302
1303                         instance.Emit (ec);
1304
1305                         // Only to make verifier happy
1306                         if (boxInstance && ExpressionAnalyzer.RequiresBoxing (instance)) {
1307                                 ec.Emit (OpCodes.Box, instance_type);
1308                         }
1309                 }
1310
1311                 public TypeSpec GetStackType (EmitContext ec)
1312                 {
1313                         var instance_type = instance.Type;
1314
1315                         if (addressRequired)
1316                                 return ReferenceContainer.MakeType (ec.Module, instance_type);
1317
1318                         if (instance_type.IsStructOrEnum)
1319                                 return ec.Module.Compiler.BuiltinTypes.Object;
1320
1321                         return instance_type;
1322                 }
1323
1324
1325         }
1326
1327         static class ExpressionAnalyzer
1328         {
1329                 public static bool RequiresBoxing (Expression instance)
1330                 {
1331                         var instance_type = instance.Type;
1332                         if (instance_type.IsGenericParameter && !(instance is This) && TypeSpec.IsReferenceType (instance_type))
1333                                 return true;
1334
1335                         if (instance_type.IsStructOrEnum)
1336                                 return true;
1337
1338                         return false;
1339                 }
1340
1341                 //
1342                 // Returns true for cheap race-free load, where we can avoid using dup
1343                 //
1344                 public static bool IsInexpensiveLoad (Expression instance)
1345                 {
1346                         if (instance is Constant)
1347                                 return instance.IsSideEffectFree;
1348
1349                         if (RequiresBoxing (instance))
1350                                 return false;
1351
1352                         var vr = instance as VariableReference;
1353                         if (vr != null) {
1354                                 // Load from captured local would be racy without dup
1355                                 return !vr.IsRef && !vr.IsHoisted;
1356                         }
1357
1358                         if (instance is LocalTemporary)
1359                                 return true;
1360
1361                         var fe = instance as FieldExpr;
1362                         if (fe != null)
1363                                 return fe.IsStatic || fe.InstanceExpression is This;
1364
1365                         return false;
1366                 }
1367         }
1368 }