Merge pull request #901 from Blewzman/FixAggregateExceptionGetBaseException
[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 TypeSpec CurrentType {
125                         get { return member_context.CurrentType; }
126                 }
127
128                 public TypeParameters CurrentTypeParameters {
129                     get { return member_context.CurrentTypeParameters; }
130                 }
131
132                 public MemberCore CurrentTypeDefinition {
133                         get { return member_context.CurrentMemberDefinition; }
134                 }
135
136                 public bool EmitAccurateDebugInfo {
137                         get {
138                                 return (flags & Options.AccurateDebugInfo) != 0;
139                         }
140                 }
141
142                 public bool HasMethodSymbolBuilder {
143                         get {
144                                 return methodSymbols != null;
145                         }
146                 }
147
148                 public bool HasReturnLabel {
149                         get {
150                                 return return_label.HasValue;
151                         }
152                 }
153
154                 public bool IsStatic {
155                         get { return member_context.IsStatic; }
156                 }
157
158                 public bool IsAnonymousStoreyMutateRequired {
159                         get {
160                                 return CurrentAnonymousMethod != null &&
161                                         CurrentAnonymousMethod.Storey != null &&
162                                         CurrentAnonymousMethod.Storey.Mutator != null;
163                         }
164                 }
165
166                 public IMemberContext MemberContext {
167                         get {
168                                 return member_context;
169                         }
170                 }
171
172                 public ModuleContainer Module {
173                         get {
174                                 return member_context.Module;
175                         }
176                 }
177
178                 // Has to be used for specific emitter errors only any
179                 // possible resolver errors have to be reported during Resolve
180                 public Report Report {
181                         get {
182                                 return member_context.Module.Compiler.Report;
183                         }
184                 }
185
186                 public TypeSpec ReturnType {
187                         get {
188                                 return return_type;
189                         }
190                 }
191
192                 //
193                 // The label where we have to jump before leaving the context
194                 //
195                 public Label ReturnLabel {
196                         get {
197                                 return return_label.Value;
198                         }
199                 }
200
201                 public List<IExpressionCleanup> StatementEpilogue {
202                         get {
203                                 return epilogue_expressions;
204                         }
205                 }
206
207                 #endregion
208
209                 public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
210                 {
211                         if (epilogue_expressions == null) {
212                                 epilogue_expressions = new List<IExpressionCleanup> ();
213                         } else if (epilogue_expressions.Contains (cleanupExpression)) {
214                                 return;
215                         }
216
217                         epilogue_expressions.Add (cleanupExpression);
218                 }
219
220                 public void AssertEmptyStack ()
221                 {
222 #if STATIC
223                         if (ig.__StackHeight != 0)
224                                 throw new InternalErrorException ("Await yields with non-empty stack in `{0}",
225                                         member_context.GetSignatureForError ());
226 #endif
227                 }
228
229                 /// <summary>
230                 ///   This is called immediately before emitting an IL opcode to tell the symbol
231                 ///   writer to which source line this opcode belongs.
232                 /// </summary>
233                 public bool Mark (Location loc)
234                 {
235                         if ((flags & Options.OmitDebugInfo) != 0)
236                                 return false;
237
238                         if (loc.IsNull || methodSymbols == null)
239                                 return false;
240
241                         var sf = loc.SourceFile;
242                         if (sf.IsHiddenLocation (loc))
243                                 return false;
244
245 #if NET_4_0
246                         methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false);
247 #endif
248                         return true;
249                 }
250
251                 public void MarkCallEntry (Location loc)
252                 {
253                         if (!EmitAccurateDebugInfo)
254                                 return;
255
256                         //
257                         // TODO: This should emit different kind of sequence point to make
258                         // step-over work for statement over multiple lines
259                         //
260                         // Debugging experience for Foo (A () + B ()) where A and B are
261                         // on separate lines is not great
262                         //
263                         Mark (loc);
264                 }
265
266                 public void DefineLocalVariable (string name, LocalBuilder builder)
267                 {
268                         if ((flags & Options.OmitDebugInfo) != 0)
269                                 return;
270
271                         methodSymbols.AddLocal (builder.LocalIndex, name);
272                 }
273
274                 public void BeginCatchBlock (TypeSpec type)
275                 {
276                         if (IsAnonymousStoreyMutateRequired)
277                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
278
279                         ig.BeginCatchBlock (type.GetMetaInfo ());
280                 }
281
282                 public void BeginExceptionBlock ()
283                 {
284                         ig.BeginExceptionBlock ();
285                 }
286
287                 public void BeginFinallyBlock ()
288                 {
289                         ig.BeginFinallyBlock ();
290                 }
291
292                 public void BeginScope ()
293                 {
294                         if ((flags & Options.OmitDebugInfo) != 0)
295                                 return;
296
297 #if NET_4_0
298                         methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset);
299 #endif
300                 }
301
302                 public void BeginCompilerScope ()
303                 {
304                         if ((flags & Options.OmitDebugInfo) != 0)
305                                 return;
306
307 #if NET_4_0
308                         methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset);
309 #endif
310                 }
311
312                 public void EndExceptionBlock ()
313                 {
314                         ig.EndExceptionBlock ();
315                 }
316
317                 public void EndScope ()
318                 {
319                         if ((flags & Options.OmitDebugInfo) != 0)
320                                 return;
321
322 #if NET_4_0
323                         methodSymbols.EndBlock (ig.ILOffset);
324 #endif
325                 }
326
327                 //
328                 // Creates a nested container in this context for all dynamic compiler generated stuff
329                 //
330                 internal DynamicSiteClass CreateDynamicSite ()
331                 {
332                         if (dynamic_site_container == null) {
333                                 var mc = member_context.CurrentMemberDefinition as MemberBase;
334                                 dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters);
335
336                                 CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
337                                 dynamic_site_container.CreateContainer ();
338                                 dynamic_site_container.DefineContainer ();
339                                 dynamic_site_container.Define ();
340
341                                 var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
342                                 var inflated = dynamic_site_container.CurrentType.InflateMember (inflator);
343                                 CurrentType.MemberCache.AddMember (inflated);
344                         }
345
346                         return dynamic_site_container;
347                 }
348
349                 public Label CreateReturnLabel ()
350                 {
351                         if (!return_label.HasValue)
352                                 return_label = DefineLabel ();
353
354                         return return_label.Value;
355                 }
356
357                 public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
358                 {
359                         if (IsAnonymousStoreyMutateRequired)
360                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
361
362                         return ig.DeclareLocal (type.GetMetaInfo (), pinned);
363                 }
364
365                 public Label DefineLabel ()
366                 {
367                         return ig.DefineLabel ();
368                 }
369
370                 //
371                 // Creates temporary field in current async storey
372                 //
373                 public StackFieldExpr GetTemporaryField (TypeSpec type)
374                 {
375                         var f = AsyncTaskStorey.AddCapturedLocalVariable (type);
376                         var fexpr = new StackFieldExpr (f);
377                         fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
378                         return fexpr;
379                 }
380
381                 public void MarkLabel (Label label)
382                 {
383                         ig.MarkLabel (label);
384                 }
385
386                 public void Emit (OpCode opcode)
387                 {
388                         ig.Emit (opcode);
389                 }
390
391                 public void Emit (OpCode opcode, LocalBuilder local)
392                 {
393                         ig.Emit (opcode, local);
394                 }
395
396                 public void Emit (OpCode opcode, string arg)
397                 {
398                         ig.Emit (opcode, arg);
399                 }
400
401                 public void Emit (OpCode opcode, double arg)
402                 {
403                         ig.Emit (opcode, arg);
404                 }
405
406                 public void Emit (OpCode opcode, float arg)
407                 {
408                         ig.Emit (opcode, arg);
409                 }
410
411                 public void Emit (OpCode opcode, Label label)
412                 {
413                         ig.Emit (opcode, label);
414                 }
415
416                 public void Emit (OpCode opcode, Label[] labels)
417                 {
418                         ig.Emit (opcode, labels);
419                 }
420
421                 public void Emit (OpCode opcode, TypeSpec type)
422                 {
423                         if (IsAnonymousStoreyMutateRequired)
424                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
425
426                         ig.Emit (opcode, type.GetMetaInfo ());
427                 }
428
429                 public void Emit (OpCode opcode, FieldSpec field)
430                 {
431                         if (IsAnonymousStoreyMutateRequired)
432                                 field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
433
434                         ig.Emit (opcode, field.GetMetaInfo ());
435                 }
436
437                 public void Emit (OpCode opcode, MethodSpec method)
438                 {
439                         if (IsAnonymousStoreyMutateRequired)
440                                 method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
441
442                         if (method.IsConstructor)
443                                 ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
444                         else
445                                 ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
446                 }
447
448                 // TODO: REMOVE breaks mutator
449                 public void Emit (OpCode opcode, MethodInfo method)
450                 {
451                         ig.Emit (opcode, method);
452                 }
453
454                 public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs)
455                 {
456                         // TODO MemberCache: This should mutate too
457                         ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
458                 }
459
460                 public void EmitArrayNew (ArrayContainer ac)
461                 {
462                         if (ac.Rank == 1) {
463                                 var type = IsAnonymousStoreyMutateRequired ?
464                                         CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
465                                         ac.Element;
466
467                                 ig.Emit (OpCodes.Newarr, type.GetMetaInfo ());
468                         } else {
469                                 if (IsAnonymousStoreyMutateRequired)
470                                         ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
471
472                                 ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
473                         }
474                 }
475
476                 public void EmitArrayAddress (ArrayContainer ac)
477                 {
478                         if (ac.Rank > 1) {
479                                 if (IsAnonymousStoreyMutateRequired)
480                                         ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
481
482                                 ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
483                         } else {
484                                 var type = IsAnonymousStoreyMutateRequired ?
485                                         CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
486                                         ac.Element;
487
488                                 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
489                         }
490                 }
491
492                 //
493                 // Emits the right opcode to load from an array
494                 //
495                 public void EmitArrayLoad (ArrayContainer ac)
496                 {
497                         if (ac.Rank > 1) {
498                                 if (IsAnonymousStoreyMutateRequired)
499                                         ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
500
501                                 ig.Emit (OpCodes.Call, ac.GetGetMethod ());
502                                 return;
503                         }
504
505
506                         var type = ac.Element;
507                         if (type.Kind == MemberKind.Enum)
508                                 type = EnumSpec.GetUnderlyingType (type);
509
510                         switch (type.BuiltinType) {
511                         case BuiltinTypeSpec.Type.Byte:
512                         case BuiltinTypeSpec.Type.Bool:
513                                 ig.Emit (OpCodes.Ldelem_U1);
514                                 break;
515                         case BuiltinTypeSpec.Type.SByte:
516                                 ig.Emit (OpCodes.Ldelem_I1);
517                                 break;
518                         case BuiltinTypeSpec.Type.Short:
519                                 ig.Emit (OpCodes.Ldelem_I2);
520                                 break;
521                         case BuiltinTypeSpec.Type.UShort:
522                         case BuiltinTypeSpec.Type.Char:
523                                 ig.Emit (OpCodes.Ldelem_U2);
524                                 break;
525                         case BuiltinTypeSpec.Type.Int:
526                                 ig.Emit (OpCodes.Ldelem_I4);
527                                 break;
528                         case BuiltinTypeSpec.Type.UInt:
529                                 ig.Emit (OpCodes.Ldelem_U4);
530                                 break;
531                         case BuiltinTypeSpec.Type.ULong:
532                         case BuiltinTypeSpec.Type.Long:
533                                 ig.Emit (OpCodes.Ldelem_I8);
534                                 break;
535                         case BuiltinTypeSpec.Type.Float:
536                                 ig.Emit (OpCodes.Ldelem_R4);
537                                 break;
538                         case BuiltinTypeSpec.Type.Double:
539                                 ig.Emit (OpCodes.Ldelem_R8);
540                                 break;
541                         case BuiltinTypeSpec.Type.IntPtr:
542                                 ig.Emit (OpCodes.Ldelem_I);
543                                 break;
544                         default:
545                                 switch (type.Kind) {
546                                 case MemberKind.Struct:
547                                         if (IsAnonymousStoreyMutateRequired)
548                                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
549
550                                         ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
551                                         ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
552                                         break;
553                                 case MemberKind.TypeParameter:
554                                         if (IsAnonymousStoreyMutateRequired)
555                                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
556
557                                         ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ());
558                                         break;
559                                 case MemberKind.PointerType:
560                                         ig.Emit (OpCodes.Ldelem_I);
561                                         break;
562                                 default:
563                                         ig.Emit (OpCodes.Ldelem_Ref);
564                                         break;
565                                 }
566                                 break;
567                         }
568                 }
569
570                 //
571                 // Emits the right opcode to store to an array
572                 //
573                 public void EmitArrayStore (ArrayContainer ac)
574                 {
575                         if (ac.Rank > 1) {
576                                 if (IsAnonymousStoreyMutateRequired)
577                                         ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
578
579                                 ig.Emit (OpCodes.Call, ac.GetSetMethod ());
580                                 return;
581                         }
582
583                         var type = ac.Element;
584
585                         if (type.Kind == MemberKind.Enum)
586                                 type = EnumSpec.GetUnderlyingType (type);
587
588                         switch (type.BuiltinType) {
589                         case BuiltinTypeSpec.Type.Byte:
590                         case BuiltinTypeSpec.Type.SByte:
591                         case BuiltinTypeSpec.Type.Bool:
592                                 Emit (OpCodes.Stelem_I1);
593                                 return;
594                         case BuiltinTypeSpec.Type.Short:
595                         case BuiltinTypeSpec.Type.UShort:
596                         case BuiltinTypeSpec.Type.Char:
597                                 Emit (OpCodes.Stelem_I2);
598                                 return;
599                         case BuiltinTypeSpec.Type.Int:
600                         case BuiltinTypeSpec.Type.UInt:
601                                 Emit (OpCodes.Stelem_I4);
602                                 return;
603                         case BuiltinTypeSpec.Type.Long:
604                         case BuiltinTypeSpec.Type.ULong:
605                                 Emit (OpCodes.Stelem_I8);
606                                 return;
607                         case BuiltinTypeSpec.Type.Float:
608                                 Emit (OpCodes.Stelem_R4);
609                                 return;
610                         case BuiltinTypeSpec.Type.Double:
611                                 Emit (OpCodes.Stelem_R8);
612                                 return;
613                         }
614
615                         switch (type.Kind) {
616                         case MemberKind.Struct:
617                                 Emit (OpCodes.Stobj, type);
618                                 break;
619                         case MemberKind.TypeParameter:
620                                 Emit (OpCodes.Stelem, type);
621                                 break;
622                         case MemberKind.PointerType:
623                                 Emit (OpCodes.Stelem_I);
624                                 break;
625                         default:
626                                 Emit (OpCodes.Stelem_Ref);
627                                 break;
628                         }
629                 }
630
631                 public void EmitInt (int i)
632                 {
633                         EmitIntConstant (i);
634                 }
635
636                 void EmitIntConstant (int i)
637                 {
638                         switch (i) {
639                         case -1:
640                                 ig.Emit (OpCodes.Ldc_I4_M1);
641                                 break;
642
643                         case 0:
644                                 ig.Emit (OpCodes.Ldc_I4_0);
645                                 break;
646
647                         case 1:
648                                 ig.Emit (OpCodes.Ldc_I4_1);
649                                 break;
650
651                         case 2:
652                                 ig.Emit (OpCodes.Ldc_I4_2);
653                                 break;
654
655                         case 3:
656                                 ig.Emit (OpCodes.Ldc_I4_3);
657                                 break;
658
659                         case 4:
660                                 ig.Emit (OpCodes.Ldc_I4_4);
661                                 break;
662
663                         case 5:
664                                 ig.Emit (OpCodes.Ldc_I4_5);
665                                 break;
666
667                         case 6:
668                                 ig.Emit (OpCodes.Ldc_I4_6);
669                                 break;
670
671                         case 7:
672                                 ig.Emit (OpCodes.Ldc_I4_7);
673                                 break;
674
675                         case 8:
676                                 ig.Emit (OpCodes.Ldc_I4_8);
677                                 break;
678
679                         default:
680                                 if (i >= -128 && i <= 127) {
681                                         ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
682                                 } else
683                                         ig.Emit (OpCodes.Ldc_I4, i);
684                                 break;
685                         }
686                 }
687
688                 public void EmitLong (long l)
689                 {
690                         if (l >= int.MinValue && l <= int.MaxValue) {
691                                 EmitIntConstant (unchecked ((int) l));
692                                 ig.Emit (OpCodes.Conv_I8);
693                         } else if (l >= 0 && l <= uint.MaxValue) {
694                                 EmitIntConstant (unchecked ((int) l));
695                                 ig.Emit (OpCodes.Conv_U8);
696                         } else {
697                                 ig.Emit (OpCodes.Ldc_I8, l);
698                         }
699                 }
700
701                 //
702                 // Load the object from the pointer.  
703                 //
704                 public void EmitLoadFromPtr (TypeSpec type)
705                 {
706                         if (type.Kind == MemberKind.Enum)
707                                 type = EnumSpec.GetUnderlyingType (type);
708
709                         switch (type.BuiltinType) {
710                         case BuiltinTypeSpec.Type.Int:
711                                 ig.Emit (OpCodes.Ldind_I4);
712                                 break;
713                         case BuiltinTypeSpec.Type.UInt:
714                                 ig.Emit (OpCodes.Ldind_U4);
715                                 break;
716                         case BuiltinTypeSpec.Type.Short:
717                                 ig.Emit (OpCodes.Ldind_I2);
718                                 break;
719                         case BuiltinTypeSpec.Type.UShort:
720                         case BuiltinTypeSpec.Type.Char:
721                                 ig.Emit (OpCodes.Ldind_U2);
722                                 break;
723                         case BuiltinTypeSpec.Type.Byte:
724                                 ig.Emit (OpCodes.Ldind_U1);
725                                 break;
726                         case BuiltinTypeSpec.Type.SByte:
727                         case BuiltinTypeSpec.Type.Bool:
728                                 ig.Emit (OpCodes.Ldind_I1);
729                                 break;
730                         case BuiltinTypeSpec.Type.ULong:
731                         case BuiltinTypeSpec.Type.Long:
732                                 ig.Emit (OpCodes.Ldind_I8);
733                                 break;
734                         case BuiltinTypeSpec.Type.Float:
735                                 ig.Emit (OpCodes.Ldind_R4);
736                                 break;
737                         case BuiltinTypeSpec.Type.Double:
738                                 ig.Emit (OpCodes.Ldind_R8);
739                                 break;
740                         case BuiltinTypeSpec.Type.IntPtr:
741                                 ig.Emit (OpCodes.Ldind_I);
742                                 break;
743                         default:
744                                 switch (type.Kind) {
745                                 case MemberKind.Struct:
746                                 case MemberKind.TypeParameter:
747                                         if (IsAnonymousStoreyMutateRequired)
748                                                 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
749
750                                         ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
751                                         break;
752                                 case MemberKind.PointerType:
753                                         ig.Emit (OpCodes.Ldind_I);
754                                         break;
755                                 default:
756                                         ig.Emit (OpCodes.Ldind_Ref);
757                                         break;
758                                 }
759                                 break;
760                         }
761                 }
762
763                 public void EmitNull ()
764                 {
765                         ig.Emit (OpCodes.Ldnull);
766                 }
767
768                 public void EmitArgumentAddress (int pos)
769                 {
770                         if (!IsStatic)
771                                 ++pos;
772
773                         if (pos > byte.MaxValue)
774                                 ig.Emit (OpCodes.Ldarga, pos);
775                         else
776                                 ig.Emit (OpCodes.Ldarga_S, (byte) pos);
777                 }
778
779                 public void EmitArgumentLoad (int pos)
780                 {
781                         if (!IsStatic)
782                                 ++pos;
783
784                         switch (pos) {
785                         case 0: ig.Emit (OpCodes.Ldarg_0); break;
786                         case 1: ig.Emit (OpCodes.Ldarg_1); break;
787                         case 2: ig.Emit (OpCodes.Ldarg_2); break;
788                         case 3: ig.Emit (OpCodes.Ldarg_3); break;
789                         default:
790                                 if (pos > byte.MaxValue)
791                                         ig.Emit (OpCodes.Ldarg, pos);
792                                 else
793                                         ig.Emit (OpCodes.Ldarg_S, (byte) pos);
794                                 break;
795                         }
796                 }
797
798                 public void EmitArgumentStore (int pos)
799                 {
800                         if (!IsStatic)
801                                 ++pos;
802
803                         if (pos > byte.MaxValue)
804                                 ig.Emit (OpCodes.Starg, pos);
805                         else
806                                 ig.Emit (OpCodes.Starg_S, (byte) pos);
807                 }
808
809                 //
810                 // The stack contains the pointer and the value of type `type'
811                 //
812                 public void EmitStoreFromPtr (TypeSpec type)
813                 {
814                         if (type.IsEnum)
815                                 type = EnumSpec.GetUnderlyingType (type);
816
817                         switch (type.BuiltinType) {
818                         case BuiltinTypeSpec.Type.Int:
819                         case BuiltinTypeSpec.Type.UInt:
820                                 ig.Emit (OpCodes.Stind_I4);
821                                 return;
822                         case BuiltinTypeSpec.Type.Long:
823                         case BuiltinTypeSpec.Type.ULong:
824                                 ig.Emit (OpCodes.Stind_I8);
825                                 return;
826                         case BuiltinTypeSpec.Type.Char:
827                         case BuiltinTypeSpec.Type.Short:
828                         case BuiltinTypeSpec.Type.UShort:
829                                 ig.Emit (OpCodes.Stind_I2);
830                                 return;
831                         case BuiltinTypeSpec.Type.Float:
832                                 ig.Emit (OpCodes.Stind_R4);
833                                 return;
834                         case BuiltinTypeSpec.Type.Double:
835                                 ig.Emit (OpCodes.Stind_R8);
836                                 return;
837                         case BuiltinTypeSpec.Type.Byte:
838                         case BuiltinTypeSpec.Type.SByte:
839                         case BuiltinTypeSpec.Type.Bool:
840                                 ig.Emit (OpCodes.Stind_I1);
841                                 return;
842                         case BuiltinTypeSpec.Type.IntPtr:
843                                 ig.Emit (OpCodes.Stind_I);
844                                 return;
845                         }
846
847                         switch (type.Kind) {
848                         case MemberKind.Struct:
849                         case MemberKind.TypeParameter:
850                                 if (IsAnonymousStoreyMutateRequired)
851                                         type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
852
853                                 ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
854                                 break;
855                         default:
856                                 ig.Emit (OpCodes.Stind_Ref);
857                                 break;
858                         }
859                 }
860
861                 public void EmitThis ()
862                 {
863                         ig.Emit (OpCodes.Ldarg_0);
864                 }
865
866                 public void EmitEpilogue ()
867                 {
868                         if (epilogue_expressions == null)
869                                 return;
870
871                         foreach (var e in epilogue_expressions)
872                                 e.EmitCleanup (this);
873
874                         epilogue_expressions = null;
875                 }
876
877                 /// <summary>
878                 ///   Returns a temporary storage for a variable of type t as 
879                 ///   a local variable in the current body.
880                 /// </summary>
881                 public LocalBuilder GetTemporaryLocal (TypeSpec t)
882                 {
883                         if (temporary_storage != null) {
884                                 object o;
885                                 if (temporary_storage.TryGetValue (t, out o)) {
886                                         if (o is Stack<LocalBuilder>) {
887                                                 var s = (Stack<LocalBuilder>) o;
888                                                 o = s.Count == 0 ? null : s.Pop ();
889                                         } else {
890                                                 temporary_storage.Remove (t);
891                                         }
892                                 }
893                                 if (o != null)
894                                         return (LocalBuilder) o;
895                         }
896                         return DeclareLocal (t, false);
897                 }
898
899                 public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
900                 {
901                         if (temporary_storage == null) {
902                                 temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
903                                 temporary_storage.Add (t, b);
904                                 return;
905                         }
906                         object o;
907                         
908                         if (!temporary_storage.TryGetValue (t, out o)) {
909                                 temporary_storage.Add (t, b);
910                                 return;
911                         }
912                         var s = o as Stack<LocalBuilder>;
913                         if (s == null) {
914                                 s = new Stack<LocalBuilder> ();
915                                 s.Push ((LocalBuilder)o);
916                                 temporary_storage [t] = s;
917                         }
918                         s.Push (b);
919                 }
920
921                 /// <summary>
922                 ///   ReturnValue creates on demand the LocalBuilder for the
923                 ///   return value from the function.  By default this is not
924                 ///   used.  This is only required when returns are found inside
925                 ///   Try or Catch statements.
926                 ///
927                 ///   This method is typically invoked from the Emit phase, so
928                 ///   we allow the creation of a return label if it was not
929                 ///   requested during the resolution phase.   Could be cleaned
930                 ///   up, but it would replicate a lot of logic in the Emit phase
931                 ///   of the code that uses it.
932                 /// </summary>
933                 public LocalBuilder TemporaryReturn ()
934                 {
935                         if (return_value == null){
936                                 return_value = DeclareLocal (return_type, false);
937                         }
938
939                         return return_value;
940                 }
941         }
942
943         struct CallEmitter
944         {
945                 public Expression InstanceExpression;
946
947                 //
948                 // When set leaves an extra copy of all arguments on the stack
949                 //
950                 public bool DuplicateArguments;
951
952                 //
953                 // Does not emit InstanceExpression load when InstanceExpressionOnStack
954                 // is set. Used by compound assignments.
955                 //
956                 public bool InstanceExpressionOnStack;
957
958                 //
959                 // Any of arguments contains await expression
960                 //
961                 public bool HasAwaitArguments;
962
963                 //
964                 // When dealing with await arguments the original arguments are converted
965                 // into a new set with hoisted stack results
966                 //
967                 public Arguments EmittedArguments;
968
969                 public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
970                 {
971                         EmitPredefined (ec, method, Arguments, loc);
972                 }
973
974                 public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, Location? loc = null)
975                 {
976                         Expression instance_copy = null;
977
978                         if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) {
979                                 HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait ();
980                                 if (HasAwaitArguments && InstanceExpressionOnStack) {
981                                         throw new NotSupportedException ();
982                                 }
983                         }
984
985                         OpCode call_op;
986                         LocalTemporary lt = null;
987
988                         if (method.IsStatic) {
989                                 call_op = OpCodes.Call;
990                         } else {
991                                 if (IsVirtualCallRequired (InstanceExpression, method)) {
992                                         call_op = OpCodes.Callvirt;
993                                 } else {
994                                         call_op = OpCodes.Call;
995                                 }
996
997                                 if (HasAwaitArguments) {
998                                         instance_copy = InstanceExpression.EmitToField (ec);
999                                         if (Arguments == null)
1000                                                 EmitCallInstance (ec, instance_copy, method.DeclaringType, call_op);
1001                                 } else if (!InstanceExpressionOnStack) {
1002                                         var instance_on_stack_type = EmitCallInstance (ec, InstanceExpression, method.DeclaringType, call_op);
1003
1004                                         if (DuplicateArguments) {
1005                                                 ec.Emit (OpCodes.Dup);
1006                                                 if (Arguments != null && Arguments.Count != 0) {
1007                                                         lt = new LocalTemporary (instance_on_stack_type);
1008                                                         lt.Store (ec);
1009                                                         instance_copy = lt;
1010                                                 }
1011                                         }
1012                                 }
1013                         }
1014
1015                         if (Arguments != null && !InstanceExpressionOnStack) {
1016                                 EmittedArguments = Arguments.Emit (ec, DuplicateArguments, HasAwaitArguments);
1017                                 if (EmittedArguments != null) {
1018                                         if (instance_copy != null) {
1019                                                 EmitCallInstance (ec, instance_copy, method.DeclaringType, call_op);
1020
1021                                                 if (lt != null)
1022                                                         lt.Release (ec);
1023                                         }
1024
1025                                         EmittedArguments.Emit (ec);
1026                                 }
1027                         }
1028
1029                         if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStruct)) {
1030                                 ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
1031                         }
1032
1033                         if (loc != null) {
1034                                 //
1035                                 // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
1036                                 // break at right place when LHS expression can be stepped-into
1037                                 //
1038                                 ec.MarkCallEntry (loc.Value);
1039                         }
1040
1041                         //
1042                         // Set instance expression to actual result expression. When it contains await it can be
1043                         // picked up by caller
1044                         //
1045                         InstanceExpression = instance_copy;
1046
1047                         if (method.Parameters.HasArglist) {
1048                                 var varargs_types = GetVarargsTypes (method, Arguments);
1049                                 ec.Emit (call_op, method, varargs_types);
1050                                 return;
1051                         }
1052
1053                         //
1054                         // If you have:
1055                         // this.DoFoo ();
1056                         // and DoFoo is not virtual, you can omit the callvirt,
1057                         // because you don't need the null checking behavior.
1058                         //
1059                         ec.Emit (call_op, method);
1060                 }
1061
1062                 static TypeSpec EmitCallInstance (EmitContext ec, Expression instance, TypeSpec declaringType, OpCode callOpcode)
1063                 {
1064                         var instance_type = instance.Type;
1065
1066                         //
1067                         // Push the instance expression
1068                         //
1069                         if ((instance_type.IsStruct && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
1070                                 instance_type.IsGenericParameter || declaringType.IsNullableType) {
1071                                 //
1072                                 // If the expression implements IMemoryLocation, then
1073                                 // we can optimize and use AddressOf on the
1074                                 // return.
1075                                 //
1076                                 // If not we have to use some temporary storage for
1077                                 // it.
1078                                 var iml = instance as IMemoryLocation;
1079                                 if (iml != null) {
1080                                         iml.AddressOf (ec, AddressOp.Load);
1081                                 } else {
1082                                         LocalTemporary temp = new LocalTemporary (instance_type);
1083                                         instance.Emit (ec);
1084                                         temp.Store (ec);
1085                                         temp.AddressOf (ec, AddressOp.Load);
1086                                 }
1087
1088                                 return ReferenceContainer.MakeType (ec.Module, instance_type);
1089                         }
1090
1091                         if (instance_type.IsEnum || instance_type.IsStruct) {
1092                                 instance.Emit (ec);
1093                                 ec.Emit (OpCodes.Box, instance_type);
1094                                 return ec.BuiltinTypes.Object;
1095                         }
1096
1097                         instance.Emit (ec);
1098                         return instance_type;
1099                 }
1100
1101                 static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments)
1102                 {
1103                         AParametersCollection pd = method.Parameters;
1104
1105                         Argument a = arguments[pd.Count - 1];
1106                         Arglist list = (Arglist) a.Expr;
1107
1108                         return list.ArgumentTypes;
1109                 }
1110
1111                 //
1112                 // Used to decide whether call or callvirt is needed
1113                 //
1114                 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
1115                 {
1116                         //
1117                         // There are 2 scenarious where we emit callvirt
1118                         //
1119                         // Case 1: A method is virtual and it's not used to call base
1120                         // Case 2: A method instance expression can be null. In this casen callvirt ensures
1121                         // correct NRE exception when the method is called
1122                         //
1123                         var decl_type = method.DeclaringType;
1124                         if (decl_type.IsStruct || decl_type.IsEnum)
1125                                 return false;
1126
1127                         if (instance is BaseThis)
1128                                 return false;
1129
1130                         //
1131                         // It's non-virtual and will never be null and it can be determined
1132                         // whether it's known value or reference type by verifier
1133                         //
1134                         if (!method.IsVirtual && (instance is This || instance is New || instance is ArrayCreation || instance is DelegateCreation) &&
1135                                 !instance.Type.IsGenericParameter)
1136                                 return false;
1137
1138                         return true;
1139                 }
1140         }
1141 }