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 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 /// Return value indicates whether all code paths emitted return.
36 public abstract bool Emit (EmitContext ec);
38 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
44 if (e.Type != TypeManager.bool_type){
45 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
51 31, loc, "Can not convert the expression to a boolean");
54 if (CodeGen.SymbolWriter != null)
61 /// Encapsulates the emission of a boolean test and jumping to a
64 /// This will emit the bool expression in `bool_expr' and if
65 /// `target_is_for_true' is true, then the code will generate a
66 /// brtrue to the target. Otherwise a brfalse.
68 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
69 Label target, bool target_is_for_true)
71 ILGenerator ig = ec.ig;
74 if (bool_expr is Unary){
75 Unary u = (Unary) bool_expr;
77 if (u.Oper == Unary.Operator.LogicalNot){
80 u.EmitLogicalNot (ec);
82 } else if (bool_expr is Binary){
83 Binary b = (Binary) bool_expr;
85 if (b.EmitBranchable (ec, target, target_is_for_true))
92 if (target_is_for_true){
94 ig.Emit (OpCodes.Brfalse, target);
96 ig.Emit (OpCodes.Brtrue, target);
99 ig.Emit (OpCodes.Brtrue, target);
101 ig.Emit (OpCodes.Brfalse, target);
105 public static void Warning_DeadCodeFound (Location loc)
107 Report.Warning (162, loc, "Unreachable code detected");
111 public class EmptyStatement : Statement {
112 public override bool Resolve (EmitContext ec)
117 public override bool Emit (EmitContext ec)
123 public class If : Statement {
125 public Statement TrueStatement;
126 public Statement FalseStatement;
128 public If (Expression expr, Statement trueStatement, Location l)
131 TrueStatement = trueStatement;
135 public If (Expression expr,
136 Statement trueStatement,
137 Statement falseStatement,
141 TrueStatement = trueStatement;
142 FalseStatement = falseStatement;
146 public override bool Resolve (EmitContext ec)
148 Report.Debug (1, "START IF BLOCK");
150 expr = ResolveBoolean (ec, expr, loc);
155 ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
157 if (!TrueStatement.Resolve (ec)) {
158 ec.KillFlowBranching ();
162 ec.CurrentBranching.CreateSibling ();
164 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
165 ec.KillFlowBranching ();
169 ec.EndFlowBranching ();
171 Report.Debug (1, "END IF BLOCK");
176 public override bool Emit (EmitContext ec)
178 ILGenerator ig = ec.ig;
179 Label false_target = ig.DefineLabel ();
181 bool is_true_ret, is_false_ret;
184 // Dead code elimination
186 if (expr is BoolConstant){
187 bool take = ((BoolConstant) expr).Value;
190 if (FalseStatement != null){
191 Warning_DeadCodeFound (FalseStatement.loc);
193 return TrueStatement.Emit (ec);
195 Warning_DeadCodeFound (TrueStatement.loc);
196 if (FalseStatement != null)
197 return FalseStatement.Emit (ec);
201 EmitBoolExpression (ec, expr, false_target, false);
203 is_true_ret = TrueStatement.Emit (ec);
204 is_false_ret = is_true_ret;
206 if (FalseStatement != null){
207 bool branch_emitted = false;
209 end = ig.DefineLabel ();
211 ig.Emit (OpCodes.Br, end);
212 branch_emitted = true;
215 ig.MarkLabel (false_target);
216 is_false_ret = FalseStatement.Emit (ec);
221 ig.MarkLabel (false_target);
222 is_false_ret = false;
225 return is_true_ret && is_false_ret;
229 public class Do : Statement {
230 public Expression expr;
231 public readonly Statement EmbeddedStatement;
233 public Do (Statement statement, Expression boolExpr, Location l)
236 EmbeddedStatement = statement;
240 public override bool Resolve (EmitContext ec)
242 if (!EmbeddedStatement.Resolve (ec))
245 expr = ResolveBoolean (ec, expr, loc);
252 public override bool Emit (EmitContext ec)
254 ILGenerator ig = ec.ig;
255 Label loop = ig.DefineLabel ();
256 Label old_begin = ec.LoopBegin;
257 Label old_end = ec.LoopEnd;
258 bool old_inloop = ec.InLoop;
259 bool old_breaks = ec.Breaks;
260 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
262 ec.LoopBegin = ig.DefineLabel ();
263 ec.LoopEnd = ig.DefineLabel ();
265 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
269 EmbeddedStatement.Emit (ec);
270 bool breaks = ec.Breaks;
271 ig.MarkLabel (ec.LoopBegin);
274 // Dead code elimination
276 if (expr is BoolConstant){
277 bool res = ((BoolConstant) expr).Value;
280 ec.ig.Emit (OpCodes.Br, loop);
282 EmitBoolExpression (ec, expr, loop, true);
284 ig.MarkLabel (ec.LoopEnd);
286 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
287 ec.LoopBegin = old_begin;
288 ec.LoopEnd = old_end;
289 ec.InLoop = old_inloop;
290 ec.Breaks = old_breaks;
293 // Inform whether we are infinite or not
295 if (expr is BoolConstant){
296 BoolConstant bc = (BoolConstant) expr;
298 if (bc.Value == true)
299 return breaks == false;
306 public class While : Statement {
307 public Expression expr;
308 public readonly Statement Statement;
310 public While (Expression boolExpr, Statement statement, Location l)
312 this.expr = boolExpr;
313 Statement = statement;
317 public override bool Resolve (EmitContext ec)
319 expr = ResolveBoolean (ec, expr, loc);
323 return Statement.Resolve (ec);
326 public override bool Emit (EmitContext ec)
328 ILGenerator ig = ec.ig;
329 Label old_begin = ec.LoopBegin;
330 Label old_end = ec.LoopEnd;
331 bool old_inloop = ec.InLoop;
332 bool old_breaks = ec.Breaks;
333 Label while_loop = ig.DefineLabel ();
334 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
337 ec.LoopBegin = ig.DefineLabel ();
338 ec.LoopEnd = ig.DefineLabel ();
340 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
342 ig.Emit (OpCodes.Br, ec.LoopBegin);
343 ig.MarkLabel (while_loop);
346 // Inform whether we are infinite or not
348 if (expr is BoolConstant){
349 BoolConstant bc = (BoolConstant) expr;
351 ig.MarkLabel (ec.LoopBegin);
352 if (bc.Value == false){
353 Warning_DeadCodeFound (Statement.loc);
361 ig.Emit (OpCodes.Br, ec.LoopBegin);
364 // Inform that we are infinite (ie, `we return'), only
365 // if we do not `break' inside the code.
367 ret = breaks == false;
369 ig.MarkLabel (ec.LoopEnd);
373 ig.MarkLabel (ec.LoopBegin);
375 EmitBoolExpression (ec, expr, while_loop, true);
376 ig.MarkLabel (ec.LoopEnd);
381 ec.LoopBegin = old_begin;
382 ec.LoopEnd = old_end;
383 ec.InLoop = old_inloop;
384 ec.Breaks = old_breaks;
385 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
391 public class For : Statement {
393 readonly Statement InitStatement;
394 readonly Statement Increment;
395 readonly Statement Statement;
397 public For (Statement initStatement,
403 InitStatement = initStatement;
405 Increment = increment;
406 Statement = statement;
410 public override bool Resolve (EmitContext ec)
414 if (InitStatement != null){
415 if (!InitStatement.Resolve (ec))
420 Test = ResolveBoolean (ec, Test, loc);
425 if (Increment != null){
426 if (!Increment.Resolve (ec))
430 return Statement.Resolve (ec) && ok;
433 public override bool Emit (EmitContext ec)
435 ILGenerator ig = ec.ig;
436 Label old_begin = ec.LoopBegin;
437 Label old_end = ec.LoopEnd;
438 bool old_inloop = ec.InLoop;
439 bool old_breaks = ec.Breaks;
440 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
441 Label loop = ig.DefineLabel ();
442 Label test = ig.DefineLabel ();
444 if (InitStatement != null)
445 if (! (InitStatement is EmptyStatement))
446 InitStatement.Emit (ec);
448 ec.LoopBegin = ig.DefineLabel ();
449 ec.LoopEnd = ig.DefineLabel ();
451 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
453 ig.Emit (OpCodes.Br, test);
457 bool breaks = ec.Breaks;
459 ig.MarkLabel (ec.LoopBegin);
460 if (!(Increment is EmptyStatement))
465 // If test is null, there is no test, and we are just
469 EmitBoolExpression (ec, Test, loop, true);
471 ig.Emit (OpCodes.Br, loop);
472 ig.MarkLabel (ec.LoopEnd);
474 ec.LoopBegin = old_begin;
475 ec.LoopEnd = old_end;
476 ec.InLoop = old_inloop;
477 ec.Breaks = old_breaks;
478 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
481 // Inform whether we are infinite or not
484 if (Test is BoolConstant){
485 BoolConstant bc = (BoolConstant) Test;
488 return breaks == false;
496 public class StatementExpression : Statement {
499 public StatementExpression (ExpressionStatement expr, Location l)
505 public override bool Resolve (EmitContext ec)
507 expr = (Expression) expr.Resolve (ec);
511 public override bool Emit (EmitContext ec)
513 ILGenerator ig = ec.ig;
515 if (expr is ExpressionStatement)
516 ((ExpressionStatement) expr).EmitStatement (ec);
519 ig.Emit (OpCodes.Pop);
525 public override string ToString ()
527 return "StatementExpression (" + expr + ")";
532 /// Implements the return statement
534 public class Return : Statement {
535 public Expression Expr;
537 public Return (Expression expr, Location l)
543 public override bool Resolve (EmitContext ec)
546 Expr = Expr.Resolve (ec);
551 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
553 if (ec.CurrentBranching.InTryBlock ())
554 ec.CurrentBranching.AddFinallyVector (vector);
556 vector.Returns = FlowReturns.ALWAYS;
557 vector.Breaks = FlowReturns.ALWAYS;
562 public override bool Emit (EmitContext ec)
565 Report.Error (157,loc,"Control can not leave the body of the finally block");
569 if (ec.ReturnType == null){
571 Report.Error (127, loc, "Return with a value not allowed here");
576 Report.Error (126, loc, "An object of type `" +
577 TypeManager.CSharpName (ec.ReturnType) + "' is " +
578 "expected for the return statement");
582 if (Expr.Type != ec.ReturnType)
583 Expr = Expression.ConvertImplicitRequired (
584 ec, Expr, ec.ReturnType, loc);
591 if (ec.InTry || ec.InCatch)
592 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
595 if (ec.InTry || ec.InCatch) {
596 if (!ec.HasReturnLabel) {
597 ec.ReturnLabel = ec.ig.DefineLabel ();
598 ec.HasReturnLabel = true;
600 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
602 ec.ig.Emit (OpCodes.Ret);
608 public class Goto : Statement {
611 LabeledStatement label;
613 public override bool Resolve (EmitContext ec)
615 label = block.LookupLabel (target);
619 "No such label `" + target + "' in this scope");
623 // If this is a forward goto.
624 if (!label.IsDefined)
625 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
627 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
632 public Goto (Block parent_block, string label, Location l)
634 block = parent_block;
639 public string Target {
645 public override bool Emit (EmitContext ec)
647 Label l = label.LabelTarget (ec);
648 ec.ig.Emit (OpCodes.Br, l);
654 public class LabeledStatement : Statement {
661 public LabeledStatement (string label_name)
663 this.label_name = label_name;
666 public Label LabelTarget (EmitContext ec)
670 label = ec.ig.DefineLabel ();
676 public bool IsDefined {
682 public void AddUsageVector (FlowBranching.UsageVector vector)
685 vectors = new ArrayList ();
687 vectors.Add (vector.Clone ());
690 public override bool Resolve (EmitContext ec)
693 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
698 public override bool Emit (EmitContext ec)
701 ec.ig.MarkLabel (label);
709 /// `goto default' statement
711 public class GotoDefault : Statement {
713 public GotoDefault (Location l)
718 public override bool Resolve (EmitContext ec)
720 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
721 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
725 public override bool Emit (EmitContext ec)
727 if (ec.Switch == null){
728 Report.Error (153, loc, "goto default is only valid in a switch statement");
732 if (!ec.Switch.GotDefault){
733 Report.Error (159, loc, "No default target on switch statement");
736 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
742 /// `goto case' statement
744 public class GotoCase : Statement {
748 public GotoCase (Expression e, Location l)
754 public override bool Resolve (EmitContext ec)
756 if (ec.Switch == null){
757 Report.Error (153, loc, "goto case is only valid in a switch statement");
761 expr = expr.Resolve (ec);
765 if (!(expr is Constant)){
766 Report.Error (159, loc, "Target expression for goto case is not constant");
770 object val = Expression.ConvertIntLiteral (
771 (Constant) expr, ec.Switch.SwitchType, loc);
776 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
781 "No such label 'case " + val + "': for the goto case");
784 label = sl.ILLabelCode;
786 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
787 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
791 public override bool Emit (EmitContext ec)
793 ec.ig.Emit (OpCodes.Br, label);
798 public class Throw : Statement {
801 public Throw (Expression expr, Location l)
807 public override bool Resolve (EmitContext ec)
810 expr = expr.Resolve (ec);
814 ExprClass eclass = expr.eclass;
816 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
817 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
818 Expression.Error118 (loc, expr, "value, variable, property " +
819 "or indexer access ");
825 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)) {
826 Report.Error (155, loc,
827 "The type caught or thrown must be derived " +
828 "from System.Exception");
833 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
834 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
838 public override bool Emit (EmitContext ec)
842 ec.ig.Emit (OpCodes.Rethrow);
846 "A throw statement with no argument is only " +
847 "allowed in a catch clause");
854 ec.ig.Emit (OpCodes.Throw);
860 public class Break : Statement {
862 public Break (Location l)
867 public override bool Resolve (EmitContext ec)
869 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
873 public override bool Emit (EmitContext ec)
875 ILGenerator ig = ec.ig;
877 if (ec.InLoop == false && ec.Switch == null){
878 Report.Error (139, loc, "No enclosing loop or switch to continue to");
883 if (ec.InTry || ec.InCatch)
884 ig.Emit (OpCodes.Leave, ec.LoopEnd);
886 ig.Emit (OpCodes.Br, ec.LoopEnd);
892 public class Continue : Statement {
894 public Continue (Location l)
899 public override bool Resolve (EmitContext ec)
901 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
905 public override bool Emit (EmitContext ec)
907 Label begin = ec.LoopBegin;
910 Report.Error (139, loc, "No enclosing loop to continue to");
915 // UGH: Non trivial. This Br might cross a try/catch boundary
919 // try { ... } catch { continue; }
923 // try {} catch { while () { continue; }}
925 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
926 ec.ig.Emit (OpCodes.Leave, begin);
927 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
928 throw new Exception ("Should never happen");
930 ec.ig.Emit (OpCodes.Br, begin);
936 // This is used in the control flow analysis code to specify whether the
937 // current code block may return to its enclosing block before reaching
940 public enum FlowReturns {
941 // It can never return.
944 // This means that the block contains a conditional return statement
948 // The code always returns, ie. there's an unconditional return / break
952 // The code always throws an exception.
955 // The current code block is unreachable. This happens if it's immediately
956 // following a FlowReturns.ALWAYS block.
961 // This is a special bit vector which can inherit from another bit vector doing a
962 // copy-on-write strategy. The inherited vector may have a smaller size than the
965 public class MyBitVector {
966 public readonly int Count;
967 public readonly MyBitVector InheritsFrom;
972 public MyBitVector (int Count)
976 public MyBitVector (MyBitVector InheritsFrom, int Count)
978 this.InheritsFrom = InheritsFrom;
983 // Checks whether this bit vector has been modified. After setting this to true,
984 // we won't use the inherited vector anymore, but our own copy of it.
986 public bool IsDirty {
993 initialize_vector ();
998 // Get/set bit `index' in the bit vector.
1000 public bool this [int index]
1004 throw new ArgumentOutOfRangeException ();
1006 // We're doing a "copy-on-write" strategy here; as long
1007 // as nobody writes to the array, we can use our parent's
1008 // copy instead of duplicating the vector.
1011 return vector [index];
1012 else if (InheritsFrom != null) {
1013 BitArray inherited = InheritsFrom.Vector;
1015 if (index < inherited.Count)
1016 return inherited [index];
1025 throw new ArgumentOutOfRangeException ();
1027 // Only copy the vector if we're actually modifying it.
1029 if (this [index] != value) {
1030 initialize_vector ();
1032 vector [index] = value;
1038 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1039 // copy of the bit vector.
1041 public static explicit operator BitArray (MyBitVector vector)
1043 vector.initialize_vector ();
1044 return vector.Vector;
1048 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1049 // different size than the current one.
1051 public void Or (MyBitVector new_vector)
1053 BitArray new_array = new_vector.Vector;
1055 initialize_vector ();
1058 if (vector.Count < new_array.Count)
1059 upper = vector.Count;
1061 upper = new_array.Count;
1063 for (int i = 0; i < upper; i++)
1064 vector [i] = vector [i] | new_array [i];
1068 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1069 // a different size than the current one.
1071 public void And (MyBitVector new_vector)
1073 BitArray new_array = new_vector.Vector;
1075 initialize_vector ();
1078 if (vector.Count < new_array.Count)
1079 lower = upper = vector.Count;
1081 lower = new_array.Count;
1082 upper = vector.Count;
1085 for (int i = 0; i < lower; i++)
1086 vector [i] = vector [i] & new_array [i];
1088 for (int i = lower; i < upper; i++)
1093 // This does a deep copy of the bit vector.
1095 public MyBitVector Clone ()
1097 MyBitVector retval = new MyBitVector (Count);
1099 retval.Vector = Vector;
1108 else if (!is_dirty && (InheritsFrom != null))
1109 return InheritsFrom.Vector;
1111 initialize_vector ();
1117 initialize_vector ();
1119 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1120 vector [i] = value [i];
1124 void initialize_vector ()
1129 vector = new BitArray (Count, false);
1130 if (InheritsFrom != null)
1131 Vector = InheritsFrom.Vector;
1136 public override string ToString ()
1138 StringBuilder sb = new StringBuilder ("MyBitVector (");
1140 BitArray vector = Vector;
1144 sb.Append ("INHERITED - ");
1145 for (int i = 0; i < vector.Count; i++) {
1148 sb.Append (vector [i]);
1152 return sb.ToString ();
1157 // The type of a FlowBranching.
1159 public enum FlowBranchingType {
1160 // Normal (conditional or toplevel) block.
1174 // A new instance of this class is created every time a new block is resolved
1175 // and if there's branching in the block's control flow.
1177 public class FlowBranching {
1179 // The type of this flow branching.
1181 public readonly FlowBranchingType Type;
1184 // The block this branching is contained in. This may be null if it's not
1185 // a top-level block and it doesn't declare any local variables.
1187 public readonly Block Block;
1190 // The parent of this branching or null if this is the top-block.
1192 public readonly FlowBranching Parent;
1195 // Start-Location of this flow branching.
1197 public readonly Location Location;
1200 // A list of UsageVectors. A new vector is added each time control flow may
1201 // take a different path.
1203 public ArrayList Siblings;
1208 InternalParameters param_info;
1211 ArrayList finally_vectors;
1213 static int next_id = 0;
1217 // Performs an `And' operation on the FlowReturns status
1218 // (for instance, a block only returns ALWAYS if all its siblings
1221 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1223 if (b == FlowReturns.UNREACHABLE)
1227 case FlowReturns.NEVER:
1228 if (b == FlowReturns.NEVER)
1229 return FlowReturns.NEVER;
1231 return FlowReturns.SOMETIMES;
1233 case FlowReturns.SOMETIMES:
1234 return FlowReturns.SOMETIMES;
1236 case FlowReturns.ALWAYS:
1237 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1238 return FlowReturns.ALWAYS;
1240 return FlowReturns.SOMETIMES;
1242 case FlowReturns.EXCEPTION:
1243 if (b == FlowReturns.EXCEPTION)
1244 return FlowReturns.EXCEPTION;
1245 else if (b == FlowReturns.ALWAYS)
1246 return FlowReturns.ALWAYS;
1248 return FlowReturns.SOMETIMES;
1255 // The vector contains a BitArray with information about which local variables
1256 // and parameters are already initialized at the current code position.
1258 public class UsageVector {
1260 // If this is true, then the usage vector has been modified and must be
1261 // merged when we're done with this branching.
1263 public bool IsDirty;
1266 // The number of parameters in this block.
1268 public readonly int CountParameters;
1271 // The number of locals in this block.
1273 public readonly int CountLocals;
1276 // If not null, then we inherit our state from this vector and do a
1277 // copy-on-write. If null, then we're the first sibling in a top-level
1278 // block and inherit from the empty vector.
1280 public readonly UsageVector InheritsFrom;
1285 MyBitVector locals, parameters;
1286 FlowReturns real_returns, real_breaks;
1287 bool returns_set, breaks_set, is_finally;
1289 static int next_id = 0;
1293 // Normally, you should not use any of these constructors.
1295 public UsageVector (UsageVector parent, int num_params, int num_locals)
1297 this.InheritsFrom = parent;
1298 this.CountParameters = num_params;
1299 this.CountLocals = num_locals;
1300 this.real_returns = FlowReturns.NEVER;
1301 this.real_breaks = FlowReturns.NEVER;
1303 if (parent != null) {
1304 locals = new MyBitVector (parent.locals, CountLocals);
1305 parameters = new MyBitVector (parent.parameters, num_params);
1307 locals = new MyBitVector (null, CountLocals);
1308 parameters = new MyBitVector (null, num_params);
1314 public UsageVector (UsageVector parent)
1315 : this (parent, parent.CountParameters, parent.CountLocals)
1319 // This does a deep copy of the usage vector.
1321 public UsageVector Clone ()
1323 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1325 retval.locals = locals.Clone ();
1326 if (parameters != null)
1327 retval.parameters = parameters.Clone ();
1328 retval.real_returns = real_returns;
1329 retval.real_breaks = real_breaks;
1335 // State of parameter `number'.
1337 public bool this [int number]
1342 else if (number == 0)
1343 throw new ArgumentException ();
1345 return parameters [number - 1];
1351 else if (number == 0)
1352 throw new ArgumentException ();
1354 parameters [number - 1] = value;
1359 // State of the local variable `vi'.
1361 public bool this [VariableInfo vi]
1364 if (vi.Number == -1)
1366 else if (vi.Number == 0)
1367 throw new ArgumentException ();
1369 return locals [vi.Number - 1];
1373 if (vi.Number == -1)
1375 else if (vi.Number == 0)
1376 throw new ArgumentException ();
1378 locals [vi.Number - 1] = value;
1383 // Specifies when the current block returns.
1385 public FlowReturns Returns {
1387 return real_returns;
1391 real_returns = value;
1397 // Specifies whether control may return to our containing block
1398 // before reaching the end of this block. This happens if there
1399 // is a break/continue/goto/return in it.
1401 public FlowReturns Breaks {
1407 real_breaks = value;
1413 // Merge a child branching.
1415 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1417 MyBitVector new_locals = null;
1418 MyBitVector new_params = null;
1420 FlowReturns new_returns = FlowReturns.NEVER;
1421 FlowReturns new_breaks = FlowReturns.NEVER;
1422 bool new_returns_set = false, new_breaks_set = false;
1425 Report.Debug (1, "MERGING CHILDREN", branching, this);
1427 foreach (UsageVector child in children) {
1428 Report.Debug (1, " MERGING CHILD", child);
1430 // If Returns is already set, perform an `And' operation on it,
1431 // otherwise just set just.
1432 if (!new_returns_set) {
1433 new_returns = child.Returns;
1434 new_returns_set = true;
1436 new_returns = AndFlowReturns (new_returns, child.Returns);
1438 // If Breaks is already set, perform an `And' operation on it,
1439 // otherwise just set just.
1440 if (!new_breaks_set) {
1441 new_breaks = child.Breaks;
1442 new_breaks_set = true;
1444 new_breaks = AndFlowReturns (new_breaks, child.Breaks);
1446 // Ignore unreachable children.
1447 if (child.Returns == FlowReturns.UNREACHABLE)
1450 // If we're a switch section, `break' won't leave the current
1451 // branching (NOTE: the type check here means that we're "a"
1452 // switch section, not that we're "in" a switch section!).
1453 breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1454 child.Returns : child.Breaks;
1456 // A local variable is initialized after a flow branching if it
1457 // has been initialized in all its branches which do neither
1458 // always return or always throw an exception.
1460 // If a branch may return, but does not always return, then we
1461 // can treat it like a never-returning branch here: control will
1462 // only reach the code position after the branching if we did not
1465 // It's important to distinguish between always and sometimes
1466 // returning branches here:
1469 // 2 if (something) {
1473 // 6 Console.WriteLine (a);
1475 // The if block in lines 3-4 always returns, so we must not look
1476 // at the initialization of `a' in line 4 - thus it'll still be
1477 // uninitialized in line 6.
1479 // On the other hand, the following is allowed:
1486 // 6 Console.WriteLine (a);
1488 // Here, `a' is initialized in line 3 and we must not look at
1489 // line 5 since it always returns.
1491 if ((breaks != FlowReturns.EXCEPTION) &&
1492 (breaks != FlowReturns.ALWAYS)) {
1493 if (new_locals != null)
1494 new_locals.And (child.locals);
1496 new_locals = locals.Clone ();
1497 new_locals.Or (child.locals);
1501 // An `out' parameter must be assigned in all branches which do
1502 // not always throw an exception.
1503 if (!child.is_finally && (child.Returns != FlowReturns.EXCEPTION)) {
1504 if (new_params != null)
1505 new_params.And (child.parameters);
1507 new_params = parameters.Clone ();
1508 new_params.Or (child.parameters);
1512 // If we always return, check whether all `out' parameters have
1514 if (child.Returns == FlowReturns.ALWAYS) {
1515 branching.CheckOutParameters (
1516 child.parameters, branching.Location);
1520 // Set new `Returns' status.
1522 Returns = new_returns;
1525 Returns = AndFlowReturns (Returns, new_returns);
1528 // We've now either reached the point after the branching or we will
1529 // never get there since we always return or always throw an exception.
1531 // If we can reach the point after the branching, mark all locals and
1532 // parameters as initialized which have been initialized in all branches
1533 // we need to look at (see above).
1536 breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1539 if ((new_locals != null) &&
1540 ((breaks == FlowReturns.NEVER) || (breaks == FlowReturns.SOMETIMES))) {
1541 locals.Or (new_locals);
1544 if ((new_params != null) && (Breaks == FlowReturns.NEVER))
1545 parameters.Or (new_params);
1548 // If we may have returned (this only happens if there was a reachable
1549 // `return' statement in one of the branches), then we may return to our
1550 // parent block before reaching the end of the block, so set `Breaks'.
1553 if ((Returns != FlowReturns.NEVER) && (Returns != FlowReturns.SOMETIMES)) {
1554 real_breaks = Returns;
1558 Report.Debug (1, "MERGING CHILDREN DONE", new_params, new_locals,
1559 new_returns, new_breaks, this);
1565 // Tells control flow analysis that the current code position may be reached with
1566 // a forward jump from any of the origins listed in `origin_vectors' which is a
1567 // list of UsageVectors.
1569 // This is used when resolving forward gotos - in the following example, the
1570 // variable `a' is uninitialized in line 8 becase this line may be reached via
1571 // the goto in line 4:
1581 // 8 Console.WriteLine (a);
1584 public void MergeJumpOrigins (ICollection origin_vectors)
1586 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1588 real_breaks = FlowReturns.NEVER;
1591 foreach (UsageVector vector in origin_vectors) {
1592 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1594 locals.And (vector.locals);
1595 parameters.And (vector.parameters);
1596 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1599 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1603 // This is used at the beginning of a finally block if there were
1604 // any return statements in the try block or one of the catch blocks.
1606 public void MergeFinallyOrigins (ICollection finally_vectors)
1608 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1610 real_breaks = FlowReturns.NEVER;
1613 foreach (UsageVector vector in finally_vectors) {
1614 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1616 parameters.And (vector.parameters);
1617 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1622 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1626 // Performs an `or' operation on the locals and the parameters.
1628 public void Or (UsageVector new_vector)
1630 locals.Or (new_vector.locals);
1631 parameters.Or (new_vector.parameters);
1635 // Performs an `and' operation on the locals.
1637 public void AndLocals (UsageVector new_vector)
1639 locals.And (new_vector.locals);
1643 // Returns a deep copy of the parameters.
1645 public MyBitVector Parameters {
1647 return parameters.Clone ();
1652 // Returns a deep copy of the locals.
1654 public MyBitVector Locals {
1656 return locals.Clone ();
1664 public override string ToString ()
1666 StringBuilder sb = new StringBuilder ();
1668 sb.Append ("Vector (");
1671 sb.Append (Returns);
1675 sb.Append (parameters);
1680 return sb.ToString ();
1684 FlowBranching (FlowBranchingType type, Location loc)
1686 this.Siblings = new ArrayList ();
1688 this.Location = loc;
1694 // Creates a new flow branching for `block'.
1695 // This is used from Block.Resolve to create the top-level branching of
1698 public FlowBranching (Block block, InternalParameters ip, Location loc)
1699 : this (FlowBranchingType.BLOCK, loc)
1705 param_map = new int [(param_info != null) ? param_info.Count : 0];
1708 for (int i = 0; i < param_map.Length; i++) {
1709 Parameter.Modifier mod = param_info.ParameterModifier (i);
1711 if ((mod & Parameter.Modifier.OUT) == 0)
1714 param_map [i] = ++num_params;
1717 Siblings = new ArrayList ();
1718 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1722 // Creates a new flow branching which is contained in `parent'.
1723 // You should only pass non-null for the `block' argument if this block
1724 // introduces any new variables - in this case, we need to create a new
1725 // usage vector with a different size than our parent's one.
1727 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1728 Block block, Location loc)
1734 if (parent != null) {
1735 param_info = parent.param_info;
1736 param_map = parent.param_map;
1737 num_params = parent.num_params;
1742 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1743 Block.CountVariables);
1745 vector = new UsageVector (Parent.CurrentUsageVector);
1747 Siblings.Add (vector);
1750 case FlowBranchingType.EXCEPTION:
1751 finally_vectors = new ArrayList ();
1760 // Returns the branching's current usage vector.
1762 public UsageVector CurrentUsageVector
1765 return (UsageVector) Siblings [Siblings.Count - 1];
1770 // Creates a sibling of the current usage vector.
1772 public void CreateSibling ()
1774 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1776 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1780 // Creates a sibling for a `finally' block.
1782 public void CreateSiblingForFinally ()
1784 if (Type != FlowBranchingType.EXCEPTION)
1785 throw new NotSupportedException ();
1789 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1793 // Check whether all `out' parameters have been assigned.
1795 public void CheckOutParameters (MyBitVector parameters, Location loc)
1800 for (int i = 0; i < param_map.Length; i++) {
1801 if (param_map [i] == 0)
1804 if (!parameters [param_map [i] - 1]) {
1806 177, loc, "The out parameter `" +
1807 param_info.ParameterName (i) + "` must be " +
1808 "assigned before control leave the current method.");
1815 // Merge a child branching.
1817 public FlowReturns MergeChild (FlowBranching child)
1819 return CurrentUsageVector.MergeChildren (child, child.Siblings);
1823 // Does the toplevel merging.
1825 public FlowReturns MergeTopBlock ()
1827 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1828 throw new NotSupportedException ();
1830 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1832 vector.MergeChildren (this, Siblings);
1835 Siblings.Add (vector);
1837 Report.Debug (1, "MERGING TOP BLOCK", vector);
1839 if (vector.Returns != FlowReturns.EXCEPTION)
1840 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1842 return vector.Returns;
1845 public bool InTryBlock ()
1847 if (finally_vectors != null)
1849 else if (Parent != null)
1850 return Parent.InTryBlock ();
1855 public void AddFinallyVector (UsageVector vector)
1857 if (finally_vectors != null) {
1858 finally_vectors.Add (vector.Clone ());
1863 Parent.AddFinallyVector (vector);
1865 throw new NotSupportedException ();
1868 public bool IsVariableAssigned (VariableInfo vi)
1870 Report.Debug (2, "CHECK VARIABLE ACCESS", this, vi);
1872 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1875 return CurrentUsageVector [vi];
1878 public void SetVariableAssigned (VariableInfo vi)
1880 Report.Debug (2, "SET VARIABLE ACCESS", this, vi, CurrentUsageVector);
1882 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1885 CurrentUsageVector [vi] = true;
1888 public bool IsParameterAssigned (int number)
1890 Report.Debug (2, "IS PARAMETER ASSIGNED", this, number);
1892 if (param_map [number] == 0)
1895 return CurrentUsageVector [param_map [number]];
1898 public void SetParameterAssigned (int number)
1900 Report.Debug (2, "SET PARAMETER ACCESS", this, number, param_map [number],
1901 CurrentUsageVector);
1903 if (param_map [number] == 0)
1906 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
1907 CurrentUsageVector [param_map [number]] = true;
1910 public override string ToString ()
1912 StringBuilder sb = new StringBuilder ("FlowBranching (");
1917 if (Block != null) {
1919 sb.Append (Block.ID);
1921 sb.Append (Block.StartLocation);
1924 sb.Append (Siblings.Count);
1926 sb.Append (CurrentUsageVector);
1928 return sb.ToString ();
1932 public class VariableInfo {
1933 public Expression Type;
1934 public LocalBuilder LocalBuilder;
1935 public Type VariableType;
1936 public readonly Location Location;
1941 public bool Assigned;
1942 public bool ReadOnly;
1944 public VariableInfo (Expression type, Location l)
1947 LocalBuilder = null;
1951 public void MakePinned ()
1953 TypeManager.MakePinned (LocalBuilder);
1956 public override string ToString ()
1958 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
1963 /// Block represents a C# block.
1967 /// This class is used in a number of places: either to represent
1968 /// explicit blocks that the programmer places or implicit blocks.
1970 /// Implicit blocks are used as labels or to introduce variable
1973 public class Block : Statement {
1974 public readonly Block Parent;
1975 public readonly bool Implicit;
1976 public readonly Location StartLocation;
1977 public Location EndLocation;
1980 // The statements in this block
1982 ArrayList statements;
1985 // An array of Blocks. We keep track of children just
1986 // to generate the local variable declarations.
1988 // Statements and child statements are handled through the
1994 // Labels. (label, block) pairs.
1999 // Keeps track of (name, type) pairs
2001 Hashtable variables;
2004 // Keeps track of constants
2005 Hashtable constants;
2008 // Maps variable names to ILGenerator.LocalBuilders
2010 Hashtable local_builders;
2018 public Block (Block parent)
2019 : this (parent, false, Location.Null, Location.Null)
2022 public Block (Block parent, bool implicit_block)
2023 : this (parent, implicit_block, Location.Null, Location.Null)
2026 public Block (Block parent, Location start, Location end)
2027 : this (parent, false, start, end)
2030 public Block (Block parent, bool implicit_block, Location start, Location end)
2033 parent.AddChild (this);
2035 this.Parent = parent;
2036 this.Implicit = implicit_block;
2037 this.StartLocation = start;
2038 this.EndLocation = end;
2041 statements = new ArrayList ();
2050 void AddChild (Block b)
2052 if (children == null)
2053 children = new ArrayList ();
2058 public void SetEndLocation (Location loc)
2064 /// Adds a label to the current block.
2068 /// false if the name already exists in this block. true
2072 public bool AddLabel (string name, LabeledStatement target)
2075 labels = new Hashtable ();
2076 if (labels.Contains (name))
2079 labels.Add (name, target);
2083 public LabeledStatement LookupLabel (string name)
2085 if (labels != null){
2086 if (labels.Contains (name))
2087 return ((LabeledStatement) labels [name]);
2091 return Parent.LookupLabel (name);
2096 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2098 if (variables == null)
2099 variables = new Hashtable ();
2101 if (GetVariableType (name) != null)
2106 Parameter p = pars.GetParameterByName (name, out idx);
2111 VariableInfo vi = new VariableInfo (type, l);
2113 variables.Add (name, vi);
2115 if (variables_initialized)
2116 throw new Exception ();
2118 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2122 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2124 if (AddVariable (type, name, pars, l) == null)
2127 if (constants == null)
2128 constants = new Hashtable ();
2130 constants.Add (name, value);
2134 public Hashtable Variables {
2140 public VariableInfo GetVariableInfo (string name)
2142 if (variables != null) {
2144 temp = variables [name];
2147 return (VariableInfo) temp;
2152 return Parent.GetVariableInfo (name);
2157 public Expression GetVariableType (string name)
2159 VariableInfo vi = GetVariableInfo (name);
2167 public Expression GetConstantExpression (string name)
2169 if (constants != null) {
2171 temp = constants [name];
2174 return (Expression) temp;
2178 return Parent.GetConstantExpression (name);
2184 /// True if the variable named @name has been defined
2187 public bool IsVariableDefined (string name)
2189 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2190 if (variables != null) {
2191 if (variables.Contains (name))
2196 return Parent.IsVariableDefined (name);
2202 /// True if the variable named @name is a constant
2204 public bool IsConstant (string name)
2206 Expression e = null;
2208 e = GetConstantExpression (name);
2214 /// Use to fetch the statement associated with this label
2216 public Statement this [string name] {
2218 return (Statement) labels [name];
2223 /// A list of labels that were not used within this block
2225 public string [] GetUnreferenced ()
2227 // FIXME: Implement me
2231 public void AddStatement (Statement s)
2248 bool variables_initialized = false;
2249 int count_variables = 0, first_variable = 0;
2251 void UpdateVariableInfo (EmitContext ec)
2253 DeclSpace ds = ec.DeclSpace;
2258 first_variable += Parent.CountVariables;
2260 count_variables = first_variable;
2261 if (variables != null) {
2262 foreach (VariableInfo vi in variables.Values) {
2263 Report.Debug (2, "VARIABLE", vi);
2265 Type type = ds.ResolveType (vi.Type, false, vi.Location);
2271 vi.VariableType = type;
2273 Report.Debug (2, "VARIABLE", vi, type, type.IsValueType,
2274 TypeManager.IsValueType (type),
2275 TypeManager.IsBuiltinType (type));
2277 // FIXME: we don't have support for structs yet.
2278 if (TypeManager.IsValueType (type) && !TypeManager.IsBuiltinType (type))
2281 vi.Number = ++count_variables;
2285 variables_initialized = true;
2290 // The number of local variables in this block
2292 public int CountVariables
2295 if (!variables_initialized)
2296 throw new Exception ();
2298 return count_variables;
2303 /// Emits the variable declarations and labels.
2306 /// tc: is our typecontainer (to resolve type references)
2307 /// ig: is the code generator:
2308 /// toplevel: the toplevel block. This is used for checking
2309 /// that no two labels with the same name are used.
2311 public void EmitMeta (EmitContext ec, Block toplevel)
2313 DeclSpace ds = ec.DeclSpace;
2314 ILGenerator ig = ec.ig;
2316 if (!variables_initialized)
2317 UpdateVariableInfo (ec);
2320 // Process this block variables
2322 if (variables != null){
2323 local_builders = new Hashtable ();
2325 foreach (DictionaryEntry de in variables){
2326 string name = (string) de.Key;
2327 VariableInfo vi = (VariableInfo) de.Value;
2329 if (vi.VariableType == null)
2332 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2334 if (CodeGen.SymbolWriter != null)
2335 vi.LocalBuilder.SetLocalSymInfo (name);
2337 if (constants == null)
2340 Expression cv = (Expression) constants [name];
2344 Expression e = cv.Resolve (ec);
2348 if (!(e is Constant)){
2349 Report.Error (133, vi.Location,
2350 "The expression being assigned to `" +
2351 name + "' must be constant (" + e + ")");
2355 constants.Remove (name);
2356 constants.Add (name, e);
2361 // Now, handle the children
2363 if (children != null){
2364 foreach (Block b in children)
2365 b.EmitMeta (ec, toplevel);
2369 public void UsageWarning ()
2373 if (variables != null){
2374 foreach (DictionaryEntry de in variables){
2375 VariableInfo vi = (VariableInfo) de.Value;
2380 name = (string) de.Key;
2384 219, vi.Location, "The variable `" + name +
2385 "' is assigned but its value is never used");
2388 168, vi.Location, "The variable `" +
2390 "' is declared but never used");
2395 if (children != null)
2396 foreach (Block b in children)
2400 public override bool Resolve (EmitContext ec)
2402 Block prev_block = ec.CurrentBlock;
2405 ec.CurrentBlock = this;
2406 ec.StartFlowBranching (this);
2408 Report.Debug (1, "RESOLVE BLOCK", StartLocation);
2410 if (!variables_initialized)
2411 UpdateVariableInfo (ec);
2413 foreach (Statement s in statements){
2414 if (s.Resolve (ec) == false)
2418 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation);
2420 ec.EndFlowBranching ();
2421 ec.CurrentBlock = prev_block;
2425 public override bool Emit (EmitContext ec)
2427 bool is_ret = false, this_ret = false;
2428 Block prev_block = ec.CurrentBlock;
2429 bool warning_shown = false;
2431 ec.CurrentBlock = this;
2433 if (CodeGen.SymbolWriter != null) {
2434 ec.Mark (StartLocation);
2436 foreach (Statement s in statements) {
2439 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2440 warning_shown = true;
2441 Warning_DeadCodeFound (s.loc);
2443 this_ret = s.Emit (ec);
2448 ec.Mark (EndLocation);
2450 foreach (Statement s in statements){
2451 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2452 warning_shown = true;
2453 Warning_DeadCodeFound (s.loc);
2455 this_ret = s.Emit (ec);
2461 ec.CurrentBlock = prev_block;
2466 public class SwitchLabel {
2469 public Location loc;
2470 public Label ILLabel;
2471 public Label ILLabelCode;
2474 // if expr == null, then it is the default case.
2476 public SwitchLabel (Expression expr, Location l)
2482 public Expression Label {
2488 public object Converted {
2495 // Resolves the expression, reduces it to a literal if possible
2496 // and then converts it to the requested type.
2498 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2500 ILLabel = ec.ig.DefineLabel ();
2501 ILLabelCode = ec.ig.DefineLabel ();
2506 Expression e = label.Resolve (ec);
2511 if (!(e is Constant)){
2512 Console.WriteLine ("Value is: " + label);
2513 Report.Error (150, loc, "A constant value is expected");
2517 if (e is StringConstant || e is NullLiteral){
2518 if (required_type == TypeManager.string_type){
2520 ILLabel = ec.ig.DefineLabel ();
2525 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2526 if (converted == null)
2533 public class SwitchSection {
2534 // An array of SwitchLabels.
2535 public readonly ArrayList Labels;
2536 public readonly Block Block;
2538 public SwitchSection (ArrayList labels, Block block)
2545 public class Switch : Statement {
2546 public readonly ArrayList Sections;
2547 public Expression Expr;
2550 /// Maps constants whose type type SwitchType to their SwitchLabels.
2552 public Hashtable Elements;
2555 /// The governing switch type
2557 public Type SwitchType;
2563 Label default_target;
2564 Expression new_expr;
2567 // The types allowed to be implicitly cast from
2568 // on the governing type
2570 static Type [] allowed_types;
2572 public Switch (Expression e, ArrayList sects, Location l)
2579 public bool GotDefault {
2585 public Label DefaultTarget {
2587 return default_target;
2592 // Determines the governing type for a switch. The returned
2593 // expression might be the expression from the switch, or an
2594 // expression that includes any potential conversions to the
2595 // integral types or to string.
2597 Expression SwitchGoverningType (EmitContext ec, Type t)
2599 if (t == TypeManager.int32_type ||
2600 t == TypeManager.uint32_type ||
2601 t == TypeManager.char_type ||
2602 t == TypeManager.byte_type ||
2603 t == TypeManager.sbyte_type ||
2604 t == TypeManager.ushort_type ||
2605 t == TypeManager.short_type ||
2606 t == TypeManager.uint64_type ||
2607 t == TypeManager.int64_type ||
2608 t == TypeManager.string_type ||
2609 t == TypeManager.bool_type ||
2610 t.IsSubclassOf (TypeManager.enum_type))
2613 if (allowed_types == null){
2614 allowed_types = new Type [] {
2615 TypeManager.sbyte_type,
2616 TypeManager.byte_type,
2617 TypeManager.short_type,
2618 TypeManager.ushort_type,
2619 TypeManager.int32_type,
2620 TypeManager.uint32_type,
2621 TypeManager.int64_type,
2622 TypeManager.uint64_type,
2623 TypeManager.char_type,
2624 TypeManager.bool_type,
2625 TypeManager.string_type
2630 // Try to find a *user* defined implicit conversion.
2632 // If there is no implicit conversion, or if there are multiple
2633 // conversions, we have to report an error
2635 Expression converted = null;
2636 foreach (Type tt in allowed_types){
2639 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
2643 if (converted != null){
2644 Report.Error (-12, loc, "More than one conversion to an integral " +
2645 " type exists for type `" +
2646 TypeManager.CSharpName (Expr.Type)+"'");
2654 void error152 (string n)
2657 152, "The label `" + n + ":' " +
2658 "is already present on this switch statement");
2662 // Performs the basic sanity checks on the switch statement
2663 // (looks for duplicate keys and non-constant expressions).
2665 // It also returns a hashtable with the keys that we will later
2666 // use to compute the switch tables
2668 bool CheckSwitch (EmitContext ec)
2672 Elements = new Hashtable ();
2674 got_default = false;
2676 if (TypeManager.IsEnumType (SwitchType)){
2677 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2679 compare_type = SwitchType;
2681 foreach (SwitchSection ss in Sections){
2682 foreach (SwitchLabel sl in ss.Labels){
2683 if (!sl.ResolveAndReduce (ec, SwitchType)){
2688 if (sl.Label == null){
2690 error152 ("default");
2697 object key = sl.Converted;
2699 if (key is Constant)
2700 key = ((Constant) key).GetValue ();
2703 key = NullLiteral.Null;
2705 string lname = null;
2706 if (compare_type == TypeManager.uint64_type){
2707 ulong v = (ulong) key;
2709 if (Elements.Contains (v))
2710 lname = v.ToString ();
2712 Elements.Add (v, sl);
2713 } else if (compare_type == TypeManager.int64_type){
2714 long v = (long) key;
2716 if (Elements.Contains (v))
2717 lname = v.ToString ();
2719 Elements.Add (v, sl);
2720 } else if (compare_type == TypeManager.uint32_type){
2721 uint v = (uint) key;
2723 if (Elements.Contains (v))
2724 lname = v.ToString ();
2726 Elements.Add (v, sl);
2727 } else if (compare_type == TypeManager.char_type){
2728 char v = (char) key;
2730 if (Elements.Contains (v))
2731 lname = v.ToString ();
2733 Elements.Add (v, sl);
2734 } else if (compare_type == TypeManager.byte_type){
2735 byte v = (byte) key;
2737 if (Elements.Contains (v))
2738 lname = v.ToString ();
2740 Elements.Add (v, sl);
2741 } else if (compare_type == TypeManager.sbyte_type){
2742 sbyte v = (sbyte) key;
2744 if (Elements.Contains (v))
2745 lname = v.ToString ();
2747 Elements.Add (v, sl);
2748 } else if (compare_type == TypeManager.short_type){
2749 short v = (short) key;
2751 if (Elements.Contains (v))
2752 lname = v.ToString ();
2754 Elements.Add (v, sl);
2755 } else if (compare_type == TypeManager.ushort_type){
2756 ushort v = (ushort) key;
2758 if (Elements.Contains (v))
2759 lname = v.ToString ();
2761 Elements.Add (v, sl);
2762 } else if (compare_type == TypeManager.string_type){
2763 if (key is NullLiteral){
2764 if (Elements.Contains (NullLiteral.Null))
2767 Elements.Add (NullLiteral.Null, null);
2769 string s = (string) key;
2771 if (Elements.Contains (s))
2774 Elements.Add (s, sl);
2776 } else if (compare_type == TypeManager.int32_type) {
2779 if (Elements.Contains (v))
2780 lname = v.ToString ();
2782 Elements.Add (v, sl);
2783 } else if (compare_type == TypeManager.bool_type) {
2784 bool v = (bool) key;
2786 if (Elements.Contains (v))
2787 lname = v.ToString ();
2789 Elements.Add (v, sl);
2793 throw new Exception ("Unknown switch type!" +
2794 SwitchType + " " + compare_type);
2798 error152 ("case + " + lname);
2809 void EmitObjectInteger (ILGenerator ig, object k)
2812 IntConstant.EmitInt (ig, (int) k);
2813 else if (k is Constant) {
2814 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2817 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2820 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2822 IntConstant.EmitInt (ig, (int) (long) k);
2823 ig.Emit (OpCodes.Conv_I8);
2826 LongConstant.EmitLong (ig, (long) k);
2828 else if (k is ulong)
2830 if ((ulong) k < (1L<<32))
2832 IntConstant.EmitInt (ig, (int) (long) k);
2833 ig.Emit (OpCodes.Conv_U8);
2837 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2841 IntConstant.EmitInt (ig, (int) ((char) k));
2842 else if (k is sbyte)
2843 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2845 IntConstant.EmitInt (ig, (int) ((byte) k));
2846 else if (k is short)
2847 IntConstant.EmitInt (ig, (int) ((short) k));
2848 else if (k is ushort)
2849 IntConstant.EmitInt (ig, (int) ((ushort) k));
2851 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2853 throw new Exception ("Unhandled case");
2856 // structure used to hold blocks of keys while calculating table switch
2857 class KeyBlock : IComparable
2859 public KeyBlock (long _nFirst)
2861 nFirst = nLast = _nFirst;
2865 public ArrayList rgKeys = null;
2868 get { return (int) (nLast - nFirst + 1); }
2870 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2872 return kbLast.nLast - kbFirst.nFirst + 1;
2874 public int CompareTo (object obj)
2876 KeyBlock kb = (KeyBlock) obj;
2877 int nLength = Length;
2878 int nLengthOther = kb.Length;
2879 if (nLengthOther == nLength)
2880 return (int) (kb.nFirst - nFirst);
2881 return nLength - nLengthOther;
2886 /// This method emits code for a lookup-based switch statement (non-string)
2887 /// Basically it groups the cases into blocks that are at least half full,
2888 /// and then spits out individual lookup opcodes for each block.
2889 /// It emits the longest blocks first, and short blocks are just
2890 /// handled with direct compares.
2892 /// <param name="ec"></param>
2893 /// <param name="val"></param>
2894 /// <returns></returns>
2895 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
2897 int cElements = Elements.Count;
2898 object [] rgKeys = new object [cElements];
2899 Elements.Keys.CopyTo (rgKeys, 0);
2900 Array.Sort (rgKeys);
2902 // initialize the block list with one element per key
2903 ArrayList rgKeyBlocks = new ArrayList ();
2904 foreach (object key in rgKeys)
2905 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
2908 // iteratively merge the blocks while they are at least half full
2909 // there's probably a really cool way to do this with a tree...
2910 while (rgKeyBlocks.Count > 1)
2912 ArrayList rgKeyBlocksNew = new ArrayList ();
2913 kbCurr = (KeyBlock) rgKeyBlocks [0];
2914 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2916 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2917 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2920 kbCurr.nLast = kb.nLast;
2924 // start a new block
2925 rgKeyBlocksNew.Add (kbCurr);
2929 rgKeyBlocksNew.Add (kbCurr);
2930 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2932 rgKeyBlocks = rgKeyBlocksNew;
2935 // initialize the key lists
2936 foreach (KeyBlock kb in rgKeyBlocks)
2937 kb.rgKeys = new ArrayList ();
2939 // fill the key lists
2941 if (rgKeyBlocks.Count > 0) {
2942 kbCurr = (KeyBlock) rgKeyBlocks [0];
2943 foreach (object key in rgKeys)
2945 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
2947 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2948 kbCurr.rgKeys.Add (key);
2952 // sort the blocks so we can tackle the largest ones first
2953 rgKeyBlocks.Sort ();
2955 // okay now we can start...
2956 ILGenerator ig = ec.ig;
2957 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2958 Label lblDefault = ig.DefineLabel ();
2960 Type typeKeys = null;
2961 if (rgKeys.Length > 0)
2962 typeKeys = rgKeys [0].GetType (); // used for conversions
2964 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2966 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2967 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2970 foreach (object key in kb.rgKeys)
2972 ig.Emit (OpCodes.Ldloc, val);
2973 EmitObjectInteger (ig, key);
2974 SwitchLabel sl = (SwitchLabel) Elements [key];
2975 ig.Emit (OpCodes.Beq, sl.ILLabel);
2980 // TODO: if all the keys in the block are the same and there are
2981 // no gaps/defaults then just use a range-check.
2982 if (SwitchType == TypeManager.int64_type ||
2983 SwitchType == TypeManager.uint64_type)
2985 // TODO: optimize constant/I4 cases
2987 // check block range (could be > 2^31)
2988 ig.Emit (OpCodes.Ldloc, val);
2989 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
2990 ig.Emit (OpCodes.Blt, lblDefault);
2991 ig.Emit (OpCodes.Ldloc, val);
2992 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
2993 ig.Emit (OpCodes.Bgt, lblDefault);
2996 ig.Emit (OpCodes.Ldloc, val);
2999 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3000 ig.Emit (OpCodes.Sub);
3002 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3007 ig.Emit (OpCodes.Ldloc, val);
3008 int nFirst = (int) kb.nFirst;
3011 IntConstant.EmitInt (ig, nFirst);
3012 ig.Emit (OpCodes.Sub);
3014 else if (nFirst < 0)
3016 IntConstant.EmitInt (ig, -nFirst);
3017 ig.Emit (OpCodes.Add);
3021 // first, build the list of labels for the switch
3023 int cJumps = kb.Length;
3024 Label [] rgLabels = new Label [cJumps];
3025 for (int iJump = 0; iJump < cJumps; iJump++)
3027 object key = kb.rgKeys [iKey];
3028 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3030 SwitchLabel sl = (SwitchLabel) Elements [key];
3031 rgLabels [iJump] = sl.ILLabel;
3035 rgLabels [iJump] = lblDefault;
3037 // emit the switch opcode
3038 ig.Emit (OpCodes.Switch, rgLabels);
3041 // mark the default for this block
3043 ig.MarkLabel (lblDefault);
3046 // TODO: find the default case and emit it here,
3047 // to prevent having to do the following jump.
3048 // make sure to mark other labels in the default section
3050 // the last default just goes to the end
3051 ig.Emit (OpCodes.Br, lblDefault);
3053 // now emit the code for the sections
3054 bool fFoundDefault = false;
3055 bool fAllReturn = true;
3056 foreach (SwitchSection ss in Sections)
3058 foreach (SwitchLabel sl in ss.Labels)
3060 ig.MarkLabel (sl.ILLabel);
3061 ig.MarkLabel (sl.ILLabelCode);
3062 if (sl.Label == null)
3064 ig.MarkLabel (lblDefault);
3065 fFoundDefault = true;
3068 fAllReturn &= ss.Block.Emit (ec);
3069 //ig.Emit (OpCodes.Br, lblEnd);
3072 if (!fFoundDefault) {
3073 ig.MarkLabel (lblDefault);
3076 ig.MarkLabel (lblEnd);
3081 // This simple emit switch works, but does not take advantage of the
3083 // TODO: remove non-string logic from here
3084 // TODO: binary search strings?
3086 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3088 ILGenerator ig = ec.ig;
3089 Label end_of_switch = ig.DefineLabel ();
3090 Label next_test = ig.DefineLabel ();
3091 Label null_target = ig.DefineLabel ();
3092 bool default_found = false;
3093 bool first_test = true;
3094 bool pending_goto_end = false;
3095 bool all_return = true;
3096 bool is_string = false;
3100 // Special processing for strings: we cant compare
3103 if (SwitchType == TypeManager.string_type){
3104 ig.Emit (OpCodes.Ldloc, val);
3107 if (Elements.Contains (NullLiteral.Null)){
3108 ig.Emit (OpCodes.Brfalse, null_target);
3110 ig.Emit (OpCodes.Brfalse, default_target);
3112 ig.Emit (OpCodes.Ldloc, val);
3113 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3114 ig.Emit (OpCodes.Stloc, val);
3117 SwitchSection last_section;
3118 last_section = (SwitchSection) Sections [Sections.Count-1];
3120 foreach (SwitchSection ss in Sections){
3121 Label sec_begin = ig.DefineLabel ();
3123 if (pending_goto_end)
3124 ig.Emit (OpCodes.Br, end_of_switch);
3126 int label_count = ss.Labels.Count;
3128 foreach (SwitchLabel sl in ss.Labels){
3129 ig.MarkLabel (sl.ILLabel);
3132 ig.MarkLabel (next_test);
3133 next_test = ig.DefineLabel ();
3136 // If we are the default target
3138 if (sl.Label == null){
3139 ig.MarkLabel (default_target);
3140 default_found = true;
3142 object lit = sl.Converted;
3144 if (lit is NullLiteral){
3146 if (label_count == 1)
3147 ig.Emit (OpCodes.Br, next_test);
3152 StringConstant str = (StringConstant) lit;
3154 ig.Emit (OpCodes.Ldloc, val);
3155 ig.Emit (OpCodes.Ldstr, str.Value);
3156 if (label_count == 1)
3157 ig.Emit (OpCodes.Bne_Un, next_test);
3159 ig.Emit (OpCodes.Beq, sec_begin);
3161 ig.Emit (OpCodes.Ldloc, val);
3162 EmitObjectInteger (ig, lit);
3163 ig.Emit (OpCodes.Ceq);
3164 if (label_count == 1)
3165 ig.Emit (OpCodes.Brfalse, next_test);
3167 ig.Emit (OpCodes.Brtrue, sec_begin);
3171 if (label_count != 1 && ss != last_section)
3172 ig.Emit (OpCodes.Br, next_test);
3175 ig.MarkLabel (null_target);
3176 ig.MarkLabel (sec_begin);
3177 foreach (SwitchLabel sl in ss.Labels)
\r
3178 ig.MarkLabel (sl.ILLabelCode);
3179 if (ss.Block.Emit (ec))
3180 pending_goto_end = false;
3183 pending_goto_end = true;
3187 if (!default_found){
3188 ig.MarkLabel (default_target);
3191 ig.MarkLabel (next_test);
3192 ig.MarkLabel (end_of_switch);
3197 public override bool Resolve (EmitContext ec)
3199 Expr = Expr.Resolve (ec);
3203 new_expr = SwitchGoverningType (ec, Expr.Type);
3204 if (new_expr == null){
3205 Report.Error (151, loc, "An integer type or string was expected for switch");
3210 SwitchType = new_expr.Type;
3212 if (!CheckSwitch (ec))
3215 Switch old_switch = ec.Switch;
3217 ec.Switch.SwitchType = SwitchType;
3219 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3222 foreach (SwitchSection ss in Sections){
3224 ec.CurrentBranching.CreateSibling ();
3228 if (ss.Block.Resolve (ec) != true)
3232 ec.EndFlowBranching ();
3233 ec.Switch = old_switch;
3238 public override bool Emit (EmitContext ec)
3240 // Store variable for comparission purposes
3241 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3243 ec.ig.Emit (OpCodes.Stloc, value);
3245 ILGenerator ig = ec.ig;
3247 default_target = ig.DefineLabel ();
3250 // Setup the codegen context
3252 Label old_end = ec.LoopEnd;
3253 Switch old_switch = ec.Switch;
3255 ec.LoopEnd = ig.DefineLabel ();
3260 if (SwitchType == TypeManager.string_type)
3261 all_return = SimpleSwitchEmit (ec, value);
3263 all_return = TableSwitchEmit (ec, value);
3265 // Restore context state.
3266 ig.MarkLabel (ec.LoopEnd);
3269 // Restore the previous context
3271 ec.LoopEnd = old_end;
3272 ec.Switch = old_switch;
3278 public class Lock : Statement {
3280 Statement Statement;
3282 public Lock (Expression expr, Statement stmt, Location l)
3289 public override bool Resolve (EmitContext ec)
3291 expr = expr.Resolve (ec);
3292 return Statement.Resolve (ec) && expr != null;
3295 public override bool Emit (EmitContext ec)
3297 Type type = expr.Type;
3300 if (type.IsValueType){
3301 Report.Error (185, loc, "lock statement requires the expression to be " +
3302 " a reference type (type is: `" +
3303 TypeManager.CSharpName (type) + "'");
3307 ILGenerator ig = ec.ig;
3308 LocalBuilder temp = ig.DeclareLocal (type);
3311 ig.Emit (OpCodes.Dup);
3312 ig.Emit (OpCodes.Stloc, temp);
3313 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3316 Label end = ig.BeginExceptionBlock ();
3317 bool old_in_try = ec.InTry;
3319 Label finish = ig.DefineLabel ();
3320 val = Statement.Emit (ec);
3321 ec.InTry = old_in_try;
3322 // ig.Emit (OpCodes.Leave, finish);
3324 ig.MarkLabel (finish);
3327 ig.BeginFinallyBlock ();
3328 ig.Emit (OpCodes.Ldloc, temp);
3329 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3330 ig.EndExceptionBlock ();
3336 public class Unchecked : Statement {
3337 public readonly Block Block;
3339 public Unchecked (Block b)
3344 public override bool Resolve (EmitContext ec)
3346 return Block.Resolve (ec);
3349 public override bool Emit (EmitContext ec)
3351 bool previous_state = ec.CheckState;
3352 bool previous_state_const = ec.ConstantCheckState;
3355 ec.CheckState = false;
3356 ec.ConstantCheckState = false;
3357 val = Block.Emit (ec);
3358 ec.CheckState = previous_state;
3359 ec.ConstantCheckState = previous_state_const;
3365 public class Checked : Statement {
3366 public readonly Block Block;
3368 public Checked (Block b)
3373 public override bool Resolve (EmitContext ec)
3375 bool previous_state = ec.CheckState;
3376 bool previous_state_const = ec.ConstantCheckState;
3378 ec.CheckState = true;
3379 ec.ConstantCheckState = true;
3380 bool ret = Block.Resolve (ec);
3381 ec.CheckState = previous_state;
3382 ec.ConstantCheckState = previous_state_const;
3387 public override bool Emit (EmitContext ec)
3389 bool previous_state = ec.CheckState;
3390 bool previous_state_const = ec.ConstantCheckState;
3393 ec.CheckState = true;
3394 ec.ConstantCheckState = true;
3395 val = Block.Emit (ec);
3396 ec.CheckState = previous_state;
3397 ec.ConstantCheckState = previous_state_const;
3403 public class Unsafe : Statement {
3404 public readonly Block Block;
3406 public Unsafe (Block b)
3411 public override bool Resolve (EmitContext ec)
3413 bool previous_state = ec.InUnsafe;
3417 val = Block.Resolve (ec);
3418 ec.InUnsafe = previous_state;
3423 public override bool Emit (EmitContext ec)
3425 bool previous_state = ec.InUnsafe;
3429 val = Block.Emit (ec);
3430 ec.InUnsafe = previous_state;
3439 public class Fixed : Statement {
3441 ArrayList declarators;
3442 Statement statement;
3447 public bool is_object;
3448 public VariableInfo vi;
3449 public Expression expr;
3450 public Expression converted;
3453 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3456 declarators = decls;
3461 public override bool Resolve (EmitContext ec)
3463 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3464 if (expr_type == null)
3467 data = new FixedData [declarators.Count];
3470 foreach (Pair p in declarators){
3471 VariableInfo vi = (VariableInfo) p.First;
3472 Expression e = (Expression) p.Second;
3477 // The rules for the possible declarators are pretty wise,
3478 // but the production on the grammar is more concise.
3480 // So we have to enforce these rules here.
3482 // We do not resolve before doing the case 1 test,
3483 // because the grammar is explicit in that the token &
3484 // is present, so we need to test for this particular case.
3488 // Case 1: & object.
3490 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3491 Expression child = ((Unary) e).Expr;
3494 if (child is ParameterReference || child is LocalVariableReference){
3497 "No need to use fixed statement for parameters or " +
3498 "local variable declarations (address is already " +
3507 child = ((Unary) e).Expr;
3509 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3512 data [i].is_object = true;
3514 data [i].converted = null;
3528 if (e.Type.IsArray){
3529 Type array_type = e.Type.GetElementType ();
3533 // Provided that array_type is unmanaged,
3535 if (!TypeManager.VerifyUnManaged (array_type, loc))
3539 // and T* is implicitly convertible to the
3540 // pointer type given in the fixed statement.
3542 ArrayPtr array_ptr = new ArrayPtr (e);
3544 Expression converted = Expression.ConvertImplicitRequired (
3545 ec, array_ptr, vi.VariableType, loc);
3546 if (converted == null)
3549 data [i].is_object = false;
3551 data [i].converted = converted;
3561 if (e.Type == TypeManager.string_type){
3562 data [i].is_object = false;
3564 data [i].converted = null;
3570 return statement.Resolve (ec);
3573 public override bool Emit (EmitContext ec)
3575 ILGenerator ig = ec.ig;
3577 bool is_ret = false;
3579 for (int i = 0; i < data.Length; i++) {
3580 VariableInfo vi = data [i].vi;
3583 // Case 1: & object.
3585 if (data [i].is_object) {
3587 // Store pointer in pinned location
3589 data [i].expr.Emit (ec);
3590 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3592 is_ret = statement.Emit (ec);
3594 // Clear the pinned variable.
3595 ig.Emit (OpCodes.Ldc_I4_0);
3596 ig.Emit (OpCodes.Conv_U);
3597 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3605 if (data [i].expr.Type.IsArray){
3607 // Store pointer in pinned location
3609 data [i].converted.Emit (ec);
3611 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3613 is_ret = statement.Emit (ec);
3615 // Clear the pinned variable.
3616 ig.Emit (OpCodes.Ldc_I4_0);
3617 ig.Emit (OpCodes.Conv_U);
3618 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3626 if (data [i].expr.Type == TypeManager.string_type){
3627 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3628 TypeManager.MakePinned (pinned_string);
3630 data [i].expr.Emit (ec);
3631 ig.Emit (OpCodes.Stloc, pinned_string);
3633 Expression sptr = new StringPtr (pinned_string);
3634 Expression converted = Expression.ConvertImplicitRequired (
3635 ec, sptr, vi.VariableType, loc);
3637 if (converted == null)
3640 converted.Emit (ec);
3641 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3643 is_ret = statement.Emit (ec);
3645 // Clear the pinned variable
3646 ig.Emit (OpCodes.Ldnull);
3647 ig.Emit (OpCodes.Stloc, pinned_string);
3655 public class Catch {
3656 public readonly string Name;
3657 public readonly Block Block;
3658 public readonly Location Location;
3662 public Catch (Expression type, string name, Block block, Location l)
3670 public Type CatchType {
3673 throw new InvalidOperationException ();
3679 public bool IsGeneral {
3681 return type == null;
3685 public bool Resolve (EmitContext ec)
3688 type = type.DoResolve (ec);
3693 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)){
3694 Report.Error (155, Location,
3695 "The type caught or thrown must be derived " +
3696 "from System.Exception");
3701 if (!Block.Resolve (ec))
3708 public class Try : Statement {
3709 public readonly Block Fini, Block;
3710 public readonly ArrayList Specific;
3711 public readonly Catch General;
3714 // specific, general and fini might all be null.
3716 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3718 if (specific == null && general == null){
3719 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3723 this.Specific = specific;
3724 this.General = general;
3729 public override bool Resolve (EmitContext ec)
3733 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
3735 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3737 if (!Block.Resolve (ec))
3740 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3742 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3744 foreach (Catch c in Specific){
3745 ec.CurrentBranching.CreateSibling ();
3746 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3748 if (c.Name != null) {
3749 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
3751 throw new Exception ();
3756 if (!c.Resolve (ec))
3759 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3761 if ((current.Returns == FlowReturns.NEVER) ||
3762 (current.Returns == FlowReturns.SOMETIMES)) {
3763 vector.AndLocals (current);
3767 if (General != null){
3768 ec.CurrentBranching.CreateSibling ();
3769 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3771 if (!General.Resolve (ec))
3774 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3776 if ((current.Returns == FlowReturns.NEVER) ||
3777 (current.Returns == FlowReturns.SOMETIMES)) {
3778 vector.AndLocals (current);
3782 ec.CurrentBranching.CreateSiblingForFinally ();
3783 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3786 if (!Fini.Resolve (ec))
3789 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3791 FlowReturns returns = ec.EndFlowBranching ();
3793 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
3795 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
3796 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
3799 ec.CurrentBranching.CurrentUsageVector.Or (vector);
3801 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
3806 public override bool Emit (EmitContext ec)
3808 ILGenerator ig = ec.ig;
3810 Label finish = ig.DefineLabel ();;
3814 end = ig.BeginExceptionBlock ();
3815 bool old_in_try = ec.InTry;
3817 returns = Block.Emit (ec);
3818 ec.InTry = old_in_try;
3821 // System.Reflection.Emit provides this automatically:
3822 // ig.Emit (OpCodes.Leave, finish);
3824 bool old_in_catch = ec.InCatch;
3826 DeclSpace ds = ec.DeclSpace;
3828 foreach (Catch c in Specific){
3831 ig.BeginCatchBlock (c.CatchType);
3833 if (c.Name != null){
3834 vi = c.Block.GetVariableInfo (c.Name);
3836 throw new Exception ("Variable does not exist in this block");
3838 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3840 ig.Emit (OpCodes.Pop);
3842 if (!c.Block.Emit (ec))
3846 if (General != null){
3847 ig.BeginCatchBlock (TypeManager.object_type);
3848 ig.Emit (OpCodes.Pop);
3849 if (!General.Block.Emit (ec))
3852 ec.InCatch = old_in_catch;
3854 ig.MarkLabel (finish);
3856 ig.BeginFinallyBlock ();
3857 bool old_in_finally = ec.InFinally;
3858 ec.InFinally = true;
3860 ec.InFinally = old_in_finally;
3863 ig.EndExceptionBlock ();
3866 if (!returns || ec.InTry || ec.InCatch)
3869 // Unfortunately, System.Reflection.Emit automatically emits a leave
3870 // to the end of the finally block. This is a problem if `returns'
3871 // is true since we may jump to a point after the end of the method.
3872 // As a workaround, emit an explicit ret here.
3874 if (ec.ReturnType != null)
3875 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
3876 ec.ig.Emit (OpCodes.Ret);
3883 // FIXME: We still do not support the expression variant of the using
3886 public class Using : Statement {
3887 object expression_or_block;
3888 Statement Statement;
3893 Expression [] converted_vars;
3894 ExpressionStatement [] assign;
3896 public Using (object expression_or_block, Statement stmt, Location l)
3898 this.expression_or_block = expression_or_block;
3904 // Resolves for the case of using using a local variable declaration.
3906 bool ResolveLocalVariableDecls (EmitContext ec)
3908 bool need_conv = false;
3909 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3912 if (expr_type == null)
3916 // The type must be an IDisposable or an implicit conversion
3919 converted_vars = new Expression [var_list.Count];
3920 assign = new ExpressionStatement [var_list.Count];
3921 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3922 foreach (DictionaryEntry e in var_list){
3923 Expression var = (Expression) e.Key;
3925 var = var.ResolveLValue (ec, new EmptyExpression ());
3929 converted_vars [i] = Expression.ConvertImplicit (
3930 ec, var, TypeManager.idisposable_type, loc);
3932 if (converted_vars [i] == null)
3940 foreach (DictionaryEntry e in var_list){
3941 LocalVariableReference var = (LocalVariableReference) e.Key;
3942 Expression new_expr = (Expression) e.Value;
3945 a = new Assign (var, new_expr, loc);
3951 converted_vars [i] = var;
3952 assign [i] = (ExpressionStatement) a;
3959 bool ResolveExpression (EmitContext ec)
3961 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3962 conv = Expression.ConvertImplicit (
3963 ec, expr, TypeManager.idisposable_type, loc);
3973 // Emits the code for the case of using using a local variable declaration.
3975 bool EmitLocalVariableDecls (EmitContext ec)
3977 ILGenerator ig = ec.ig;
3980 bool old_in_try = ec.InTry;
3982 for (i = 0; i < assign.Length; i++) {
3983 assign [i].EmitStatement (ec);
3985 ig.BeginExceptionBlock ();
3987 Statement.Emit (ec);
3988 ec.InTry = old_in_try;
3990 bool old_in_finally = ec.InFinally;
3991 ec.InFinally = true;
3992 var_list.Reverse ();
3993 foreach (DictionaryEntry e in var_list){
3994 LocalVariableReference var = (LocalVariableReference) e.Key;
3995 Label skip = ig.DefineLabel ();
3998 ig.BeginFinallyBlock ();
4001 ig.Emit (OpCodes.Brfalse, skip);
4002 converted_vars [i].Emit (ec);
4003 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4004 ig.MarkLabel (skip);
4005 ig.EndExceptionBlock ();
4007 ec.InFinally = old_in_finally;
4012 bool EmitExpression (EmitContext ec)
4015 // Make a copy of the expression and operate on that.
4017 ILGenerator ig = ec.ig;
4018 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4023 ig.Emit (OpCodes.Stloc, local_copy);
4025 bool old_in_try = ec.InTry;
4027 ig.BeginExceptionBlock ();
4028 Statement.Emit (ec);
4029 ec.InTry = old_in_try;
4031 Label skip = ig.DefineLabel ();
4032 bool old_in_finally = ec.InFinally;
4033 ig.BeginFinallyBlock ();
4034 ig.Emit (OpCodes.Ldloc, local_copy);
4035 ig.Emit (OpCodes.Brfalse, skip);
4036 ig.Emit (OpCodes.Ldloc, local_copy);
4037 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4038 ig.MarkLabel (skip);
4039 ec.InFinally = old_in_finally;
4040 ig.EndExceptionBlock ();
4045 public override bool Resolve (EmitContext ec)
4047 if (expression_or_block is DictionaryEntry){
4048 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4049 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4051 if (!ResolveLocalVariableDecls (ec))
4054 } else if (expression_or_block is Expression){
4055 expr = (Expression) expression_or_block;
4057 expr = expr.Resolve (ec);
4061 expr_type = expr.Type;
4063 if (!ResolveExpression (ec))
4067 return Statement.Resolve (ec);
4070 public override bool Emit (EmitContext ec)
4072 if (expression_or_block is DictionaryEntry)
4073 return EmitLocalVariableDecls (ec);
4074 else if (expression_or_block is Expression)
4075 return EmitExpression (ec);
4082 /// Implementation of the foreach C# statement
4084 public class Foreach : Statement {
4086 LocalVariableReference variable;
4088 Statement statement;
4089 ForeachHelperMethods hm;
4090 Expression empty, conv;
4091 Type array_type, element_type;
4094 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4095 Statement stmt, Location l)
4098 this.variable = var;
4104 public override bool Resolve (EmitContext ec)
4106 expr = expr.Resolve (ec);
4110 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4111 if (var_type == null)
4115 // We need an instance variable. Not sure this is the best
4116 // way of doing this.
4118 // FIXME: When we implement propertyaccess, will those turn
4119 // out to return values in ExprClass? I think they should.
4121 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4122 expr.eclass == ExprClass.PropertyAccess)){
4123 error1579 (expr.Type);
4127 if (expr.Type.IsArray) {
4128 array_type = expr.Type;
4129 element_type = array_type.GetElementType ();
4131 empty = new EmptyExpression (element_type);
4133 hm = ProbeCollectionType (ec, expr.Type);
4135 error1579 (expr.Type);
4139 array_type = expr.Type;
4140 element_type = hm.element_type;
4142 empty = new EmptyExpression (hm.element_type);
4146 // FIXME: maybe we can apply the same trick we do in the
4147 // array handling to avoid creating empty and conv in some cases.
4149 // Although it is not as important in this case, as the type
4150 // will not likely be object (what the enumerator will return).
4152 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4156 if (variable.ResolveLValue (ec, empty) == null)
4159 if (!statement.Resolve (ec))
4166 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4168 static MethodInfo FetchMethodMoveNext (Type t)
4170 MemberInfo [] move_next_list;
4172 move_next_list = TypeContainer.FindMembers (
4173 t, MemberTypes.Method,
4174 BindingFlags.Public | BindingFlags.Instance,
4175 Type.FilterName, "MoveNext");
4176 if (move_next_list == null || move_next_list.Length == 0)
4179 foreach (MemberInfo m in move_next_list){
4180 MethodInfo mi = (MethodInfo) m;
4183 args = TypeManager.GetArgumentTypes (mi);
4184 if (args != null && args.Length == 0){
4185 if (mi.ReturnType == TypeManager.bool_type)
4193 // Retrieves a `public T get_Current ()' method from the Type `t'
4195 static MethodInfo FetchMethodGetCurrent (Type t)
4197 MemberInfo [] move_next_list;
4199 move_next_list = TypeContainer.FindMembers (
4200 t, MemberTypes.Method,
4201 BindingFlags.Public | BindingFlags.Instance,
4202 Type.FilterName, "get_Current");
4203 if (move_next_list == null || move_next_list.Length == 0)
4206 foreach (MemberInfo m in move_next_list){
4207 MethodInfo mi = (MethodInfo) m;
4210 args = TypeManager.GetArgumentTypes (mi);
4211 if (args != null && args.Length == 0)
4218 // This struct records the helper methods used by the Foreach construct
4220 class ForeachHelperMethods {
4221 public EmitContext ec;
4222 public MethodInfo get_enumerator;
4223 public MethodInfo move_next;
4224 public MethodInfo get_current;
4225 public Type element_type;
4226 public Type enumerator_type;
4227 public bool is_disposable;
4229 public ForeachHelperMethods (EmitContext ec)
4232 this.element_type = TypeManager.object_type;
4233 this.enumerator_type = TypeManager.ienumerator_type;
4234 this.is_disposable = true;
4238 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4243 if (!(m is MethodInfo))
4246 if (m.Name != "GetEnumerator")
4249 MethodInfo mi = (MethodInfo) m;
4250 Type [] args = TypeManager.GetArgumentTypes (mi);
4252 if (args.Length != 0)
4255 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4256 EmitContext ec = hm.ec;
4259 // Check whether GetEnumerator is accessible to us
4261 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4263 Type declaring = mi.DeclaringType;
4264 if (prot == MethodAttributes.Private){
4265 if (declaring != ec.ContainerType)
4267 } else if (prot == MethodAttributes.FamANDAssem){
4268 // If from a different assembly, false
4269 if (!(mi is MethodBuilder))
4272 // Are we being invoked from the same class, or from a derived method?
4274 if (ec.ContainerType != declaring){
4275 if (!ec.ContainerType.IsSubclassOf (declaring))
4278 } else if (prot == MethodAttributes.FamORAssem){
4279 if (!(mi is MethodBuilder ||
4280 ec.ContainerType == declaring ||
4281 ec.ContainerType.IsSubclassOf (declaring)))
4283 } if (prot == MethodAttributes.Family){
4284 if (!(ec.ContainerType == declaring ||
4285 ec.ContainerType.IsSubclassOf (declaring)))
4290 // Ok, we can access it, now make sure that we can do something
4291 // with this `GetEnumerator'
4294 if (mi.ReturnType == TypeManager.ienumerator_type ||
4295 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4296 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4297 hm.move_next = TypeManager.bool_movenext_void;
4298 hm.get_current = TypeManager.object_getcurrent_void;
4303 // Ok, so they dont return an IEnumerable, we will have to
4304 // find if they support the GetEnumerator pattern.
4306 Type return_type = mi.ReturnType;
4308 hm.move_next = FetchMethodMoveNext (return_type);
4309 if (hm.move_next == null)
4311 hm.get_current = FetchMethodGetCurrent (return_type);
4312 if (hm.get_current == null)
4315 hm.element_type = hm.get_current.ReturnType;
4316 hm.enumerator_type = return_type;
4317 hm.is_disposable = TypeManager.ImplementsInterface (
4318 hm.enumerator_type, TypeManager.idisposable_type);
4324 /// This filter is used to find the GetEnumerator method
4325 /// on which IEnumerator operates
4327 static MemberFilter FilterEnumerator;
4331 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4334 void error1579 (Type t)
4336 Report.Error (1579, loc,
4337 "foreach statement cannot operate on variables of type `" +
4338 t.FullName + "' because that class does not provide a " +
4339 " GetEnumerator method or it is inaccessible");
4342 static bool TryType (Type t, ForeachHelperMethods hm)
4346 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4347 BindingFlags.Public | BindingFlags.NonPublic |
4348 BindingFlags.Instance,
4349 FilterEnumerator, hm);
4351 if (mi == null || mi.Length == 0)
4354 hm.get_enumerator = (MethodInfo) mi [0];
4359 // Looks for a usable GetEnumerator in the Type, and if found returns
4360 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4362 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4364 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4366 if (TryType (t, hm))
4370 // Now try to find the method in the interfaces
4373 Type [] ifaces = t.GetInterfaces ();
4375 foreach (Type i in ifaces){
4376 if (TryType (i, hm))
4381 // Since TypeBuilder.GetInterfaces only returns the interface
4382 // types for this type, we have to keep looping, but once
4383 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4384 // done, because it returns all the types
4386 if ((t is TypeBuilder))
4396 // FIXME: possible optimization.
4397 // We might be able to avoid creating `empty' if the type is the sam
4399 bool EmitCollectionForeach (EmitContext ec)
4401 ILGenerator ig = ec.ig;
4402 LocalBuilder enumerator, disposable;
4404 enumerator = ig.DeclareLocal (hm.enumerator_type);
4405 if (hm.is_disposable)
4406 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4411 // Instantiate the enumerator
4413 if (expr.Type.IsValueType){
4414 if (expr is IMemoryLocation){
4415 IMemoryLocation ml = (IMemoryLocation) expr;
4417 ml.AddressOf (ec, AddressOp.Load);
4419 throw new Exception ("Expr " + expr + " of type " + expr.Type +
4420 " does not implement IMemoryLocation");
4421 ig.Emit (OpCodes.Call, hm.get_enumerator);
4424 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4426 ig.Emit (OpCodes.Stloc, enumerator);
4429 // Protect the code in a try/finalize block, so that
4430 // if the beast implement IDisposable, we get rid of it
4433 bool old_in_try = ec.InTry;
4435 if (hm.is_disposable) {
4436 l = ig.BeginExceptionBlock ();
4440 Label end_try = ig.DefineLabel ();
4442 ig.MarkLabel (ec.LoopBegin);
4443 ig.Emit (OpCodes.Ldloc, enumerator);
4444 ig.Emit (OpCodes.Callvirt, hm.move_next);
4445 ig.Emit (OpCodes.Brfalse, end_try);
4446 ig.Emit (OpCodes.Ldloc, enumerator);
4447 ig.Emit (OpCodes.Callvirt, hm.get_current);
4448 variable.EmitAssign (ec, conv);
4449 statement.Emit (ec);
4450 ig.Emit (OpCodes.Br, ec.LoopBegin);
4451 ig.MarkLabel (end_try);
4452 ec.InTry = old_in_try;
4454 // The runtime provides this for us.
4455 // ig.Emit (OpCodes.Leave, end);
4458 // Now the finally block
4460 if (hm.is_disposable) {
4461 Label end_finally = ig.DefineLabel ();
4462 bool old_in_finally = ec.InFinally;
4463 ec.InFinally = true;
4464 ig.BeginFinallyBlock ();
4466 ig.Emit (OpCodes.Ldloc, enumerator);
4467 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4468 ig.Emit (OpCodes.Stloc, disposable);
4469 ig.Emit (OpCodes.Ldloc, disposable);
4470 ig.Emit (OpCodes.Brfalse, end_finally);
4471 ig.Emit (OpCodes.Ldloc, disposable);
4472 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4473 ig.MarkLabel (end_finally);
4474 ec.InFinally = old_in_finally;
4476 // The runtime generates this anyways.
4477 // ig.Emit (OpCodes.Endfinally);
4479 ig.EndExceptionBlock ();
4482 ig.MarkLabel (ec.LoopEnd);
4487 // FIXME: possible optimization.
4488 // We might be able to avoid creating `empty' if the type is the sam
4490 bool EmitArrayForeach (EmitContext ec)
4492 int rank = array_type.GetArrayRank ();
4493 ILGenerator ig = ec.ig;
4495 LocalBuilder copy = ig.DeclareLocal (array_type);
4498 // Make our copy of the array
4501 ig.Emit (OpCodes.Stloc, copy);
4504 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
4508 ig.Emit (OpCodes.Ldc_I4_0);
4509 ig.Emit (OpCodes.Stloc, counter);
4510 test = ig.DefineLabel ();
4511 ig.Emit (OpCodes.Br, test);
4513 loop = ig.DefineLabel ();
4514 ig.MarkLabel (loop);
4516 ig.Emit (OpCodes.Ldloc, copy);
4517 ig.Emit (OpCodes.Ldloc, counter);
4518 ArrayAccess.EmitLoadOpcode (ig, var_type);
4520 variable.EmitAssign (ec, conv);
4522 statement.Emit (ec);
4524 ig.MarkLabel (ec.LoopBegin);
4525 ig.Emit (OpCodes.Ldloc, counter);
4526 ig.Emit (OpCodes.Ldc_I4_1);
4527 ig.Emit (OpCodes.Add);
4528 ig.Emit (OpCodes.Stloc, counter);
4530 ig.MarkLabel (test);
4531 ig.Emit (OpCodes.Ldloc, counter);
4532 ig.Emit (OpCodes.Ldloc, copy);
4533 ig.Emit (OpCodes.Ldlen);
4534 ig.Emit (OpCodes.Conv_I4);
4535 ig.Emit (OpCodes.Blt, loop);
4537 LocalBuilder [] dim_len = new LocalBuilder [rank];
4538 LocalBuilder [] dim_count = new LocalBuilder [rank];
4539 Label [] loop = new Label [rank];
4540 Label [] test = new Label [rank];
4543 for (dim = 0; dim < rank; dim++){
4544 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
4545 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
4546 test [dim] = ig.DefineLabel ();
4547 loop [dim] = ig.DefineLabel ();
4550 for (dim = 0; dim < rank; dim++){
4551 ig.Emit (OpCodes.Ldloc, copy);
4552 IntLiteral.EmitInt (ig, dim);
4553 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4554 ig.Emit (OpCodes.Stloc, dim_len [dim]);
4557 for (dim = 0; dim < rank; dim++){
4558 ig.Emit (OpCodes.Ldc_I4_0);
4559 ig.Emit (OpCodes.Stloc, dim_count [dim]);
4560 ig.Emit (OpCodes.Br, test [dim]);
4561 ig.MarkLabel (loop [dim]);
4564 ig.Emit (OpCodes.Ldloc, copy);
4565 for (dim = 0; dim < rank; dim++)
4566 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4569 // FIXME: Maybe we can cache the computation of `get'?
4571 Type [] args = new Type [rank];
4574 for (int i = 0; i < rank; i++)
4575 args [i] = TypeManager.int32_type;
4577 ModuleBuilder mb = CodeGen.ModuleBuilder;
4578 get = mb.GetArrayMethod (
4580 CallingConventions.HasThis| CallingConventions.Standard,
4582 ig.Emit (OpCodes.Call, get);
4583 variable.EmitAssign (ec, conv);
4584 statement.Emit (ec);
4585 ig.MarkLabel (ec.LoopBegin);
4586 for (dim = rank - 1; dim >= 0; dim--){
4587 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4588 ig.Emit (OpCodes.Ldc_I4_1);
4589 ig.Emit (OpCodes.Add);
4590 ig.Emit (OpCodes.Stloc, dim_count [dim]);
4592 ig.MarkLabel (test [dim]);
4593 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4594 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
4595 ig.Emit (OpCodes.Blt, loop [dim]);
4598 ig.MarkLabel (ec.LoopEnd);
4603 public override bool Emit (EmitContext ec)
4607 ILGenerator ig = ec.ig;
4609 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4610 bool old_inloop = ec.InLoop;
4611 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4612 ec.LoopBegin = ig.DefineLabel ();
4613 ec.LoopEnd = ig.DefineLabel ();
4615 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4618 ret_val = EmitCollectionForeach (ec);
4620 ret_val = EmitArrayForeach (ec);
4622 ec.LoopBegin = old_begin;
4623 ec.LoopEnd = old_end;
4624 ec.InLoop = old_inloop;
4625 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;