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 ConditionalAccessContext ConditionalAccess { get; set; }
126 public TypeSpec CurrentType {
127 get { return member_context.CurrentType; }
130 public TypeParameters CurrentTypeParameters {
131 get { return member_context.CurrentTypeParameters; }
134 public MemberCore CurrentTypeDefinition {
135 get { return member_context.CurrentMemberDefinition; }
138 public bool EmitAccurateDebugInfo {
140 return (flags & Options.AccurateDebugInfo) != 0;
144 public bool HasMethodSymbolBuilder {
146 return methodSymbols != null;
150 public bool HasReturnLabel {
152 return return_label.HasValue;
156 public bool IsStatic {
157 get { return member_context.IsStatic; }
160 public bool IsStaticConstructor {
162 return member_context.IsStatic && (flags & Options.ConstructorScope) != 0;
166 public bool IsAnonymousStoreyMutateRequired {
168 return CurrentAnonymousMethod != null &&
169 CurrentAnonymousMethod.Storey != null &&
170 CurrentAnonymousMethod.Storey.Mutator != null;
174 public IMemberContext MemberContext {
176 return member_context;
180 public ModuleContainer Module {
182 return member_context.Module;
186 public bool NotifyEvaluatorOnStore {
188 return Module.Evaluator != null && Module.Evaluator.ModificationListener != null;
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 {
196 return member_context.Module.Compiler.Report;
200 public TypeSpec ReturnType {
207 // The label where we have to jump before leaving the context
209 public Label ReturnLabel {
211 return return_label.Value;
215 public List<IExpressionCleanup> StatementEpilogue {
217 return epilogue_expressions;
221 public LocalVariable AsyncThrowVariable { get; set; }
223 public List<TryFinally> TryFinallyUnwind { get; set; }
227 public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
229 if (epilogue_expressions == null) {
230 epilogue_expressions = new List<IExpressionCleanup> ();
231 } else if (epilogue_expressions.Contains (cleanupExpression)) {
235 epilogue_expressions.Add (cleanupExpression);
238 public void AssertEmptyStack ()
241 if (ig.__StackHeight != 0)
242 throw new InternalErrorException ("Await yields with non-empty stack in `{0}",
243 member_context.GetSignatureForError ());
248 /// This is called immediately before emitting an IL opcode to tell the symbol
249 /// writer to which source line this opcode belongs.
251 public bool Mark (Location loc)
253 if ((flags & Options.OmitDebugInfo) != 0)
256 if (loc.IsNull || methodSymbols == null)
259 var sf = loc.SourceFile;
260 if (sf.IsHiddenLocation (loc))
264 methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false);
269 public void MarkCallEntry (Location loc)
271 if (!EmitAccurateDebugInfo)
275 // TODO: This should emit different kind of sequence point to make
276 // step-over work for statement over multiple lines
278 // Debugging experience for Foo (A () + B ()) where A and B are
279 // on separate lines is not great
284 public void DefineLocalVariable (string name, LocalBuilder builder)
286 if ((flags & Options.OmitDebugInfo) != 0)
289 methodSymbols.AddLocal (builder.LocalIndex, name);
292 public void BeginCatchBlock (TypeSpec type)
294 if (IsAnonymousStoreyMutateRequired)
295 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
297 ig.BeginCatchBlock (type.GetMetaInfo ());
300 public void BeginFilterHandler ()
302 ig.BeginCatchBlock (null);
305 public void BeginExceptionBlock ()
307 ig.BeginExceptionBlock ();
310 public void BeginExceptionFilterBlock ()
312 ig.BeginExceptFilterBlock ();
315 public void BeginFinallyBlock ()
317 ig.BeginFinallyBlock ();
320 public void BeginScope ()
322 if ((flags & Options.OmitDebugInfo) != 0)
326 methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset);
330 public void BeginCompilerScope ()
332 if ((flags & Options.OmitDebugInfo) != 0)
336 methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset);
340 public void EndExceptionBlock ()
342 ig.EndExceptionBlock ();
345 public void EndScope ()
347 if ((flags & Options.OmitDebugInfo) != 0)
351 methodSymbols.EndBlock (ig.ILOffset);
355 public void CloseConditionalAccess (TypeSpec type)
358 Emit (OpCodes.Newobj, Nullable.NullableInfo.GetConstructor (type));
360 MarkLabel (ConditionalAccess.EndLabel);
361 ConditionalAccess = null;
365 // Creates a nested container in this context for all dynamic compiler generated stuff
367 internal DynamicSiteClass CreateDynamicSite ()
369 if (dynamic_site_container == null) {
370 var mc = member_context.CurrentMemberDefinition as MemberBase;
371 dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters);
373 CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
374 dynamic_site_container.CreateContainer ();
375 dynamic_site_container.DefineContainer ();
376 dynamic_site_container.Define ();
378 var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
379 var inflated = dynamic_site_container.CurrentType.InflateMember (inflator);
380 CurrentType.MemberCache.AddMember (inflated);
383 return dynamic_site_container;
386 public Label CreateReturnLabel ()
388 if (!return_label.HasValue)
389 return_label = DefineLabel ();
391 return return_label.Value;
394 public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
396 if (IsAnonymousStoreyMutateRequired)
397 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
399 return ig.DeclareLocal (type.GetMetaInfo (), pinned);
402 public Label DefineLabel ()
404 return ig.DefineLabel ();
408 // Creates temporary field in current async storey
410 public StackFieldExpr GetTemporaryField (TypeSpec type, bool initializedFieldRequired = false)
412 var f = AsyncTaskStorey.AddCapturedLocalVariable (type, initializedFieldRequired);
413 var fexpr = new StackFieldExpr (f);
414 fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
418 public void MarkLabel (Label label)
420 ig.MarkLabel (label);
423 public void Emit (OpCode opcode)
428 public void Emit (OpCode opcode, LocalBuilder local)
430 ig.Emit (opcode, local);
433 public void Emit (OpCode opcode, string arg)
435 ig.Emit (opcode, arg);
438 public void Emit (OpCode opcode, double arg)
440 ig.Emit (opcode, arg);
443 public void Emit (OpCode opcode, float arg)
445 ig.Emit (opcode, arg);
448 public void Emit (OpCode opcode, Label label)
450 ig.Emit (opcode, label);
453 public void Emit (OpCode opcode, Label[] labels)
455 ig.Emit (opcode, labels);
458 public void Emit (OpCode opcode, TypeSpec type)
460 if (IsAnonymousStoreyMutateRequired)
461 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
463 ig.Emit (opcode, type.GetMetaInfo ());
466 public void Emit (OpCode opcode, FieldSpec field)
468 if (IsAnonymousStoreyMutateRequired)
469 field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
471 ig.Emit (opcode, field.GetMetaInfo ());
474 public void Emit (OpCode opcode, MethodSpec method)
476 if (IsAnonymousStoreyMutateRequired)
477 method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
479 if (method.IsConstructor)
480 ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
482 ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
485 // TODO: REMOVE breaks mutator
486 public void Emit (OpCode opcode, MethodInfo method)
488 ig.Emit (opcode, method);
491 public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs)
493 // TODO MemberCache: This should mutate too
494 ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
497 public void EmitArrayNew (ArrayContainer ac)
500 var type = IsAnonymousStoreyMutateRequired ?
501 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
504 ig.Emit (OpCodes.Newarr, type.GetMetaInfo ());
506 if (IsAnonymousStoreyMutateRequired)
507 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
509 ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
513 public void EmitArrayAddress (ArrayContainer ac)
516 if (IsAnonymousStoreyMutateRequired)
517 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
519 ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
521 var type = IsAnonymousStoreyMutateRequired ?
522 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
525 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
530 // Emits the right opcode to load from an array
532 public void EmitArrayLoad (ArrayContainer ac)
535 if (IsAnonymousStoreyMutateRequired)
536 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
538 ig.Emit (OpCodes.Call, ac.GetGetMethod ());
543 var type = ac.Element;
544 if (type.Kind == MemberKind.Enum)
545 type = EnumSpec.GetUnderlyingType (type);
547 switch (type.BuiltinType) {
548 case BuiltinTypeSpec.Type.Bool:
550 // Workaround MSIL limitation. Load bool element as single bit,
551 // bool array can actually store any byte value
553 ig.Emit (OpCodes.Ldelem_U1);
554 ig.Emit (OpCodes.Ldc_I4_0);
555 ig.Emit (OpCodes.Cgt_Un);
557 case BuiltinTypeSpec.Type.Byte:
558 ig.Emit (OpCodes.Ldelem_U1);
560 case BuiltinTypeSpec.Type.SByte:
561 ig.Emit (OpCodes.Ldelem_I1);
563 case BuiltinTypeSpec.Type.Short:
564 ig.Emit (OpCodes.Ldelem_I2);
566 case BuiltinTypeSpec.Type.UShort:
567 case BuiltinTypeSpec.Type.Char:
568 ig.Emit (OpCodes.Ldelem_U2);
570 case BuiltinTypeSpec.Type.Int:
571 ig.Emit (OpCodes.Ldelem_I4);
573 case BuiltinTypeSpec.Type.UInt:
574 ig.Emit (OpCodes.Ldelem_U4);
576 case BuiltinTypeSpec.Type.ULong:
577 case BuiltinTypeSpec.Type.Long:
578 ig.Emit (OpCodes.Ldelem_I8);
580 case BuiltinTypeSpec.Type.Float:
581 ig.Emit (OpCodes.Ldelem_R4);
583 case BuiltinTypeSpec.Type.Double:
584 ig.Emit (OpCodes.Ldelem_R8);
586 case BuiltinTypeSpec.Type.IntPtr:
587 ig.Emit (OpCodes.Ldelem_I);
591 case MemberKind.Struct:
592 if (IsAnonymousStoreyMutateRequired)
593 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
595 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
596 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
598 case MemberKind.TypeParameter:
599 if (IsAnonymousStoreyMutateRequired)
600 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
602 ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ());
604 case MemberKind.PointerType:
605 ig.Emit (OpCodes.Ldelem_I);
608 ig.Emit (OpCodes.Ldelem_Ref);
616 // Emits the right opcode to store to an array
618 public void EmitArrayStore (ArrayContainer ac)
621 if (IsAnonymousStoreyMutateRequired)
622 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
624 ig.Emit (OpCodes.Call, ac.GetSetMethod ());
628 var type = ac.Element;
630 if (type.Kind == MemberKind.Enum)
631 type = EnumSpec.GetUnderlyingType (type);
633 switch (type.BuiltinType) {
634 case BuiltinTypeSpec.Type.Byte:
635 case BuiltinTypeSpec.Type.SByte:
636 case BuiltinTypeSpec.Type.Bool:
637 Emit (OpCodes.Stelem_I1);
639 case BuiltinTypeSpec.Type.Short:
640 case BuiltinTypeSpec.Type.UShort:
641 case BuiltinTypeSpec.Type.Char:
642 Emit (OpCodes.Stelem_I2);
644 case BuiltinTypeSpec.Type.Int:
645 case BuiltinTypeSpec.Type.UInt:
646 Emit (OpCodes.Stelem_I4);
648 case BuiltinTypeSpec.Type.Long:
649 case BuiltinTypeSpec.Type.ULong:
650 Emit (OpCodes.Stelem_I8);
652 case BuiltinTypeSpec.Type.Float:
653 Emit (OpCodes.Stelem_R4);
655 case BuiltinTypeSpec.Type.Double:
656 Emit (OpCodes.Stelem_R8);
661 case MemberKind.Struct:
662 Emit (OpCodes.Stobj, type);
664 case MemberKind.TypeParameter:
665 Emit (OpCodes.Stelem, type);
667 case MemberKind.PointerType:
668 Emit (OpCodes.Stelem_I);
671 Emit (OpCodes.Stelem_Ref);
676 public void EmitInt (int i)
681 void EmitIntConstant (int i)
685 ig.Emit (OpCodes.Ldc_I4_M1);
689 ig.Emit (OpCodes.Ldc_I4_0);
693 ig.Emit (OpCodes.Ldc_I4_1);
697 ig.Emit (OpCodes.Ldc_I4_2);
701 ig.Emit (OpCodes.Ldc_I4_3);
705 ig.Emit (OpCodes.Ldc_I4_4);
709 ig.Emit (OpCodes.Ldc_I4_5);
713 ig.Emit (OpCodes.Ldc_I4_6);
717 ig.Emit (OpCodes.Ldc_I4_7);
721 ig.Emit (OpCodes.Ldc_I4_8);
725 if (i >= -128 && i <= 127) {
726 ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
728 ig.Emit (OpCodes.Ldc_I4, i);
733 public void EmitLong (long l)
735 if (l >= int.MinValue && l <= int.MaxValue) {
736 EmitIntConstant (unchecked ((int) l));
737 ig.Emit (OpCodes.Conv_I8);
738 } else if (l >= 0 && l <= uint.MaxValue) {
739 EmitIntConstant (unchecked ((int) l));
740 ig.Emit (OpCodes.Conv_U8);
742 ig.Emit (OpCodes.Ldc_I8, l);
747 // Load the object from the pointer.
749 public void EmitLoadFromPtr (TypeSpec type)
751 if (type.Kind == MemberKind.Enum)
752 type = EnumSpec.GetUnderlyingType (type);
754 switch (type.BuiltinType) {
755 case BuiltinTypeSpec.Type.Int:
756 ig.Emit (OpCodes.Ldind_I4);
758 case BuiltinTypeSpec.Type.UInt:
759 ig.Emit (OpCodes.Ldind_U4);
761 case BuiltinTypeSpec.Type.Short:
762 ig.Emit (OpCodes.Ldind_I2);
764 case BuiltinTypeSpec.Type.UShort:
765 case BuiltinTypeSpec.Type.Char:
766 ig.Emit (OpCodes.Ldind_U2);
768 case BuiltinTypeSpec.Type.Byte:
769 ig.Emit (OpCodes.Ldind_U1);
771 case BuiltinTypeSpec.Type.SByte:
772 ig.Emit (OpCodes.Ldind_I1);
774 case BuiltinTypeSpec.Type.Bool:
775 ig.Emit (OpCodes.Ldind_I1);
776 ig.Emit (OpCodes.Ldc_I4_0);
777 ig.Emit (OpCodes.Cgt_Un);
779 case BuiltinTypeSpec.Type.ULong:
780 case BuiltinTypeSpec.Type.Long:
781 ig.Emit (OpCodes.Ldind_I8);
783 case BuiltinTypeSpec.Type.Float:
784 ig.Emit (OpCodes.Ldind_R4);
786 case BuiltinTypeSpec.Type.Double:
787 ig.Emit (OpCodes.Ldind_R8);
789 case BuiltinTypeSpec.Type.IntPtr:
790 ig.Emit (OpCodes.Ldind_I);
794 case MemberKind.Struct:
795 case MemberKind.TypeParameter:
796 if (IsAnonymousStoreyMutateRequired)
797 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
799 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
801 case MemberKind.PointerType:
802 ig.Emit (OpCodes.Ldind_I);
805 ig.Emit (OpCodes.Ldind_Ref);
812 public void EmitNull ()
814 ig.Emit (OpCodes.Ldnull);
817 public void EmitArgumentAddress (int pos)
822 if (pos > byte.MaxValue)
823 ig.Emit (OpCodes.Ldarga, pos);
825 ig.Emit (OpCodes.Ldarga_S, (byte) pos);
828 public void EmitArgumentLoad (int pos)
834 case 0: ig.Emit (OpCodes.Ldarg_0); break;
835 case 1: ig.Emit (OpCodes.Ldarg_1); break;
836 case 2: ig.Emit (OpCodes.Ldarg_2); break;
837 case 3: ig.Emit (OpCodes.Ldarg_3); break;
839 if (pos > byte.MaxValue)
840 ig.Emit (OpCodes.Ldarg, pos);
842 ig.Emit (OpCodes.Ldarg_S, (byte) pos);
847 public void EmitArgumentStore (int pos)
852 if (pos > byte.MaxValue)
853 ig.Emit (OpCodes.Starg, pos);
855 ig.Emit (OpCodes.Starg_S, (byte) pos);
859 // The stack contains the pointer and the value of type `type'
861 public void EmitStoreFromPtr (TypeSpec type)
864 type = EnumSpec.GetUnderlyingType (type);
866 switch (type.BuiltinType) {
867 case BuiltinTypeSpec.Type.Int:
868 case BuiltinTypeSpec.Type.UInt:
869 ig.Emit (OpCodes.Stind_I4);
871 case BuiltinTypeSpec.Type.Long:
872 case BuiltinTypeSpec.Type.ULong:
873 ig.Emit (OpCodes.Stind_I8);
875 case BuiltinTypeSpec.Type.Char:
876 case BuiltinTypeSpec.Type.Short:
877 case BuiltinTypeSpec.Type.UShort:
878 ig.Emit (OpCodes.Stind_I2);
880 case BuiltinTypeSpec.Type.Float:
881 ig.Emit (OpCodes.Stind_R4);
883 case BuiltinTypeSpec.Type.Double:
884 ig.Emit (OpCodes.Stind_R8);
886 case BuiltinTypeSpec.Type.Byte:
887 case BuiltinTypeSpec.Type.SByte:
888 case BuiltinTypeSpec.Type.Bool:
889 ig.Emit (OpCodes.Stind_I1);
891 case BuiltinTypeSpec.Type.IntPtr:
892 ig.Emit (OpCodes.Stind_I);
897 case MemberKind.Struct:
898 case MemberKind.TypeParameter:
899 if (IsAnonymousStoreyMutateRequired)
900 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
902 ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
905 ig.Emit (OpCodes.Stind_Ref);
910 public void EmitThis ()
912 ig.Emit (OpCodes.Ldarg_0);
915 public void EmitEpilogue ()
917 if (epilogue_expressions == null)
920 foreach (var e in epilogue_expressions)
921 e.EmitCleanup (this);
923 epilogue_expressions = null;
927 /// Returns a temporary storage for a variable of type t as
928 /// a local variable in the current body.
930 public LocalBuilder GetTemporaryLocal (TypeSpec t)
932 if (temporary_storage != null) {
934 if (temporary_storage.TryGetValue (t, out o)) {
935 if (o is Stack<LocalBuilder>) {
936 var s = (Stack<LocalBuilder>) o;
937 o = s.Count == 0 ? null : s.Pop ();
939 temporary_storage.Remove (t);
943 return (LocalBuilder) o;
945 return DeclareLocal (t, false);
948 public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
950 if (temporary_storage == null) {
951 temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
952 temporary_storage.Add (t, b);
957 if (!temporary_storage.TryGetValue (t, out o)) {
958 temporary_storage.Add (t, b);
961 var s = o as Stack<LocalBuilder>;
963 s = new Stack<LocalBuilder> ();
964 s.Push ((LocalBuilder)o);
965 temporary_storage [t] = s;
971 /// ReturnValue creates on demand the LocalBuilder for the
972 /// return value from the function. By default this is not
973 /// used. This is only required when returns are found inside
974 /// Try or Catch statements.
976 /// This method is typically invoked from the Emit phase, so
977 /// we allow the creation of a return label if it was not
978 /// requested during the resolution phase. Could be cleaned
979 /// up, but it would replicate a lot of logic in the Emit phase
980 /// of the code that uses it.
982 public LocalBuilder TemporaryReturn ()
984 if (return_value == null){
985 return_value = DeclareLocal (return_type, false);
992 public class ConditionalAccessContext
994 public ConditionalAccessContext (TypeSpec type, Label endLabel)
1000 public bool Statement { get; set; }
1001 public Label EndLabel { get; private set; }
1002 public TypeSpec Type { get; private set; }
1007 public Expression InstanceExpression;
1010 // When call has to leave an extra copy of all arguments on the stack
1012 public bool DuplicateArguments;
1015 // Does not emit InstanceExpression load when InstanceExpressionOnStack
1016 // is set. Used by compound assignments.
1018 public bool InstanceExpressionOnStack;
1021 // Any of arguments contains await expression
1023 public bool HasAwaitArguments;
1025 public bool ConditionalAccess;
1028 // When dealing with await arguments the original arguments are converted
1029 // into a new set with hoisted stack results
1031 public Arguments EmittedArguments;
1033 public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
1035 EmitPredefined (ec, method, Arguments, false, loc);
1038 public void EmitStatement (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
1040 EmitPredefined (ec, method, Arguments, true, loc);
1043 public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, bool statement = false, Location? loc = null)
1045 Expression instance_copy = null;
1047 if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) {
1048 HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait ();
1049 if (HasAwaitArguments && InstanceExpressionOnStack) {
1050 throw new NotSupportedException ();
1055 LocalTemporary lt = null;
1057 if (method.IsStatic) {
1058 call_op = OpCodes.Call;
1060 call_op = IsVirtualCallRequired (InstanceExpression, method) ? OpCodes.Callvirt : OpCodes.Call;
1062 if (HasAwaitArguments) {
1063 instance_copy = InstanceExpression.EmitToField (ec);
1064 var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType));
1066 if (Arguments == null) {
1069 } else if (!InstanceExpressionOnStack) {
1070 var ie = new InstanceEmitter (InstanceExpression, IsAddressCall (InstanceExpression, call_op, method.DeclaringType));
1071 ie.Emit (ec, ConditionalAccess);
1073 if (DuplicateArguments) {
1074 ec.Emit (OpCodes.Dup);
1075 if (Arguments != null && Arguments.Count != 0) {
1076 lt = new LocalTemporary (ie.GetStackType (ec));
1084 if (Arguments != null && !InstanceExpressionOnStack) {
1085 EmittedArguments = Arguments.Emit (ec, DuplicateArguments, HasAwaitArguments);
1086 if (EmittedArguments != null) {
1087 if (instance_copy != null) {
1088 var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType));
1089 ie.Emit (ec, ConditionalAccess);
1095 EmittedArguments.Emit (ec);
1099 if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStructOrEnum)) {
1100 ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
1105 // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
1106 // break at right place when LHS expression can be stepped-into
1108 ec.MarkCallEntry (loc.Value);
1112 // Set instance expression to actual result expression. When it contains await it can be
1113 // picked up by caller
1115 InstanceExpression = instance_copy;
1117 if (method.Parameters.HasArglist) {
1118 var varargs_types = GetVarargsTypes (method, Arguments);
1119 ec.Emit (call_op, method, varargs_types);
1124 // and DoFoo is not virtual, you can omit the callvirt,
1125 // because you don't need the null checking behavior.
1127 ec.Emit (call_op, method);
1131 // Pop the return value if there is one and stack should be empty
1133 if (statement && method.ReturnType.Kind != MemberKind.Void)
1134 ec.Emit (OpCodes.Pop);
1137 static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments)
1139 AParametersCollection pd = method.Parameters;
1141 Argument a = arguments[pd.Count - 1];
1142 Arglist list = (Arglist) a.Expr;
1144 return list.ArgumentTypes;
1148 // Used to decide whether call or callvirt is needed
1150 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
1153 // There are 2 scenarious where we emit callvirt
1155 // Case 1: A method is virtual and it's not used to call base
1156 // Case 2: A method instance expression can be null. In this casen callvirt ensures
1157 // correct NRE exception when the method is called
1159 var decl_type = method.DeclaringType;
1160 if (decl_type.IsStruct || decl_type.IsEnum)
1163 if (instance is BaseThis)
1167 // It's non-virtual and will never be null and it can be determined
1168 // whether it's known value or reference type by verifier
1170 if (!method.IsVirtual && Expression.IsNeverNull (instance) && !instance.Type.IsGenericParameter)
1176 static bool IsAddressCall (Expression instance, OpCode callOpcode, TypeSpec declaringType)
1178 var instance_type = instance.Type;
1179 return (instance_type.IsStructOrEnum && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
1180 instance_type.IsGenericParameter || declaringType.IsNullableType;
1184 public struct InstanceEmitter
1186 readonly Expression instance;
1187 readonly bool addressRequired;
1189 public InstanceEmitter (Expression instance, bool addressLoad)
1191 this.instance = instance;
1192 this.addressRequired = addressLoad;
1195 public void Emit (EmitContext ec, bool conditionalAccess)
1197 Label NullOperatorLabel;
1198 Nullable.Unwrap unwrap;
1200 if (conditionalAccess && Expression.IsNeverNull (instance))
1201 conditionalAccess = false;
1203 if (conditionalAccess) {
1204 NullOperatorLabel = ec.DefineLabel ();
1205 unwrap = instance as Nullable.Unwrap;
1207 NullOperatorLabel = new Label ();
1211 IMemoryLocation instance_address = null;
1212 bool conditional_access_dup = false;
1214 if (unwrap != null) {
1216 unwrap.EmitCheck (ec);
1217 ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel);
1219 if (conditionalAccess && addressRequired) {
1221 // Don't allocate temp variable when instance load is cheap and load and load-address
1222 // operate on same memory
1224 instance_address = instance as VariableReference;
1225 if (instance_address == null)
1226 instance_address = instance as LocalTemporary;
1228 if (instance_address == null) {
1230 ec.Emit (OpCodes.Dup);
1231 ec.EmitLoadFromPtr (instance.Type);
1233 conditional_access_dup = true;
1238 if (instance.Type.Kind == MemberKind.TypeParameter)
1239 ec.Emit (OpCodes.Box, instance.Type);
1243 if (conditionalAccess) {
1244 conditional_access_dup = !IsInexpensiveLoad ();
1245 if (conditional_access_dup)
1246 ec.Emit (OpCodes.Dup);
1250 if (conditionalAccess) {
1251 ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel);
1253 if (conditional_access_dup)
1254 ec.Emit (OpCodes.Pop);
1258 if (conditionalAccess) {
1259 if (!ec.ConditionalAccess.Statement) {
1260 if (ec.ConditionalAccess.Type.IsNullableType)
1261 Nullable.LiftedNull.Create (ec.ConditionalAccess.Type, Location.Null).Emit (ec);
1266 ec.Emit (OpCodes.Br, ec.ConditionalAccess.EndLabel);
1267 ec.MarkLabel (NullOperatorLabel);
1269 if (instance_address != null) {
1270 instance_address.AddressOf (ec, AddressOp.Load);
1271 } else if (unwrap != null) {
1273 var tmp = ec.GetTemporaryLocal (unwrap.Type);
1274 ec.Emit (OpCodes.Stloc, tmp);
1275 ec.Emit (OpCodes.Ldloca, tmp);
1276 ec.FreeTemporaryLocal (tmp, unwrap.Type);
1277 } else if (!conditional_access_dup) {
1283 public void EmitLoad (EmitContext ec)
1285 var instance_type = instance.Type;
1288 // Push the instance expression
1290 if (addressRequired) {
1292 // If the expression implements IMemoryLocation, then
1293 // we can optimize and use AddressOf on the
1296 // If not we have to use some temporary storage for
1298 var iml = instance as IMemoryLocation;
1300 iml.AddressOf (ec, AddressOp.Load);
1302 LocalTemporary temp = new LocalTemporary (instance_type);
1305 temp.AddressOf (ec, AddressOp.Load);
1313 // Only to make verifier happy
1314 if (RequiresBoxing ())
1315 ec.Emit (OpCodes.Box, instance_type);
1318 public TypeSpec GetStackType (EmitContext ec)
1320 var instance_type = instance.Type;
1322 if (addressRequired)
1323 return ReferenceContainer.MakeType (ec.Module, instance_type);
1325 if (instance_type.IsStructOrEnum)
1326 return ec.Module.Compiler.BuiltinTypes.Object;
1328 return instance_type;
1331 bool RequiresBoxing ()
1333 var instance_type = instance.Type;
1334 if (instance_type.IsGenericParameter && !(instance is This) && TypeSpec.IsReferenceType (instance_type))
1337 if (instance_type.IsStructOrEnum)
1343 bool IsInexpensiveLoad ()
1345 if (instance is Constant)
1346 return instance.IsSideEffectFree;
1348 if (RequiresBoxing ())
1351 var vr = instance as VariableReference;
1355 if (instance is LocalTemporary)
1358 var fe = instance as FieldExpr;
1360 return fe.IsStatic || fe.InstanceExpression is This;