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 if (VariableType.IsAbstract && VariableType.IsSealed) {
1026 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1029 // TODO: breaks the build
1030 // if (VariableType.IsPointer && !ec.InUnsafe)
1031 // Expression.UnsafeError (Location);
1037 // Whether the variable is Fixed (because its Pinned or its a value type)
1039 public bool IsFixed {
1041 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1048 public override string ToString ()
1050 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1051 Name, Type, VariableInfo, Location);
1056 return (flags & Flags.Used) != 0;
1059 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1063 public bool ReadOnly {
1065 return (flags & Flags.ReadOnly) != 0;
1068 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1073 // Whether the variable is pinned, if Pinned the variable has been
1074 // allocated in a pinned slot with DeclareLocal.
1076 public bool Pinned {
1078 return (flags & Flags.Pinned) != 0;
1081 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1085 public bool IsThis {
1087 return (flags & Flags.IsThis) != 0;
1090 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1096 /// Block represents a C# block.
1100 /// This class is used in a number of places: either to represent
1101 /// explicit blocks that the programmer places or implicit blocks.
1103 /// Implicit blocks are used as labels or to introduce variable
1106 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1107 /// they contain extra information that is not necessary on normal blocks.
1109 public class Block : Statement {
1110 public readonly Block Parent;
1111 public readonly Location StartLocation;
1112 public Location EndLocation = Location.Null;
1115 public enum Flags : byte {
1119 VariablesInitialized = 8,
1126 public bool Implicit {
1128 return (flags & Flags.Implicit) != 0;
1132 public bool Unchecked {
1134 return (flags & Flags.Unchecked) != 0;
1137 flags |= Flags.Unchecked;
1141 public bool HasVarargs {
1144 return Parent.HasVarargs;
1146 return (flags & Flags.HasVarargs) != 0;
1149 flags |= Flags.HasVarargs;
1154 // The statements in this block
1156 ArrayList statements;
1160 // An array of Blocks. We keep track of children just
1161 // to generate the local variable declarations.
1163 // Statements and child statements are handled through the
1169 // Labels. (label, block) pairs.
1174 // Keeps track of (name, type) pairs
1176 Hashtable variables;
1179 // Keeps track of constants
1180 Hashtable constants;
1183 // If this is a switch section, the enclosing switch block.
1191 public Block (Block parent)
1192 : this (parent, (Flags) 0, Location.Null, Location.Null)
1195 public Block (Block parent, Flags flags)
1196 : this (parent, flags, Location.Null, Location.Null)
1199 public Block (Block parent, Flags flags, Parameters parameters)
1200 : this (parent, flags, parameters, Location.Null, Location.Null)
1203 public Block (Block parent, Location start, Location end)
1204 : this (parent, (Flags) 0, start, end)
1207 public Block (Block parent, Parameters parameters, Location start, Location end)
1208 : this (parent, (Flags) 0, parameters, start, end)
1211 public Block (Block parent, Flags flags, Location start, Location end)
1212 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1215 public Block (Block parent, Flags flags, Parameters parameters,
1216 Location start, Location end)
1219 parent.AddChild (this);
1221 this.Parent = parent;
1223 this.parameters = parameters;
1224 this.StartLocation = start;
1225 this.EndLocation = end;
1228 statements = new ArrayList ();
1230 if (parent != null && Implicit) {
1231 if (parent.child_variable_names == null)
1232 parent.child_variable_names = new Hashtable();
1233 // share with parent
1234 child_variable_names = parent.child_variable_names;
1239 public Block CreateSwitchBlock (Location start)
1241 Block new_block = new Block (this, start, start);
1242 new_block.switch_block = this;
1252 void AddChild (Block b)
1254 if (children == null)
1255 children = new ArrayList ();
1260 public void SetEndLocation (Location loc)
1266 /// Adds a label to the current block.
1270 /// false if the name already exists in this block. true
1274 public bool AddLabel (string name, LabeledStatement target, Location loc)
1276 if (switch_block != null)
1277 return switch_block.AddLabel (name, target, loc);
1280 while (cur != null) {
1281 if (cur.DoLookupLabel (name) != null) {
1283 140, loc, "The label '{0}' is a duplicate",
1294 while (cur != null) {
1295 if (cur.DoLookupLabel (name) != null) {
1298 "The label '{0}' shadows another label " +
1299 "by the same name in a containing scope.",
1304 if (children != null) {
1305 foreach (Block b in children) {
1306 LabeledStatement s = b.DoLookupLabel (name);
1312 "The label '{0}' shadows another " +
1313 "label by the same name in a " +
1314 "containing scope.",
1325 labels = new Hashtable ();
1327 labels.Add (name, target);
1331 public LabeledStatement LookupLabel (string name)
1333 LabeledStatement s = DoLookupLabel (name);
1337 if (children == null)
1340 foreach (Block child in children) {
1341 if (!child.Implicit)
1344 s = child.LookupLabel (name);
1352 LabeledStatement DoLookupLabel (string name)
1354 if (switch_block != null)
1355 return switch_block.LookupLabel (name);
1358 if (labels.Contains (name))
1359 return ((LabeledStatement) labels [name]);
1364 LocalInfo this_variable = null;
1367 // Returns the "this" instance variable of this block.
1368 // See AddThisVariable() for more information.
1370 public LocalInfo ThisVariable {
1372 if (this_variable != null)
1373 return this_variable;
1374 else if (Parent != null)
1375 return Parent.ThisVariable;
1381 Hashtable child_variable_names;
1384 // Marks a variable with name @name as being used in a child block.
1385 // If a variable name has been used in a child block, it's illegal to
1386 // declare a variable with the same name in the current block.
1388 public void AddChildVariableName (string name)
1390 if (child_variable_names == null)
1391 child_variable_names = new Hashtable ();
1393 if (!child_variable_names.Contains (name))
1394 child_variable_names.Add (name, true);
1398 // Checks whether a variable name has already been used in a child block.
1400 public bool IsVariableNameUsedInChildBlock (string name)
1402 if (child_variable_names == null)
1405 return child_variable_names.Contains (name);
1409 // This is used by non-static `struct' constructors which do not have an
1410 // initializer - in this case, the constructor must initialize all of the
1411 // struct's fields. To do this, we add a "this" variable and use the flow
1412 // analysis code to ensure that it's been fully initialized before control
1413 // leaves the constructor.
1415 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1417 if (this_variable != null)
1418 return this_variable;
1420 if (variables == null)
1421 variables = new Hashtable ();
1423 this_variable = new LocalInfo (tc, this, l);
1424 this_variable.Used = true;
1425 this_variable.IsThis = true;
1427 variables.Add ("this", this_variable);
1429 return this_variable;
1432 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1434 if (variables == null)
1435 variables = new Hashtable ();
1437 LocalInfo vi = GetLocalInfo (name);
1439 if (vi.Block != this)
1440 Report.Error (136, l, "A local variable named `" + name + "' " +
1441 "cannot be declared in this scope since it would " +
1442 "give a different meaning to `" + name + "', which " +
1443 "is already used in a `parent or current' scope to " +
1444 "denote something else");
1446 Report.Error (128, l, "A local variable `" + name + "' is already " +
1447 "defined in this scope");
1451 if (IsVariableNameUsedInChildBlock (name)) {
1452 Report.Error (136, l, "A local variable named `" + name + "' " +
1453 "cannot be declared in this scope since it would " +
1454 "give a different meaning to `" + name + "', which " +
1455 "is already used in a `child' scope to denote something " +
1462 Parameter p = pars.GetParameterByName (name, out idx);
1464 Report.Error (136, l, "A local variable named `" + name + "' " +
1465 "cannot be declared in this scope since it would " +
1466 "give a different meaning to `" + name + "', which " +
1467 "is already used in a `parent or current' scope to " +
1468 "denote something else");
1473 vi = new LocalInfo (type, name, this, l);
1475 variables.Add (name, vi);
1477 // Mark 'name' as "used by a child block" in every surrounding block
1479 while (cur != null && cur.Implicit)
1482 for (Block par = cur.Parent; par != null; par = par.Parent)
1483 par.AddChildVariableName (name);
1485 if ((flags & Flags.VariablesInitialized) != 0)
1486 throw new Exception ();
1488 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1492 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1494 if (AddVariable (type, name, pars, l) == null)
1497 if (constants == null)
1498 constants = new Hashtable ();
1500 constants.Add (name, value);
1504 public Hashtable Variables {
1510 public LocalInfo GetLocalInfo (string name)
1512 for (Block b = this; b != null; b = b.Parent) {
1513 if (b.variables != null) {
1514 LocalInfo ret = b.variables [name] as LocalInfo;
1522 public Expression GetVariableType (string name)
1524 LocalInfo vi = GetLocalInfo (name);
1532 public Expression GetConstantExpression (string name)
1534 for (Block b = this; b != null; b = b.Parent) {
1535 if (b.constants != null) {
1536 Expression ret = b.constants [name] as Expression;
1545 /// True if the variable named @name is a constant
1547 public bool IsConstant (string name)
1549 Expression e = null;
1551 e = GetConstantExpression (name);
1556 Parameters parameters = null;
1557 public Parameters Parameters {
1560 while (b.Parent != null)
1562 return b.parameters;
1567 /// A list of labels that were not used within this block
1569 public string [] GetUnreferenced ()
1571 // FIXME: Implement me
1575 public void AddStatement (Statement s)
1578 flags |= Flags.BlockUsed;
1583 return (flags & Flags.BlockUsed) != 0;
1589 flags |= Flags.BlockUsed;
1592 public bool HasRet {
1594 return (flags & Flags.HasRet) != 0;
1598 public bool IsDestructor {
1600 return (flags & Flags.IsDestructor) != 0;
1604 public void SetDestructor ()
1606 flags |= Flags.IsDestructor;
1609 VariableMap param_map, local_map;
1611 public VariableMap ParameterMap {
1613 if ((flags & Flags.VariablesInitialized) == 0)
1614 throw new Exception ();
1620 public VariableMap LocalMap {
1622 if ((flags & Flags.VariablesInitialized) == 0)
1623 throw new Exception ();
1629 public bool LiftVariable (LocalInfo local_info)
1635 /// Emits the variable declarations and labels.
1638 /// tc: is our typecontainer (to resolve type references)
1639 /// ig: is the code generator:
1641 public void EmitMeta (EmitContext ec, InternalParameters ip)
1643 ILGenerator ig = ec.ig;
1646 // Compute the VariableMap's.
1648 // Unfortunately, we don't know the type when adding variables with
1649 // AddVariable(), so we need to compute this info here.
1653 if (variables != null) {
1654 foreach (LocalInfo li in variables.Values)
1657 locals = new LocalInfo [variables.Count];
1658 variables.Values.CopyTo (locals, 0);
1660 locals = new LocalInfo [0];
1663 local_map = new VariableMap (Parent.LocalMap, locals);
1665 local_map = new VariableMap (locals);
1667 param_map = new VariableMap (ip);
1668 flags |= Flags.VariablesInitialized;
1670 bool old_check_state = ec.ConstantCheckState;
1671 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1672 bool remap_locals = ec.RemapToProxy;
1675 // Process this block variables
1677 if (variables != null){
1678 foreach (DictionaryEntry de in variables){
1679 string name = (string) de.Key;
1680 LocalInfo vi = (LocalInfo) de.Value;
1682 if (vi.VariableType == null)
1685 Type variable_type = vi.VariableType;
1687 if (variable_type.IsPointer){
1689 // Am not really convinced that this test is required (Microsoft does it)
1690 // but the fact is that you would not be able to use the pointer variable
1693 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1699 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1702 // This is needed to compile on both .NET 1.x and .NET 2.x
1703 // the later introduced `DeclareLocal (Type t, bool pinned)'
1705 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1706 else if (!vi.IsThis)
1707 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1709 if (constants == null)
1712 Expression cv = (Expression) constants [name];
1716 ec.CurrentBlock = this;
1717 Expression e = cv.Resolve (ec);
1721 Constant ce = e as Constant;
1723 Report.Error (133, vi.Location,
1724 "The expression being assigned to `" +
1725 name + "' must be constant (" + e + ")");
1729 if (e.Type != variable_type){
1730 e = Const.ChangeType (vi.Location, ce, variable_type);
1735 constants.Remove (name);
1736 constants.Add (name, e);
1739 ec.ConstantCheckState = old_check_state;
1742 // Now, handle the children
1744 if (children != null){
1745 foreach (Block b in children)
1746 b.EmitMeta (ec, ip);
1750 void UsageWarning (FlowBranching.UsageVector vector)
1754 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1755 foreach (DictionaryEntry de in variables){
1756 LocalInfo vi = (LocalInfo) de.Value;
1761 name = (string) de.Key;
1763 if (vector.IsAssigned (vi.VariableInfo)){
1764 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1766 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1772 bool unreachable_shown;
1774 public override bool Resolve (EmitContext ec)
1776 Block prev_block = ec.CurrentBlock;
1779 int errors = Report.Errors;
1781 ec.CurrentBlock = this;
1782 ec.StartFlowBranching (this);
1784 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1786 bool unreachable = false;
1788 int statement_count = statements.Count;
1789 for (int ix = 0; ix < statement_count; ix++){
1790 Statement s = (Statement) statements [ix];
1792 if (unreachable && !(s is LabeledStatement)) {
1793 if (s == EmptyStatement.Value)
1794 s.loc = EndLocation;
1796 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1799 if (s != EmptyStatement.Value)
1800 unreachable_shown = true;
1802 s.loc = Location.Null;
1804 statements [ix] = EmptyStatement.Value;
1808 if (s.Resolve (ec) == false) {
1810 statements [ix] = EmptyStatement.Value;
1814 num_statements = ix + 1;
1816 if (s is LabeledStatement)
1817 unreachable = false;
1819 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1822 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1823 ec.CurrentBranching, statement_count, num_statements);
1826 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1828 ec.CurrentBlock = prev_block;
1830 // If we're a non-static `struct' constructor which doesn't have an
1831 // initializer, then we must initialize all of the struct's fields.
1832 if ((this_variable != null) &&
1833 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1834 !this_variable.IsThisAssigned (ec, loc))
1837 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1838 foreach (LabeledStatement label in labels.Values)
1839 if (!label.HasBeenReferenced)
1840 Report.Warning (164, label.Location,
1841 "This label has not been referenced");
1844 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1846 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1847 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1848 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1849 flags |= Flags.HasRet;
1851 if (ok && (errors == Report.Errors)) {
1852 if (RootContext.WarningLevel >= 3)
1853 UsageWarning (vector);
1859 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1861 unreachable_shown = true;
1862 return base.ResolveUnreachable (ec, warn);
1865 protected override void DoEmit (EmitContext ec)
1867 for (int ix = 0; ix < num_statements; ix++){
1868 Statement s = (Statement) statements [ix];
1870 // Check whether we are the last statement in a
1873 if ((Parent == null) && (ix+1 == num_statements))
1874 ec.IsLastStatement = true;
1876 ec.IsLastStatement = false;
1882 public override void Emit (EmitContext ec)
1884 Block prev_block = ec.CurrentBlock;
1886 ec.CurrentBlock = this;
1888 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1889 bool is_lexical_block = !Implicit && (Parent != null);
1891 if (emit_debug_info) {
1892 if (is_lexical_block)
1893 ec.ig.BeginScope ();
1895 if (variables != null) {
1896 foreach (DictionaryEntry de in variables) {
1897 string name = (string) de.Key;
1898 LocalInfo vi = (LocalInfo) de.Value;
1900 if (vi.LocalBuilder == null)
1903 ec.DefineLocalVariable (name, vi.LocalBuilder);
1908 ec.Mark (StartLocation, true);
1910 ec.Mark (EndLocation, true);
1912 if (emit_debug_info && is_lexical_block)
1915 ec.CurrentBlock = prev_block;
1921 public class ToplevelBlock : Block {
1922 public ToplevelBlock (Parameters parameters, Location start) :
1923 base (null, parameters, start, Location.Null)
1927 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1928 base (null, flags, parameters, start, Location.Null)
1933 public class SwitchLabel {
1936 public Location loc;
1937 public Label ILLabel;
1938 public Label ILLabelCode;
1941 // if expr == null, then it is the default case.
1943 public SwitchLabel (Expression expr, Location l)
1949 public Expression Label {
1955 public object Converted {
1962 // Resolves the expression, reduces it to a literal if possible
1963 // and then converts it to the requested type.
1965 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1967 ILLabel = ec.ig.DefineLabel ();
1968 ILLabelCode = ec.ig.DefineLabel ();
1973 Expression e = label.Resolve (ec);
1978 if (!(e is Constant)){
1979 Report.Error (150, loc, "A constant value is expected, got: " + e);
1983 if (e is StringConstant || e is NullLiteral){
1984 if (required_type == TypeManager.string_type){
1986 ILLabel = ec.ig.DefineLabel ();
1991 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1992 if (converted == null)
1999 public class SwitchSection {
2000 // An array of SwitchLabels.
2001 public readonly ArrayList Labels;
2002 public readonly Block Block;
2004 public SwitchSection (ArrayList labels, Block block)
2011 public class Switch : Statement {
2012 public readonly ArrayList Sections;
2013 public Expression Expr;
2016 /// Maps constants whose type type SwitchType to their SwitchLabels.
2018 public Hashtable Elements;
2021 /// The governing switch type
2023 public Type SwitchType;
2029 Label default_target;
2030 Expression new_expr;
2032 SwitchSection constant_section;
2035 // The types allowed to be implicitly cast from
2036 // on the governing type
2038 static Type [] allowed_types;
2040 public Switch (Expression e, ArrayList sects, Location l)
2047 public bool GotDefault {
2053 public Label DefaultTarget {
2055 return default_target;
2060 // Determines the governing type for a switch. The returned
2061 // expression might be the expression from the switch, or an
2062 // expression that includes any potential conversions to the
2063 // integral types or to string.
2065 Expression SwitchGoverningType (EmitContext ec, Type t)
2067 if (t == TypeManager.int32_type ||
2068 t == TypeManager.uint32_type ||
2069 t == TypeManager.char_type ||
2070 t == TypeManager.byte_type ||
2071 t == TypeManager.sbyte_type ||
2072 t == TypeManager.ushort_type ||
2073 t == TypeManager.short_type ||
2074 t == TypeManager.uint64_type ||
2075 t == TypeManager.int64_type ||
2076 t == TypeManager.string_type ||
2077 t == TypeManager.bool_type ||
2078 t.IsSubclassOf (TypeManager.enum_type))
2081 if (allowed_types == null){
2082 allowed_types = new Type [] {
2083 TypeManager.sbyte_type,
2084 TypeManager.byte_type,
2085 TypeManager.short_type,
2086 TypeManager.ushort_type,
2087 TypeManager.int32_type,
2088 TypeManager.uint32_type,
2089 TypeManager.int64_type,
2090 TypeManager.uint64_type,
2091 TypeManager.char_type,
2092 TypeManager.bool_type,
2093 TypeManager.string_type
2098 // Try to find a *user* defined implicit conversion.
2100 // If there is no implicit conversion, or if there are multiple
2101 // conversions, we have to report an error
2103 Expression converted = null;
2104 foreach (Type tt in allowed_types){
2107 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2111 if (converted != null){
2112 Report.Error (-12, loc, "More than one conversion to an integral " +
2113 " type exists for type `" +
2114 TypeManager.CSharpName (Expr.Type)+"'");
2122 void error152 (string n)
2125 152, "The label `" + n + ":' " +
2126 "is already present on this switch statement");
2130 // Performs the basic sanity checks on the switch statement
2131 // (looks for duplicate keys and non-constant expressions).
2133 // It also returns a hashtable with the keys that we will later
2134 // use to compute the switch tables
2136 bool CheckSwitch (EmitContext ec)
2140 Elements = new Hashtable ();
2142 got_default = false;
2144 if (TypeManager.IsEnumType (SwitchType)){
2145 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2147 compare_type = SwitchType;
2149 foreach (SwitchSection ss in Sections){
2150 foreach (SwitchLabel sl in ss.Labels){
2151 if (!sl.ResolveAndReduce (ec, SwitchType)){
2156 if (sl.Label == null){
2158 error152 ("default");
2165 object key = sl.Converted;
2167 if (key is Constant)
2168 key = ((Constant) key).GetValue ();
2171 key = NullLiteral.Null;
2173 string lname = null;
2174 if (compare_type == TypeManager.uint64_type){
2175 ulong v = (ulong) key;
2177 if (Elements.Contains (v))
2178 lname = v.ToString ();
2180 Elements.Add (v, sl);
2181 } else if (compare_type == TypeManager.int64_type){
2182 long v = (long) key;
2184 if (Elements.Contains (v))
2185 lname = v.ToString ();
2187 Elements.Add (v, sl);
2188 } else if (compare_type == TypeManager.uint32_type){
2189 uint v = (uint) key;
2191 if (Elements.Contains (v))
2192 lname = v.ToString ();
2194 Elements.Add (v, sl);
2195 } else if (compare_type == TypeManager.char_type){
2196 char v = (char) key;
2198 if (Elements.Contains (v))
2199 lname = v.ToString ();
2201 Elements.Add (v, sl);
2202 } else if (compare_type == TypeManager.byte_type){
2203 byte v = (byte) key;
2205 if (Elements.Contains (v))
2206 lname = v.ToString ();
2208 Elements.Add (v, sl);
2209 } else if (compare_type == TypeManager.sbyte_type){
2210 sbyte v = (sbyte) key;
2212 if (Elements.Contains (v))
2213 lname = v.ToString ();
2215 Elements.Add (v, sl);
2216 } else if (compare_type == TypeManager.short_type){
2217 short v = (short) key;
2219 if (Elements.Contains (v))
2220 lname = v.ToString ();
2222 Elements.Add (v, sl);
2223 } else if (compare_type == TypeManager.ushort_type){
2224 ushort v = (ushort) key;
2226 if (Elements.Contains (v))
2227 lname = v.ToString ();
2229 Elements.Add (v, sl);
2230 } else if (compare_type == TypeManager.string_type){
2231 if (key is NullLiteral){
2232 if (Elements.Contains (NullLiteral.Null))
2235 Elements.Add (NullLiteral.Null, null);
2237 string s = (string) key;
2239 if (Elements.Contains (s))
2242 Elements.Add (s, sl);
2244 } else if (compare_type == TypeManager.int32_type) {
2247 if (Elements.Contains (v))
2248 lname = v.ToString ();
2250 Elements.Add (v, sl);
2251 } else if (compare_type == TypeManager.bool_type) {
2252 bool v = (bool) key;
2254 if (Elements.Contains (v))
2255 lname = v.ToString ();
2257 Elements.Add (v, sl);
2261 throw new Exception ("Unknown switch type!" +
2262 SwitchType + " " + compare_type);
2266 error152 ("case + " + lname);
2277 void EmitObjectInteger (ILGenerator ig, object k)
2280 IntConstant.EmitInt (ig, (int) k);
2281 else if (k is Constant) {
2282 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2285 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2288 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2290 IntConstant.EmitInt (ig, (int) (long) k);
2291 ig.Emit (OpCodes.Conv_I8);
2294 LongConstant.EmitLong (ig, (long) k);
2296 else if (k is ulong)
2298 if ((ulong) k < (1L<<32))
2300 IntConstant.EmitInt (ig, (int) (long) k);
2301 ig.Emit (OpCodes.Conv_U8);
2305 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2309 IntConstant.EmitInt (ig, (int) ((char) k));
2310 else if (k is sbyte)
2311 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2313 IntConstant.EmitInt (ig, (int) ((byte) k));
2314 else if (k is short)
2315 IntConstant.EmitInt (ig, (int) ((short) k));
2316 else if (k is ushort)
2317 IntConstant.EmitInt (ig, (int) ((ushort) k));
2319 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2321 throw new Exception ("Unhandled case");
2324 // structure used to hold blocks of keys while calculating table switch
2325 class KeyBlock : IComparable
2327 public KeyBlock (long _nFirst)
2329 nFirst = nLast = _nFirst;
2333 public ArrayList rgKeys = null;
2334 // how many items are in the bucket
2335 public int Size = 1;
2338 get { return (int) (nLast - nFirst + 1); }
2340 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2342 return kbLast.nLast - kbFirst.nFirst + 1;
2344 public int CompareTo (object obj)
2346 KeyBlock kb = (KeyBlock) obj;
2347 int nLength = Length;
2348 int nLengthOther = kb.Length;
2349 if (nLengthOther == nLength)
2350 return (int) (kb.nFirst - nFirst);
2351 return nLength - nLengthOther;
2356 /// This method emits code for a lookup-based switch statement (non-string)
2357 /// Basically it groups the cases into blocks that are at least half full,
2358 /// and then spits out individual lookup opcodes for each block.
2359 /// It emits the longest blocks first, and short blocks are just
2360 /// handled with direct compares.
2362 /// <param name="ec"></param>
2363 /// <param name="val"></param>
2364 /// <returns></returns>
2365 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2367 int cElements = Elements.Count;
2368 object [] rgKeys = new object [cElements];
2369 Elements.Keys.CopyTo (rgKeys, 0);
2370 Array.Sort (rgKeys);
2372 // initialize the block list with one element per key
2373 ArrayList rgKeyBlocks = new ArrayList ();
2374 foreach (object key in rgKeys)
2375 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2378 // iteratively merge the blocks while they are at least half full
2379 // there's probably a really cool way to do this with a tree...
2380 while (rgKeyBlocks.Count > 1)
2382 ArrayList rgKeyBlocksNew = new ArrayList ();
2383 kbCurr = (KeyBlock) rgKeyBlocks [0];
2384 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2386 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2387 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2390 kbCurr.nLast = kb.nLast;
2391 kbCurr.Size += kb.Size;
2395 // start a new block
2396 rgKeyBlocksNew.Add (kbCurr);
2400 rgKeyBlocksNew.Add (kbCurr);
2401 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2403 rgKeyBlocks = rgKeyBlocksNew;
2406 // initialize the key lists
2407 foreach (KeyBlock kb in rgKeyBlocks)
2408 kb.rgKeys = new ArrayList ();
2410 // fill the key lists
2412 if (rgKeyBlocks.Count > 0) {
2413 kbCurr = (KeyBlock) rgKeyBlocks [0];
2414 foreach (object key in rgKeys)
2416 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2417 System.Convert.ToInt64 (key) > kbCurr.nLast;
2419 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2420 kbCurr.rgKeys.Add (key);
2424 // sort the blocks so we can tackle the largest ones first
2425 rgKeyBlocks.Sort ();
2427 // okay now we can start...
2428 ILGenerator ig = ec.ig;
2429 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2430 Label lblDefault = ig.DefineLabel ();
2432 Type typeKeys = null;
2433 if (rgKeys.Length > 0)
2434 typeKeys = rgKeys [0].GetType (); // used for conversions
2438 if (TypeManager.IsEnumType (SwitchType))
2439 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2441 compare_type = SwitchType;
2443 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2445 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2446 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2449 foreach (object key in kb.rgKeys)
2451 ig.Emit (OpCodes.Ldloc, val);
2452 EmitObjectInteger (ig, key);
2453 SwitchLabel sl = (SwitchLabel) Elements [key];
2454 ig.Emit (OpCodes.Beq, sl.ILLabel);
2459 // TODO: if all the keys in the block are the same and there are
2460 // no gaps/defaults then just use a range-check.
2461 if (compare_type == TypeManager.int64_type ||
2462 compare_type == TypeManager.uint64_type)
2464 // TODO: optimize constant/I4 cases
2466 // check block range (could be > 2^31)
2467 ig.Emit (OpCodes.Ldloc, val);
2468 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2469 ig.Emit (OpCodes.Blt, lblDefault);
2470 ig.Emit (OpCodes.Ldloc, val);
2471 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2472 ig.Emit (OpCodes.Bgt, lblDefault);
2475 ig.Emit (OpCodes.Ldloc, val);
2478 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2479 ig.Emit (OpCodes.Sub);
2481 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2486 ig.Emit (OpCodes.Ldloc, val);
2487 int nFirst = (int) kb.nFirst;
2490 IntConstant.EmitInt (ig, nFirst);
2491 ig.Emit (OpCodes.Sub);
2493 else if (nFirst < 0)
2495 IntConstant.EmitInt (ig, -nFirst);
2496 ig.Emit (OpCodes.Add);
2500 // first, build the list of labels for the switch
2502 int cJumps = kb.Length;
2503 Label [] rgLabels = new Label [cJumps];
2504 for (int iJump = 0; iJump < cJumps; iJump++)
2506 object key = kb.rgKeys [iKey];
2507 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2509 SwitchLabel sl = (SwitchLabel) Elements [key];
2510 rgLabels [iJump] = sl.ILLabel;
2514 rgLabels [iJump] = lblDefault;
2516 // emit the switch opcode
2517 ig.Emit (OpCodes.Switch, rgLabels);
2520 // mark the default for this block
2522 ig.MarkLabel (lblDefault);
2525 // TODO: find the default case and emit it here,
2526 // to prevent having to do the following jump.
2527 // make sure to mark other labels in the default section
2529 // the last default just goes to the end
2530 ig.Emit (OpCodes.Br, lblDefault);
2532 // now emit the code for the sections
2533 bool fFoundDefault = false;
2534 foreach (SwitchSection ss in Sections)
2536 foreach (SwitchLabel sl in ss.Labels)
2538 ig.MarkLabel (sl.ILLabel);
2539 ig.MarkLabel (sl.ILLabelCode);
2540 if (sl.Label == null)
2542 ig.MarkLabel (lblDefault);
2543 fFoundDefault = true;
2547 //ig.Emit (OpCodes.Br, lblEnd);
2550 if (!fFoundDefault) {
2551 ig.MarkLabel (lblDefault);
2553 ig.MarkLabel (lblEnd);
2556 // This simple emit switch works, but does not take advantage of the
2558 // TODO: remove non-string logic from here
2559 // TODO: binary search strings?
2561 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2563 ILGenerator ig = ec.ig;
2564 Label end_of_switch = ig.DefineLabel ();
2565 Label next_test = ig.DefineLabel ();
2566 Label null_target = ig.DefineLabel ();
2567 bool default_found = false;
2568 bool first_test = true;
2569 bool pending_goto_end = false;
2571 bool default_at_end = false;
2573 ig.Emit (OpCodes.Ldloc, val);
2575 if (Elements.Contains (NullLiteral.Null)){
2576 ig.Emit (OpCodes.Brfalse, null_target);
2578 ig.Emit (OpCodes.Brfalse, default_target);
2580 ig.Emit (OpCodes.Ldloc, val);
2581 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2582 ig.Emit (OpCodes.Stloc, val);
2584 int section_count = Sections.Count;
2585 for (int section = 0; section < section_count; section++){
2586 SwitchSection ss = (SwitchSection) Sections [section];
2587 Label sec_begin = ig.DefineLabel ();
2589 if (pending_goto_end)
2590 ig.Emit (OpCodes.Br, end_of_switch);
2592 int label_count = ss.Labels.Count;
2593 bool mark_default = false;
2595 for (int label = 0; label < label_count; label++){
2596 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2597 ig.MarkLabel (sl.ILLabel);
2600 ig.MarkLabel (next_test);
2601 next_test = ig.DefineLabel ();
2604 // If we are the default target
2606 if (sl.Label == null){
2607 if (label+1 == label_count)
2608 default_at_end = true;
2609 mark_default = true;
2610 default_found = true;
2612 object lit = sl.Converted;
2614 if (lit is NullLiteral){
2616 if (label_count == 1)
2617 ig.Emit (OpCodes.Br, next_test);
2621 StringConstant str = (StringConstant) lit;
2623 ig.Emit (OpCodes.Ldloc, val);
2624 ig.Emit (OpCodes.Ldstr, str.Value);
2625 if (label_count == 1)
2626 ig.Emit (OpCodes.Bne_Un, next_test);
2628 if (label+1 == label_count)
2629 ig.Emit (OpCodes.Bne_Un, next_test);
2631 ig.Emit (OpCodes.Beq, sec_begin);
2636 ig.MarkLabel (null_target);
2637 ig.MarkLabel (sec_begin);
2638 foreach (SwitchLabel sl in ss.Labels)
2639 ig.MarkLabel (sl.ILLabelCode);
2642 ig.MarkLabel (default_target);
2644 pending_goto_end = !ss.Block.HasRet;
2647 ig.MarkLabel (next_test);
2649 if (!default_at_end)
2650 ig.Emit (OpCodes.Br, default_target);
2652 ig.MarkLabel (default_target);
2653 ig.MarkLabel (end_of_switch);
2656 SwitchSection FindSection (SwitchLabel label)
2658 foreach (SwitchSection ss in Sections){
2659 foreach (SwitchLabel sl in ss.Labels){
2668 bool ResolveConstantSwitch (EmitContext ec)
2670 object key = ((Constant) new_expr).GetValue ();
2671 SwitchLabel label = (SwitchLabel) Elements [key];
2676 constant_section = FindSection (label);
2677 if (constant_section == null)
2680 if (constant_section.Block.Resolve (ec) != true)
2686 public override bool Resolve (EmitContext ec)
2688 Expr = Expr.Resolve (ec);
2692 new_expr = SwitchGoverningType (ec, Expr.Type);
2693 if (new_expr == null){
2694 Report.Error (151, loc, "An integer type or string was expected for switch");
2699 SwitchType = new_expr.Type;
2701 if (!CheckSwitch (ec))
2704 Switch old_switch = ec.Switch;
2706 ec.Switch.SwitchType = SwitchType;
2708 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2709 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2711 is_constant = new_expr is Constant;
2713 object key = ((Constant) new_expr).GetValue ();
2714 SwitchLabel label = (SwitchLabel) Elements [key];
2716 constant_section = FindSection (label);
2720 foreach (SwitchSection ss in Sections){
2722 ec.CurrentBranching.CreateSibling (
2723 null, FlowBranching.SiblingType.SwitchSection);
2727 if (is_constant && (ss != constant_section)) {
2728 // If we're a constant switch, we're only emitting
2729 // one single section - mark all the others as
2731 ec.CurrentBranching.CurrentUsageVector.Goto ();
2732 if (!ss.Block.ResolveUnreachable (ec, true))
2735 if (!ss.Block.Resolve (ec))
2741 ec.CurrentBranching.CreateSibling (
2742 null, FlowBranching.SiblingType.SwitchSection);
2744 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2745 ec.Switch = old_switch;
2747 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2753 protected override void DoEmit (EmitContext ec)
2755 ILGenerator ig = ec.ig;
2757 // Store variable for comparission purposes
2760 value = ig.DeclareLocal (SwitchType);
2762 ig.Emit (OpCodes.Stloc, value);
2766 default_target = ig.DefineLabel ();
2769 // Setup the codegen context
2771 Label old_end = ec.LoopEnd;
2772 Switch old_switch = ec.Switch;
2774 ec.LoopEnd = ig.DefineLabel ();
2779 if (constant_section != null)
2780 constant_section.Block.Emit (ec);
2781 } else if (SwitchType == TypeManager.string_type)
2782 SimpleSwitchEmit (ec, value);
2784 TableSwitchEmit (ec, value);
2786 // Restore context state.
2787 ig.MarkLabel (ec.LoopEnd);
2790 // Restore the previous context
2792 ec.LoopEnd = old_end;
2793 ec.Switch = old_switch;
2797 public abstract class ExceptionStatement : Statement
2799 public abstract void EmitFinally (EmitContext ec);
2801 protected bool emit_finally = true;
2802 ArrayList parent_vectors;
2804 protected void DoEmitFinally (EmitContext ec)
2807 ec.ig.BeginFinallyBlock ();
2809 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
2813 protected void ResolveFinally (FlowBranchingException branching)
2815 emit_finally = branching.EmitFinally;
2817 branching.Parent.StealFinallyClauses (ref parent_vectors);
2821 public class Lock : ExceptionStatement {
2823 Statement Statement;
2826 public Lock (Expression expr, Statement stmt, Location l)
2833 public override bool Resolve (EmitContext ec)
2835 expr = expr.Resolve (ec);
2839 if (expr.Type.IsValueType){
2840 Error (185, "lock statement requires the expression to be " +
2841 " a reference type (type is: `{0}'",
2842 TypeManager.CSharpName (expr.Type));
2846 FlowBranchingException branching = ec.StartFlowBranching (this);
2847 bool ok = Statement.Resolve (ec);
2849 ec.KillFlowBranching ();
2853 ResolveFinally (branching);
2855 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2856 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
2857 // Unfortunately, System.Reflection.Emit automatically emits
2858 // a leave to the end of the finally block.
2859 // This is a problem if `returns' is true since we may jump
2860 // to a point after the end of the method.
2861 // As a workaround, emit an explicit ret here.
2862 ec.NeedReturnLabel ();
2868 protected override void DoEmit (EmitContext ec)
2870 Type type = expr.Type;
2872 ILGenerator ig = ec.ig;
2873 temp = ig.DeclareLocal (type);
2876 ig.Emit (OpCodes.Dup);
2877 ig.Emit (OpCodes.Stloc, temp);
2878 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2882 ig.BeginExceptionBlock ();
2883 Statement.Emit (ec);
2888 ig.EndExceptionBlock ();
2891 public override void EmitFinally (EmitContext ec)
2893 ILGenerator ig = ec.ig;
2894 ig.Emit (OpCodes.Ldloc, temp);
2895 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2899 public class Unchecked : Statement {
2900 public readonly Block Block;
2902 public Unchecked (Block b)
2908 public override bool Resolve (EmitContext ec)
2910 bool previous_state = ec.CheckState;
2911 bool previous_state_const = ec.ConstantCheckState;
2913 ec.CheckState = false;
2914 ec.ConstantCheckState = false;
2915 bool ret = Block.Resolve (ec);
2916 ec.CheckState = previous_state;
2917 ec.ConstantCheckState = previous_state_const;
2922 protected override void DoEmit (EmitContext ec)
2924 bool previous_state = ec.CheckState;
2925 bool previous_state_const = ec.ConstantCheckState;
2927 ec.CheckState = false;
2928 ec.ConstantCheckState = false;
2930 ec.CheckState = previous_state;
2931 ec.ConstantCheckState = previous_state_const;
2935 public class Checked : Statement {
2936 public readonly Block Block;
2938 public Checked (Block b)
2941 b.Unchecked = false;
2944 public override bool Resolve (EmitContext ec)
2946 bool previous_state = ec.CheckState;
2947 bool previous_state_const = ec.ConstantCheckState;
2949 ec.CheckState = true;
2950 ec.ConstantCheckState = true;
2951 bool ret = Block.Resolve (ec);
2952 ec.CheckState = previous_state;
2953 ec.ConstantCheckState = previous_state_const;
2958 protected override void DoEmit (EmitContext ec)
2960 bool previous_state = ec.CheckState;
2961 bool previous_state_const = ec.ConstantCheckState;
2963 ec.CheckState = true;
2964 ec.ConstantCheckState = true;
2966 ec.CheckState = previous_state;
2967 ec.ConstantCheckState = previous_state_const;
2971 public class Unsafe : Statement {
2972 public readonly Block Block;
2974 public Unsafe (Block b)
2979 public override bool Resolve (EmitContext ec)
2981 bool previous_state = ec.InUnsafe;
2985 val = Block.Resolve (ec);
2986 ec.InUnsafe = previous_state;
2991 protected override void DoEmit (EmitContext ec)
2993 bool previous_state = ec.InUnsafe;
2997 ec.InUnsafe = previous_state;
3004 public class Fixed : Statement {
3006 ArrayList declarators;
3007 Statement statement;
3013 public bool is_object;
3014 public LocalInfo vi;
3015 public Expression expr;
3016 public Expression converted;
3019 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3022 declarators = decls;
3027 public override bool Resolve (EmitContext ec)
3030 Expression.UnsafeError (loc);
3034 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3035 if (expr_type == null)
3038 CheckObsolete (expr_type);
3040 if (ec.RemapToProxy){
3041 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3045 data = new FixedData [declarators.Count];
3047 if (!expr_type.IsPointer){
3048 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3053 foreach (Pair p in declarators){
3054 LocalInfo vi = (LocalInfo) p.First;
3055 Expression e = (Expression) p.Second;
3057 vi.VariableInfo = null;
3061 // The rules for the possible declarators are pretty wise,
3062 // but the production on the grammar is more concise.
3064 // So we have to enforce these rules here.
3066 // We do not resolve before doing the case 1 test,
3067 // because the grammar is explicit in that the token &
3068 // is present, so we need to test for this particular case.
3072 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3077 // Case 1: & object.
3079 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3080 Expression child = ((Unary) e).Expr;
3082 if (child is ParameterReference || child is LocalVariableReference){
3085 "No need to use fixed statement for parameters or " +
3086 "local variable declarations (address is already " +
3091 ec.InFixedInitializer = true;
3093 ec.InFixedInitializer = false;
3097 child = ((Unary) e).Expr;
3099 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3102 data [i].is_object = true;
3104 data [i].converted = null;
3111 ec.InFixedInitializer = true;
3113 ec.InFixedInitializer = false;
3120 if (e.Type.IsArray){
3121 Type array_type = TypeManager.GetElementType (e.Type);
3124 // Provided that array_type is unmanaged,
3126 if (!TypeManager.VerifyUnManaged (array_type, loc))
3130 // and T* is implicitly convertible to the
3131 // pointer type given in the fixed statement.
3133 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3135 Expression converted = Convert.ImplicitConversionRequired (
3136 ec, array_ptr, vi.VariableType, loc);
3137 if (converted == null)
3140 data [i].is_object = false;
3142 data [i].converted = converted;
3152 if (e.Type == TypeManager.string_type){
3153 data [i].is_object = false;
3155 data [i].converted = null;
3162 // For other cases, flag a `this is already fixed expression'
3164 if (e is LocalVariableReference || e is ParameterReference ||
3165 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3167 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3171 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3175 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3177 if (!statement.Resolve (ec)) {
3178 ec.KillFlowBranching ();
3182 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3183 has_ret = reachability.IsUnreachable;
3188 protected override void DoEmit (EmitContext ec)
3190 ILGenerator ig = ec.ig;
3192 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3194 for (int i = 0; i < data.Length; i++) {
3195 LocalInfo vi = data [i].vi;
3198 // Case 1: & object.
3200 if (data [i].is_object) {
3202 // Store pointer in pinned location
3204 data [i].expr.Emit (ec);
3205 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3206 clear_list [i] = vi.LocalBuilder;
3213 if (data [i].expr.Type.IsArray){
3215 // Store pointer in pinned location
3217 data [i].converted.Emit (ec);
3219 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3220 clear_list [i] = vi.LocalBuilder;
3227 if (data [i].expr.Type == TypeManager.string_type){
3228 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3229 clear_list [i] = pinned_string;
3231 data [i].expr.Emit (ec);
3232 ig.Emit (OpCodes.Stloc, pinned_string);
3234 Expression sptr = new StringPtr (pinned_string, loc);
3235 Expression converted = Convert.ImplicitConversionRequired (
3236 ec, sptr, vi.VariableType, loc);
3238 if (converted == null)
3241 converted.Emit (ec);
3242 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3246 statement.Emit (ec);
3252 // Clear the pinned variable
3254 for (int i = 0; i < data.Length; i++) {
3255 if (data [i].is_object || data [i].expr.Type.IsArray) {
3256 ig.Emit (OpCodes.Ldc_I4_0);
3257 ig.Emit (OpCodes.Conv_U);
3258 ig.Emit (OpCodes.Stloc, clear_list [i]);
3259 } else if (data [i].expr.Type == TypeManager.string_type){
3260 ig.Emit (OpCodes.Ldnull);
3261 ig.Emit (OpCodes.Stloc, clear_list [i]);
3267 public class Catch: Statement {
3268 public readonly string Name;
3269 public readonly Block Block;
3271 Expression type_expr;
3274 public Catch (Expression type, string name, Block block, Location l)
3282 public Type CatchType {
3288 public bool IsGeneral {
3290 return type_expr == null;
3294 protected override void DoEmit(EmitContext ec)
3298 public override bool Resolve (EmitContext ec)
3300 if (type_expr != null) {
3301 type = ec.DeclSpace.ResolveType (type_expr, false, loc);
3305 CheckObsolete (type);
3307 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3308 Error (155, "The type caught or thrown must be derived from System.Exception");
3314 return Block.Resolve (ec);
3318 public class Try : ExceptionStatement {
3319 public readonly Block Fini, Block;
3320 public readonly ArrayList Specific;
3321 public readonly Catch General;
3323 bool need_exc_block;
3326 // specific, general and fini might all be null.
3328 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3330 if (specific == null && general == null){
3331 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3335 this.Specific = specific;
3336 this.General = general;
3341 public override bool Resolve (EmitContext ec)
3345 FlowBranchingException branching = ec.StartFlowBranching (this);
3347 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3349 if (!Block.Resolve (ec))
3352 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3354 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3356 Type[] prevCatches = new Type [Specific.Count];
3358 foreach (Catch c in Specific){
3359 ec.CurrentBranching.CreateSibling (
3360 c.Block, FlowBranching.SiblingType.Catch);
3362 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3364 if (c.Name != null) {
3365 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3367 throw new Exception ();
3369 vi.VariableInfo = null;
3372 if (!c.Resolve (ec))
3375 Type resolvedType = c.CatchType;
3376 for (int ii = 0; ii < last_index; ++ii) {
3377 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3378 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3383 prevCatches [last_index++] = resolvedType;
3384 need_exc_block = true;
3387 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3389 if (General != null){
3390 ec.CurrentBranching.CreateSibling (
3391 General.Block, FlowBranching.SiblingType.Catch);
3393 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3395 if (!General.Resolve (ec))
3398 need_exc_block = true;
3401 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3405 ec.CurrentBranching.CreateSibling (
3406 Fini, FlowBranching.SiblingType.Finally);
3408 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3410 if (!Fini.Resolve (ec))
3414 ResolveFinally (branching);
3415 need_exc_block |= emit_finally;
3417 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3419 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3421 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3423 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3424 // Unfortunately, System.Reflection.Emit automatically emits
3425 // a leave to the end of the finally block. This is a problem
3426 // if `returns' is true since we may jump to a point after the
3427 // end of the method.
3428 // As a workaround, emit an explicit ret here.
3429 ec.NeedReturnLabel ();
3435 protected override void DoEmit (EmitContext ec)
3437 ILGenerator ig = ec.ig;
3440 ig.BeginExceptionBlock ();
3443 foreach (Catch c in Specific){
3446 ig.BeginCatchBlock (c.CatchType);
3448 if (c.Name != null){
3449 vi = c.Block.GetLocalInfo (c.Name);
3451 throw new Exception ("Variable does not exist in this block");
3453 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3455 ig.Emit (OpCodes.Pop);
3460 if (General != null){
3461 ig.BeginCatchBlock (TypeManager.object_type);
3462 ig.Emit (OpCodes.Pop);
3463 General.Block.Emit (ec);
3468 ig.EndExceptionBlock ();
3471 public override void EmitFinally (EmitContext ec)
3479 public class Using : ExceptionStatement {
3480 object expression_or_block;
3481 Statement Statement;
3486 Expression [] resolved_vars;
3487 Expression [] converted_vars;
3488 ExpressionStatement [] assign;
3489 LocalBuilder local_copy;
3491 public Using (object expression_or_block, Statement stmt, Location l)
3493 this.expression_or_block = expression_or_block;
3499 // Resolves for the case of using using a local variable declaration.
3501 bool ResolveLocalVariableDecls (EmitContext ec)
3503 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3506 if (expr_type == null)
3510 // The type must be an IDisposable or an implicit conversion
3513 converted_vars = new Expression [var_list.Count];
3514 resolved_vars = new Expression [var_list.Count];
3515 assign = new ExpressionStatement [var_list.Count];
3517 bool need_conv = !TypeManager.ImplementsInterface (
3518 expr_type, TypeManager.idisposable_type);
3520 foreach (DictionaryEntry e in var_list){
3521 Expression var = (Expression) e.Key;
3523 var = var.ResolveLValue (ec, new EmptyExpression ());
3527 resolved_vars [i] = var;
3534 converted_vars [i] = Convert.ImplicitConversionRequired (
3535 ec, var, TypeManager.idisposable_type, loc);
3537 if (converted_vars [i] == null)
3544 foreach (DictionaryEntry e in var_list){
3545 Expression var = resolved_vars [i];
3546 Expression new_expr = (Expression) e.Value;
3549 a = new Assign (var, new_expr, loc);
3555 converted_vars [i] = var;
3556 assign [i] = (ExpressionStatement) a;
3563 bool ResolveExpression (EmitContext ec)
3565 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3566 conv = Convert.ImplicitConversionRequired (
3567 ec, expr, TypeManager.idisposable_type, loc);
3577 // Emits the code for the case of using using a local variable declaration.
3579 void EmitLocalVariableDecls (EmitContext ec)
3581 ILGenerator ig = ec.ig;
3584 for (i = 0; i < assign.Length; i++) {
3585 assign [i].EmitStatement (ec);
3588 ig.BeginExceptionBlock ();
3590 Statement.Emit (ec);
3592 var_list.Reverse ();
3597 void EmitLocalVariableDeclFinally (EmitContext ec)
3599 ILGenerator ig = ec.ig;
3601 int i = assign.Length;
3602 foreach (DictionaryEntry e in var_list){
3603 Expression var = resolved_vars [--i];
3604 Label skip = ig.DefineLabel ();
3606 ig.BeginFinallyBlock ();
3608 if (!var.Type.IsValueType) {
3610 ig.Emit (OpCodes.Brfalse, skip);
3611 converted_vars [i].Emit (ec);
3612 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3614 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3616 if (!(ml is MethodGroupExpr)) {
3618 ig.Emit (OpCodes.Box, var.Type);
3619 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3621 MethodInfo mi = null;
3623 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3624 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3631 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3635 IMemoryLocation mloc = (IMemoryLocation) var;
3637 mloc.AddressOf (ec, AddressOp.Load);
3638 ig.Emit (OpCodes.Call, mi);
3642 ig.MarkLabel (skip);
3645 ig.EndExceptionBlock ();
3647 ig.BeginFinallyBlock ();
3652 void EmitExpression (EmitContext ec)
3655 // Make a copy of the expression and operate on that.
3657 ILGenerator ig = ec.ig;
3658 local_copy = ig.DeclareLocal (expr_type);
3663 ig.Emit (OpCodes.Stloc, local_copy);
3666 ig.BeginExceptionBlock ();
3668 Statement.Emit (ec);
3672 ig.EndExceptionBlock ();
3675 void EmitExpressionFinally (EmitContext ec)
3677 ILGenerator ig = ec.ig;
3678 Label skip = ig.DefineLabel ();
3679 ig.Emit (OpCodes.Ldloc, local_copy);
3680 ig.Emit (OpCodes.Brfalse, skip);
3681 ig.Emit (OpCodes.Ldloc, local_copy);
3682 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3683 ig.MarkLabel (skip);
3686 public override bool Resolve (EmitContext ec)
3688 if (expression_or_block is DictionaryEntry){
3689 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3690 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3692 if (!ResolveLocalVariableDecls (ec))
3695 } else if (expression_or_block is Expression){
3696 expr = (Expression) expression_or_block;
3698 expr = expr.Resolve (ec);
3702 expr_type = expr.Type;
3704 if (!ResolveExpression (ec))
3708 FlowBranchingException branching = ec.StartFlowBranching (this);
3710 bool ok = Statement.Resolve (ec);
3713 ec.KillFlowBranching ();
3717 ResolveFinally (branching);
3718 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3720 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3721 // Unfortunately, System.Reflection.Emit automatically emits a leave
3722 // to the end of the finally block. This is a problem if `returns'
3723 // is true since we may jump to a point after the end of the method.
3724 // As a workaround, emit an explicit ret here.
3725 ec.NeedReturnLabel ();
3731 protected override void DoEmit (EmitContext ec)
3733 if (expression_or_block is DictionaryEntry)
3734 EmitLocalVariableDecls (ec);
3735 else if (expression_or_block is Expression)
3736 EmitExpression (ec);
3739 public override void EmitFinally (EmitContext ec)
3741 if (expression_or_block is DictionaryEntry)
3742 EmitLocalVariableDeclFinally (ec);
3743 else if (expression_or_block is Expression)
3744 EmitExpressionFinally (ec);
3749 /// Implementation of the foreach C# statement
3751 public class Foreach : ExceptionStatement {
3753 Expression variable;
3755 Statement statement;
3756 ForeachHelperMethods hm;
3757 Expression empty, conv;
3758 Type array_type, element_type;
3760 VariableStorage enumerator;
3762 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3763 Statement stmt, Location l)
3766 this.variable = var;
3772 public override bool Resolve (EmitContext ec)
3774 expr = expr.Resolve (ec);
3778 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3779 if (var_type == null)
3783 // We need an instance variable. Not sure this is the best
3784 // way of doing this.
3786 // FIXME: When we implement propertyaccess, will those turn
3787 // out to return values in ExprClass? I think they should.
3789 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3790 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3791 error1579 (expr.Type);
3795 if (expr.Type.IsArray) {
3796 array_type = expr.Type;
3797 element_type = TypeManager.GetElementType (array_type);
3799 empty = new EmptyExpression (element_type);
3801 hm = ProbeCollectionType (ec, expr.Type);
3803 error1579 (expr.Type);
3807 array_type = expr.Type;
3808 element_type = hm.element_type;
3810 empty = new EmptyExpression (hm.element_type);
3815 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3816 ec.CurrentBranching.CreateSibling ();
3820 // FIXME: maybe we can apply the same trick we do in the
3821 // array handling to avoid creating empty and conv in some cases.
3823 // Although it is not as important in this case, as the type
3824 // will not likely be object (what the enumerator will return).
3826 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3830 variable = variable.ResolveLValue (ec, empty);
3831 if (variable == null)
3834 bool disposable = (hm != null) && hm.is_disposable;
3835 FlowBranchingException branching = null;
3837 branching = ec.StartFlowBranching (this);
3839 if (!statement.Resolve (ec))
3843 ResolveFinally (branching);
3844 ec.EndFlowBranching ();
3846 emit_finally = true;
3848 ec.EndFlowBranching ();
3854 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3856 static MethodInfo FetchMethodMoveNext (Type t)
3858 MemberList move_next_list;
3860 move_next_list = TypeContainer.FindMembers (
3861 t, MemberTypes.Method,
3862 BindingFlags.Public | BindingFlags.Instance,
3863 Type.FilterName, "MoveNext");
3864 if (move_next_list.Count == 0)
3867 foreach (MemberInfo m in move_next_list){
3868 MethodInfo mi = (MethodInfo) m;
3871 args = TypeManager.GetArgumentTypes (mi);
3872 if (args != null && args.Length == 0){
3873 if (mi.ReturnType == TypeManager.bool_type)
3881 // Retrieves a `public T get_Current ()' method from the Type `t'
3883 static MethodInfo FetchMethodGetCurrent (Type t)
3885 MemberList get_current_list;
3887 get_current_list = TypeContainer.FindMembers (
3888 t, MemberTypes.Method,
3889 BindingFlags.Public | BindingFlags.Instance,
3890 Type.FilterName, "get_Current");
3891 if (get_current_list.Count == 0)
3894 foreach (MemberInfo m in get_current_list){
3895 MethodInfo mi = (MethodInfo) m;
3898 args = TypeManager.GetArgumentTypes (mi);
3899 if (args != null && args.Length == 0)
3906 // Retrieves a `public void Dispose ()' method from the Type `t'
3908 static MethodInfo FetchMethodDispose (Type t)
3910 MemberList dispose_list;
3912 dispose_list = TypeContainer.FindMembers (
3913 t, MemberTypes.Method,
3914 BindingFlags.Public | BindingFlags.Instance,
3915 Type.FilterName, "Dispose");
3916 if (dispose_list.Count == 0)
3919 foreach (MemberInfo m in dispose_list){
3920 MethodInfo mi = (MethodInfo) m;
3923 args = TypeManager.GetArgumentTypes (mi);
3924 if (args != null && args.Length == 0){
3925 if (mi.ReturnType == TypeManager.void_type)
3933 // This struct records the helper methods used by the Foreach construct
3935 class ForeachHelperMethods {
3936 public EmitContext ec;
3937 public MethodInfo get_enumerator;
3938 public MethodInfo move_next;
3939 public MethodInfo get_current;
3940 public Type element_type;
3941 public Type enumerator_type;
3942 public bool is_disposable;
3944 public ForeachHelperMethods (EmitContext ec)
3947 this.element_type = TypeManager.object_type;
3948 this.enumerator_type = TypeManager.ienumerator_type;
3949 this.is_disposable = true;
3953 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3958 if (!(m is MethodInfo))
3961 if (m.Name != "GetEnumerator")
3964 MethodInfo mi = (MethodInfo) m;
3965 Type [] args = TypeManager.GetArgumentTypes (mi);
3967 if (args.Length != 0)
3970 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3971 EmitContext ec = hm.ec;
3973 // Check whether GetEnumerator is public
3974 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
3977 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
3979 // Apply the same optimization as MS: skip the GetEnumerator
3980 // returning an IEnumerator, and use the one returning a
3981 // CharEnumerator instead. This allows us to avoid the
3982 // try-finally block and the boxing.
3987 // Ok, we can access it, now make sure that we can do something
3988 // with this `GetEnumerator'
3991 Type return_type = mi.ReturnType;
3992 if (mi.ReturnType == TypeManager.ienumerator_type ||
3993 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3994 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3997 // If it is not an interface, lets try to find the methods ourselves.
3998 // For example, if we have:
3999 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4000 // We can avoid the iface call. This is a runtime perf boost.
4001 // even bigger if we have a ValueType, because we avoid the cost
4004 // We have to make sure that both methods exist for us to take
4005 // this path. If one of the methods does not exist, we will just
4006 // use the interface. Sadly, this complex if statement is the only
4007 // way I could do this without a goto
4010 if (return_type.IsInterface ||
4011 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4012 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4014 hm.move_next = TypeManager.bool_movenext_void;
4015 hm.get_current = TypeManager.object_getcurrent_void;
4022 // Ok, so they dont return an IEnumerable, we will have to
4023 // find if they support the GetEnumerator pattern.
4026 hm.move_next = FetchMethodMoveNext (return_type);
4027 if (hm.move_next == null)
4030 hm.get_current = FetchMethodGetCurrent (return_type);
4031 if (hm.get_current == null)
4035 hm.element_type = hm.get_current.ReturnType;
4036 hm.enumerator_type = return_type;
4037 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4038 TypeManager.ImplementsInterface (
4039 hm.enumerator_type, TypeManager.idisposable_type);
4045 /// This filter is used to find the GetEnumerator method
4046 /// on which IEnumerator operates
4048 static MemberFilter FilterEnumerator;
4052 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4055 void error1579 (Type t)
4057 Report.Error (1579, loc,
4058 "foreach statement cannot operate on variables of type `" +
4059 t.FullName + "' because that class does not provide a " +
4060 " GetEnumerator method or it is inaccessible");
4063 static bool TryType (Type t, ForeachHelperMethods hm)
4067 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4068 BindingFlags.Public | BindingFlags.NonPublic |
4069 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4070 FilterEnumerator, hm);
4075 hm.get_enumerator = (MethodInfo) mi [0];
4080 // Looks for a usable GetEnumerator in the Type, and if found returns
4081 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4083 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4085 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4087 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4088 if (TryType (tt, hm))
4094 // Now try to find the method in the interfaces
4097 Type [] ifaces = t.GetInterfaces ();
4099 foreach (Type i in ifaces){
4100 if (TryType (i, hm))
4105 // Since TypeBuilder.GetInterfaces only returns the interface
4106 // types for this type, we have to keep looping, but once
4107 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4108 // done, because it returns all the types
4110 if ((t is TypeBuilder))
4120 // FIXME: possible optimization.
4121 // We might be able to avoid creating `empty' if the type is the sam
4123 bool EmitCollectionForeach (EmitContext ec)
4125 ILGenerator ig = ec.ig;
4127 enumerator = new VariableStorage (ec, hm.enumerator_type);
4128 enumerator.EmitThis ();
4130 // Instantiate the enumerator
4132 if (expr.Type.IsValueType){
4133 IMemoryLocation ml = expr as IMemoryLocation;
4134 // Load the address of the value type.
4136 // This happens if, for example, you have a property
4137 // returning a struct which is IEnumerable
4138 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4140 ig.Emit (OpCodes.Stloc, t);
4141 ig.Emit (OpCodes.Ldloca, t);
4142 ec.FreeTemporaryLocal (t, expr.Type);
4144 ml.AddressOf (ec, AddressOp.Load);
4148 if (hm.get_enumerator.DeclaringType.IsValueType) {
4149 // the method is declared on the value type
4150 ig.Emit (OpCodes.Call, hm.get_enumerator);
4152 // it is an interface method, so we must box
4153 ig.Emit (OpCodes.Box, expr.Type);
4154 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4158 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4160 enumerator.EmitStore ();
4163 // Protect the code in a try/finalize block, so that
4164 // if the beast implement IDisposable, we get rid of it
4166 if (hm.is_disposable && emit_finally)
4167 ig.BeginExceptionBlock ();
4169 Label end_try = ig.DefineLabel ();
4171 ig.MarkLabel (ec.LoopBegin);
4173 enumerator.EmitCall (hm.move_next);
4175 ig.Emit (OpCodes.Brfalse, end_try);
4179 enumerator.EmitCall (hm.get_current);
4183 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4185 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4187 statement.Emit (ec);
4188 ig.Emit (OpCodes.Br, ec.LoopBegin);
4189 ig.MarkLabel (end_try);
4191 // The runtime provides this for us.
4192 // ig.Emit (OpCodes.Leave, end);
4195 // Now the finally block
4197 if (hm.is_disposable) {
4200 ig.EndExceptionBlock ();
4203 ig.MarkLabel (ec.LoopEnd);
4207 public override void EmitFinally (EmitContext ec)
4209 ILGenerator ig = ec.ig;
4211 if (hm.enumerator_type.IsValueType) {
4212 enumerator.EmitThis ();
4214 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4216 enumerator.EmitLoadAddress ();
4217 ig.Emit (OpCodes.Call, mi);
4219 enumerator.EmitLoad ();
4220 ig.Emit (OpCodes.Box, hm.enumerator_type);
4221 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4224 Label call_dispose = ig.DefineLabel ();
4226 enumerator.EmitThis ();
4227 enumerator.EmitLoad ();
4228 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4229 ig.Emit (OpCodes.Dup);
4230 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4231 ig.Emit (OpCodes.Pop);
4232 ig.Emit (OpCodes.Endfinally);
4234 ig.MarkLabel (call_dispose);
4235 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4240 // FIXME: possible optimization.
4241 // We might be able to avoid creating `empty' if the type is the sam
4243 bool EmitArrayForeach (EmitContext ec)
4245 int rank = array_type.GetArrayRank ();
4246 ILGenerator ig = ec.ig;
4248 VariableStorage copy = new VariableStorage (ec, array_type);
4251 // Make our copy of the array
4258 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4262 counter.EmitThis ();
4263 ig.Emit (OpCodes.Ldc_I4_0);
4264 counter.EmitStore ();
4265 test = ig.DefineLabel ();
4266 ig.Emit (OpCodes.Br, test);
4268 loop = ig.DefineLabel ();
4269 ig.MarkLabel (loop);
4276 counter.EmitThis ();
4277 counter.EmitLoad ();
4280 // Load the value, we load the value using the underlying type,
4281 // then we use the variable.EmitAssign to load using the proper cast.
4283 ArrayAccess.EmitLoadOpcode (ig, element_type);
4286 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4288 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4290 statement.Emit (ec);
4292 ig.MarkLabel (ec.LoopBegin);
4293 counter.EmitThis ();
4294 counter.EmitThis ();
4295 counter.EmitLoad ();
4296 ig.Emit (OpCodes.Ldc_I4_1);
4297 ig.Emit (OpCodes.Add);
4298 counter.EmitStore ();
4300 ig.MarkLabel (test);
4301 counter.EmitThis ();
4302 counter.EmitLoad ();
4305 ig.Emit (OpCodes.Ldlen);
4306 ig.Emit (OpCodes.Conv_I4);
4307 ig.Emit (OpCodes.Blt, loop);
4309 VariableStorage [] dim_len = new VariableStorage [rank];
4310 VariableStorage [] dim_count = new VariableStorage [rank];
4311 Label [] loop = new Label [rank];
4312 Label [] test = new Label [rank];
4315 for (dim = 0; dim < rank; dim++){
4316 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4317 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4318 test [dim] = ig.DefineLabel ();
4319 loop [dim] = ig.DefineLabel ();
4322 for (dim = 0; dim < rank; dim++){
4323 dim_len [dim].EmitThis ();
4326 IntLiteral.EmitInt (ig, dim);
4327 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4328 dim_len [dim].EmitStore ();
4332 for (dim = 0; dim < rank; dim++){
4333 dim_count [dim].EmitThis ();
4334 ig.Emit (OpCodes.Ldc_I4_0);
4335 dim_count [dim].EmitStore ();
4336 ig.Emit (OpCodes.Br, test [dim]);
4337 ig.MarkLabel (loop [dim]);
4344 for (dim = 0; dim < rank; dim++){
4345 dim_count [dim].EmitThis ();
4346 dim_count [dim].EmitLoad ();
4350 // FIXME: Maybe we can cache the computation of `get'?
4352 Type [] args = new Type [rank];
4355 for (int i = 0; i < rank; i++)
4356 args [i] = TypeManager.int32_type;
4358 ModuleBuilder mb = CodeGen.Module.Builder;
4359 get = mb.GetArrayMethod (
4361 CallingConventions.HasThis| CallingConventions.Standard,
4363 ig.Emit (OpCodes.Call, get);
4366 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4368 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4369 statement.Emit (ec);
4370 ig.MarkLabel (ec.LoopBegin);
4371 for (dim = rank - 1; dim >= 0; dim--){
4372 dim_count [dim].EmitThis ();
4373 dim_count [dim].EmitThis ();
4374 dim_count [dim].EmitLoad ();
4375 ig.Emit (OpCodes.Ldc_I4_1);
4376 ig.Emit (OpCodes.Add);
4377 dim_count [dim].EmitStore ();
4379 ig.MarkLabel (test [dim]);
4380 dim_count [dim].EmitThis ();
4381 dim_count [dim].EmitLoad ();
4382 dim_len [dim].EmitThis ();
4383 dim_len [dim].EmitLoad ();
4384 ig.Emit (OpCodes.Blt, loop [dim]);
4387 ig.MarkLabel (ec.LoopEnd);
4392 protected override void DoEmit (EmitContext ec)
4394 ILGenerator ig = ec.ig;
4396 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4397 ec.LoopBegin = ig.DefineLabel ();
4398 ec.LoopEnd = ig.DefineLabel ();
4401 EmitCollectionForeach (ec);
4403 EmitArrayForeach (ec);
4405 ec.LoopBegin = old_begin;
4406 ec.LoopEnd = old_end;