2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 using System.Collections;
21 public abstract class Statement {
25 /// Resolves the statement, true means that all sub-statements
28 public virtual bool Resolve (EmitContext ec)
34 /// We already know that the statement is unreachable, but we still
35 /// need to resolve it to catch errors.
37 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
40 // This conflicts with csc's way of doing this, but IMHO it's
41 // the right thing to do.
43 // If something is unreachable, we still check whether it's
44 // correct. This means that you cannot use unassigned variables
45 // in unreachable code, for instance.
48 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
49 bool ok = Resolve (ec);
50 ec.KillFlowBranching ();
55 if (warn && (RootContext.WarningLevel >= 2))
56 Report.Warning (162, loc, "Unreachable code detected");
60 protected void CheckObsolete (Type type)
62 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
63 if (obsolete_attr == null)
66 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
70 /// Return value indicates whether all code paths emitted return.
72 protected abstract void DoEmit (EmitContext ec);
75 /// Utility wrapper routine for Error, just to beautify the code
77 public void Error (int error, string format, params object[] args)
79 Error (error, String.Format (format, args));
82 public void Error (int error, string s)
84 if (!Location.IsNull (loc))
85 Report.Error (error, loc, s);
87 Report.Error (error, s);
91 /// Return value indicates whether all code paths emitted return.
93 public virtual void Emit (EmitContext ec)
100 public sealed class EmptyStatement : Statement {
102 private EmptyStatement () {}
104 public static readonly EmptyStatement Value = new EmptyStatement ();
106 public override bool Resolve (EmitContext ec)
111 protected override void DoEmit (EmitContext ec)
116 public class If : Statement {
118 public Statement TrueStatement;
119 public Statement FalseStatement;
123 public If (Expression expr, Statement trueStatement, Location l)
126 TrueStatement = trueStatement;
130 public If (Expression expr,
131 Statement trueStatement,
132 Statement falseStatement,
136 TrueStatement = trueStatement;
137 FalseStatement = falseStatement;
141 public override bool Resolve (EmitContext ec)
143 Report.Debug (1, "START IF BLOCK", loc);
145 expr = Expression.ResolveBoolean (ec, expr, loc);
151 // Dead code elimination
153 if (expr is BoolConstant){
154 bool take = ((BoolConstant) expr).Value;
157 if (!TrueStatement.Resolve (ec))
160 if ((FalseStatement != null) &&
161 !FalseStatement.ResolveUnreachable (ec, true))
163 FalseStatement = null;
165 if (!TrueStatement.ResolveUnreachable (ec, true))
167 TrueStatement = null;
169 if ((FalseStatement != null) &&
170 !FalseStatement.Resolve (ec))
177 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
179 bool ok = TrueStatement.Resolve (ec);
181 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
183 ec.CurrentBranching.CreateSibling ();
185 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
188 ec.EndFlowBranching ();
190 Report.Debug (1, "END IF BLOCK", loc);
195 protected override void DoEmit (EmitContext ec)
197 ILGenerator ig = ec.ig;
198 Label false_target = ig.DefineLabel ();
202 // If we're a boolean expression, Resolve() already
203 // eliminated dead code for us.
205 if (expr is BoolConstant){
206 bool take = ((BoolConstant) expr).Value;
209 TrueStatement.Emit (ec);
210 else if (FalseStatement != null)
211 FalseStatement.Emit (ec);
216 expr.EmitBranchable (ec, false_target, false);
218 TrueStatement.Emit (ec);
220 if (FalseStatement != null){
221 bool branch_emitted = false;
223 end = ig.DefineLabel ();
225 ig.Emit (OpCodes.Br, end);
226 branch_emitted = true;
229 ig.MarkLabel (false_target);
230 FalseStatement.Emit (ec);
235 ig.MarkLabel (false_target);
240 public class Do : Statement {
241 public Expression expr;
242 public readonly Statement EmbeddedStatement;
245 public Do (Statement statement, Expression boolExpr, Location l)
248 EmbeddedStatement = statement;
252 public override bool Resolve (EmitContext ec)
256 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
258 if (!EmbeddedStatement.Resolve (ec))
261 expr = Expression.ResolveBoolean (ec, expr, loc);
264 else if (expr is BoolConstant){
265 bool res = ((BoolConstant) expr).Value;
271 ec.CurrentBranching.Infinite = infinite;
272 ec.EndFlowBranching ();
277 protected override void DoEmit (EmitContext ec)
279 ILGenerator ig = ec.ig;
280 Label loop = ig.DefineLabel ();
281 Label old_begin = ec.LoopBegin;
282 Label old_end = ec.LoopEnd;
284 ec.LoopBegin = ig.DefineLabel ();
285 ec.LoopEnd = ig.DefineLabel ();
288 EmbeddedStatement.Emit (ec);
289 ig.MarkLabel (ec.LoopBegin);
292 // Dead code elimination
294 if (expr is BoolConstant){
295 bool res = ((BoolConstant) expr).Value;
298 ec.ig.Emit (OpCodes.Br, loop);
300 expr.EmitBranchable (ec, loop, true);
302 ig.MarkLabel (ec.LoopEnd);
304 ec.LoopBegin = old_begin;
305 ec.LoopEnd = old_end;
309 public class While : Statement {
310 public Expression expr;
311 public readonly Statement Statement;
312 bool infinite, empty;
314 public While (Expression boolExpr, Statement statement, Location l)
316 this.expr = boolExpr;
317 Statement = statement;
321 public override bool Resolve (EmitContext ec)
325 expr = Expression.ResolveBoolean (ec, expr, loc);
330 // Inform whether we are infinite or not
332 if (expr is BoolConstant){
333 BoolConstant bc = (BoolConstant) expr;
335 if (bc.Value == false){
336 if (!Statement.ResolveUnreachable (ec, true))
344 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
346 if (!Statement.Resolve (ec))
349 ec.CurrentBranching.Infinite = infinite;
350 ec.EndFlowBranching ();
355 protected override void DoEmit (EmitContext ec)
360 ILGenerator ig = ec.ig;
361 Label old_begin = ec.LoopBegin;
362 Label old_end = ec.LoopEnd;
364 ec.LoopBegin = ig.DefineLabel ();
365 ec.LoopEnd = ig.DefineLabel ();
368 // Inform whether we are infinite or not
370 if (expr is BoolConstant){
371 ig.MarkLabel (ec.LoopBegin);
373 ig.Emit (OpCodes.Br, ec.LoopBegin);
376 // Inform that we are infinite (ie, `we return'), only
377 // if we do not `break' inside the code.
379 ig.MarkLabel (ec.LoopEnd);
381 Label while_loop = ig.DefineLabel ();
383 ig.Emit (OpCodes.Br, ec.LoopBegin);
384 ig.MarkLabel (while_loop);
388 ig.MarkLabel (ec.LoopBegin);
390 expr.EmitBranchable (ec, while_loop, true);
392 ig.MarkLabel (ec.LoopEnd);
395 ec.LoopBegin = old_begin;
396 ec.LoopEnd = old_end;
400 public class For : Statement {
402 readonly Statement InitStatement;
403 readonly Statement Increment;
404 readonly Statement Statement;
405 bool infinite, empty;
407 public For (Statement initStatement,
413 InitStatement = initStatement;
415 Increment = increment;
416 Statement = statement;
420 public override bool Resolve (EmitContext ec)
424 if (InitStatement != null){
425 if (!InitStatement.Resolve (ec))
430 Test = Expression.ResolveBoolean (ec, Test, loc);
433 else if (Test is BoolConstant){
434 BoolConstant bc = (BoolConstant) Test;
436 if (bc.Value == false){
437 if (!Statement.ResolveUnreachable (ec, true))
439 if ((Increment != null) &&
440 !Increment.ResolveUnreachable (ec, false))
450 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
452 ec.CurrentBranching.CreateSibling ();
454 if (!Statement.Resolve (ec))
457 if (Increment != null){
458 if (!Increment.Resolve (ec))
462 ec.CurrentBranching.Infinite = infinite;
463 ec.EndFlowBranching ();
468 protected override void DoEmit (EmitContext ec)
473 ILGenerator ig = ec.ig;
474 Label old_begin = ec.LoopBegin;
475 Label old_end = ec.LoopEnd;
476 Label loop = ig.DefineLabel ();
477 Label test = ig.DefineLabel ();
479 if (InitStatement != null && InitStatement != EmptyStatement.Value)
480 InitStatement.Emit (ec);
482 ec.LoopBegin = ig.DefineLabel ();
483 ec.LoopEnd = ig.DefineLabel ();
485 ig.Emit (OpCodes.Br, test);
489 ig.MarkLabel (ec.LoopBegin);
490 if (Increment != EmptyStatement.Value)
495 // If test is null, there is no test, and we are just
500 // The Resolve code already catches the case for
501 // Test == BoolConstant (false) so we know that
504 if (Test is BoolConstant)
505 ig.Emit (OpCodes.Br, loop);
507 Test.EmitBranchable (ec, loop, true);
510 ig.Emit (OpCodes.Br, loop);
511 ig.MarkLabel (ec.LoopEnd);
513 ec.LoopBegin = old_begin;
514 ec.LoopEnd = old_end;
518 public class StatementExpression : Statement {
519 ExpressionStatement expr;
521 public StatementExpression (ExpressionStatement expr, Location l)
527 public override bool Resolve (EmitContext ec)
529 expr = expr.ResolveStatement (ec);
533 protected override void DoEmit (EmitContext ec)
535 expr.EmitStatement (ec);
538 public override string ToString ()
540 return "StatementExpression (" + expr + ")";
545 /// Implements the return statement
547 public class Return : Statement {
548 public Expression Expr;
550 public Return (Expression expr, Location l)
558 public override bool Resolve (EmitContext ec)
560 if (ec.ReturnType == null){
562 Error (127, "Return with a value not allowed here");
567 Error (126, "An object of type `{0}' is expected " +
568 "for the return statement",
569 TypeManager.CSharpName (ec.ReturnType));
573 Expr = Expr.Resolve (ec);
577 if (Expr.Type != ec.ReturnType) {
578 Expr = Convert.ImplicitConversionRequired (
579 ec, Expr, ec.ReturnType, loc);
586 Error (-206, "Return statement not allowed inside iterators");
590 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
592 if (ec.CurrentBranching.InTryOrCatch (true)) {
593 ec.CurrentBranching.AddFinallyVector (vector);
595 } else if (ec.CurrentBranching.InFinally (true)) {
596 Error (157, "Control can not leave the body of the finally block");
599 vector.CheckOutParameters (ec.CurrentBranching);
601 ec.CurrentBranching.CurrentUsageVector.Return ();
605 protected override void DoEmit (EmitContext ec)
611 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
615 ec.NeedReturnLabel ();
616 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
618 ec.ig.Emit (OpCodes.Ret);
623 public class Goto : Statement {
626 LabeledStatement label;
628 public override bool Resolve (EmitContext ec)
630 label = ec.CurrentBranching.LookupLabel (target, loc);
634 // If this is a forward goto.
635 if (!label.IsDefined)
636 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
638 ec.CurrentBranching.CurrentUsageVector.Goto ();
643 public Goto (Block parent_block, string label, Location l)
645 block = parent_block;
650 public string Target {
656 protected override void DoEmit (EmitContext ec)
658 Label l = label.LabelTarget (ec);
659 ec.ig.Emit (OpCodes.Br, l);
663 public class LabeledStatement : Statement {
664 public readonly Location Location;
669 FlowBranching.UsageVector vectors;
671 public LabeledStatement (string label_name, Location l)
676 public Label LabelTarget (EmitContext ec)
680 label = ec.ig.DefineLabel ();
686 public bool IsDefined {
692 public bool HasBeenReferenced {
698 public void AddUsageVector (FlowBranching.UsageVector vector)
700 vector = vector.Clone ();
701 vector.Next = vectors;
705 public override bool Resolve (EmitContext ec)
707 ec.CurrentBranching.Label (vectors);
714 protected override void DoEmit (EmitContext ec)
717 ec.ig.MarkLabel (label);
723 /// `goto default' statement
725 public class GotoDefault : Statement {
727 public GotoDefault (Location l)
732 public override bool Resolve (EmitContext ec)
734 ec.CurrentBranching.CurrentUsageVector.Goto ();
738 protected override void DoEmit (EmitContext ec)
740 if (ec.Switch == null){
741 Report.Error (153, loc, "goto default is only valid in a switch statement");
745 if (!ec.Switch.GotDefault){
746 Report.Error (159, loc, "No default target on switch statement");
749 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
754 /// `goto case' statement
756 public class GotoCase : Statement {
760 public GotoCase (Expression e, Location l)
766 public override bool Resolve (EmitContext ec)
768 if (ec.Switch == null){
769 Report.Error (153, loc, "goto case is only valid in a switch statement");
773 expr = expr.Resolve (ec);
777 if (!(expr is Constant)){
778 Report.Error (159, loc, "Target expression for goto case is not constant");
782 object val = Expression.ConvertIntLiteral (
783 (Constant) expr, ec.Switch.SwitchType, loc);
788 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
793 "No such label 'case " + val + "': for the goto case");
797 label = sl.ILLabelCode;
799 ec.CurrentBranching.CurrentUsageVector.Goto ();
803 protected override void DoEmit (EmitContext ec)
805 ec.ig.Emit (OpCodes.Br, label);
809 public class Throw : Statement {
812 public Throw (Expression expr, Location l)
818 public override bool Resolve (EmitContext ec)
820 bool in_catch = ec.CurrentBranching.InCatch ();
821 ec.CurrentBranching.CurrentUsageVector.Throw ();
824 expr = expr.Resolve (ec);
828 ExprClass eclass = expr.eclass;
830 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
831 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
832 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
838 if ((t != TypeManager.exception_type) &&
839 !t.IsSubclassOf (TypeManager.exception_type) &&
840 !(expr is NullLiteral)) {
842 "The type caught or thrown must be derived " +
843 "from System.Exception");
846 } else if (!in_catch) {
848 "A throw statement with no argument is only " +
849 "allowed in a catch clause");
856 protected override void DoEmit (EmitContext ec)
859 ec.ig.Emit (OpCodes.Rethrow);
863 ec.ig.Emit (OpCodes.Throw);
868 public class Break : Statement {
870 public Break (Location l)
877 public override bool Resolve (EmitContext ec)
879 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
880 Error (139, "No enclosing loop or switch to continue to");
882 } else if (ec.CurrentBranching.InFinally (false)) {
883 Error (157, "Control can not leave the body of the finally block");
885 } else if (ec.CurrentBranching.InTryOrCatch (false))
886 ec.CurrentBranching.AddFinallyVector (
887 ec.CurrentBranching.CurrentUsageVector);
888 else if (ec.CurrentBranching.InLoop ())
889 ec.CurrentBranching.AddBreakVector (
890 ec.CurrentBranching.CurrentUsageVector);
892 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
894 ec.CurrentBranching.CurrentUsageVector.Break ();
898 protected override void DoEmit (EmitContext ec)
900 ILGenerator ig = ec.ig;
903 ig.Emit (OpCodes.Leave, ec.LoopEnd);
905 ec.NeedReturnLabel ();
906 ig.Emit (OpCodes.Br, ec.LoopEnd);
911 public class Continue : Statement {
913 public Continue (Location l)
920 public override bool Resolve (EmitContext ec)
922 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
923 Error (139, "No enclosing loop to continue to");
925 } else if (ec.CurrentBranching.InFinally (false)) {
926 Error (157, "Control can not leave the body of the finally block");
928 } else if (ec.CurrentBranching.InTryOrCatch (false))
929 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
931 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
933 ec.CurrentBranching.CurrentUsageVector.Goto ();
937 protected override void DoEmit (EmitContext ec)
939 Label begin = ec.LoopBegin;
942 ec.ig.Emit (OpCodes.Leave, begin);
944 ec.ig.Emit (OpCodes.Br, begin);
948 public class LocalInfo {
949 public Expression Type;
952 // Most of the time a variable will be stored in a LocalBuilder
954 // But sometimes, it will be stored in a field. The context of the field will
955 // be stored in the EmitContext
958 public LocalBuilder LocalBuilder;
959 public FieldBuilder FieldBuilder;
961 public Type VariableType;
962 public readonly string Name;
963 public readonly Location Location;
964 public readonly Block Block;
966 public VariableInfo VariableInfo;
977 public LocalInfo (Expression type, string name, Block block, Location l)
985 public LocalInfo (TypeContainer tc, Block block, Location l)
987 VariableType = tc.TypeBuilder;
992 public bool IsThisAssigned (EmitContext ec, Location loc)
994 if (VariableInfo == null)
995 throw new Exception ();
997 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1000 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1003 public bool IsAssigned (EmitContext ec)
1005 if (VariableInfo == null)
1006 throw new Exception ();
1008 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1011 public bool Resolve (EmitContext ec)
1013 if (VariableType == null)
1014 VariableType = ec.DeclSpace.ResolveType (Type, false, Location);
1016 if (VariableType == TypeManager.void_type) {
1017 Report.Error (1547, Location,
1018 "Keyword 'void' cannot be used in this context");
1022 if (VariableType == null)
1025 // TODO: breaks the build
1026 // if (VariableType.IsPointer && !ec.InUnsafe)
1027 // Expression.UnsafeError (Location);
1033 // Whether the variable is Fixed (because its Pinned or its a value type)
1035 public bool IsFixed {
1037 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1044 public override string ToString ()
1046 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1047 Name, Type, VariableInfo, Location);
1052 return (flags & Flags.Used) != 0;
1055 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1059 public bool ReadOnly {
1061 return (flags & Flags.ReadOnly) != 0;
1064 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1069 // Whether the variable is pinned, if Pinned the variable has been
1070 // allocated in a pinned slot with DeclareLocal.
1072 public bool Pinned {
1074 return (flags & Flags.Pinned) != 0;
1077 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1081 public bool IsThis {
1083 return (flags & Flags.IsThis) != 0;
1086 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1092 /// Block represents a C# block.
1096 /// This class is used in a number of places: either to represent
1097 /// explicit blocks that the programmer places or implicit blocks.
1099 /// Implicit blocks are used as labels or to introduce variable
1102 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1103 /// they contain extra information that is not necessary on normal blocks.
1105 public class Block : Statement {
1106 public readonly Block Parent;
1107 public readonly Location StartLocation;
1108 public Location EndLocation = Location.Null;
1111 public enum Flags : byte {
1115 VariablesInitialized = 8,
1122 public bool Implicit {
1124 return (flags & Flags.Implicit) != 0;
1128 public bool Unchecked {
1130 return (flags & Flags.Unchecked) != 0;
1133 flags |= Flags.Unchecked;
1137 public bool HasVarargs {
1140 return Parent.HasVarargs;
1142 return (flags & Flags.HasVarargs) != 0;
1145 flags |= Flags.HasVarargs;
1150 // The statements in this block
1152 ArrayList statements;
1156 // An array of Blocks. We keep track of children just
1157 // to generate the local variable declarations.
1159 // Statements and child statements are handled through the
1165 // Labels. (label, block) pairs.
1170 // Keeps track of (name, type) pairs
1172 Hashtable variables;
1175 // Keeps track of constants
1176 Hashtable constants;
1179 // If this is a switch section, the enclosing switch block.
1187 public Block (Block parent)
1188 : this (parent, (Flags) 0, Location.Null, Location.Null)
1191 public Block (Block parent, Flags flags)
1192 : this (parent, flags, Location.Null, Location.Null)
1195 public Block (Block parent, Flags flags, Parameters parameters)
1196 : this (parent, flags, parameters, Location.Null, Location.Null)
1199 public Block (Block parent, Location start, Location end)
1200 : this (parent, (Flags) 0, start, end)
1203 public Block (Block parent, Parameters parameters, Location start, Location end)
1204 : this (parent, (Flags) 0, parameters, start, end)
1207 public Block (Block parent, Flags flags, Location start, Location end)
1208 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1211 public Block (Block parent, Flags flags, Parameters parameters,
1212 Location start, Location end)
1215 parent.AddChild (this);
1217 this.Parent = parent;
1219 this.parameters = parameters;
1220 this.StartLocation = start;
1221 this.EndLocation = end;
1224 statements = new ArrayList ();
1226 if (parent != null && Implicit) {
1227 if (parent.child_variable_names == null)
1228 parent.child_variable_names = new Hashtable();
1229 // share with parent
1230 child_variable_names = parent.child_variable_names;
1235 public Block CreateSwitchBlock (Location start)
1237 Block new_block = new Block (this, start, start);
1238 new_block.switch_block = this;
1248 void AddChild (Block b)
1250 if (children == null)
1251 children = new ArrayList ();
1256 public void SetEndLocation (Location loc)
1262 /// Adds a label to the current block.
1266 /// false if the name already exists in this block. true
1270 public bool AddLabel (string name, LabeledStatement target, Location loc)
1272 if (switch_block != null)
1273 return switch_block.AddLabel (name, target, loc);
1276 while (cur != null) {
1277 if (cur.DoLookupLabel (name) != null) {
1279 140, loc, "The label '{0}' is a duplicate",
1290 while (cur != null) {
1291 if (cur.DoLookupLabel (name) != null) {
1294 "The label '{0}' shadows another label " +
1295 "by the same name in a containing scope.",
1300 if (children != null) {
1301 foreach (Block b in children) {
1302 LabeledStatement s = b.DoLookupLabel (name);
1308 "The label '{0}' shadows another " +
1309 "label by the same name in a " +
1310 "containing scope.",
1321 labels = new Hashtable ();
1323 labels.Add (name, target);
1327 public LabeledStatement LookupLabel (string name)
1329 LabeledStatement s = DoLookupLabel (name);
1333 if (children == null)
1336 foreach (Block child in children) {
1337 if (!child.Implicit)
1340 s = child.LookupLabel (name);
1348 LabeledStatement DoLookupLabel (string name)
1350 if (switch_block != null)
1351 return switch_block.LookupLabel (name);
1354 if (labels.Contains (name))
1355 return ((LabeledStatement) labels [name]);
1360 LocalInfo this_variable = null;
1363 // Returns the "this" instance variable of this block.
1364 // See AddThisVariable() for more information.
1366 public LocalInfo ThisVariable {
1368 if (this_variable != null)
1369 return this_variable;
1370 else if (Parent != null)
1371 return Parent.ThisVariable;
1377 Hashtable child_variable_names;
1380 // Marks a variable with name @name as being used in a child block.
1381 // If a variable name has been used in a child block, it's illegal to
1382 // declare a variable with the same name in the current block.
1384 public void AddChildVariableName (string name)
1386 if (child_variable_names == null)
1387 child_variable_names = new Hashtable ();
1389 if (!child_variable_names.Contains (name))
1390 child_variable_names.Add (name, true);
1394 // Checks whether a variable name has already been used in a child block.
1396 public bool IsVariableNameUsedInChildBlock (string name)
1398 if (child_variable_names == null)
1401 return child_variable_names.Contains (name);
1405 // This is used by non-static `struct' constructors which do not have an
1406 // initializer - in this case, the constructor must initialize all of the
1407 // struct's fields. To do this, we add a "this" variable and use the flow
1408 // analysis code to ensure that it's been fully initialized before control
1409 // leaves the constructor.
1411 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1413 if (this_variable != null)
1414 return this_variable;
1416 if (variables == null)
1417 variables = new Hashtable ();
1419 this_variable = new LocalInfo (tc, this, l);
1420 this_variable.Used = true;
1421 this_variable.IsThis = true;
1423 variables.Add ("this", this_variable);
1425 return this_variable;
1428 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1430 if (variables == null)
1431 variables = new Hashtable ();
1433 LocalInfo vi = GetLocalInfo (name);
1435 if (vi.Block != this)
1436 Report.Error (136, l, "A local variable named `" + name + "' " +
1437 "cannot be declared in this scope since it would " +
1438 "give a different meaning to `" + name + "', which " +
1439 "is already used in a `parent or current' scope to " +
1440 "denote something else");
1442 Report.Error (128, l, "A local variable `" + name + "' is already " +
1443 "defined in this scope");
1447 if (IsVariableNameUsedInChildBlock (name)) {
1448 Report.Error (136, l, "A local variable named `" + name + "' " +
1449 "cannot be declared in this scope since it would " +
1450 "give a different meaning to `" + name + "', which " +
1451 "is already used in a `child' scope to denote something " +
1458 Parameter p = pars.GetParameterByName (name, out idx);
1460 Report.Error (136, l, "A local variable named `" + name + "' " +
1461 "cannot be declared in this scope since it would " +
1462 "give a different meaning to `" + name + "', which " +
1463 "is already used in a `parent or current' scope to " +
1464 "denote something else");
1469 vi = new LocalInfo (type, name, this, l);
1471 variables.Add (name, vi);
1473 // Mark 'name' as "used by a child block" in every surrounding block
1475 while (cur != null && cur.Implicit)
1478 for (Block par = cur.Parent; par != null; par = par.Parent)
1479 par.AddChildVariableName (name);
1481 if ((flags & Flags.VariablesInitialized) != 0)
1482 throw new Exception ();
1484 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1488 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1490 if (AddVariable (type, name, pars, l) == null)
1493 if (constants == null)
1494 constants = new Hashtable ();
1496 constants.Add (name, value);
1500 public Hashtable Variables {
1506 public LocalInfo GetLocalInfo (string name)
1508 for (Block b = this; b != null; b = b.Parent) {
1509 if (b.variables != null) {
1510 LocalInfo ret = b.variables [name] as LocalInfo;
1518 public Expression GetVariableType (string name)
1520 LocalInfo vi = GetLocalInfo (name);
1528 public Expression GetConstantExpression (string name)
1530 for (Block b = this; b != null; b = b.Parent) {
1531 if (b.constants != null) {
1532 Expression ret = b.constants [name] as Expression;
1541 /// True if the variable named @name is a constant
1543 public bool IsConstant (string name)
1545 Expression e = null;
1547 e = GetConstantExpression (name);
1552 Parameters parameters = null;
1553 public Parameters Parameters {
1556 while (b.Parent != null)
1558 return b.parameters;
1563 /// A list of labels that were not used within this block
1565 public string [] GetUnreferenced ()
1567 // FIXME: Implement me
1571 public void AddStatement (Statement s)
1574 flags |= Flags.BlockUsed;
1579 return (flags & Flags.BlockUsed) != 0;
1585 flags |= Flags.BlockUsed;
1588 public bool HasRet {
1590 return (flags & Flags.HasRet) != 0;
1594 public bool IsDestructor {
1596 return (flags & Flags.IsDestructor) != 0;
1600 public void SetDestructor ()
1602 flags |= Flags.IsDestructor;
1605 VariableMap param_map, local_map;
1607 public VariableMap ParameterMap {
1609 if ((flags & Flags.VariablesInitialized) == 0)
1610 throw new Exception ();
1616 public VariableMap LocalMap {
1618 if ((flags & Flags.VariablesInitialized) == 0)
1619 throw new Exception ();
1625 public bool LiftVariable (LocalInfo local_info)
1631 /// Emits the variable declarations and labels.
1634 /// tc: is our typecontainer (to resolve type references)
1635 /// ig: is the code generator:
1637 public void EmitMeta (EmitContext ec, InternalParameters ip)
1639 ILGenerator ig = ec.ig;
1642 // Compute the VariableMap's.
1644 // Unfortunately, we don't know the type when adding variables with
1645 // AddVariable(), so we need to compute this info here.
1649 if (variables != null) {
1650 foreach (LocalInfo li in variables.Values)
1653 locals = new LocalInfo [variables.Count];
1654 variables.Values.CopyTo (locals, 0);
1656 locals = new LocalInfo [0];
1659 local_map = new VariableMap (Parent.LocalMap, locals);
1661 local_map = new VariableMap (locals);
1663 param_map = new VariableMap (ip);
1664 flags |= Flags.VariablesInitialized;
1666 bool old_check_state = ec.ConstantCheckState;
1667 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1668 bool remap_locals = ec.RemapToProxy;
1671 // Process this block variables
1673 if (variables != null){
1674 foreach (DictionaryEntry de in variables){
1675 string name = (string) de.Key;
1676 LocalInfo vi = (LocalInfo) de.Value;
1678 if (vi.VariableType == null)
1681 Type variable_type = vi.VariableType;
1683 if (variable_type.IsPointer){
1685 // Am not really convinced that this test is required (Microsoft does it)
1686 // but the fact is that you would not be able to use the pointer variable
1689 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1695 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1698 // This is needed to compile on both .NET 1.x and .NET 2.x
1699 // the later introduced `DeclareLocal (Type t, bool pinned)'
1701 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1702 else if (!vi.IsThis)
1703 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1705 if (constants == null)
1708 Expression cv = (Expression) constants [name];
1712 ec.CurrentBlock = this;
1713 Expression e = cv.Resolve (ec);
1717 Constant ce = e as Constant;
1719 Report.Error (133, vi.Location,
1720 "The expression being assigned to `" +
1721 name + "' must be constant (" + e + ")");
1725 if (e.Type != variable_type){
1726 e = Const.ChangeType (vi.Location, ce, variable_type);
1731 constants.Remove (name);
1732 constants.Add (name, e);
1735 ec.ConstantCheckState = old_check_state;
1738 // Now, handle the children
1740 if (children != null){
1741 foreach (Block b in children)
1742 b.EmitMeta (ec, ip);
1746 void UsageWarning (FlowBranching.UsageVector vector)
1750 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1751 foreach (DictionaryEntry de in variables){
1752 LocalInfo vi = (LocalInfo) de.Value;
1757 name = (string) de.Key;
1759 if (vector.IsAssigned (vi.VariableInfo)){
1760 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1762 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1768 bool unreachable_shown;
1770 public override bool Resolve (EmitContext ec)
1772 Block prev_block = ec.CurrentBlock;
1775 int errors = Report.Errors;
1777 ec.CurrentBlock = this;
1778 ec.StartFlowBranching (this);
1780 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1782 bool unreachable = false;
1784 int statement_count = statements.Count;
1785 for (int ix = 0; ix < statement_count; ix++){
1786 Statement s = (Statement) statements [ix];
1788 if (unreachable && !(s is LabeledStatement)) {
1789 if (s == EmptyStatement.Value)
1790 s.loc = EndLocation;
1792 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1795 if (s != EmptyStatement.Value)
1796 unreachable_shown = true;
1798 s.loc = Location.Null;
1800 statements [ix] = EmptyStatement.Value;
1804 if (s.Resolve (ec) == false) {
1806 statements [ix] = EmptyStatement.Value;
1810 num_statements = ix + 1;
1812 if (s is LabeledStatement)
1813 unreachable = false;
1815 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1818 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1819 ec.CurrentBranching, statement_count, num_statements);
1822 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1824 ec.CurrentBlock = prev_block;
1826 // If we're a non-static `struct' constructor which doesn't have an
1827 // initializer, then we must initialize all of the struct's fields.
1828 if ((this_variable != null) &&
1829 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1830 !this_variable.IsThisAssigned (ec, loc))
1833 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1834 foreach (LabeledStatement label in labels.Values)
1835 if (!label.HasBeenReferenced)
1836 Report.Warning (164, label.Location,
1837 "This label has not been referenced");
1840 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1842 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1843 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1844 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1845 flags |= Flags.HasRet;
1847 if (ok && (errors == Report.Errors)) {
1848 if (RootContext.WarningLevel >= 3)
1849 UsageWarning (vector);
1855 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1857 unreachable_shown = true;
1858 return base.ResolveUnreachable (ec, warn);
1861 protected override void DoEmit (EmitContext ec)
1863 for (int ix = 0; ix < num_statements; ix++){
1864 Statement s = (Statement) statements [ix];
1866 // Check whether we are the last statement in a
1869 if ((Parent == null) && (ix+1 == num_statements))
1870 ec.IsLastStatement = true;
1872 ec.IsLastStatement = false;
1878 public override void Emit (EmitContext ec)
1880 Block prev_block = ec.CurrentBlock;
1882 ec.CurrentBlock = this;
1884 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1885 bool is_lexical_block = !Implicit && (Parent != null);
1887 if (emit_debug_info) {
1888 if (is_lexical_block)
1889 ec.ig.BeginScope ();
1891 if (variables != null) {
1892 foreach (DictionaryEntry de in variables) {
1893 string name = (string) de.Key;
1894 LocalInfo vi = (LocalInfo) de.Value;
1896 if (vi.LocalBuilder == null)
1899 ec.DefineLocalVariable (name, vi.LocalBuilder);
1904 ec.Mark (StartLocation, true);
1906 ec.Mark (EndLocation, true);
1908 if (emit_debug_info && is_lexical_block)
1911 ec.CurrentBlock = prev_block;
1917 public class ToplevelBlock : Block {
1918 public ToplevelBlock (Parameters parameters, Location start) :
1919 base (null, parameters, start, Location.Null)
1923 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1924 base (null, flags, parameters, start, Location.Null)
1929 public class SwitchLabel {
1932 public Location loc;
1933 public Label ILLabel;
1934 public Label ILLabelCode;
1937 // if expr == null, then it is the default case.
1939 public SwitchLabel (Expression expr, Location l)
1945 public Expression Label {
1951 public object Converted {
1958 // Resolves the expression, reduces it to a literal if possible
1959 // and then converts it to the requested type.
1961 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1963 ILLabel = ec.ig.DefineLabel ();
1964 ILLabelCode = ec.ig.DefineLabel ();
1969 Expression e = label.Resolve (ec);
1974 if (!(e is Constant)){
1975 Report.Error (150, loc, "A constant value is expected, got: " + e);
1979 if (e is StringConstant || e is NullLiteral){
1980 if (required_type == TypeManager.string_type){
1982 ILLabel = ec.ig.DefineLabel ();
1987 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1988 if (converted == null)
1995 public class SwitchSection {
1996 // An array of SwitchLabels.
1997 public readonly ArrayList Labels;
1998 public readonly Block Block;
2000 public SwitchSection (ArrayList labels, Block block)
2007 public class Switch : Statement {
2008 public readonly ArrayList Sections;
2009 public Expression Expr;
2012 /// Maps constants whose type type SwitchType to their SwitchLabels.
2014 public Hashtable Elements;
2017 /// The governing switch type
2019 public Type SwitchType;
2025 Label default_target;
2026 Expression new_expr;
2028 SwitchSection constant_section;
2031 // The types allowed to be implicitly cast from
2032 // on the governing type
2034 static Type [] allowed_types;
2036 public Switch (Expression e, ArrayList sects, Location l)
2043 public bool GotDefault {
2049 public Label DefaultTarget {
2051 return default_target;
2056 // Determines the governing type for a switch. The returned
2057 // expression might be the expression from the switch, or an
2058 // expression that includes any potential conversions to the
2059 // integral types or to string.
2061 Expression SwitchGoverningType (EmitContext ec, Type t)
2063 if (t == TypeManager.int32_type ||
2064 t == TypeManager.uint32_type ||
2065 t == TypeManager.char_type ||
2066 t == TypeManager.byte_type ||
2067 t == TypeManager.sbyte_type ||
2068 t == TypeManager.ushort_type ||
2069 t == TypeManager.short_type ||
2070 t == TypeManager.uint64_type ||
2071 t == TypeManager.int64_type ||
2072 t == TypeManager.string_type ||
2073 t == TypeManager.bool_type ||
2074 t.IsSubclassOf (TypeManager.enum_type))
2077 if (allowed_types == null){
2078 allowed_types = new Type [] {
2079 TypeManager.sbyte_type,
2080 TypeManager.byte_type,
2081 TypeManager.short_type,
2082 TypeManager.ushort_type,
2083 TypeManager.int32_type,
2084 TypeManager.uint32_type,
2085 TypeManager.int64_type,
2086 TypeManager.uint64_type,
2087 TypeManager.char_type,
2088 TypeManager.bool_type,
2089 TypeManager.string_type
2094 // Try to find a *user* defined implicit conversion.
2096 // If there is no implicit conversion, or if there are multiple
2097 // conversions, we have to report an error
2099 Expression converted = null;
2100 foreach (Type tt in allowed_types){
2103 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2107 if (converted != null){
2108 Report.Error (-12, loc, "More than one conversion to an integral " +
2109 " type exists for type `" +
2110 TypeManager.CSharpName (Expr.Type)+"'");
2118 void error152 (string n)
2121 152, "The label `" + n + ":' " +
2122 "is already present on this switch statement");
2126 // Performs the basic sanity checks on the switch statement
2127 // (looks for duplicate keys and non-constant expressions).
2129 // It also returns a hashtable with the keys that we will later
2130 // use to compute the switch tables
2132 bool CheckSwitch (EmitContext ec)
2136 Elements = new Hashtable ();
2138 got_default = false;
2140 if (TypeManager.IsEnumType (SwitchType)){
2141 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2143 compare_type = SwitchType;
2145 foreach (SwitchSection ss in Sections){
2146 foreach (SwitchLabel sl in ss.Labels){
2147 if (!sl.ResolveAndReduce (ec, SwitchType)){
2152 if (sl.Label == null){
2154 error152 ("default");
2161 object key = sl.Converted;
2163 if (key is Constant)
2164 key = ((Constant) key).GetValue ();
2167 key = NullLiteral.Null;
2169 string lname = null;
2170 if (compare_type == TypeManager.uint64_type){
2171 ulong v = (ulong) key;
2173 if (Elements.Contains (v))
2174 lname = v.ToString ();
2176 Elements.Add (v, sl);
2177 } else if (compare_type == TypeManager.int64_type){
2178 long v = (long) key;
2180 if (Elements.Contains (v))
2181 lname = v.ToString ();
2183 Elements.Add (v, sl);
2184 } else if (compare_type == TypeManager.uint32_type){
2185 uint v = (uint) key;
2187 if (Elements.Contains (v))
2188 lname = v.ToString ();
2190 Elements.Add (v, sl);
2191 } else if (compare_type == TypeManager.char_type){
2192 char v = (char) key;
2194 if (Elements.Contains (v))
2195 lname = v.ToString ();
2197 Elements.Add (v, sl);
2198 } else if (compare_type == TypeManager.byte_type){
2199 byte v = (byte) key;
2201 if (Elements.Contains (v))
2202 lname = v.ToString ();
2204 Elements.Add (v, sl);
2205 } else if (compare_type == TypeManager.sbyte_type){
2206 sbyte v = (sbyte) key;
2208 if (Elements.Contains (v))
2209 lname = v.ToString ();
2211 Elements.Add (v, sl);
2212 } else if (compare_type == TypeManager.short_type){
2213 short v = (short) key;
2215 if (Elements.Contains (v))
2216 lname = v.ToString ();
2218 Elements.Add (v, sl);
2219 } else if (compare_type == TypeManager.ushort_type){
2220 ushort v = (ushort) key;
2222 if (Elements.Contains (v))
2223 lname = v.ToString ();
2225 Elements.Add (v, sl);
2226 } else if (compare_type == TypeManager.string_type){
2227 if (key is NullLiteral){
2228 if (Elements.Contains (NullLiteral.Null))
2231 Elements.Add (NullLiteral.Null, null);
2233 string s = (string) key;
2235 if (Elements.Contains (s))
2238 Elements.Add (s, sl);
2240 } else if (compare_type == TypeManager.int32_type) {
2243 if (Elements.Contains (v))
2244 lname = v.ToString ();
2246 Elements.Add (v, sl);
2247 } else if (compare_type == TypeManager.bool_type) {
2248 bool v = (bool) key;
2250 if (Elements.Contains (v))
2251 lname = v.ToString ();
2253 Elements.Add (v, sl);
2257 throw new Exception ("Unknown switch type!" +
2258 SwitchType + " " + compare_type);
2262 error152 ("case + " + lname);
2273 void EmitObjectInteger (ILGenerator ig, object k)
2276 IntConstant.EmitInt (ig, (int) k);
2277 else if (k is Constant) {
2278 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2281 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2284 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2286 IntConstant.EmitInt (ig, (int) (long) k);
2287 ig.Emit (OpCodes.Conv_I8);
2290 LongConstant.EmitLong (ig, (long) k);
2292 else if (k is ulong)
2294 if ((ulong) k < (1L<<32))
2296 IntConstant.EmitInt (ig, (int) (long) k);
2297 ig.Emit (OpCodes.Conv_U8);
2301 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2305 IntConstant.EmitInt (ig, (int) ((char) k));
2306 else if (k is sbyte)
2307 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2309 IntConstant.EmitInt (ig, (int) ((byte) k));
2310 else if (k is short)
2311 IntConstant.EmitInt (ig, (int) ((short) k));
2312 else if (k is ushort)
2313 IntConstant.EmitInt (ig, (int) ((ushort) k));
2315 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2317 throw new Exception ("Unhandled case");
2320 // structure used to hold blocks of keys while calculating table switch
2321 class KeyBlock : IComparable
2323 public KeyBlock (long _nFirst)
2325 nFirst = nLast = _nFirst;
2329 public ArrayList rgKeys = null;
2330 // how many items are in the bucket
2331 public int Size = 1;
2334 get { return (int) (nLast - nFirst + 1); }
2336 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2338 return kbLast.nLast - kbFirst.nFirst + 1;
2340 public int CompareTo (object obj)
2342 KeyBlock kb = (KeyBlock) obj;
2343 int nLength = Length;
2344 int nLengthOther = kb.Length;
2345 if (nLengthOther == nLength)
2346 return (int) (kb.nFirst - nFirst);
2347 return nLength - nLengthOther;
2352 /// This method emits code for a lookup-based switch statement (non-string)
2353 /// Basically it groups the cases into blocks that are at least half full,
2354 /// and then spits out individual lookup opcodes for each block.
2355 /// It emits the longest blocks first, and short blocks are just
2356 /// handled with direct compares.
2358 /// <param name="ec"></param>
2359 /// <param name="val"></param>
2360 /// <returns></returns>
2361 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2363 int cElements = Elements.Count;
2364 object [] rgKeys = new object [cElements];
2365 Elements.Keys.CopyTo (rgKeys, 0);
2366 Array.Sort (rgKeys);
2368 // initialize the block list with one element per key
2369 ArrayList rgKeyBlocks = new ArrayList ();
2370 foreach (object key in rgKeys)
2371 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2374 // iteratively merge the blocks while they are at least half full
2375 // there's probably a really cool way to do this with a tree...
2376 while (rgKeyBlocks.Count > 1)
2378 ArrayList rgKeyBlocksNew = new ArrayList ();
2379 kbCurr = (KeyBlock) rgKeyBlocks [0];
2380 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2382 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2383 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2386 kbCurr.nLast = kb.nLast;
2387 kbCurr.Size += kb.Size;
2391 // start a new block
2392 rgKeyBlocksNew.Add (kbCurr);
2396 rgKeyBlocksNew.Add (kbCurr);
2397 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2399 rgKeyBlocks = rgKeyBlocksNew;
2402 // initialize the key lists
2403 foreach (KeyBlock kb in rgKeyBlocks)
2404 kb.rgKeys = new ArrayList ();
2406 // fill the key lists
2408 if (rgKeyBlocks.Count > 0) {
2409 kbCurr = (KeyBlock) rgKeyBlocks [0];
2410 foreach (object key in rgKeys)
2412 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2413 System.Convert.ToInt64 (key) > kbCurr.nLast;
2415 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2416 kbCurr.rgKeys.Add (key);
2420 // sort the blocks so we can tackle the largest ones first
2421 rgKeyBlocks.Sort ();
2423 // okay now we can start...
2424 ILGenerator ig = ec.ig;
2425 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2426 Label lblDefault = ig.DefineLabel ();
2428 Type typeKeys = null;
2429 if (rgKeys.Length > 0)
2430 typeKeys = rgKeys [0].GetType (); // used for conversions
2434 if (TypeManager.IsEnumType (SwitchType))
2435 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2437 compare_type = SwitchType;
2439 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2441 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2442 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2445 foreach (object key in kb.rgKeys)
2447 ig.Emit (OpCodes.Ldloc, val);
2448 EmitObjectInteger (ig, key);
2449 SwitchLabel sl = (SwitchLabel) Elements [key];
2450 ig.Emit (OpCodes.Beq, sl.ILLabel);
2455 // TODO: if all the keys in the block are the same and there are
2456 // no gaps/defaults then just use a range-check.
2457 if (compare_type == TypeManager.int64_type ||
2458 compare_type == TypeManager.uint64_type)
2460 // TODO: optimize constant/I4 cases
2462 // check block range (could be > 2^31)
2463 ig.Emit (OpCodes.Ldloc, val);
2464 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2465 ig.Emit (OpCodes.Blt, lblDefault);
2466 ig.Emit (OpCodes.Ldloc, val);
2467 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2468 ig.Emit (OpCodes.Bgt, lblDefault);
2471 ig.Emit (OpCodes.Ldloc, val);
2474 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2475 ig.Emit (OpCodes.Sub);
2477 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2482 ig.Emit (OpCodes.Ldloc, val);
2483 int nFirst = (int) kb.nFirst;
2486 IntConstant.EmitInt (ig, nFirst);
2487 ig.Emit (OpCodes.Sub);
2489 else if (nFirst < 0)
2491 IntConstant.EmitInt (ig, -nFirst);
2492 ig.Emit (OpCodes.Add);
2496 // first, build the list of labels for the switch
2498 int cJumps = kb.Length;
2499 Label [] rgLabels = new Label [cJumps];
2500 for (int iJump = 0; iJump < cJumps; iJump++)
2502 object key = kb.rgKeys [iKey];
2503 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2505 SwitchLabel sl = (SwitchLabel) Elements [key];
2506 rgLabels [iJump] = sl.ILLabel;
2510 rgLabels [iJump] = lblDefault;
2512 // emit the switch opcode
2513 ig.Emit (OpCodes.Switch, rgLabels);
2516 // mark the default for this block
2518 ig.MarkLabel (lblDefault);
2521 // TODO: find the default case and emit it here,
2522 // to prevent having to do the following jump.
2523 // make sure to mark other labels in the default section
2525 // the last default just goes to the end
2526 ig.Emit (OpCodes.Br, lblDefault);
2528 // now emit the code for the sections
2529 bool fFoundDefault = false;
2530 foreach (SwitchSection ss in Sections)
2532 foreach (SwitchLabel sl in ss.Labels)
2534 ig.MarkLabel (sl.ILLabel);
2535 ig.MarkLabel (sl.ILLabelCode);
2536 if (sl.Label == null)
2538 ig.MarkLabel (lblDefault);
2539 fFoundDefault = true;
2543 //ig.Emit (OpCodes.Br, lblEnd);
2546 if (!fFoundDefault) {
2547 ig.MarkLabel (lblDefault);
2549 ig.MarkLabel (lblEnd);
2552 // This simple emit switch works, but does not take advantage of the
2554 // TODO: remove non-string logic from here
2555 // TODO: binary search strings?
2557 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2559 ILGenerator ig = ec.ig;
2560 Label end_of_switch = ig.DefineLabel ();
2561 Label next_test = ig.DefineLabel ();
2562 Label null_target = ig.DefineLabel ();
2563 bool default_found = false;
2564 bool first_test = true;
2565 bool pending_goto_end = false;
2567 bool default_at_end = false;
2569 ig.Emit (OpCodes.Ldloc, val);
2571 if (Elements.Contains (NullLiteral.Null)){
2572 ig.Emit (OpCodes.Brfalse, null_target);
2574 ig.Emit (OpCodes.Brfalse, default_target);
2576 ig.Emit (OpCodes.Ldloc, val);
2577 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2578 ig.Emit (OpCodes.Stloc, val);
2580 int section_count = Sections.Count;
2581 for (int section = 0; section < section_count; section++){
2582 SwitchSection ss = (SwitchSection) Sections [section];
2583 Label sec_begin = ig.DefineLabel ();
2585 if (pending_goto_end)
2586 ig.Emit (OpCodes.Br, end_of_switch);
2588 int label_count = ss.Labels.Count;
2589 bool mark_default = false;
2591 for (int label = 0; label < label_count; label++){
2592 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2593 ig.MarkLabel (sl.ILLabel);
2596 ig.MarkLabel (next_test);
2597 next_test = ig.DefineLabel ();
2600 // If we are the default target
2602 if (sl.Label == null){
2603 if (label+1 == label_count)
2604 default_at_end = true;
2605 mark_default = true;
2606 default_found = true;
2608 object lit = sl.Converted;
2610 if (lit is NullLiteral){
2612 if (label_count == 1)
2613 ig.Emit (OpCodes.Br, next_test);
2617 StringConstant str = (StringConstant) lit;
2619 ig.Emit (OpCodes.Ldloc, val);
2620 ig.Emit (OpCodes.Ldstr, str.Value);
2621 if (label_count == 1)
2622 ig.Emit (OpCodes.Bne_Un, next_test);
2624 if (label+1 == label_count)
2625 ig.Emit (OpCodes.Bne_Un, next_test);
2627 ig.Emit (OpCodes.Beq, sec_begin);
2632 ig.MarkLabel (null_target);
2633 ig.MarkLabel (sec_begin);
2634 foreach (SwitchLabel sl in ss.Labels)
2635 ig.MarkLabel (sl.ILLabelCode);
2638 ig.MarkLabel (default_target);
2640 pending_goto_end = !ss.Block.HasRet;
2643 ig.MarkLabel (next_test);
2645 if (!default_at_end)
2646 ig.Emit (OpCodes.Br, default_target);
2648 ig.MarkLabel (default_target);
2649 ig.MarkLabel (end_of_switch);
2652 SwitchSection FindSection (SwitchLabel label)
2654 foreach (SwitchSection ss in Sections){
2655 foreach (SwitchLabel sl in ss.Labels){
2664 bool ResolveConstantSwitch (EmitContext ec)
2666 object key = ((Constant) new_expr).GetValue ();
2667 SwitchLabel label = (SwitchLabel) Elements [key];
2672 constant_section = FindSection (label);
2673 if (constant_section == null)
2676 if (constant_section.Block.Resolve (ec) != true)
2682 public override bool Resolve (EmitContext ec)
2684 Expr = Expr.Resolve (ec);
2688 new_expr = SwitchGoverningType (ec, Expr.Type);
2689 if (new_expr == null){
2690 Report.Error (151, loc, "An integer type or string was expected for switch");
2695 SwitchType = new_expr.Type;
2697 if (!CheckSwitch (ec))
2700 Switch old_switch = ec.Switch;
2702 ec.Switch.SwitchType = SwitchType;
2704 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2705 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2707 is_constant = new_expr is Constant;
2709 object key = ((Constant) new_expr).GetValue ();
2710 SwitchLabel label = (SwitchLabel) Elements [key];
2712 constant_section = FindSection (label);
2716 foreach (SwitchSection ss in Sections){
2718 ec.CurrentBranching.CreateSibling (
2719 null, FlowBranching.SiblingType.SwitchSection);
2723 if (is_constant && (ss != constant_section)) {
2724 // If we're a constant switch, we're only emitting
2725 // one single section - mark all the others as
2727 ec.CurrentBranching.CurrentUsageVector.Goto ();
2728 if (!ss.Block.ResolveUnreachable (ec, true))
2731 if (!ss.Block.Resolve (ec))
2737 ec.CurrentBranching.CreateSibling (
2738 null, FlowBranching.SiblingType.SwitchSection);
2740 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2741 ec.Switch = old_switch;
2743 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2749 protected override void DoEmit (EmitContext ec)
2751 ILGenerator ig = ec.ig;
2753 // Store variable for comparission purposes
2756 value = ig.DeclareLocal (SwitchType);
2758 ig.Emit (OpCodes.Stloc, value);
2762 default_target = ig.DefineLabel ();
2765 // Setup the codegen context
2767 Label old_end = ec.LoopEnd;
2768 Switch old_switch = ec.Switch;
2770 ec.LoopEnd = ig.DefineLabel ();
2775 if (constant_section != null)
2776 constant_section.Block.Emit (ec);
2777 } else if (SwitchType == TypeManager.string_type)
2778 SimpleSwitchEmit (ec, value);
2780 TableSwitchEmit (ec, value);
2782 // Restore context state.
2783 ig.MarkLabel (ec.LoopEnd);
2786 // Restore the previous context
2788 ec.LoopEnd = old_end;
2789 ec.Switch = old_switch;
2793 public abstract class ExceptionStatement : Statement
2795 public abstract void EmitFinally (EmitContext ec);
2797 protected bool emit_finally = true;
2798 ArrayList parent_vectors;
2800 protected void DoEmitFinally (EmitContext ec)
2803 ec.ig.BeginFinallyBlock ();
2805 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
2809 protected void ResolveFinally (FlowBranchingException branching)
2811 emit_finally = branching.EmitFinally;
2813 branching.Parent.StealFinallyClauses (ref parent_vectors);
2817 public class Lock : ExceptionStatement {
2819 Statement Statement;
2822 public Lock (Expression expr, Statement stmt, Location l)
2829 public override bool Resolve (EmitContext ec)
2831 expr = expr.Resolve (ec);
2835 if (expr.Type.IsValueType){
2836 Error (185, "lock statement requires the expression to be " +
2837 " a reference type (type is: `{0}'",
2838 TypeManager.CSharpName (expr.Type));
2842 FlowBranchingException branching = ec.StartFlowBranching (this);
2843 bool ok = Statement.Resolve (ec);
2845 ec.KillFlowBranching ();
2849 ResolveFinally (branching);
2851 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2852 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
2853 // Unfortunately, System.Reflection.Emit automatically emits
2854 // a leave to the end of the finally block.
2855 // This is a problem if `returns' is true since we may jump
2856 // to a point after the end of the method.
2857 // As a workaround, emit an explicit ret here.
2858 ec.NeedReturnLabel ();
2864 protected override void DoEmit (EmitContext ec)
2866 Type type = expr.Type;
2868 ILGenerator ig = ec.ig;
2869 temp = ig.DeclareLocal (type);
2872 ig.Emit (OpCodes.Dup);
2873 ig.Emit (OpCodes.Stloc, temp);
2874 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2878 ig.BeginExceptionBlock ();
2879 Statement.Emit (ec);
2884 ig.EndExceptionBlock ();
2887 public override void EmitFinally (EmitContext ec)
2889 ILGenerator ig = ec.ig;
2890 ig.Emit (OpCodes.Ldloc, temp);
2891 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2895 public class Unchecked : Statement {
2896 public readonly Block Block;
2898 public Unchecked (Block b)
2904 public override bool Resolve (EmitContext ec)
2906 bool previous_state = ec.CheckState;
2907 bool previous_state_const = ec.ConstantCheckState;
2909 ec.CheckState = false;
2910 ec.ConstantCheckState = false;
2911 bool ret = Block.Resolve (ec);
2912 ec.CheckState = previous_state;
2913 ec.ConstantCheckState = previous_state_const;
2918 protected override void DoEmit (EmitContext ec)
2920 bool previous_state = ec.CheckState;
2921 bool previous_state_const = ec.ConstantCheckState;
2923 ec.CheckState = false;
2924 ec.ConstantCheckState = false;
2926 ec.CheckState = previous_state;
2927 ec.ConstantCheckState = previous_state_const;
2931 public class Checked : Statement {
2932 public readonly Block Block;
2934 public Checked (Block b)
2937 b.Unchecked = false;
2940 public override bool Resolve (EmitContext ec)
2942 bool previous_state = ec.CheckState;
2943 bool previous_state_const = ec.ConstantCheckState;
2945 ec.CheckState = true;
2946 ec.ConstantCheckState = true;
2947 bool ret = Block.Resolve (ec);
2948 ec.CheckState = previous_state;
2949 ec.ConstantCheckState = previous_state_const;
2954 protected override void DoEmit (EmitContext ec)
2956 bool previous_state = ec.CheckState;
2957 bool previous_state_const = ec.ConstantCheckState;
2959 ec.CheckState = true;
2960 ec.ConstantCheckState = true;
2962 ec.CheckState = previous_state;
2963 ec.ConstantCheckState = previous_state_const;
2967 public class Unsafe : Statement {
2968 public readonly Block Block;
2970 public Unsafe (Block b)
2975 public override bool Resolve (EmitContext ec)
2977 bool previous_state = ec.InUnsafe;
2981 val = Block.Resolve (ec);
2982 ec.InUnsafe = previous_state;
2987 protected override void DoEmit (EmitContext ec)
2989 bool previous_state = ec.InUnsafe;
2993 ec.InUnsafe = previous_state;
3000 public class Fixed : Statement {
3002 ArrayList declarators;
3003 Statement statement;
3009 public bool is_object;
3010 public LocalInfo vi;
3011 public Expression expr;
3012 public Expression converted;
3015 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3018 declarators = decls;
3023 public override bool Resolve (EmitContext ec)
3026 Expression.UnsafeError (loc);
3030 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3031 if (expr_type == null)
3034 CheckObsolete (expr_type);
3036 if (ec.RemapToProxy){
3037 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3041 data = new FixedData [declarators.Count];
3043 if (!expr_type.IsPointer){
3044 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3049 foreach (Pair p in declarators){
3050 LocalInfo vi = (LocalInfo) p.First;
3051 Expression e = (Expression) p.Second;
3053 vi.VariableInfo = null;
3057 // The rules for the possible declarators are pretty wise,
3058 // but the production on the grammar is more concise.
3060 // So we have to enforce these rules here.
3062 // We do not resolve before doing the case 1 test,
3063 // because the grammar is explicit in that the token &
3064 // is present, so we need to test for this particular case.
3068 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3073 // Case 1: & object.
3075 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3076 Expression child = ((Unary) e).Expr;
3078 if (child is ParameterReference || child is LocalVariableReference){
3081 "No need to use fixed statement for parameters or " +
3082 "local variable declarations (address is already " +
3087 ec.InFixedInitializer = true;
3089 ec.InFixedInitializer = false;
3093 child = ((Unary) e).Expr;
3095 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3098 data [i].is_object = true;
3100 data [i].converted = null;
3107 ec.InFixedInitializer = true;
3109 ec.InFixedInitializer = false;
3116 if (e.Type.IsArray){
3117 Type array_type = TypeManager.GetElementType (e.Type);
3120 // Provided that array_type is unmanaged,
3122 if (!TypeManager.VerifyUnManaged (array_type, loc))
3126 // and T* is implicitly convertible to the
3127 // pointer type given in the fixed statement.
3129 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3131 Expression converted = Convert.ImplicitConversionRequired (
3132 ec, array_ptr, vi.VariableType, loc);
3133 if (converted == null)
3136 data [i].is_object = false;
3138 data [i].converted = converted;
3148 if (e.Type == TypeManager.string_type){
3149 data [i].is_object = false;
3151 data [i].converted = null;
3158 // For other cases, flag a `this is already fixed expression'
3160 if (e is LocalVariableReference || e is ParameterReference ||
3161 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3163 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3167 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3171 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3173 if (!statement.Resolve (ec)) {
3174 ec.KillFlowBranching ();
3178 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3179 has_ret = reachability.IsUnreachable;
3184 protected override void DoEmit (EmitContext ec)
3186 ILGenerator ig = ec.ig;
3188 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3190 for (int i = 0; i < data.Length; i++) {
3191 LocalInfo vi = data [i].vi;
3194 // Case 1: & object.
3196 if (data [i].is_object) {
3198 // Store pointer in pinned location
3200 data [i].expr.Emit (ec);
3201 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3202 clear_list [i] = vi.LocalBuilder;
3209 if (data [i].expr.Type.IsArray){
3211 // Store pointer in pinned location
3213 data [i].converted.Emit (ec);
3215 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3216 clear_list [i] = vi.LocalBuilder;
3223 if (data [i].expr.Type == TypeManager.string_type){
3224 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3225 clear_list [i] = pinned_string;
3227 data [i].expr.Emit (ec);
3228 ig.Emit (OpCodes.Stloc, pinned_string);
3230 Expression sptr = new StringPtr (pinned_string, loc);
3231 Expression converted = Convert.ImplicitConversionRequired (
3232 ec, sptr, vi.VariableType, loc);
3234 if (converted == null)
3237 converted.Emit (ec);
3238 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3242 statement.Emit (ec);
3248 // Clear the pinned variable
3250 for (int i = 0; i < data.Length; i++) {
3251 if (data [i].is_object || data [i].expr.Type.IsArray) {
3252 ig.Emit (OpCodes.Ldc_I4_0);
3253 ig.Emit (OpCodes.Conv_U);
3254 ig.Emit (OpCodes.Stloc, clear_list [i]);
3255 } else if (data [i].expr.Type == TypeManager.string_type){
3256 ig.Emit (OpCodes.Ldnull);
3257 ig.Emit (OpCodes.Stloc, clear_list [i]);
3263 public class Catch: Statement {
3264 public readonly string Name;
3265 public readonly Block Block;
3267 Expression type_expr;
3270 public Catch (Expression type, string name, Block block, Location l)
3278 public Type CatchType {
3284 public bool IsGeneral {
3286 return type_expr == null;
3290 protected override void DoEmit(EmitContext ec)
3294 public override bool Resolve (EmitContext ec)
3296 if (type_expr != null) {
3297 type = ec.DeclSpace.ResolveType (type_expr, false, loc);
3301 CheckObsolete (type);
3303 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3304 Error (155, "The type caught or thrown must be derived from System.Exception");
3310 return Block.Resolve (ec);
3314 public class Try : ExceptionStatement {
3315 public readonly Block Fini, Block;
3316 public readonly ArrayList Specific;
3317 public readonly Catch General;
3319 bool need_exc_block;
3322 // specific, general and fini might all be null.
3324 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3326 if (specific == null && general == null){
3327 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3331 this.Specific = specific;
3332 this.General = general;
3337 public override bool Resolve (EmitContext ec)
3341 FlowBranchingException branching = ec.StartFlowBranching (this);
3343 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3345 if (!Block.Resolve (ec))
3348 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3350 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3352 Type[] prevCatches = new Type [Specific.Count];
3354 foreach (Catch c in Specific){
3355 ec.CurrentBranching.CreateSibling (
3356 c.Block, FlowBranching.SiblingType.Catch);
3358 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3360 if (c.Name != null) {
3361 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3363 throw new Exception ();
3365 vi.VariableInfo = null;
3368 if (!c.Resolve (ec))
3371 Type resolvedType = c.CatchType;
3372 for (int ii = 0; ii < last_index; ++ii) {
3373 if (resolvedType.IsSubclassOf (prevCatches [ii])) {
3374 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3379 prevCatches [last_index++] = resolvedType;
3380 need_exc_block = true;
3383 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3385 if (General != null){
3386 ec.CurrentBranching.CreateSibling (
3387 General.Block, FlowBranching.SiblingType.Catch);
3389 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3391 if (!General.Resolve (ec))
3394 need_exc_block = true;
3397 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3401 ec.CurrentBranching.CreateSibling (
3402 Fini, FlowBranching.SiblingType.Finally);
3404 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3406 if (!Fini.Resolve (ec))
3410 ResolveFinally (branching);
3411 need_exc_block |= emit_finally;
3413 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3415 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3417 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3419 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3420 // Unfortunately, System.Reflection.Emit automatically emits
3421 // a leave to the end of the finally block. This is a problem
3422 // if `returns' is true since we may jump to a point after the
3423 // end of the method.
3424 // As a workaround, emit an explicit ret here.
3425 ec.NeedReturnLabel ();
3431 protected override void DoEmit (EmitContext ec)
3433 ILGenerator ig = ec.ig;
3436 ig.BeginExceptionBlock ();
3439 foreach (Catch c in Specific){
3442 ig.BeginCatchBlock (c.CatchType);
3444 if (c.Name != null){
3445 vi = c.Block.GetLocalInfo (c.Name);
3447 throw new Exception ("Variable does not exist in this block");
3449 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3451 ig.Emit (OpCodes.Pop);
3456 if (General != null){
3457 ig.BeginCatchBlock (TypeManager.object_type);
3458 ig.Emit (OpCodes.Pop);
3459 General.Block.Emit (ec);
3464 ig.EndExceptionBlock ();
3467 public override void EmitFinally (EmitContext ec)
3475 public class Using : ExceptionStatement {
3476 object expression_or_block;
3477 Statement Statement;
3482 Expression [] resolved_vars;
3483 Expression [] converted_vars;
3484 ExpressionStatement [] assign;
3485 LocalBuilder local_copy;
3487 public Using (object expression_or_block, Statement stmt, Location l)
3489 this.expression_or_block = expression_or_block;
3495 // Resolves for the case of using using a local variable declaration.
3497 bool ResolveLocalVariableDecls (EmitContext ec)
3499 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3502 if (expr_type == null)
3506 // The type must be an IDisposable or an implicit conversion
3509 converted_vars = new Expression [var_list.Count];
3510 resolved_vars = new Expression [var_list.Count];
3511 assign = new ExpressionStatement [var_list.Count];
3513 bool need_conv = !TypeManager.ImplementsInterface (
3514 expr_type, TypeManager.idisposable_type);
3516 foreach (DictionaryEntry e in var_list){
3517 Expression var = (Expression) e.Key;
3519 var = var.ResolveLValue (ec, new EmptyExpression ());
3523 resolved_vars [i] = var;
3530 converted_vars [i] = Convert.ImplicitConversionRequired (
3531 ec, var, TypeManager.idisposable_type, loc);
3533 if (converted_vars [i] == null)
3540 foreach (DictionaryEntry e in var_list){
3541 Expression var = resolved_vars [i];
3542 Expression new_expr = (Expression) e.Value;
3545 a = new Assign (var, new_expr, loc);
3551 converted_vars [i] = var;
3552 assign [i] = (ExpressionStatement) a;
3559 bool ResolveExpression (EmitContext ec)
3561 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3562 conv = Convert.ImplicitConversionRequired (
3563 ec, expr, TypeManager.idisposable_type, loc);
3573 // Emits the code for the case of using using a local variable declaration.
3575 void EmitLocalVariableDecls (EmitContext ec)
3577 ILGenerator ig = ec.ig;
3580 for (i = 0; i < assign.Length; i++) {
3581 assign [i].EmitStatement (ec);
3584 ig.BeginExceptionBlock ();
3586 Statement.Emit (ec);
3588 var_list.Reverse ();
3593 void EmitLocalVariableDeclFinally (EmitContext ec)
3595 ILGenerator ig = ec.ig;
3597 int i = assign.Length;
3598 foreach (DictionaryEntry e in var_list){
3599 Expression var = resolved_vars [--i];
3600 Label skip = ig.DefineLabel ();
3602 ig.BeginFinallyBlock ();
3604 if (!var.Type.IsValueType) {
3606 ig.Emit (OpCodes.Brfalse, skip);
3607 converted_vars [i].Emit (ec);
3608 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3610 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3612 if (!(ml is MethodGroupExpr)) {
3614 ig.Emit (OpCodes.Box, var.Type);
3615 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3617 MethodInfo mi = null;
3619 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3620 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3627 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3631 IMemoryLocation mloc = (IMemoryLocation) var;
3633 mloc.AddressOf (ec, AddressOp.Load);
3634 ig.Emit (OpCodes.Call, mi);
3638 ig.MarkLabel (skip);
3641 ig.EndExceptionBlock ();
3643 ig.BeginFinallyBlock ();
3648 void EmitExpression (EmitContext ec)
3651 // Make a copy of the expression and operate on that.
3653 ILGenerator ig = ec.ig;
3654 local_copy = ig.DeclareLocal (expr_type);
3659 ig.Emit (OpCodes.Stloc, local_copy);
3662 ig.BeginExceptionBlock ();
3664 Statement.Emit (ec);
3668 ig.EndExceptionBlock ();
3671 void EmitExpressionFinally (EmitContext ec)
3673 ILGenerator ig = ec.ig;
3674 Label skip = ig.DefineLabel ();
3675 ig.Emit (OpCodes.Ldloc, local_copy);
3676 ig.Emit (OpCodes.Brfalse, skip);
3677 ig.Emit (OpCodes.Ldloc, local_copy);
3678 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3679 ig.MarkLabel (skip);
3682 public override bool Resolve (EmitContext ec)
3684 if (expression_or_block is DictionaryEntry){
3685 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3686 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3688 if (!ResolveLocalVariableDecls (ec))
3691 } else if (expression_or_block is Expression){
3692 expr = (Expression) expression_or_block;
3694 expr = expr.Resolve (ec);
3698 expr_type = expr.Type;
3700 if (!ResolveExpression (ec))
3704 FlowBranchingException branching = ec.StartFlowBranching (this);
3706 bool ok = Statement.Resolve (ec);
3709 ec.KillFlowBranching ();
3713 ResolveFinally (branching);
3714 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3716 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3717 // Unfortunately, System.Reflection.Emit automatically emits a leave
3718 // to the end of the finally block. This is a problem if `returns'
3719 // is true since we may jump to a point after the end of the method.
3720 // As a workaround, emit an explicit ret here.
3721 ec.NeedReturnLabel ();
3727 protected override void DoEmit (EmitContext ec)
3729 if (expression_or_block is DictionaryEntry)
3730 EmitLocalVariableDecls (ec);
3731 else if (expression_or_block is Expression)
3732 EmitExpression (ec);
3735 public override void EmitFinally (EmitContext ec)
3737 if (expression_or_block is DictionaryEntry)
3738 EmitLocalVariableDeclFinally (ec);
3739 else if (expression_or_block is Expression)
3740 EmitExpressionFinally (ec);
3745 /// Implementation of the foreach C# statement
3747 public class Foreach : ExceptionStatement {
3749 Expression variable;
3751 Statement statement;
3752 ForeachHelperMethods hm;
3753 Expression empty, conv;
3754 Type array_type, element_type;
3756 VariableStorage enumerator;
3758 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3759 Statement stmt, Location l)
3762 this.variable = var;
3768 public override bool Resolve (EmitContext ec)
3770 expr = expr.Resolve (ec);
3774 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3775 if (var_type == null)
3779 // We need an instance variable. Not sure this is the best
3780 // way of doing this.
3782 // FIXME: When we implement propertyaccess, will those turn
3783 // out to return values in ExprClass? I think they should.
3785 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3786 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3787 error1579 (expr.Type);
3791 if (expr.Type.IsArray) {
3792 array_type = expr.Type;
3793 element_type = TypeManager.GetElementType (array_type);
3795 empty = new EmptyExpression (element_type);
3797 hm = ProbeCollectionType (ec, expr.Type);
3799 error1579 (expr.Type);
3803 array_type = expr.Type;
3804 element_type = hm.element_type;
3806 empty = new EmptyExpression (hm.element_type);
3811 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3812 ec.CurrentBranching.CreateSibling ();
3816 // FIXME: maybe we can apply the same trick we do in the
3817 // array handling to avoid creating empty and conv in some cases.
3819 // Although it is not as important in this case, as the type
3820 // will not likely be object (what the enumerator will return).
3822 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3826 variable = variable.ResolveLValue (ec, empty);
3827 if (variable == null)
3830 bool disposable = (hm != null) && hm.is_disposable;
3831 FlowBranchingException branching = null;
3833 branching = ec.StartFlowBranching (this);
3835 if (!statement.Resolve (ec))
3839 ResolveFinally (branching);
3840 ec.EndFlowBranching ();
3842 emit_finally = true;
3844 ec.EndFlowBranching ();
3850 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3852 static MethodInfo FetchMethodMoveNext (Type t)
3854 MemberList move_next_list;
3856 move_next_list = TypeContainer.FindMembers (
3857 t, MemberTypes.Method,
3858 BindingFlags.Public | BindingFlags.Instance,
3859 Type.FilterName, "MoveNext");
3860 if (move_next_list.Count == 0)
3863 foreach (MemberInfo m in move_next_list){
3864 MethodInfo mi = (MethodInfo) m;
3867 args = TypeManager.GetArgumentTypes (mi);
3868 if (args != null && args.Length == 0){
3869 if (mi.ReturnType == TypeManager.bool_type)
3877 // Retrieves a `public T get_Current ()' method from the Type `t'
3879 static MethodInfo FetchMethodGetCurrent (Type t)
3881 MemberList get_current_list;
3883 get_current_list = TypeContainer.FindMembers (
3884 t, MemberTypes.Method,
3885 BindingFlags.Public | BindingFlags.Instance,
3886 Type.FilterName, "get_Current");
3887 if (get_current_list.Count == 0)
3890 foreach (MemberInfo m in get_current_list){
3891 MethodInfo mi = (MethodInfo) m;
3894 args = TypeManager.GetArgumentTypes (mi);
3895 if (args != null && args.Length == 0)
3902 // Retrieves a `public void Dispose ()' method from the Type `t'
3904 static MethodInfo FetchMethodDispose (Type t)
3906 MemberList dispose_list;
3908 dispose_list = TypeContainer.FindMembers (
3909 t, MemberTypes.Method,
3910 BindingFlags.Public | BindingFlags.Instance,
3911 Type.FilterName, "Dispose");
3912 if (dispose_list.Count == 0)
3915 foreach (MemberInfo m in dispose_list){
3916 MethodInfo mi = (MethodInfo) m;
3919 args = TypeManager.GetArgumentTypes (mi);
3920 if (args != null && args.Length == 0){
3921 if (mi.ReturnType == TypeManager.void_type)
3929 // This struct records the helper methods used by the Foreach construct
3931 class ForeachHelperMethods {
3932 public EmitContext ec;
3933 public MethodInfo get_enumerator;
3934 public MethodInfo move_next;
3935 public MethodInfo get_current;
3936 public Type element_type;
3937 public Type enumerator_type;
3938 public bool is_disposable;
3940 public ForeachHelperMethods (EmitContext ec)
3943 this.element_type = TypeManager.object_type;
3944 this.enumerator_type = TypeManager.ienumerator_type;
3945 this.is_disposable = true;
3949 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3954 if (!(m is MethodInfo))
3957 if (m.Name != "GetEnumerator")
3960 MethodInfo mi = (MethodInfo) m;
3961 Type [] args = TypeManager.GetArgumentTypes (mi);
3963 if (args.Length != 0)
3966 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3967 EmitContext ec = hm.ec;
3969 // Check whether GetEnumerator is public
3970 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
3973 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
3975 // Apply the same optimization as MS: skip the GetEnumerator
3976 // returning an IEnumerator, and use the one returning a
3977 // CharEnumerator instead. This allows us to avoid the
3978 // try-finally block and the boxing.
3983 // Ok, we can access it, now make sure that we can do something
3984 // with this `GetEnumerator'
3987 Type return_type = mi.ReturnType;
3988 if (mi.ReturnType == TypeManager.ienumerator_type ||
3989 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3990 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3993 // If it is not an interface, lets try to find the methods ourselves.
3994 // For example, if we have:
3995 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3996 // We can avoid the iface call. This is a runtime perf boost.
3997 // even bigger if we have a ValueType, because we avoid the cost
4000 // We have to make sure that both methods exist for us to take
4001 // this path. If one of the methods does not exist, we will just
4002 // use the interface. Sadly, this complex if statement is the only
4003 // way I could do this without a goto
4006 if (return_type.IsInterface ||
4007 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4008 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4010 hm.move_next = TypeManager.bool_movenext_void;
4011 hm.get_current = TypeManager.object_getcurrent_void;
4018 // Ok, so they dont return an IEnumerable, we will have to
4019 // find if they support the GetEnumerator pattern.
4022 hm.move_next = FetchMethodMoveNext (return_type);
4023 if (hm.move_next == null)
4026 hm.get_current = FetchMethodGetCurrent (return_type);
4027 if (hm.get_current == null)
4031 hm.element_type = hm.get_current.ReturnType;
4032 hm.enumerator_type = return_type;
4033 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4034 TypeManager.ImplementsInterface (
4035 hm.enumerator_type, TypeManager.idisposable_type);
4041 /// This filter is used to find the GetEnumerator method
4042 /// on which IEnumerator operates
4044 static MemberFilter FilterEnumerator;
4048 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4051 void error1579 (Type t)
4053 Report.Error (1579, loc,
4054 "foreach statement cannot operate on variables of type `" +
4055 t.FullName + "' because that class does not provide a " +
4056 " GetEnumerator method or it is inaccessible");
4059 static bool TryType (Type t, ForeachHelperMethods hm)
4063 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4064 BindingFlags.Public | BindingFlags.NonPublic |
4065 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4066 FilterEnumerator, hm);
4071 hm.get_enumerator = (MethodInfo) mi [0];
4076 // Looks for a usable GetEnumerator in the Type, and if found returns
4077 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4079 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4081 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4083 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4084 if (TryType (tt, hm))
4090 // Now try to find the method in the interfaces
4093 Type [] ifaces = t.GetInterfaces ();
4095 foreach (Type i in ifaces){
4096 if (TryType (i, hm))
4101 // Since TypeBuilder.GetInterfaces only returns the interface
4102 // types for this type, we have to keep looping, but once
4103 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4104 // done, because it returns all the types
4106 if ((t is TypeBuilder))
4116 // FIXME: possible optimization.
4117 // We might be able to avoid creating `empty' if the type is the sam
4119 bool EmitCollectionForeach (EmitContext ec)
4121 ILGenerator ig = ec.ig;
4123 enumerator = new VariableStorage (ec, hm.enumerator_type);
4124 enumerator.EmitThis ();
4126 // Instantiate the enumerator
4128 if (expr.Type.IsValueType){
4129 IMemoryLocation ml = expr as IMemoryLocation;
4130 // Load the address of the value type.
4132 // This happens if, for example, you have a property
4133 // returning a struct which is IEnumerable
4134 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4136 ig.Emit (OpCodes.Stloc, t);
4137 ig.Emit (OpCodes.Ldloca, t);
4138 ec.FreeTemporaryLocal (t, expr.Type);
4140 ml.AddressOf (ec, AddressOp.Load);
4144 if (hm.get_enumerator.DeclaringType.IsValueType) {
4145 // the method is declared on the value type
4146 ig.Emit (OpCodes.Call, hm.get_enumerator);
4148 // it is an interface method, so we must box
4149 ig.Emit (OpCodes.Box, expr.Type);
4150 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4154 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4156 enumerator.EmitStore ();
4159 // Protect the code in a try/finalize block, so that
4160 // if the beast implement IDisposable, we get rid of it
4162 if (hm.is_disposable && emit_finally)
4163 ig.BeginExceptionBlock ();
4165 Label end_try = ig.DefineLabel ();
4167 ig.MarkLabel (ec.LoopBegin);
4169 enumerator.EmitCall (hm.move_next);
4171 ig.Emit (OpCodes.Brfalse, end_try);
4175 enumerator.EmitCall (hm.get_current);
4179 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4181 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4183 statement.Emit (ec);
4184 ig.Emit (OpCodes.Br, ec.LoopBegin);
4185 ig.MarkLabel (end_try);
4187 // The runtime provides this for us.
4188 // ig.Emit (OpCodes.Leave, end);
4191 // Now the finally block
4193 if (hm.is_disposable) {
4196 ig.EndExceptionBlock ();
4199 ig.MarkLabel (ec.LoopEnd);
4203 public override void EmitFinally (EmitContext ec)
4205 ILGenerator ig = ec.ig;
4207 if (hm.enumerator_type.IsValueType) {
4208 enumerator.EmitThis ();
4210 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4212 enumerator.EmitLoadAddress ();
4213 ig.Emit (OpCodes.Call, mi);
4215 enumerator.EmitLoad ();
4216 ig.Emit (OpCodes.Box, hm.enumerator_type);
4217 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4220 Label call_dispose = ig.DefineLabel ();
4222 enumerator.EmitThis ();
4223 enumerator.EmitLoad ();
4224 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4225 ig.Emit (OpCodes.Dup);
4226 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4227 ig.Emit (OpCodes.Pop);
4228 ig.Emit (OpCodes.Endfinally);
4230 ig.MarkLabel (call_dispose);
4231 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4236 // FIXME: possible optimization.
4237 // We might be able to avoid creating `empty' if the type is the sam
4239 bool EmitArrayForeach (EmitContext ec)
4241 int rank = array_type.GetArrayRank ();
4242 ILGenerator ig = ec.ig;
4244 VariableStorage copy = new VariableStorage (ec, array_type);
4247 // Make our copy of the array
4254 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4258 counter.EmitThis ();
4259 ig.Emit (OpCodes.Ldc_I4_0);
4260 counter.EmitStore ();
4261 test = ig.DefineLabel ();
4262 ig.Emit (OpCodes.Br, test);
4264 loop = ig.DefineLabel ();
4265 ig.MarkLabel (loop);
4272 counter.EmitThis ();
4273 counter.EmitLoad ();
4276 // Load the value, we load the value using the underlying type,
4277 // then we use the variable.EmitAssign to load using the proper cast.
4279 ArrayAccess.EmitLoadOpcode (ig, element_type);
4282 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4284 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4286 statement.Emit (ec);
4288 ig.MarkLabel (ec.LoopBegin);
4289 counter.EmitThis ();
4290 counter.EmitThis ();
4291 counter.EmitLoad ();
4292 ig.Emit (OpCodes.Ldc_I4_1);
4293 ig.Emit (OpCodes.Add);
4294 counter.EmitStore ();
4296 ig.MarkLabel (test);
4297 counter.EmitThis ();
4298 counter.EmitLoad ();
4301 ig.Emit (OpCodes.Ldlen);
4302 ig.Emit (OpCodes.Conv_I4);
4303 ig.Emit (OpCodes.Blt, loop);
4305 VariableStorage [] dim_len = new VariableStorage [rank];
4306 VariableStorage [] dim_count = new VariableStorage [rank];
4307 Label [] loop = new Label [rank];
4308 Label [] test = new Label [rank];
4311 for (dim = 0; dim < rank; dim++){
4312 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4313 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4314 test [dim] = ig.DefineLabel ();
4315 loop [dim] = ig.DefineLabel ();
4318 for (dim = 0; dim < rank; dim++){
4319 dim_len [dim].EmitThis ();
4322 IntLiteral.EmitInt (ig, dim);
4323 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4324 dim_len [dim].EmitStore ();
4328 for (dim = 0; dim < rank; dim++){
4329 dim_count [dim].EmitThis ();
4330 ig.Emit (OpCodes.Ldc_I4_0);
4331 dim_count [dim].EmitStore ();
4332 ig.Emit (OpCodes.Br, test [dim]);
4333 ig.MarkLabel (loop [dim]);
4340 for (dim = 0; dim < rank; dim++){
4341 dim_count [dim].EmitThis ();
4342 dim_count [dim].EmitLoad ();
4346 // FIXME: Maybe we can cache the computation of `get'?
4348 Type [] args = new Type [rank];
4351 for (int i = 0; i < rank; i++)
4352 args [i] = TypeManager.int32_type;
4354 ModuleBuilder mb = CodeGen.Module.Builder;
4355 get = mb.GetArrayMethod (
4357 CallingConventions.HasThis| CallingConventions.Standard,
4359 ig.Emit (OpCodes.Call, get);
4362 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4364 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4365 statement.Emit (ec);
4366 ig.MarkLabel (ec.LoopBegin);
4367 for (dim = rank - 1; dim >= 0; dim--){
4368 dim_count [dim].EmitThis ();
4369 dim_count [dim].EmitThis ();
4370 dim_count [dim].EmitLoad ();
4371 ig.Emit (OpCodes.Ldc_I4_1);
4372 ig.Emit (OpCodes.Add);
4373 dim_count [dim].EmitStore ();
4375 ig.MarkLabel (test [dim]);
4376 dim_count [dim].EmitThis ();
4377 dim_count [dim].EmitLoad ();
4378 dim_len [dim].EmitThis ();
4379 dim_len [dim].EmitLoad ();
4380 ig.Emit (OpCodes.Blt, loop [dim]);
4383 ig.MarkLabel (ec.LoopEnd);
4388 protected override void DoEmit (EmitContext ec)
4390 ILGenerator ig = ec.ig;
4392 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4393 ec.LoopBegin = ig.DefineLabel ();
4394 ec.LoopEnd = ig.DefineLabel ();
4397 EmitCollectionForeach (ec);
4399 EmitArrayForeach (ec);
4401 ec.LoopBegin = old_begin;
4402 ec.LoopEnd = old_end;