2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2004 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
14 using System.Collections.Generic;
15 using Mono.CompilerServices.SymbolWriter;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
30 /// An Emit Context is created for each body of code (from methods,
31 /// properties bodies, indexer bodies or constructor bodies)
33 public class EmitContext : BuilderContext
35 // TODO: Has to be private
36 public readonly ILGenerator ig;
39 /// The value that is allowed to be returned or NULL if there is no
42 readonly TypeSpec return_type;
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)
49 Dictionary<TypeSpec, object> temporary_storage;
52 /// The location where we store the return value.
54 public LocalBuilder return_value;
58 /// Current loop begin and end labels.
60 public Label LoopBegin, LoopEnd;
63 /// Default target in a switch statement. Only valid if
66 public Label DefaultTarget;
69 /// If this is non-null, points to the current switch statement
74 /// Whether we are inside an anonymous method.
76 public AnonymousExpression CurrentAnonymousMethod;
78 readonly IMemberContext member_context;
80 readonly SourceMethodBuilder methodSymbols;
82 DynamicSiteClass dynamic_site_container;
86 List<IExpressionCleanup> epilogue_expressions;
88 public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type, SourceMethodBuilder methodSymbols)
90 this.member_context = rc;
92 this.return_type = return_type;
94 if (rc.Module.Compiler.Settings.Checked)
95 flags |= Options.CheckedScope;
97 if (methodSymbols != null) {
98 this.methodSymbols = methodSymbols;
99 if (!rc.Module.Compiler.Settings.Optimize)
100 flags |= Options.AccurateDebugInfo;
102 flags |= Options.OmitDebugInfo;
106 ig.__CleverExceptionBlockAssistance ();
112 internal AsyncTaskStorey AsyncTaskStorey {
114 return CurrentAnonymousMethod.Storey as AsyncTaskStorey;
118 public BuiltinTypes BuiltinTypes {
120 return MemberContext.Module.Compiler.BuiltinTypes;
124 public TypeSpec CurrentType {
125 get { return member_context.CurrentType; }
128 public TypeParameters CurrentTypeParameters {
129 get { return member_context.CurrentTypeParameters; }
132 public MemberCore CurrentTypeDefinition {
133 get { return member_context.CurrentMemberDefinition; }
136 public bool EmitAccurateDebugInfo {
138 return (flags & Options.AccurateDebugInfo) != 0;
142 public bool HasMethodSymbolBuilder {
144 return methodSymbols != null;
148 public bool HasReturnLabel {
150 return return_label.HasValue;
154 public bool IsStatic {
155 get { return member_context.IsStatic; }
158 public bool IsAnonymousStoreyMutateRequired {
160 return CurrentAnonymousMethod != null &&
161 CurrentAnonymousMethod.Storey != null &&
162 CurrentAnonymousMethod.Storey.Mutator != null;
166 public IMemberContext MemberContext {
168 return member_context;
172 public ModuleContainer Module {
174 return member_context.Module;
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 {
182 return member_context.Module.Compiler.Report;
186 public TypeSpec ReturnType {
193 // The label where we have to jump before leaving the context
195 public Label ReturnLabel {
197 return return_label.Value;
201 public List<IExpressionCleanup> StatementEpilogue {
203 return epilogue_expressions;
209 public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
211 if (epilogue_expressions == null) {
212 epilogue_expressions = new List<IExpressionCleanup> ();
213 } else if (epilogue_expressions.Contains (cleanupExpression)) {
217 epilogue_expressions.Add (cleanupExpression);
220 public void AssertEmptyStack ()
223 if (ig.__StackHeight != 0)
224 throw new InternalErrorException ("Await yields with non-empty stack in `{0}",
225 member_context.GetSignatureForError ());
230 /// This is called immediately before emitting an IL opcode to tell the symbol
231 /// writer to which source line this opcode belongs.
233 public bool Mark (Location loc)
235 if ((flags & Options.OmitDebugInfo) != 0)
238 if (loc.IsNull || methodSymbols == null)
241 var sf = loc.SourceFile;
242 if (sf.IsHiddenLocation (loc))
246 methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false);
251 public void MarkCallEntry (Location loc)
253 if (!EmitAccurateDebugInfo)
257 // TODO: This should emit different kind of sequence point to make
258 // step-over work for statement over multiple lines
260 // Debugging experience for Foo (A () + B ()) where A and B are
261 // on separate lines is not great
266 public void DefineLocalVariable (string name, LocalBuilder builder)
268 if ((flags & Options.OmitDebugInfo) != 0)
271 methodSymbols.AddLocal (builder.LocalIndex, name);
274 public void BeginCatchBlock (TypeSpec type)
276 if (IsAnonymousStoreyMutateRequired)
277 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
279 ig.BeginCatchBlock (type.GetMetaInfo ());
282 public void BeginExceptionBlock ()
284 ig.BeginExceptionBlock ();
287 public void BeginFinallyBlock ()
289 ig.BeginFinallyBlock ();
292 public void BeginScope ()
294 if ((flags & Options.OmitDebugInfo) != 0)
298 methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset);
302 public void BeginCompilerScope ()
304 if ((flags & Options.OmitDebugInfo) != 0)
308 methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset);
312 public void EndExceptionBlock ()
314 ig.EndExceptionBlock ();
317 public void EndScope ()
319 if ((flags & Options.OmitDebugInfo) != 0)
323 methodSymbols.EndBlock (ig.ILOffset);
328 // Creates a nested container in this context for all dynamic compiler generated stuff
330 internal DynamicSiteClass CreateDynamicSite ()
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);
336 CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
337 dynamic_site_container.CreateContainer ();
338 dynamic_site_container.DefineContainer ();
339 dynamic_site_container.Define ();
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);
346 return dynamic_site_container;
349 public Label CreateReturnLabel ()
351 if (!return_label.HasValue)
352 return_label = DefineLabel ();
354 return return_label.Value;
357 public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
359 if (IsAnonymousStoreyMutateRequired)
360 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
362 return ig.DeclareLocal (type.GetMetaInfo (), pinned);
365 public Label DefineLabel ()
367 return ig.DefineLabel ();
371 // Creates temporary field in current async storey
373 public StackFieldExpr GetTemporaryField (TypeSpec type)
375 var f = AsyncTaskStorey.AddCapturedLocalVariable (type);
376 var fexpr = new StackFieldExpr (f);
377 fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
381 public void MarkLabel (Label label)
383 ig.MarkLabel (label);
386 public void Emit (OpCode opcode)
391 public void Emit (OpCode opcode, LocalBuilder local)
393 ig.Emit (opcode, local);
396 public void Emit (OpCode opcode, string arg)
398 ig.Emit (opcode, arg);
401 public void Emit (OpCode opcode, double arg)
403 ig.Emit (opcode, arg);
406 public void Emit (OpCode opcode, float arg)
408 ig.Emit (opcode, arg);
411 public void Emit (OpCode opcode, Label label)
413 ig.Emit (opcode, label);
416 public void Emit (OpCode opcode, Label[] labels)
418 ig.Emit (opcode, labels);
421 public void Emit (OpCode opcode, TypeSpec type)
423 if (IsAnonymousStoreyMutateRequired)
424 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
426 ig.Emit (opcode, type.GetMetaInfo ());
429 public void Emit (OpCode opcode, FieldSpec field)
431 if (IsAnonymousStoreyMutateRequired)
432 field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
434 ig.Emit (opcode, field.GetMetaInfo ());
437 public void Emit (OpCode opcode, MethodSpec method)
439 if (IsAnonymousStoreyMutateRequired)
440 method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
442 if (method.IsConstructor)
443 ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
445 ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
448 // TODO: REMOVE breaks mutator
449 public void Emit (OpCode opcode, MethodInfo method)
451 ig.Emit (opcode, method);
454 public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs)
456 // TODO MemberCache: This should mutate too
457 ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
460 public void EmitArrayNew (ArrayContainer ac)
463 var type = IsAnonymousStoreyMutateRequired ?
464 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
467 ig.Emit (OpCodes.Newarr, type.GetMetaInfo ());
469 if (IsAnonymousStoreyMutateRequired)
470 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
472 ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
476 public void EmitArrayAddress (ArrayContainer ac)
479 if (IsAnonymousStoreyMutateRequired)
480 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
482 ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
484 var type = IsAnonymousStoreyMutateRequired ?
485 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
488 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
493 // Emits the right opcode to load from an array
495 public void EmitArrayLoad (ArrayContainer ac)
498 if (IsAnonymousStoreyMutateRequired)
499 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
501 ig.Emit (OpCodes.Call, ac.GetGetMethod ());
506 var type = ac.Element;
507 if (type.Kind == MemberKind.Enum)
508 type = EnumSpec.GetUnderlyingType (type);
510 switch (type.BuiltinType) {
511 case BuiltinTypeSpec.Type.Byte:
512 case BuiltinTypeSpec.Type.Bool:
513 ig.Emit (OpCodes.Ldelem_U1);
515 case BuiltinTypeSpec.Type.SByte:
516 ig.Emit (OpCodes.Ldelem_I1);
518 case BuiltinTypeSpec.Type.Short:
519 ig.Emit (OpCodes.Ldelem_I2);
521 case BuiltinTypeSpec.Type.UShort:
522 case BuiltinTypeSpec.Type.Char:
523 ig.Emit (OpCodes.Ldelem_U2);
525 case BuiltinTypeSpec.Type.Int:
526 ig.Emit (OpCodes.Ldelem_I4);
528 case BuiltinTypeSpec.Type.UInt:
529 ig.Emit (OpCodes.Ldelem_U4);
531 case BuiltinTypeSpec.Type.ULong:
532 case BuiltinTypeSpec.Type.Long:
533 ig.Emit (OpCodes.Ldelem_I8);
535 case BuiltinTypeSpec.Type.Float:
536 ig.Emit (OpCodes.Ldelem_R4);
538 case BuiltinTypeSpec.Type.Double:
539 ig.Emit (OpCodes.Ldelem_R8);
541 case BuiltinTypeSpec.Type.IntPtr:
542 ig.Emit (OpCodes.Ldelem_I);
546 case MemberKind.Struct:
547 if (IsAnonymousStoreyMutateRequired)
548 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
550 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
551 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
553 case MemberKind.TypeParameter:
554 if (IsAnonymousStoreyMutateRequired)
555 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
557 ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ());
559 case MemberKind.PointerType:
560 ig.Emit (OpCodes.Ldelem_I);
563 ig.Emit (OpCodes.Ldelem_Ref);
571 // Emits the right opcode to store to an array
573 public void EmitArrayStore (ArrayContainer ac)
576 if (IsAnonymousStoreyMutateRequired)
577 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
579 ig.Emit (OpCodes.Call, ac.GetSetMethod ());
583 var type = ac.Element;
585 if (type.Kind == MemberKind.Enum)
586 type = EnumSpec.GetUnderlyingType (type);
588 switch (type.BuiltinType) {
589 case BuiltinTypeSpec.Type.Byte:
590 case BuiltinTypeSpec.Type.SByte:
591 case BuiltinTypeSpec.Type.Bool:
592 Emit (OpCodes.Stelem_I1);
594 case BuiltinTypeSpec.Type.Short:
595 case BuiltinTypeSpec.Type.UShort:
596 case BuiltinTypeSpec.Type.Char:
597 Emit (OpCodes.Stelem_I2);
599 case BuiltinTypeSpec.Type.Int:
600 case BuiltinTypeSpec.Type.UInt:
601 Emit (OpCodes.Stelem_I4);
603 case BuiltinTypeSpec.Type.Long:
604 case BuiltinTypeSpec.Type.ULong:
605 Emit (OpCodes.Stelem_I8);
607 case BuiltinTypeSpec.Type.Float:
608 Emit (OpCodes.Stelem_R4);
610 case BuiltinTypeSpec.Type.Double:
611 Emit (OpCodes.Stelem_R8);
616 case MemberKind.Struct:
617 Emit (OpCodes.Stobj, type);
619 case MemberKind.TypeParameter:
620 Emit (OpCodes.Stelem, type);
622 case MemberKind.PointerType:
623 Emit (OpCodes.Stelem_I);
626 Emit (OpCodes.Stelem_Ref);
631 public void EmitInt (int i)
636 void EmitIntConstant (int i)
640 ig.Emit (OpCodes.Ldc_I4_M1);
644 ig.Emit (OpCodes.Ldc_I4_0);
648 ig.Emit (OpCodes.Ldc_I4_1);
652 ig.Emit (OpCodes.Ldc_I4_2);
656 ig.Emit (OpCodes.Ldc_I4_3);
660 ig.Emit (OpCodes.Ldc_I4_4);
664 ig.Emit (OpCodes.Ldc_I4_5);
668 ig.Emit (OpCodes.Ldc_I4_6);
672 ig.Emit (OpCodes.Ldc_I4_7);
676 ig.Emit (OpCodes.Ldc_I4_8);
680 if (i >= -128 && i <= 127) {
681 ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
683 ig.Emit (OpCodes.Ldc_I4, i);
688 public void EmitLong (long l)
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);
697 ig.Emit (OpCodes.Ldc_I8, l);
702 // Load the object from the pointer.
704 public void EmitLoadFromPtr (TypeSpec type)
706 if (type.Kind == MemberKind.Enum)
707 type = EnumSpec.GetUnderlyingType (type);
709 switch (type.BuiltinType) {
710 case BuiltinTypeSpec.Type.Int:
711 ig.Emit (OpCodes.Ldind_I4);
713 case BuiltinTypeSpec.Type.UInt:
714 ig.Emit (OpCodes.Ldind_U4);
716 case BuiltinTypeSpec.Type.Short:
717 ig.Emit (OpCodes.Ldind_I2);
719 case BuiltinTypeSpec.Type.UShort:
720 case BuiltinTypeSpec.Type.Char:
721 ig.Emit (OpCodes.Ldind_U2);
723 case BuiltinTypeSpec.Type.Byte:
724 ig.Emit (OpCodes.Ldind_U1);
726 case BuiltinTypeSpec.Type.SByte:
727 case BuiltinTypeSpec.Type.Bool:
728 ig.Emit (OpCodes.Ldind_I1);
730 case BuiltinTypeSpec.Type.ULong:
731 case BuiltinTypeSpec.Type.Long:
732 ig.Emit (OpCodes.Ldind_I8);
734 case BuiltinTypeSpec.Type.Float:
735 ig.Emit (OpCodes.Ldind_R4);
737 case BuiltinTypeSpec.Type.Double:
738 ig.Emit (OpCodes.Ldind_R8);
740 case BuiltinTypeSpec.Type.IntPtr:
741 ig.Emit (OpCodes.Ldind_I);
745 case MemberKind.Struct:
746 case MemberKind.TypeParameter:
747 if (IsAnonymousStoreyMutateRequired)
748 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
750 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
752 case MemberKind.PointerType:
753 ig.Emit (OpCodes.Ldind_I);
756 ig.Emit (OpCodes.Ldind_Ref);
763 public void EmitNull ()
765 ig.Emit (OpCodes.Ldnull);
768 public void EmitArgumentAddress (int pos)
773 if (pos > byte.MaxValue)
774 ig.Emit (OpCodes.Ldarga, pos);
776 ig.Emit (OpCodes.Ldarga_S, (byte) pos);
779 public void EmitArgumentLoad (int 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;
790 if (pos > byte.MaxValue)
791 ig.Emit (OpCodes.Ldarg, pos);
793 ig.Emit (OpCodes.Ldarg_S, (byte) pos);
798 public void EmitArgumentStore (int pos)
803 if (pos > byte.MaxValue)
804 ig.Emit (OpCodes.Starg, pos);
806 ig.Emit (OpCodes.Starg_S, (byte) pos);
810 // The stack contains the pointer and the value of type `type'
812 public void EmitStoreFromPtr (TypeSpec type)
815 type = EnumSpec.GetUnderlyingType (type);
817 switch (type.BuiltinType) {
818 case BuiltinTypeSpec.Type.Int:
819 case BuiltinTypeSpec.Type.UInt:
820 ig.Emit (OpCodes.Stind_I4);
822 case BuiltinTypeSpec.Type.Long:
823 case BuiltinTypeSpec.Type.ULong:
824 ig.Emit (OpCodes.Stind_I8);
826 case BuiltinTypeSpec.Type.Char:
827 case BuiltinTypeSpec.Type.Short:
828 case BuiltinTypeSpec.Type.UShort:
829 ig.Emit (OpCodes.Stind_I2);
831 case BuiltinTypeSpec.Type.Float:
832 ig.Emit (OpCodes.Stind_R4);
834 case BuiltinTypeSpec.Type.Double:
835 ig.Emit (OpCodes.Stind_R8);
837 case BuiltinTypeSpec.Type.Byte:
838 case BuiltinTypeSpec.Type.SByte:
839 case BuiltinTypeSpec.Type.Bool:
840 ig.Emit (OpCodes.Stind_I1);
842 case BuiltinTypeSpec.Type.IntPtr:
843 ig.Emit (OpCodes.Stind_I);
848 case MemberKind.Struct:
849 case MemberKind.TypeParameter:
850 if (IsAnonymousStoreyMutateRequired)
851 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
853 ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
856 ig.Emit (OpCodes.Stind_Ref);
861 public void EmitThis ()
863 ig.Emit (OpCodes.Ldarg_0);
866 public void EmitEpilogue ()
868 if (epilogue_expressions == null)
871 foreach (var e in epilogue_expressions)
872 e.EmitCleanup (this);
874 epilogue_expressions = null;
878 /// Returns a temporary storage for a variable of type t as
879 /// a local variable in the current body.
881 public LocalBuilder GetTemporaryLocal (TypeSpec t)
883 if (temporary_storage != null) {
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 ();
890 temporary_storage.Remove (t);
894 return (LocalBuilder) o;
896 return DeclareLocal (t, false);
899 public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
901 if (temporary_storage == null) {
902 temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
903 temporary_storage.Add (t, b);
908 if (!temporary_storage.TryGetValue (t, out o)) {
909 temporary_storage.Add (t, b);
912 var s = o as Stack<LocalBuilder>;
914 s = new Stack<LocalBuilder> ();
915 s.Push ((LocalBuilder)o);
916 temporary_storage [t] = s;
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.
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.
933 public LocalBuilder TemporaryReturn ()
935 if (return_value == null){
936 return_value = DeclareLocal (return_type, false);
945 public Expression InstanceExpression;
948 // When set leaves an extra copy of all arguments on the stack
950 public bool DuplicateArguments;
953 // Does not emit InstanceExpression load when InstanceExpressionOnStack
954 // is set. Used by compound assignments.
956 public bool InstanceExpressionOnStack;
959 // Any of arguments contains await expression
961 public bool HasAwaitArguments;
964 // When dealing with await arguments the original arguments are converted
965 // into a new set with hoisted stack results
967 public Arguments EmittedArguments;
969 public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
971 EmitPredefined (ec, method, Arguments, loc);
974 public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, Location? loc = null)
976 Expression instance_copy = null;
978 if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) {
979 HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait ();
980 if (HasAwaitArguments && InstanceExpressionOnStack) {
981 throw new NotSupportedException ();
986 LocalTemporary lt = null;
988 if (method.IsStatic) {
989 call_op = OpCodes.Call;
991 if (IsVirtualCallRequired (InstanceExpression, method)) {
992 call_op = OpCodes.Callvirt;
994 call_op = OpCodes.Call;
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);
1004 if (DuplicateArguments) {
1005 ec.Emit (OpCodes.Dup);
1006 if (Arguments != null && Arguments.Count != 0) {
1007 lt = new LocalTemporary (instance_on_stack_type);
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);
1025 EmittedArguments.Emit (ec);
1029 if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStruct)) {
1030 ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
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
1038 ec.MarkCallEntry (loc.Value);
1042 // Set instance expression to actual result expression. When it contains await it can be
1043 // picked up by caller
1045 InstanceExpression = instance_copy;
1047 if (method.Parameters.HasArglist) {
1048 var varargs_types = GetVarargsTypes (method, Arguments);
1049 ec.Emit (call_op, method, varargs_types);
1056 // and DoFoo is not virtual, you can omit the callvirt,
1057 // because you don't need the null checking behavior.
1059 ec.Emit (call_op, method);
1062 static TypeSpec EmitCallInstance (EmitContext ec, Expression instance, TypeSpec declaringType, OpCode callOpcode)
1064 var instance_type = instance.Type;
1067 // Push the instance expression
1069 if ((instance_type.IsStruct && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
1070 instance_type.IsGenericParameter || declaringType.IsNullableType) {
1072 // If the expression implements IMemoryLocation, then
1073 // we can optimize and use AddressOf on the
1076 // If not we have to use some temporary storage for
1078 var iml = instance as IMemoryLocation;
1080 iml.AddressOf (ec, AddressOp.Load);
1082 LocalTemporary temp = new LocalTemporary (instance_type);
1085 temp.AddressOf (ec, AddressOp.Load);
1088 return ReferenceContainer.MakeType (ec.Module, instance_type);
1091 if (instance_type.IsEnum || instance_type.IsStruct) {
1093 ec.Emit (OpCodes.Box, instance_type);
1094 return ec.BuiltinTypes.Object;
1098 return instance_type;
1101 static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments)
1103 AParametersCollection pd = method.Parameters;
1105 Argument a = arguments[pd.Count - 1];
1106 Arglist list = (Arglist) a.Expr;
1108 return list.ArgumentTypes;
1112 // Used to decide whether call or callvirt is needed
1114 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
1117 // There are 2 scenarious where we emit callvirt
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
1123 var decl_type = method.DeclaringType;
1124 if (decl_type.IsStruct || decl_type.IsEnum)
1127 if (instance is BaseThis)
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
1134 if (!method.IsVirtual && (instance is This || instance is New || instance is ArrayCreation || instance is DelegateCreation) &&
1135 !instance.Type.IsGenericParameter)