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", loc);
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", loc);
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;
232 bool infinite, may_return;
234 public Do (Statement statement, Expression boolExpr, Location l)
237 EmbeddedStatement = statement;
241 public override bool Resolve (EmitContext ec)
245 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
247 if (!EmbeddedStatement.Resolve (ec))
250 expr = ResolveBoolean (ec, expr, loc);
253 else if (expr is BoolConstant){
254 bool res = ((BoolConstant) expr).Value;
260 ec.CurrentBranching.Infinite = infinite;
261 FlowReturns returns = ec.EndFlowBranching ();
262 may_return = returns != FlowReturns.NEVER;
267 public override bool Emit (EmitContext ec)
269 ILGenerator ig = ec.ig;
270 Label loop = ig.DefineLabel ();
271 Label old_begin = ec.LoopBegin;
272 Label old_end = ec.LoopEnd;
273 bool old_inloop = ec.InLoop;
274 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
276 ec.LoopBegin = ig.DefineLabel ();
277 ec.LoopEnd = ig.DefineLabel ();
279 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
282 EmbeddedStatement.Emit (ec);
283 ig.MarkLabel (ec.LoopBegin);
286 // Dead code elimination
288 if (expr is BoolConstant){
289 bool res = ((BoolConstant) expr).Value;
292 ec.ig.Emit (OpCodes.Br, loop);
294 EmitBoolExpression (ec, expr, loop, true);
296 ig.MarkLabel (ec.LoopEnd);
298 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
299 ec.LoopBegin = old_begin;
300 ec.LoopEnd = old_end;
301 ec.InLoop = old_inloop;
304 return may_return == false;
310 public class While : Statement {
311 public Expression expr;
312 public readonly Statement Statement;
313 bool may_return, empty, infinite;
315 public While (Expression boolExpr, Statement statement, Location l)
317 this.expr = boolExpr;
318 Statement = statement;
322 public override bool Resolve (EmitContext ec)
326 expr = ResolveBoolean (ec, expr, loc);
330 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
333 // Inform whether we are infinite or not
335 if (expr is BoolConstant){
336 BoolConstant bc = (BoolConstant) expr;
338 if (bc.Value == false){
339 Warning_DeadCodeFound (Statement.loc);
345 // We are not infinite, so the loop may or may not be executed.
347 ec.CurrentBranching.CreateSibling ();
350 if (!Statement.Resolve (ec))
354 ec.KillFlowBranching ();
356 ec.CurrentBranching.Infinite = infinite;
357 FlowReturns returns = ec.EndFlowBranching ();
358 may_return = returns != FlowReturns.NEVER;
364 public override bool Emit (EmitContext ec)
369 ILGenerator ig = ec.ig;
370 Label old_begin = ec.LoopBegin;
371 Label old_end = ec.LoopEnd;
372 bool old_inloop = ec.InLoop;
373 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
376 ec.LoopBegin = ig.DefineLabel ();
377 ec.LoopEnd = ig.DefineLabel ();
379 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
382 // Inform whether we are infinite or not
384 if (expr is BoolConstant){
385 BoolConstant bc = (BoolConstant) expr;
387 ig.MarkLabel (ec.LoopBegin);
389 ig.Emit (OpCodes.Br, ec.LoopBegin);
392 // Inform that we are infinite (ie, `we return'), only
393 // if we do not `break' inside the code.
395 ret = may_return == false;
396 ig.MarkLabel (ec.LoopEnd);
398 Label while_loop = ig.DefineLabel ();
400 ig.Emit (OpCodes.Br, ec.LoopBegin);
401 ig.MarkLabel (while_loop);
405 ig.MarkLabel (ec.LoopBegin);
407 EmitBoolExpression (ec, expr, while_loop, true);
408 ig.MarkLabel (ec.LoopEnd);
413 ec.LoopBegin = old_begin;
414 ec.LoopEnd = old_end;
415 ec.InLoop = old_inloop;
416 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
422 public class For : Statement {
424 readonly Statement InitStatement;
425 readonly Statement Increment;
426 readonly Statement Statement;
427 bool may_return, infinite, empty;
429 public For (Statement initStatement,
435 InitStatement = initStatement;
437 Increment = increment;
438 Statement = statement;
442 public override bool Resolve (EmitContext ec)
446 if (InitStatement != null){
447 if (!InitStatement.Resolve (ec))
452 Test = ResolveBoolean (ec, Test, loc);
455 else if (Test is BoolConstant){
456 BoolConstant bc = (BoolConstant) Test;
458 if (bc.Value == false){
459 Warning_DeadCodeFound (Statement.loc);
467 if (Increment != null){
468 if (!Increment.Resolve (ec))
472 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
474 ec.CurrentBranching.CreateSibling ();
476 if (!Statement.Resolve (ec))
480 ec.KillFlowBranching ();
482 ec.CurrentBranching.Infinite = infinite;
483 FlowReturns returns = ec.EndFlowBranching ();
484 may_return = returns != FlowReturns.NEVER;
490 public override bool Emit (EmitContext ec)
495 ILGenerator ig = ec.ig;
496 Label old_begin = ec.LoopBegin;
497 Label old_end = ec.LoopEnd;
498 bool old_inloop = ec.InLoop;
499 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
500 Label loop = ig.DefineLabel ();
501 Label test = ig.DefineLabel ();
503 if (InitStatement != null)
504 if (! (InitStatement is EmptyStatement))
505 InitStatement.Emit (ec);
507 ec.LoopBegin = ig.DefineLabel ();
508 ec.LoopEnd = ig.DefineLabel ();
510 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
512 ig.Emit (OpCodes.Br, test);
516 ig.MarkLabel (ec.LoopBegin);
517 if (!(Increment is EmptyStatement))
522 // If test is null, there is no test, and we are just
526 EmitBoolExpression (ec, Test, loop, true);
528 ig.Emit (OpCodes.Br, loop);
529 ig.MarkLabel (ec.LoopEnd);
531 ec.LoopBegin = old_begin;
532 ec.LoopEnd = old_end;
533 ec.InLoop = old_inloop;
534 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
537 // Inform whether we are infinite or not
540 if (Test is BoolConstant){
541 BoolConstant bc = (BoolConstant) Test;
544 return may_return == false;
548 return may_return == false;
552 public class StatementExpression : Statement {
555 public StatementExpression (ExpressionStatement expr, Location l)
561 public override bool Resolve (EmitContext ec)
563 expr = (Expression) expr.Resolve (ec);
567 public override bool Emit (EmitContext ec)
569 ILGenerator ig = ec.ig;
571 if (expr is ExpressionStatement)
572 ((ExpressionStatement) expr).EmitStatement (ec);
575 ig.Emit (OpCodes.Pop);
581 public override string ToString ()
583 return "StatementExpression (" + expr + ")";
588 /// Implements the return statement
590 public class Return : Statement {
591 public Expression Expr;
593 public Return (Expression expr, Location l)
599 public override bool Resolve (EmitContext ec)
602 Expr = Expr.Resolve (ec);
607 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
609 if (ec.CurrentBranching.InTryBlock ())
610 ec.CurrentBranching.AddFinallyVector (vector);
612 vector.CheckOutParameters (ec.CurrentBranching);
614 vector.Returns = FlowReturns.ALWAYS;
615 vector.Breaks = FlowReturns.ALWAYS;
619 public override bool Emit (EmitContext ec)
622 Report.Error (157,loc,"Control can not leave the body of the finally block");
626 if (ec.ReturnType == null){
628 Report.Error (127, loc, "Return with a value not allowed here");
633 Report.Error (126, loc, "An object of type `" +
634 TypeManager.CSharpName (ec.ReturnType) + "' is " +
635 "expected for the return statement");
639 if (Expr.Type != ec.ReturnType)
640 Expr = Expression.ConvertImplicitRequired (
641 ec, Expr, ec.ReturnType, loc);
648 if (ec.InTry || ec.InCatch)
649 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
652 if (ec.InTry || ec.InCatch) {
653 if (!ec.HasReturnLabel) {
654 ec.ReturnLabel = ec.ig.DefineLabel ();
655 ec.HasReturnLabel = true;
657 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
659 ec.ig.Emit (OpCodes.Ret);
665 public class Goto : Statement {
668 LabeledStatement label;
670 public override bool Resolve (EmitContext ec)
672 label = block.LookupLabel (target);
676 "No such label `" + target + "' in this scope");
680 // If this is a forward goto.
681 if (!label.IsDefined)
682 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
684 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
689 public Goto (Block parent_block, string label, Location l)
691 block = parent_block;
696 public string Target {
702 public override bool Emit (EmitContext ec)
704 Label l = label.LabelTarget (ec);
705 ec.ig.Emit (OpCodes.Br, l);
711 public class LabeledStatement : Statement {
712 public readonly Location Location;
720 public LabeledStatement (string label_name, Location l)
722 this.label_name = label_name;
726 public Label LabelTarget (EmitContext ec)
730 label = ec.ig.DefineLabel ();
736 public bool IsDefined {
742 public bool HasBeenReferenced {
748 public void AddUsageVector (FlowBranching.UsageVector vector)
751 vectors = new ArrayList ();
753 vectors.Add (vector.Clone ());
756 public override bool Resolve (EmitContext ec)
759 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
761 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
762 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
770 public override bool Emit (EmitContext ec)
773 ec.ig.MarkLabel (label);
781 /// `goto default' statement
783 public class GotoDefault : Statement {
785 public GotoDefault (Location l)
790 public override bool Resolve (EmitContext ec)
792 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
796 public override bool Emit (EmitContext ec)
798 if (ec.Switch == null){
799 Report.Error (153, loc, "goto default is only valid in a switch statement");
803 if (!ec.Switch.GotDefault){
804 Report.Error (159, loc, "No default target on switch statement");
807 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
813 /// `goto case' statement
815 public class GotoCase : Statement {
819 public GotoCase (Expression e, Location l)
825 public override bool Resolve (EmitContext ec)
827 if (ec.Switch == null){
828 Report.Error (153, loc, "goto case is only valid in a switch statement");
832 expr = expr.Resolve (ec);
836 if (!(expr is Constant)){
837 Report.Error (159, loc, "Target expression for goto case is not constant");
841 object val = Expression.ConvertIntLiteral (
842 (Constant) expr, ec.Switch.SwitchType, loc);
847 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
852 "No such label 'case " + val + "': for the goto case");
855 label = sl.ILLabelCode;
857 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
861 public override bool Emit (EmitContext ec)
863 ec.ig.Emit (OpCodes.Br, label);
868 public class Throw : Statement {
871 public Throw (Expression expr, Location l)
877 public override bool Resolve (EmitContext ec)
880 expr = expr.Resolve (ec);
884 ExprClass eclass = expr.eclass;
886 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
887 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
888 expr.Error118 ("value, variable, property or indexer access ");
894 if ((t != TypeManager.exception_type) &&
895 !t.IsSubclassOf (TypeManager.exception_type) &&
896 !(expr is NullLiteral)) {
897 Report.Error (155, loc,
898 "The type caught or thrown must be derived " +
899 "from System.Exception");
904 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
905 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
909 public override bool Emit (EmitContext ec)
913 ec.ig.Emit (OpCodes.Rethrow);
917 "A throw statement with no argument is only " +
918 "allowed in a catch clause");
925 ec.ig.Emit (OpCodes.Throw);
931 public class Break : Statement {
933 public Break (Location l)
938 public override bool Resolve (EmitContext ec)
940 ec.CurrentBranching.MayLeaveLoop = true;
941 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
945 public override bool Emit (EmitContext ec)
947 ILGenerator ig = ec.ig;
949 if (ec.InLoop == false && ec.Switch == null){
950 Report.Error (139, loc, "No enclosing loop or switch to continue to");
954 if (ec.InTry || ec.InCatch)
955 ig.Emit (OpCodes.Leave, ec.LoopEnd);
957 ig.Emit (OpCodes.Br, ec.LoopEnd);
963 public class Continue : Statement {
965 public Continue (Location l)
970 public override bool Resolve (EmitContext ec)
972 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
976 public override bool Emit (EmitContext ec)
978 Label begin = ec.LoopBegin;
981 Report.Error (139, loc, "No enclosing loop to continue to");
986 // UGH: Non trivial. This Br might cross a try/catch boundary
990 // try { ... } catch { continue; }
994 // try {} catch { while () { continue; }}
996 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
997 ec.ig.Emit (OpCodes.Leave, begin);
998 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
999 throw new Exception ("Should never happen");
1001 ec.ig.Emit (OpCodes.Br, begin);
1007 // This is used in the control flow analysis code to specify whether the
1008 // current code block may return to its enclosing block before reaching
1011 public enum FlowReturns {
1012 // It can never return.
1015 // This means that the block contains a conditional return statement
1019 // The code always returns, ie. there's an unconditional return / break
1023 // The code always throws an exception.
1026 // The current code block is unreachable. This happens if it's immediately
1027 // following a FlowReturns.ALWAYS block.
1032 // This is a special bit vector which can inherit from another bit vector doing a
1033 // copy-on-write strategy. The inherited vector may have a smaller size than the
1036 public class MyBitVector {
1037 public readonly int Count;
1038 public readonly MyBitVector InheritsFrom;
1043 public MyBitVector (int Count)
1044 : this (null, Count)
1047 public MyBitVector (MyBitVector InheritsFrom, int Count)
1049 this.InheritsFrom = InheritsFrom;
1054 // Checks whether this bit vector has been modified. After setting this to true,
1055 // we won't use the inherited vector anymore, but our own copy of it.
1057 public bool IsDirty {
1064 initialize_vector ();
1069 // Get/set bit `index' in the bit vector.
1071 public bool this [int index]
1075 throw new ArgumentOutOfRangeException ();
1077 // We're doing a "copy-on-write" strategy here; as long
1078 // as nobody writes to the array, we can use our parent's
1079 // copy instead of duplicating the vector.
1082 return vector [index];
1083 else if (InheritsFrom != null) {
1084 BitArray inherited = InheritsFrom.Vector;
1086 if (index < inherited.Count)
1087 return inherited [index];
1096 throw new ArgumentOutOfRangeException ();
1098 // Only copy the vector if we're actually modifying it.
1100 if (this [index] != value) {
1101 initialize_vector ();
1103 vector [index] = value;
1109 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1110 // copy of the bit vector.
1112 public static explicit operator BitArray (MyBitVector vector)
1114 vector.initialize_vector ();
1115 return vector.Vector;
1119 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1120 // different size than the current one.
1122 public void Or (MyBitVector new_vector)
1124 BitArray new_array = new_vector.Vector;
1126 initialize_vector ();
1129 if (vector.Count < new_array.Count)
1130 upper = vector.Count;
1132 upper = new_array.Count;
1134 for (int i = 0; i < upper; i++)
1135 vector [i] = vector [i] | new_array [i];
1139 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1140 // a different size than the current one.
1142 public void And (MyBitVector new_vector)
1144 BitArray new_array = new_vector.Vector;
1146 initialize_vector ();
1149 if (vector.Count < new_array.Count)
1150 lower = upper = vector.Count;
1152 lower = new_array.Count;
1153 upper = vector.Count;
1156 for (int i = 0; i < lower; i++)
1157 vector [i] = vector [i] & new_array [i];
1159 for (int i = lower; i < upper; i++)
1164 // This does a deep copy of the bit vector.
1166 public MyBitVector Clone ()
1168 MyBitVector retval = new MyBitVector (Count);
1170 retval.Vector = Vector;
1179 else if (!is_dirty && (InheritsFrom != null))
1180 return InheritsFrom.Vector;
1182 initialize_vector ();
1188 initialize_vector ();
1190 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1191 vector [i] = value [i];
1195 void initialize_vector ()
1200 vector = new BitArray (Count, false);
1201 if (InheritsFrom != null)
1202 Vector = InheritsFrom.Vector;
1207 public override string ToString ()
1209 StringBuilder sb = new StringBuilder ("MyBitVector (");
1211 BitArray vector = Vector;
1215 sb.Append ("INHERITED - ");
1216 for (int i = 0; i < vector.Count; i++) {
1219 sb.Append (vector [i]);
1223 return sb.ToString ();
1228 // The type of a FlowBranching.
1230 public enum FlowBranchingType {
1231 // Normal (conditional or toplevel) block.
1248 // A new instance of this class is created every time a new block is resolved
1249 // and if there's branching in the block's control flow.
1251 public class FlowBranching {
1253 // The type of this flow branching.
1255 public readonly FlowBranchingType Type;
1258 // The block this branching is contained in. This may be null if it's not
1259 // a top-level block and it doesn't declare any local variables.
1261 public readonly Block Block;
1264 // The parent of this branching or null if this is the top-block.
1266 public readonly FlowBranching Parent;
1269 // Start-Location of this flow branching.
1271 public readonly Location Location;
1274 // A list of UsageVectors. A new vector is added each time control flow may
1275 // take a different path.
1277 public ArrayList Siblings;
1280 // If this is an infinite loop.
1282 public bool Infinite;
1285 // If we may leave the current loop.
1287 public bool MayLeaveLoop;
1292 InternalParameters param_info;
1294 MyStructInfo[] struct_params;
1296 ArrayList finally_vectors;
1298 static int next_id = 0;
1302 // Performs an `And' operation on the FlowReturns status
1303 // (for instance, a block only returns ALWAYS if all its siblings
1306 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1308 if (b == FlowReturns.UNREACHABLE)
1312 case FlowReturns.NEVER:
1313 if (b == FlowReturns.NEVER)
1314 return FlowReturns.NEVER;
1316 return FlowReturns.SOMETIMES;
1318 case FlowReturns.SOMETIMES:
1319 return FlowReturns.SOMETIMES;
1321 case FlowReturns.ALWAYS:
1322 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1323 return FlowReturns.ALWAYS;
1325 return FlowReturns.SOMETIMES;
1327 case FlowReturns.EXCEPTION:
1328 if (b == FlowReturns.EXCEPTION)
1329 return FlowReturns.EXCEPTION;
1330 else if (b == FlowReturns.ALWAYS)
1331 return FlowReturns.ALWAYS;
1333 return FlowReturns.SOMETIMES;
1340 // The vector contains a BitArray with information about which local variables
1341 // and parameters are already initialized at the current code position.
1343 public class UsageVector {
1345 // If this is true, then the usage vector has been modified and must be
1346 // merged when we're done with this branching.
1348 public bool IsDirty;
1351 // The number of parameters in this block.
1353 public readonly int CountParameters;
1356 // The number of locals in this block.
1358 public readonly int CountLocals;
1361 // If not null, then we inherit our state from this vector and do a
1362 // copy-on-write. If null, then we're the first sibling in a top-level
1363 // block and inherit from the empty vector.
1365 public readonly UsageVector InheritsFrom;
1370 MyBitVector locals, parameters;
1371 FlowReturns real_returns, real_breaks;
1374 static int next_id = 0;
1378 // Normally, you should not use any of these constructors.
1380 public UsageVector (UsageVector parent, int num_params, int num_locals)
1382 this.InheritsFrom = parent;
1383 this.CountParameters = num_params;
1384 this.CountLocals = num_locals;
1385 this.real_returns = FlowReturns.NEVER;
1386 this.real_breaks = FlowReturns.NEVER;
1388 if (parent != null) {
1389 locals = new MyBitVector (parent.locals, CountLocals);
1391 parameters = new MyBitVector (parent.parameters, num_params);
1392 real_returns = parent.Returns;
1393 real_breaks = parent.Breaks;
1395 locals = new MyBitVector (null, CountLocals);
1397 parameters = new MyBitVector (null, num_params);
1403 public UsageVector (UsageVector parent)
1404 : this (parent, parent.CountParameters, parent.CountLocals)
1408 // This does a deep copy of the usage vector.
1410 public UsageVector Clone ()
1412 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1414 retval.locals = locals.Clone ();
1415 if (parameters != null)
1416 retval.parameters = parameters.Clone ();
1417 retval.real_returns = real_returns;
1418 retval.real_breaks = real_breaks;
1424 // State of parameter `number'.
1426 public bool this [int number]
1431 else if (number == 0)
1432 throw new ArgumentException ();
1434 return parameters [number - 1];
1440 else if (number == 0)
1441 throw new ArgumentException ();
1443 parameters [number - 1] = value;
1448 // State of the local variable `vi'.
1449 // If the local variable is a struct, use a non-zero `field_idx'
1450 // to check an individual field in it.
1452 public bool this [VariableInfo vi, int field_idx]
1455 if (vi.Number == -1)
1457 else if (vi.Number == 0)
1458 throw new ArgumentException ();
1460 return locals [vi.Number + field_idx - 1];
1464 if (vi.Number == -1)
1466 else if (vi.Number == 0)
1467 throw new ArgumentException ();
1469 locals [vi.Number + field_idx - 1] = value;
1474 // Specifies when the current block returns.
1475 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1476 // end of the method (so that we don't need to emit a return statement).
1477 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1478 // value will never be used.
1480 public FlowReturns Returns {
1482 return real_returns;
1486 real_returns = value;
1491 // Specifies whether control may return to our containing block
1492 // before reaching the end of this block. This happens if there
1493 // is a break/continue/goto/return in it.
1494 // This can also be used to find out whether the statement immediately
1495 // following the current block may be reached or not.
1497 public FlowReturns Breaks {
1503 real_breaks = value;
1507 public bool AlwaysBreaks {
1509 return (Breaks == FlowReturns.ALWAYS) ||
1510 (Breaks == FlowReturns.EXCEPTION) ||
1511 (Breaks == FlowReturns.UNREACHABLE);
1515 public bool MayBreak {
1517 return Breaks != FlowReturns.NEVER;
1521 public bool AlwaysReturns {
1523 return (Returns == FlowReturns.ALWAYS) ||
1524 (Returns == FlowReturns.EXCEPTION);
1528 public bool MayReturn {
1530 return (Returns == FlowReturns.SOMETIMES) ||
1531 (Returns == FlowReturns.ALWAYS);
1536 // Merge a child branching.
1538 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1540 MyBitVector new_locals = null;
1541 MyBitVector new_params = null;
1543 FlowReturns new_returns = FlowReturns.NEVER;
1544 FlowReturns new_breaks = FlowReturns.NEVER;
1545 bool new_returns_set = false, new_breaks_set = false;
1547 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1548 this, children.Count);
1550 foreach (UsageVector child in children) {
1551 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1553 if (!child.is_finally) {
1554 if (child.Breaks != FlowReturns.UNREACHABLE) {
1555 // If Returns is already set, perform an
1556 // `And' operation on it, otherwise just set just.
1557 if (!new_returns_set) {
1558 new_returns = child.Returns;
1559 new_returns_set = true;
1561 new_returns = AndFlowReturns (
1562 new_returns, child.Returns);
1565 // If Breaks is already set, perform an
1566 // `And' operation on it, otherwise just set just.
1567 if (!new_breaks_set) {
1568 new_breaks = child.Breaks;
1569 new_breaks_set = true;
1571 new_breaks = AndFlowReturns (
1572 new_breaks, child.Breaks);
1575 // Ignore unreachable children.
1576 if (child.Returns == FlowReturns.UNREACHABLE)
1579 // A local variable is initialized after a flow branching if it
1580 // has been initialized in all its branches which do neither
1581 // always return or always throw an exception.
1583 // If a branch may return, but does not always return, then we
1584 // can treat it like a never-returning branch here: control will
1585 // only reach the code position after the branching if we did not
1588 // It's important to distinguish between always and sometimes
1589 // returning branches here:
1592 // 2 if (something) {
1596 // 6 Console.WriteLine (a);
1598 // The if block in lines 3-4 always returns, so we must not look
1599 // at the initialization of `a' in line 4 - thus it'll still be
1600 // uninitialized in line 6.
1602 // On the other hand, the following is allowed:
1609 // 6 Console.WriteLine (a);
1611 // Here, `a' is initialized in line 3 and we must not look at
1612 // line 5 since it always returns.
1614 if (child.is_finally) {
1615 if (new_locals == null)
1616 new_locals = locals.Clone ();
1617 new_locals.Or (child.locals);
1619 if (parameters != null) {
1620 if (new_params == null)
1621 new_params = parameters.Clone ();
1622 new_params.Or (child.parameters);
1626 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1627 if (new_locals != null)
1628 new_locals.And (child.locals);
1630 new_locals = locals.Clone ();
1631 new_locals.Or (child.locals);
1633 } else if (children.Count == 1) {
1634 new_locals = locals.Clone ();
1635 new_locals.Or (child.locals);
1638 // An `out' parameter must be assigned in all branches which do
1639 // not always throw an exception.
1640 if (parameters != null) {
1641 if (child.Breaks != FlowReturns.EXCEPTION) {
1642 if (new_params != null)
1643 new_params.And (child.parameters);
1645 new_params = parameters.Clone ();
1646 new_params.Or (child.parameters);
1648 } else if (children.Count == 1) {
1649 new_params = parameters.Clone ();
1650 new_params.Or (child.parameters);
1656 Returns = new_returns;
1657 if ((branching.Type == FlowBranchingType.BLOCK) ||
1658 (branching.Type == FlowBranchingType.EXCEPTION) ||
1659 (new_breaks == FlowReturns.UNREACHABLE) ||
1660 (new_breaks == FlowReturns.EXCEPTION))
1661 Breaks = new_breaks;
1662 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1663 Breaks = new_returns;
1666 // We've now either reached the point after the branching or we will
1667 // never get there since we always return or always throw an exception.
1669 // If we can reach the point after the branching, mark all locals and
1670 // parameters as initialized which have been initialized in all branches
1671 // we need to look at (see above).
1674 if (((new_breaks != FlowReturns.ALWAYS) &&
1675 (new_breaks != FlowReturns.EXCEPTION) &&
1676 (new_breaks != FlowReturns.UNREACHABLE)) ||
1677 (children.Count == 1)) {
1678 if (new_locals != null)
1679 locals.Or (new_locals);
1681 if (new_params != null)
1682 parameters.Or (new_params);
1685 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1686 new_params, new_locals, new_returns, new_breaks,
1687 branching.Infinite, branching.MayLeaveLoop, this);
1689 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1690 if ((new_breaks != FlowReturns.ALWAYS) &&
1691 (new_breaks != FlowReturns.EXCEPTION) &&
1692 (new_breaks != FlowReturns.UNREACHABLE))
1693 Report.Error (163, branching.Location,
1694 "Control cannot fall through from one " +
1695 "case label to another");
1698 if (branching.Infinite && !branching.MayLeaveLoop) {
1699 Report.Debug (1, "INFINITE", new_returns, new_breaks,
1700 Returns, Breaks, this);
1702 // We're actually infinite.
1703 if (new_returns == FlowReturns.NEVER) {
1704 Breaks = FlowReturns.UNREACHABLE;
1705 return FlowReturns.UNREACHABLE;
1708 // If we're an infinite loop and do not break, the code after
1709 // the loop can never be reached. However, if we may return
1710 // from the loop, then we do always return (or stay in the loop
1712 if ((new_returns == FlowReturns.SOMETIMES) ||
1713 (new_returns == FlowReturns.ALWAYS)) {
1714 Returns = FlowReturns.ALWAYS;
1715 return FlowReturns.ALWAYS;
1723 // Tells control flow analysis that the current code position may be reached with
1724 // a forward jump from any of the origins listed in `origin_vectors' which is a
1725 // list of UsageVectors.
1727 // This is used when resolving forward gotos - in the following example, the
1728 // variable `a' is uninitialized in line 8 becase this line may be reached via
1729 // the goto in line 4:
1739 // 8 Console.WriteLine (a);
1742 public void MergeJumpOrigins (ICollection origin_vectors)
1744 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1746 real_breaks = FlowReturns.NEVER;
1747 real_returns = FlowReturns.NEVER;
1749 foreach (UsageVector vector in origin_vectors) {
1750 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1752 locals.And (vector.locals);
1753 if (parameters != null)
1754 parameters.And (vector.parameters);
1755 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1756 Returns = AndFlowReturns (Returns, vector.Returns);
1759 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1763 // This is used at the beginning of a finally block if there were
1764 // any return statements in the try block or one of the catch blocks.
1766 public void MergeFinallyOrigins (ICollection finally_vectors)
1768 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1770 real_breaks = FlowReturns.NEVER;
1772 foreach (UsageVector vector in finally_vectors) {
1773 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1775 if (parameters != null)
1776 parameters.And (vector.parameters);
1777 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1782 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1785 public void CheckOutParameters (FlowBranching branching)
1787 if (parameters != null)
1788 branching.CheckOutParameters (parameters, branching.Location);
1792 // Performs an `or' operation on the locals and the parameters.
1794 public void Or (UsageVector new_vector)
1796 locals.Or (new_vector.locals);
1797 if (parameters != null)
1798 parameters.Or (new_vector.parameters);
1802 // Performs an `and' operation on the locals.
1804 public void AndLocals (UsageVector new_vector)
1806 locals.And (new_vector.locals);
1810 // Returns a deep copy of the parameters.
1812 public MyBitVector Parameters {
1814 if (parameters != null)
1815 return parameters.Clone ();
1822 // Returns a deep copy of the locals.
1824 public MyBitVector Locals {
1826 return locals.Clone ();
1834 public override string ToString ()
1836 StringBuilder sb = new StringBuilder ();
1838 sb.Append ("Vector (");
1841 sb.Append (Returns);
1844 if (parameters != null) {
1846 sb.Append (parameters);
1852 return sb.ToString ();
1856 FlowBranching (FlowBranchingType type, Location loc)
1858 this.Siblings = new ArrayList ();
1860 this.Location = loc;
1866 // Creates a new flow branching for `block'.
1867 // This is used from Block.Resolve to create the top-level branching of
1870 public FlowBranching (Block block, InternalParameters ip, Location loc)
1871 : this (FlowBranchingType.BLOCK, loc)
1876 int count = (ip != null) ? ip.Count : 0;
1879 param_map = new int [count];
1880 struct_params = new MyStructInfo [count];
1883 for (int i = 0; i < count; i++) {
1884 Parameter.Modifier mod = param_info.ParameterModifier (i);
1886 if ((mod & Parameter.Modifier.OUT) == 0)
1889 param_map [i] = ++num_params;
1891 Type param_type = param_info.ParameterType (i);
1893 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1894 if (struct_params [i] != null)
1895 num_params += struct_params [i].Count;
1898 Siblings = new ArrayList ();
1899 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1903 // Creates a new flow branching which is contained in `parent'.
1904 // You should only pass non-null for the `block' argument if this block
1905 // introduces any new variables - in this case, we need to create a new
1906 // usage vector with a different size than our parent's one.
1908 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1909 Block block, Location loc)
1915 if (parent != null) {
1916 param_info = parent.param_info;
1917 param_map = parent.param_map;
1918 struct_params = parent.struct_params;
1919 num_params = parent.num_params;
1924 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1925 Block.CountVariables);
1927 vector = new UsageVector (Parent.CurrentUsageVector);
1929 Siblings.Add (vector);
1932 case FlowBranchingType.EXCEPTION:
1933 finally_vectors = new ArrayList ();
1942 // Returns the branching's current usage vector.
1944 public UsageVector CurrentUsageVector
1947 return (UsageVector) Siblings [Siblings.Count - 1];
1952 // Creates a sibling of the current usage vector.
1954 public void CreateSibling ()
1956 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1958 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1962 // Creates a sibling for a `finally' block.
1964 public void CreateSiblingForFinally ()
1966 if (Type != FlowBranchingType.EXCEPTION)
1967 throw new NotSupportedException ();
1971 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1975 // Check whether all `out' parameters have been assigned.
1977 public void CheckOutParameters (MyBitVector parameters, Location loc)
1982 for (int i = 0; i < param_map.Length; i++) {
1983 int index = param_map [i];
1988 if (parameters [index - 1])
1991 // If it's a struct, we must ensure that all its fields have
1992 // been assigned. If the struct has any non-public fields, this
1993 // can only be done by assigning the whole struct.
1995 MyStructInfo struct_info = struct_params [index - 1];
1996 if ((struct_info == null) || struct_info.HasNonPublicFields) {
1998 177, loc, "The out parameter `" +
1999 param_info.ParameterName (i) + "' must be " +
2000 "assigned before control leave the current method.");
2006 for (int j = 0; j < struct_info.Count; j++) {
2007 if (!parameters [index + j]) {
2009 177, loc, "The out parameter `" +
2010 param_info.ParameterName (i) + "' must be " +
2011 "assigned before control leave the current method.");
2020 // Merge a child branching.
2022 public FlowReturns MergeChild (FlowBranching child)
2024 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2026 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2027 MayLeaveLoop |= child.MayLeaveLoop;
2029 MayLeaveLoop = false;
2035 // Does the toplevel merging.
2037 public FlowReturns MergeTopBlock ()
2039 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2040 throw new NotSupportedException ();
2042 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2044 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2046 vector.MergeChildren (this, Siblings);
2049 Siblings.Add (vector);
2051 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2053 if (vector.Breaks != FlowReturns.EXCEPTION) {
2054 if (!vector.AlwaysBreaks)
2055 CheckOutParameters (CurrentUsageVector.Parameters, Location);
2056 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2058 return FlowReturns.EXCEPTION;
2061 public bool InTryBlock ()
2063 if (finally_vectors != null)
2065 else if (Parent != null)
2066 return Parent.InTryBlock ();
2071 public void AddFinallyVector (UsageVector vector)
2073 if (finally_vectors != null) {
2074 finally_vectors.Add (vector.Clone ());
2079 Parent.AddFinallyVector (vector);
2081 throw new NotSupportedException ();
2084 public bool IsVariableAssigned (VariableInfo vi)
2086 if (CurrentUsageVector.AlwaysBreaks)
2089 return CurrentUsageVector [vi, 0];
2092 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2094 if (CurrentUsageVector.AlwaysBreaks)
2097 return CurrentUsageVector [vi, field_idx];
2100 public void SetVariableAssigned (VariableInfo vi)
2102 if (CurrentUsageVector.AlwaysBreaks)
2105 CurrentUsageVector [vi, 0] = true;
2108 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2110 if (CurrentUsageVector.AlwaysBreaks)
2113 CurrentUsageVector [vi, field_idx] = true;
2116 public bool IsParameterAssigned (int number)
2118 int index = param_map [number];
2123 if (CurrentUsageVector [index])
2126 // Parameter is not assigned, so check whether it's a struct.
2127 // If it's either not a struct or a struct which non-public
2128 // fields, return false.
2129 MyStructInfo struct_info = struct_params [number];
2130 if ((struct_info == null) || struct_info.HasNonPublicFields)
2133 // Ok, so each field must be assigned.
2134 for (int i = 0; i < struct_info.Count; i++)
2135 if (!CurrentUsageVector [index + i])
2141 public bool IsParameterAssigned (int number, string field_name)
2143 int index = param_map [number];
2148 MyStructInfo info = (MyStructInfo) struct_params [number];
2152 int field_idx = info [field_name];
2154 return CurrentUsageVector [index + field_idx];
2157 public void SetParameterAssigned (int number)
2159 if (param_map [number] == 0)
2162 if (!CurrentUsageVector.AlwaysBreaks)
2163 CurrentUsageVector [param_map [number]] = true;
2166 public void SetParameterAssigned (int number, string field_name)
2168 int index = param_map [number];
2173 MyStructInfo info = (MyStructInfo) struct_params [number];
2177 int field_idx = info [field_name];
2179 if (!CurrentUsageVector.AlwaysBreaks)
2180 CurrentUsageVector [index + field_idx] = true;
2183 public bool IsReachable ()
2188 case FlowBranchingType.SWITCH_SECTION:
2189 // The code following a switch block is reachable unless the switch
2190 // block always returns.
2191 reachable = !CurrentUsageVector.AlwaysReturns;
2194 case FlowBranchingType.LOOP_BLOCK:
2195 // The code following a loop is reachable unless the loop always
2196 // returns or it's an infinite loop without any `break's in it.
2197 reachable = !CurrentUsageVector.AlwaysReturns &&
2198 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2202 // The code following a block or exception is reachable unless the
2203 // block either always returns or always breaks.
2204 reachable = !CurrentUsageVector.AlwaysBreaks &&
2205 !CurrentUsageVector.AlwaysReturns;
2209 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2210 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2215 public override string ToString ()
2217 StringBuilder sb = new StringBuilder ("FlowBranching (");
2222 if (Block != null) {
2224 sb.Append (Block.ID);
2226 sb.Append (Block.StartLocation);
2229 sb.Append (Siblings.Count);
2231 sb.Append (CurrentUsageVector);
2233 return sb.ToString ();
2237 public class MyStructInfo {
2238 public readonly Type Type;
2239 public readonly FieldInfo[] Fields;
2240 public readonly FieldInfo[] NonPublicFields;
2241 public readonly int Count;
2242 public readonly int CountNonPublic;
2243 public readonly bool HasNonPublicFields;
2245 private static Hashtable field_type_hash = new Hashtable ();
2246 private Hashtable field_hash;
2248 // Private constructor. To save memory usage, we only need to create one instance
2249 // of this class per struct type.
2250 private MyStructInfo (Type type)
2254 if (type is TypeBuilder) {
2255 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2257 ArrayList fields = tc.Fields;
2258 if (fields != null) {
2259 foreach (Field field in fields) {
2260 if ((field.ModFlags & Modifiers.STATIC) != 0)
2262 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2269 Fields = new FieldInfo [Count];
2270 NonPublicFields = new FieldInfo [CountNonPublic];
2272 Count = CountNonPublic = 0;
2273 if (fields != null) {
2274 foreach (Field field in fields) {
2275 if ((field.ModFlags & Modifiers.STATIC) != 0)
2277 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2278 Fields [Count++] = field.FieldBuilder;
2280 NonPublicFields [CountNonPublic++] =
2286 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2287 Count = Fields.Length;
2289 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2290 CountNonPublic = NonPublicFields.Length;
2293 Count += NonPublicFields.Length;
2296 field_hash = new Hashtable ();
2297 foreach (FieldInfo field in Fields)
2298 field_hash.Add (field.Name, ++number);
2300 if (NonPublicFields.Length != 0)
2301 HasNonPublicFields = true;
2303 foreach (FieldInfo field in NonPublicFields)
2304 field_hash.Add (field.Name, ++number);
2307 public int this [string name] {
2309 if (field_hash.Contains (name))
2310 return (int) field_hash [name];
2316 public FieldInfo this [int index] {
2318 if (index >= Fields.Length)
2319 return NonPublicFields [index - Fields.Length];
2321 return Fields [index];
2325 public static MyStructInfo GetStructInfo (Type type)
2327 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2330 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2333 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2337 info = new MyStructInfo (type);
2338 field_type_hash.Add (type, info);
2342 public static MyStructInfo GetStructInfo (TypeContainer tc)
2344 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2348 info = new MyStructInfo (tc.TypeBuilder);
2349 field_type_hash.Add (tc.TypeBuilder, info);
2354 public class VariableInfo : IVariable {
2355 public Expression Type;
2356 public LocalBuilder LocalBuilder;
2357 public Type VariableType;
2358 public readonly string Name;
2359 public readonly Location Location;
2360 public readonly int Block;
2365 public bool Assigned;
2366 public bool ReadOnly;
2368 public VariableInfo (Expression type, string name, int block, Location l)
2373 LocalBuilder = null;
2377 public VariableInfo (TypeContainer tc, int block, Location l)
2379 VariableType = tc.TypeBuilder;
2380 struct_info = MyStructInfo.GetStructInfo (tc);
2382 LocalBuilder = null;
2386 MyStructInfo struct_info;
2387 public MyStructInfo StructInfo {
2393 public bool IsAssigned (EmitContext ec, Location loc)
2395 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2398 MyStructInfo struct_info = StructInfo;
2399 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2400 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2401 ec.CurrentBranching.SetVariableAssigned (this);
2405 int count = struct_info.Count;
2407 for (int i = 0; i < count; i++) {
2408 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2410 Report.Error (165, loc,
2411 "Use of unassigned local variable `" +
2413 ec.CurrentBranching.SetVariableAssigned (this);
2417 FieldInfo field = struct_info [i];
2418 Report.Error (171, loc,
2419 "Field `" + TypeManager.CSharpName (VariableType) +
2420 "." + field.Name + "' must be fully initialized " +
2421 "before control leaves the constructor");
2429 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2431 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2432 (struct_info == null))
2435 int field_idx = StructInfo [name];
2439 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2440 Report.Error (170, loc,
2441 "Use of possibly unassigned field `" + name + "'");
2442 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2449 public void SetAssigned (EmitContext ec)
2451 if (ec.DoFlowAnalysis)
2452 ec.CurrentBranching.SetVariableAssigned (this);
2455 public void SetFieldAssigned (EmitContext ec, string name)
2457 if (ec.DoFlowAnalysis && (struct_info != null))
2458 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2461 public bool Resolve (DeclSpace decl)
2463 if (struct_info != null)
2466 if (VariableType == null)
2467 VariableType = decl.ResolveType (Type, false, Location);
2469 if (VariableType == null)
2472 struct_info = MyStructInfo.GetStructInfo (VariableType);
2477 public void MakePinned ()
2479 TypeManager.MakePinned (LocalBuilder);
2482 public override string ToString ()
2484 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2489 /// Block represents a C# block.
2493 /// This class is used in a number of places: either to represent
2494 /// explicit blocks that the programmer places or implicit blocks.
2496 /// Implicit blocks are used as labels or to introduce variable
2499 public class Block : Statement {
2500 public readonly Block Parent;
2501 public readonly bool Implicit;
2502 public readonly Location StartLocation;
2503 public Location EndLocation;
2506 // The statements in this block
2508 ArrayList statements;
2511 // An array of Blocks. We keep track of children just
2512 // to generate the local variable declarations.
2514 // Statements and child statements are handled through the
2520 // Labels. (label, block) pairs.
2525 // Keeps track of (name, type) pairs
2527 Hashtable variables;
2530 // Keeps track of constants
2531 Hashtable constants;
2534 // Maps variable names to ILGenerator.LocalBuilders
2536 Hashtable local_builders;
2544 public Block (Block parent)
2545 : this (parent, false, Location.Null, Location.Null)
2548 public Block (Block parent, bool implicit_block)
2549 : this (parent, implicit_block, Location.Null, Location.Null)
2552 public Block (Block parent, bool implicit_block, Parameters parameters)
2553 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2556 public Block (Block parent, Location start, Location end)
2557 : this (parent, false, start, end)
2560 public Block (Block parent, Parameters parameters, Location start, Location end)
2561 : this (parent, false, parameters, start, end)
2564 public Block (Block parent, bool implicit_block, Location start, Location end)
2565 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2569 public Block (Block parent, bool implicit_block, Parameters parameters,
2570 Location start, Location end)
2573 parent.AddChild (this);
2575 this.Parent = parent;
2576 this.Implicit = implicit_block;
2577 this.parameters = parameters;
2578 this.StartLocation = start;
2579 this.EndLocation = end;
2582 statements = new ArrayList ();
2591 void AddChild (Block b)
2593 if (children == null)
2594 children = new ArrayList ();
2599 public void SetEndLocation (Location loc)
2605 /// Adds a label to the current block.
2609 /// false if the name already exists in this block. true
2613 public bool AddLabel (string name, LabeledStatement target)
2616 labels = new Hashtable ();
2617 if (labels.Contains (name))
2620 labels.Add (name, target);
2624 public LabeledStatement LookupLabel (string name)
2626 if (labels != null){
2627 if (labels.Contains (name))
2628 return ((LabeledStatement) labels [name]);
2632 return Parent.LookupLabel (name);
2637 VariableInfo this_variable = null;
2640 // Returns the "this" instance variable of this block.
2641 // See AddThisVariable() for more information.
2643 public VariableInfo ThisVariable {
2645 if (this_variable != null)
2646 return this_variable;
2647 else if (Parent != null)
2648 return Parent.ThisVariable;
2654 Hashtable child_variable_names;
2657 // Marks a variable with name @name as being used in a child block.
2658 // If a variable name has been used in a child block, it's illegal to
2659 // declare a variable with the same name in the current block.
2661 public void AddChildVariableName (string name)
2663 if (child_variable_names == null)
2664 child_variable_names = new Hashtable ();
2666 if (!child_variable_names.Contains (name))
2667 child_variable_names.Add (name, true);
2671 // Marks all variables from block @block and all its children as being
2672 // used in a child block.
2674 public void AddChildVariableNames (Block block)
2676 if (block.Variables != null) {
2677 foreach (string name in block.Variables.Keys)
2678 AddChildVariableName (name);
2681 foreach (Block child in block.children) {
2682 if (child.Variables != null) {
2683 foreach (string name in child.Variables.Keys)
2684 AddChildVariableName (name);
2690 // Checks whether a variable name has already been used in a child block.
2692 public bool IsVariableNameUsedInChildBlock (string name)
2694 if (child_variable_names == null)
2697 return child_variable_names.Contains (name);
2701 // This is used by non-static `struct' constructors which do not have an
2702 // initializer - in this case, the constructor must initialize all of the
2703 // struct's fields. To do this, we add a "this" variable and use the flow
2704 // analysis code to ensure that it's been fully initialized before control
2705 // leaves the constructor.
2707 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2709 if (this_variable != null)
2710 return this_variable;
2712 this_variable = new VariableInfo (tc, ID, l);
2714 if (variables == null)
2715 variables = new Hashtable ();
2716 variables.Add ("this", this_variable);
2718 return this_variable;
2721 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2723 if (variables == null)
2724 variables = new Hashtable ();
2726 VariableInfo vi = GetVariableInfo (name);
2729 Report.Error (136, l, "A local variable named `" + name + "' " +
2730 "cannot be declared in this scope since it would " +
2731 "give a different meaning to `" + name + "', which " +
2732 "is already used in a `parent or current' scope to " +
2733 "denote something else");
2735 Report.Error (128, l, "A local variable `" + name + "' is already " +
2736 "defined in this scope");
2740 if (IsVariableNameUsedInChildBlock (name)) {
2741 Report.Error (136, l, "A local variable named `" + name + "' " +
2742 "cannot be declared in this scope since it would " +
2743 "give a different meaning to `" + name + "', which " +
2744 "is already used in a `child' scope to denote something " +
2751 Parameter p = pars.GetParameterByName (name, out idx);
2753 Report.Error (136, l, "A local variable named `" + name + "' " +
2754 "cannot be declared in this scope since it would " +
2755 "give a different meaning to `" + name + "', which " +
2756 "is already used in a `parent or current' scope to " +
2757 "denote something else");
2762 vi = new VariableInfo (type, name, ID, l);
2764 variables.Add (name, vi);
2766 if (variables_initialized)
2767 throw new Exception ();
2769 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2773 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2775 if (AddVariable (type, name, pars, l) == null)
2778 if (constants == null)
2779 constants = new Hashtable ();
2781 constants.Add (name, value);
2785 public Hashtable Variables {
2791 public VariableInfo GetVariableInfo (string name)
2793 if (variables != null) {
2795 temp = variables [name];
2798 return (VariableInfo) temp;
2803 return Parent.GetVariableInfo (name);
2808 public Expression GetVariableType (string name)
2810 VariableInfo vi = GetVariableInfo (name);
2818 public Expression GetConstantExpression (string name)
2820 if (constants != null) {
2822 temp = constants [name];
2825 return (Expression) temp;
2829 return Parent.GetConstantExpression (name);
2835 /// True if the variable named @name has been defined
2838 public bool IsVariableDefined (string name)
2840 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2841 if (variables != null) {
2842 if (variables.Contains (name))
2847 return Parent.IsVariableDefined (name);
2853 /// True if the variable named @name is a constant
2855 public bool IsConstant (string name)
2857 Expression e = null;
2859 e = GetConstantExpression (name);
2865 /// Use to fetch the statement associated with this label
2867 public Statement this [string name] {
2869 return (Statement) labels [name];
2873 Parameters parameters = null;
2874 public Parameters Parameters {
2877 return Parent.Parameters;
2884 /// A list of labels that were not used within this block
2886 public string [] GetUnreferenced ()
2888 // FIXME: Implement me
2892 public void AddStatement (Statement s)
2909 bool variables_initialized = false;
2910 int count_variables = 0, first_variable = 0;
2912 void UpdateVariableInfo (EmitContext ec)
2914 DeclSpace ds = ec.DeclSpace;
2919 first_variable += Parent.CountVariables;
2921 count_variables = first_variable;
2922 if (variables != null) {
2923 foreach (VariableInfo vi in variables.Values) {
2924 if (!vi.Resolve (ds)) {
2929 vi.Number = ++count_variables;
2931 if (vi.StructInfo != null)
2932 count_variables += vi.StructInfo.Count;
2936 variables_initialized = true;
2941 // The number of local variables in this block
2943 public int CountVariables
2946 if (!variables_initialized)
2947 throw new Exception ();
2949 return count_variables;
2954 /// Emits the variable declarations and labels.
2957 /// tc: is our typecontainer (to resolve type references)
2958 /// ig: is the code generator:
2959 /// toplevel: the toplevel block. This is used for checking
2960 /// that no two labels with the same name are used.
2962 public void EmitMeta (EmitContext ec, Block toplevel)
2964 DeclSpace ds = ec.DeclSpace;
2965 ILGenerator ig = ec.ig;
2967 if (!variables_initialized)
2968 UpdateVariableInfo (ec);
2971 // Process this block variables
2973 if (variables != null){
2974 local_builders = new Hashtable ();
2976 foreach (DictionaryEntry de in variables){
2977 string name = (string) de.Key;
2978 VariableInfo vi = (VariableInfo) de.Value;
2980 if (vi.VariableType == null)
2983 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2985 if (CodeGen.SymbolWriter != null)
2986 vi.LocalBuilder.SetLocalSymInfo (name);
2988 if (constants == null)
2991 Expression cv = (Expression) constants [name];
2995 Expression e = cv.Resolve (ec);
2999 if (!(e is Constant)){
3000 Report.Error (133, vi.Location,
3001 "The expression being assigned to `" +
3002 name + "' must be constant (" + e + ")");
3006 constants.Remove (name);
3007 constants.Add (name, e);
3012 // Now, handle the children
3014 if (children != null){
3015 foreach (Block b in children)
3016 b.EmitMeta (ec, toplevel);
3020 public void UsageWarning ()
3024 if (variables != null){
3025 foreach (DictionaryEntry de in variables){
3026 VariableInfo vi = (VariableInfo) de.Value;
3031 name = (string) de.Key;
3035 219, vi.Location, "The variable `" + name +
3036 "' is assigned but its value is never used");
3039 168, vi.Location, "The variable `" +
3041 "' is declared but never used");
3046 if (children != null)
3047 foreach (Block b in children)
3051 bool has_ret = false;
3053 public override bool Resolve (EmitContext ec)
3055 Block prev_block = ec.CurrentBlock;
3058 ec.CurrentBlock = this;
3059 ec.StartFlowBranching (this);
3061 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3063 if (!variables_initialized)
3064 UpdateVariableInfo (ec);
3066 ArrayList new_statements = new ArrayList ();
3067 bool unreachable = false, warning_shown = false;
3069 foreach (Statement s in statements){
3070 if (unreachable && !(s is LabeledStatement)) {
3071 if (!warning_shown && !(s is EmptyStatement)) {
3072 warning_shown = true;
3073 Warning_DeadCodeFound (s.loc);
3079 if (s.Resolve (ec) == false) {
3084 if (s is LabeledStatement)
3085 unreachable = false;
3087 unreachable = ! ec.CurrentBranching.IsReachable ();
3089 new_statements.Add (s);
3092 statements = new_statements;
3094 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3096 FlowReturns returns = ec.EndFlowBranching ();
3097 ec.CurrentBlock = prev_block;
3099 // If we're a non-static `struct' constructor which doesn't have an
3100 // initializer, then we must initialize all of the struct's fields.
3101 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3102 !this_variable.IsAssigned (ec, loc))
3105 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3106 foreach (LabeledStatement label in labels.Values)
3107 if (!label.HasBeenReferenced)
3108 Report.Warning (164, label.Location,
3109 "This label has not been referenced");
3112 if ((returns == FlowReturns.ALWAYS) ||
3113 (returns == FlowReturns.EXCEPTION) ||
3114 (returns == FlowReturns.UNREACHABLE))
3120 public override bool Emit (EmitContext ec)
3122 Block prev_block = ec.CurrentBlock;
3124 ec.CurrentBlock = this;
3126 if (CodeGen.SymbolWriter != null) {
3127 ec.Mark (StartLocation);
3129 foreach (Statement s in statements) {
3134 ec.Mark (EndLocation);
3136 foreach (Statement s in statements){
3141 ec.CurrentBlock = prev_block;
3146 public class SwitchLabel {
3149 public Location loc;
3150 public Label ILLabel;
3151 public Label ILLabelCode;
3154 // if expr == null, then it is the default case.
3156 public SwitchLabel (Expression expr, Location l)
3162 public Expression Label {
3168 public object Converted {
3175 // Resolves the expression, reduces it to a literal if possible
3176 // and then converts it to the requested type.
3178 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3180 ILLabel = ec.ig.DefineLabel ();
3181 ILLabelCode = ec.ig.DefineLabel ();
3186 Expression e = label.Resolve (ec);
3191 if (!(e is Constant)){
3192 Console.WriteLine ("Value is: " + label);
3193 Report.Error (150, loc, "A constant value is expected");
3197 if (e is StringConstant || e is NullLiteral){
3198 if (required_type == TypeManager.string_type){
3200 ILLabel = ec.ig.DefineLabel ();
3205 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3206 if (converted == null)
3213 public class SwitchSection {
3214 // An array of SwitchLabels.
3215 public readonly ArrayList Labels;
3216 public readonly Block Block;
3218 public SwitchSection (ArrayList labels, Block block)
3225 public class Switch : Statement {
3226 public readonly ArrayList Sections;
3227 public Expression Expr;
3230 /// Maps constants whose type type SwitchType to their SwitchLabels.
3232 public Hashtable Elements;
3235 /// The governing switch type
3237 public Type SwitchType;
3243 Label default_target;
3244 Expression new_expr;
3247 // The types allowed to be implicitly cast from
3248 // on the governing type
3250 static Type [] allowed_types;
3252 public Switch (Expression e, ArrayList sects, Location l)
3259 public bool GotDefault {
3265 public Label DefaultTarget {
3267 return default_target;
3272 // Determines the governing type for a switch. The returned
3273 // expression might be the expression from the switch, or an
3274 // expression that includes any potential conversions to the
3275 // integral types or to string.
3277 Expression SwitchGoverningType (EmitContext ec, Type t)
3279 if (t == TypeManager.int32_type ||
3280 t == TypeManager.uint32_type ||
3281 t == TypeManager.char_type ||
3282 t == TypeManager.byte_type ||
3283 t == TypeManager.sbyte_type ||
3284 t == TypeManager.ushort_type ||
3285 t == TypeManager.short_type ||
3286 t == TypeManager.uint64_type ||
3287 t == TypeManager.int64_type ||
3288 t == TypeManager.string_type ||
3289 t == TypeManager.bool_type ||
3290 t.IsSubclassOf (TypeManager.enum_type))
3293 if (allowed_types == null){
3294 allowed_types = new Type [] {
3295 TypeManager.sbyte_type,
3296 TypeManager.byte_type,
3297 TypeManager.short_type,
3298 TypeManager.ushort_type,
3299 TypeManager.int32_type,
3300 TypeManager.uint32_type,
3301 TypeManager.int64_type,
3302 TypeManager.uint64_type,
3303 TypeManager.char_type,
3304 TypeManager.bool_type,
3305 TypeManager.string_type
3310 // Try to find a *user* defined implicit conversion.
3312 // If there is no implicit conversion, or if there are multiple
3313 // conversions, we have to report an error
3315 Expression converted = null;
3316 foreach (Type tt in allowed_types){
3319 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3323 if (converted != null){
3324 Report.Error (-12, loc, "More than one conversion to an integral " +
3325 " type exists for type `" +
3326 TypeManager.CSharpName (Expr.Type)+"'");
3334 void error152 (string n)
3337 152, "The label `" + n + ":' " +
3338 "is already present on this switch statement");
3342 // Performs the basic sanity checks on the switch statement
3343 // (looks for duplicate keys and non-constant expressions).
3345 // It also returns a hashtable with the keys that we will later
3346 // use to compute the switch tables
3348 bool CheckSwitch (EmitContext ec)
3352 Elements = new Hashtable ();
3354 got_default = false;
3356 if (TypeManager.IsEnumType (SwitchType)){
3357 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3359 compare_type = SwitchType;
3361 foreach (SwitchSection ss in Sections){
3362 foreach (SwitchLabel sl in ss.Labels){
3363 if (!sl.ResolveAndReduce (ec, SwitchType)){
3368 if (sl.Label == null){
3370 error152 ("default");
3377 object key = sl.Converted;
3379 if (key is Constant)
3380 key = ((Constant) key).GetValue ();
3383 key = NullLiteral.Null;
3385 string lname = null;
3386 if (compare_type == TypeManager.uint64_type){
3387 ulong v = (ulong) key;
3389 if (Elements.Contains (v))
3390 lname = v.ToString ();
3392 Elements.Add (v, sl);
3393 } else if (compare_type == TypeManager.int64_type){
3394 long v = (long) key;
3396 if (Elements.Contains (v))
3397 lname = v.ToString ();
3399 Elements.Add (v, sl);
3400 } else if (compare_type == TypeManager.uint32_type){
3401 uint v = (uint) key;
3403 if (Elements.Contains (v))
3404 lname = v.ToString ();
3406 Elements.Add (v, sl);
3407 } else if (compare_type == TypeManager.char_type){
3408 char v = (char) key;
3410 if (Elements.Contains (v))
3411 lname = v.ToString ();
3413 Elements.Add (v, sl);
3414 } else if (compare_type == TypeManager.byte_type){
3415 byte v = (byte) key;
3417 if (Elements.Contains (v))
3418 lname = v.ToString ();
3420 Elements.Add (v, sl);
3421 } else if (compare_type == TypeManager.sbyte_type){
3422 sbyte v = (sbyte) key;
3424 if (Elements.Contains (v))
3425 lname = v.ToString ();
3427 Elements.Add (v, sl);
3428 } else if (compare_type == TypeManager.short_type){
3429 short v = (short) key;
3431 if (Elements.Contains (v))
3432 lname = v.ToString ();
3434 Elements.Add (v, sl);
3435 } else if (compare_type == TypeManager.ushort_type){
3436 ushort v = (ushort) key;
3438 if (Elements.Contains (v))
3439 lname = v.ToString ();
3441 Elements.Add (v, sl);
3442 } else if (compare_type == TypeManager.string_type){
3443 if (key is NullLiteral){
3444 if (Elements.Contains (NullLiteral.Null))
3447 Elements.Add (NullLiteral.Null, null);
3449 string s = (string) key;
3451 if (Elements.Contains (s))
3454 Elements.Add (s, sl);
3456 } else if (compare_type == TypeManager.int32_type) {
3459 if (Elements.Contains (v))
3460 lname = v.ToString ();
3462 Elements.Add (v, sl);
3463 } else if (compare_type == TypeManager.bool_type) {
3464 bool v = (bool) key;
3466 if (Elements.Contains (v))
3467 lname = v.ToString ();
3469 Elements.Add (v, sl);
3473 throw new Exception ("Unknown switch type!" +
3474 SwitchType + " " + compare_type);
3478 error152 ("case + " + lname);
3489 void EmitObjectInteger (ILGenerator ig, object k)
3492 IntConstant.EmitInt (ig, (int) k);
3493 else if (k is Constant) {
3494 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3497 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3500 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3502 IntConstant.EmitInt (ig, (int) (long) k);
3503 ig.Emit (OpCodes.Conv_I8);
3506 LongConstant.EmitLong (ig, (long) k);
3508 else if (k is ulong)
3510 if ((ulong) k < (1L<<32))
3512 IntConstant.EmitInt (ig, (int) (long) k);
3513 ig.Emit (OpCodes.Conv_U8);
3517 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3521 IntConstant.EmitInt (ig, (int) ((char) k));
3522 else if (k is sbyte)
3523 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3525 IntConstant.EmitInt (ig, (int) ((byte) k));
3526 else if (k is short)
3527 IntConstant.EmitInt (ig, (int) ((short) k));
3528 else if (k is ushort)
3529 IntConstant.EmitInt (ig, (int) ((ushort) k));
3531 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3533 throw new Exception ("Unhandled case");
3536 // structure used to hold blocks of keys while calculating table switch
3537 class KeyBlock : IComparable
3539 public KeyBlock (long _nFirst)
3541 nFirst = nLast = _nFirst;
3545 public ArrayList rgKeys = null;
3548 get { return (int) (nLast - nFirst + 1); }
3550 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3552 return kbLast.nLast - kbFirst.nFirst + 1;
3554 public int CompareTo (object obj)
3556 KeyBlock kb = (KeyBlock) obj;
3557 int nLength = Length;
3558 int nLengthOther = kb.Length;
3559 if (nLengthOther == nLength)
3560 return (int) (kb.nFirst - nFirst);
3561 return nLength - nLengthOther;
3566 /// This method emits code for a lookup-based switch statement (non-string)
3567 /// Basically it groups the cases into blocks that are at least half full,
3568 /// and then spits out individual lookup opcodes for each block.
3569 /// It emits the longest blocks first, and short blocks are just
3570 /// handled with direct compares.
3572 /// <param name="ec"></param>
3573 /// <param name="val"></param>
3574 /// <returns></returns>
3575 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3577 int cElements = Elements.Count;
3578 object [] rgKeys = new object [cElements];
3579 Elements.Keys.CopyTo (rgKeys, 0);
3580 Array.Sort (rgKeys);
3582 // initialize the block list with one element per key
3583 ArrayList rgKeyBlocks = new ArrayList ();
3584 foreach (object key in rgKeys)
3585 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3588 // iteratively merge the blocks while they are at least half full
3589 // there's probably a really cool way to do this with a tree...
3590 while (rgKeyBlocks.Count > 1)
3592 ArrayList rgKeyBlocksNew = new ArrayList ();
3593 kbCurr = (KeyBlock) rgKeyBlocks [0];
3594 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3596 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3597 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3600 kbCurr.nLast = kb.nLast;
3604 // start a new block
3605 rgKeyBlocksNew.Add (kbCurr);
3609 rgKeyBlocksNew.Add (kbCurr);
3610 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3612 rgKeyBlocks = rgKeyBlocksNew;
3615 // initialize the key lists
3616 foreach (KeyBlock kb in rgKeyBlocks)
3617 kb.rgKeys = new ArrayList ();
3619 // fill the key lists
3621 if (rgKeyBlocks.Count > 0) {
3622 kbCurr = (KeyBlock) rgKeyBlocks [0];
3623 foreach (object key in rgKeys)
3625 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3627 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3628 kbCurr.rgKeys.Add (key);
3632 // sort the blocks so we can tackle the largest ones first
3633 rgKeyBlocks.Sort ();
3635 // okay now we can start...
3636 ILGenerator ig = ec.ig;
3637 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3638 Label lblDefault = ig.DefineLabel ();
3640 Type typeKeys = null;
3641 if (rgKeys.Length > 0)
3642 typeKeys = rgKeys [0].GetType (); // used for conversions
3644 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3646 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3647 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3650 foreach (object key in kb.rgKeys)
3652 ig.Emit (OpCodes.Ldloc, val);
3653 EmitObjectInteger (ig, key);
3654 SwitchLabel sl = (SwitchLabel) Elements [key];
3655 ig.Emit (OpCodes.Beq, sl.ILLabel);
3660 // TODO: if all the keys in the block are the same and there are
3661 // no gaps/defaults then just use a range-check.
3662 if (SwitchType == TypeManager.int64_type ||
3663 SwitchType == TypeManager.uint64_type)
3665 // TODO: optimize constant/I4 cases
3667 // check block range (could be > 2^31)
3668 ig.Emit (OpCodes.Ldloc, val);
3669 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3670 ig.Emit (OpCodes.Blt, lblDefault);
3671 ig.Emit (OpCodes.Ldloc, val);
3672 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3673 ig.Emit (OpCodes.Bgt, lblDefault);
3676 ig.Emit (OpCodes.Ldloc, val);
3679 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3680 ig.Emit (OpCodes.Sub);
3682 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3687 ig.Emit (OpCodes.Ldloc, val);
3688 int nFirst = (int) kb.nFirst;
3691 IntConstant.EmitInt (ig, nFirst);
3692 ig.Emit (OpCodes.Sub);
3694 else if (nFirst < 0)
3696 IntConstant.EmitInt (ig, -nFirst);
3697 ig.Emit (OpCodes.Add);
3701 // first, build the list of labels for the switch
3703 int cJumps = kb.Length;
3704 Label [] rgLabels = new Label [cJumps];
3705 for (int iJump = 0; iJump < cJumps; iJump++)
3707 object key = kb.rgKeys [iKey];
3708 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3710 SwitchLabel sl = (SwitchLabel) Elements [key];
3711 rgLabels [iJump] = sl.ILLabel;
3715 rgLabels [iJump] = lblDefault;
3717 // emit the switch opcode
3718 ig.Emit (OpCodes.Switch, rgLabels);
3721 // mark the default for this block
3723 ig.MarkLabel (lblDefault);
3726 // TODO: find the default case and emit it here,
3727 // to prevent having to do the following jump.
3728 // make sure to mark other labels in the default section
3730 // the last default just goes to the end
3731 ig.Emit (OpCodes.Br, lblDefault);
3733 // now emit the code for the sections
3734 bool fFoundDefault = false;
3735 bool fAllReturn = true;
3736 foreach (SwitchSection ss in Sections)
3738 foreach (SwitchLabel sl in ss.Labels)
3740 ig.MarkLabel (sl.ILLabel);
3741 ig.MarkLabel (sl.ILLabelCode);
3742 if (sl.Label == null)
3744 ig.MarkLabel (lblDefault);
3745 fFoundDefault = true;
3748 bool returns = ss.Block.Emit (ec);
3749 fAllReturn &= returns;
3750 //ig.Emit (OpCodes.Br, lblEnd);
3753 if (!fFoundDefault) {
3754 ig.MarkLabel (lblDefault);
3757 ig.MarkLabel (lblEnd);
3762 // This simple emit switch works, but does not take advantage of the
3764 // TODO: remove non-string logic from here
3765 // TODO: binary search strings?
3767 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3769 ILGenerator ig = ec.ig;
3770 Label end_of_switch = ig.DefineLabel ();
3771 Label next_test = ig.DefineLabel ();
3772 Label null_target = ig.DefineLabel ();
3773 bool default_found = false;
3774 bool first_test = true;
3775 bool pending_goto_end = false;
3776 bool all_return = true;
3777 bool is_string = false;
3781 // Special processing for strings: we cant compare
3784 if (SwitchType == TypeManager.string_type){
3785 ig.Emit (OpCodes.Ldloc, val);
3788 if (Elements.Contains (NullLiteral.Null)){
3789 ig.Emit (OpCodes.Brfalse, null_target);
3791 ig.Emit (OpCodes.Brfalse, default_target);
3793 ig.Emit (OpCodes.Ldloc, val);
3794 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3795 ig.Emit (OpCodes.Stloc, val);
3798 SwitchSection last_section;
3799 last_section = (SwitchSection) Sections [Sections.Count-1];
3801 foreach (SwitchSection ss in Sections){
3802 Label sec_begin = ig.DefineLabel ();
3804 if (pending_goto_end)
3805 ig.Emit (OpCodes.Br, end_of_switch);
3807 int label_count = ss.Labels.Count;
3809 foreach (SwitchLabel sl in ss.Labels){
3810 ig.MarkLabel (sl.ILLabel);
3813 ig.MarkLabel (next_test);
3814 next_test = ig.DefineLabel ();
3817 // If we are the default target
3819 if (sl.Label == null){
3820 ig.MarkLabel (default_target);
3821 default_found = true;
3823 object lit = sl.Converted;
3825 if (lit is NullLiteral){
3827 if (label_count == 1)
3828 ig.Emit (OpCodes.Br, next_test);
3833 StringConstant str = (StringConstant) lit;
3835 ig.Emit (OpCodes.Ldloc, val);
3836 ig.Emit (OpCodes.Ldstr, str.Value);
3837 if (label_count == 1)
3838 ig.Emit (OpCodes.Bne_Un, next_test);
3840 ig.Emit (OpCodes.Beq, sec_begin);
3842 ig.Emit (OpCodes.Ldloc, val);
3843 EmitObjectInteger (ig, lit);
3844 ig.Emit (OpCodes.Ceq);
3845 if (label_count == 1)
3846 ig.Emit (OpCodes.Brfalse, next_test);
3848 ig.Emit (OpCodes.Brtrue, sec_begin);
3852 if (label_count != 1 && ss != last_section)
3853 ig.Emit (OpCodes.Br, next_test);
3856 ig.MarkLabel (null_target);
3857 ig.MarkLabel (sec_begin);
3858 foreach (SwitchLabel sl in ss.Labels)
\r
3859 ig.MarkLabel (sl.ILLabelCode);
3861 bool returns = ss.Block.Emit (ec);
3863 pending_goto_end = false;
3866 pending_goto_end = true;
3870 if (!default_found){
3871 ig.MarkLabel (default_target);
3874 ig.MarkLabel (next_test);
3875 ig.MarkLabel (end_of_switch);
3880 public override bool Resolve (EmitContext ec)
3882 Expr = Expr.Resolve (ec);
3886 new_expr = SwitchGoverningType (ec, Expr.Type);
3887 if (new_expr == null){
3888 Report.Error (151, loc, "An integer type or string was expected for switch");
3893 SwitchType = new_expr.Type;
3895 if (!CheckSwitch (ec))
3898 Switch old_switch = ec.Switch;
3900 ec.Switch.SwitchType = SwitchType;
3902 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3905 foreach (SwitchSection ss in Sections){
3907 ec.CurrentBranching.CreateSibling ();
3911 if (ss.Block.Resolve (ec) != true)
3917 ec.CurrentBranching.CreateSibling ();
3919 ec.EndFlowBranching ();
3920 ec.Switch = old_switch;
3925 public override bool Emit (EmitContext ec)
3927 // Store variable for comparission purposes
3928 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3930 ec.ig.Emit (OpCodes.Stloc, value);
3932 ILGenerator ig = ec.ig;
3934 default_target = ig.DefineLabel ();
3937 // Setup the codegen context
3939 Label old_end = ec.LoopEnd;
3940 Switch old_switch = ec.Switch;
3942 ec.LoopEnd = ig.DefineLabel ();
3947 if (SwitchType == TypeManager.string_type)
3948 all_return = SimpleSwitchEmit (ec, value);
3950 all_return = TableSwitchEmit (ec, value);
3952 // Restore context state.
3953 ig.MarkLabel (ec.LoopEnd);
3956 // Restore the previous context
3958 ec.LoopEnd = old_end;
3959 ec.Switch = old_switch;
3965 public class Lock : Statement {
3967 Statement Statement;
3969 public Lock (Expression expr, Statement stmt, Location l)
3976 public override bool Resolve (EmitContext ec)
3978 expr = expr.Resolve (ec);
3979 return Statement.Resolve (ec) && expr != null;
3982 public override bool Emit (EmitContext ec)
3984 Type type = expr.Type;
3987 if (type.IsValueType){
3988 Report.Error (185, loc, "lock statement requires the expression to be " +
3989 " a reference type (type is: `" +
3990 TypeManager.CSharpName (type) + "'");
3994 ILGenerator ig = ec.ig;
3995 LocalBuilder temp = ig.DeclareLocal (type);
3998 ig.Emit (OpCodes.Dup);
3999 ig.Emit (OpCodes.Stloc, temp);
4000 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4003 Label end = ig.BeginExceptionBlock ();
4004 bool old_in_try = ec.InTry;
4006 Label finish = ig.DefineLabel ();
4007 val = Statement.Emit (ec);
4008 ec.InTry = old_in_try;
4009 // ig.Emit (OpCodes.Leave, finish);
4011 ig.MarkLabel (finish);
4014 ig.BeginFinallyBlock ();
4015 ig.Emit (OpCodes.Ldloc, temp);
4016 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4017 ig.EndExceptionBlock ();
4023 public class Unchecked : Statement {
4024 public readonly Block Block;
4026 public Unchecked (Block b)
4031 public override bool Resolve (EmitContext ec)
4033 return Block.Resolve (ec);
4036 public override bool Emit (EmitContext ec)
4038 bool previous_state = ec.CheckState;
4039 bool previous_state_const = ec.ConstantCheckState;
4042 ec.CheckState = false;
4043 ec.ConstantCheckState = false;
4044 val = Block.Emit (ec);
4045 ec.CheckState = previous_state;
4046 ec.ConstantCheckState = previous_state_const;
4052 public class Checked : Statement {
4053 public readonly Block Block;
4055 public Checked (Block b)
4060 public override bool Resolve (EmitContext ec)
4062 bool previous_state = ec.CheckState;
4063 bool previous_state_const = ec.ConstantCheckState;
4065 ec.CheckState = true;
4066 ec.ConstantCheckState = true;
4067 bool ret = Block.Resolve (ec);
4068 ec.CheckState = previous_state;
4069 ec.ConstantCheckState = previous_state_const;
4074 public override bool Emit (EmitContext ec)
4076 bool previous_state = ec.CheckState;
4077 bool previous_state_const = ec.ConstantCheckState;
4080 ec.CheckState = true;
4081 ec.ConstantCheckState = true;
4082 val = Block.Emit (ec);
4083 ec.CheckState = previous_state;
4084 ec.ConstantCheckState = previous_state_const;
4090 public class Unsafe : Statement {
4091 public readonly Block Block;
4093 public Unsafe (Block b)
4098 public override bool Resolve (EmitContext ec)
4100 bool previous_state = ec.InUnsafe;
4104 val = Block.Resolve (ec);
4105 ec.InUnsafe = previous_state;
4110 public override bool Emit (EmitContext ec)
4112 bool previous_state = ec.InUnsafe;
4116 val = Block.Emit (ec);
4117 ec.InUnsafe = previous_state;
4126 public class Fixed : Statement {
4128 ArrayList declarators;
4129 Statement statement;
4134 public bool is_object;
4135 public VariableInfo vi;
4136 public Expression expr;
4137 public Expression converted;
4140 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4143 declarators = decls;
4148 public override bool Resolve (EmitContext ec)
4150 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4151 if (expr_type == null)
4154 data = new FixedData [declarators.Count];
4157 foreach (Pair p in declarators){
4158 VariableInfo vi = (VariableInfo) p.First;
4159 Expression e = (Expression) p.Second;
4164 // The rules for the possible declarators are pretty wise,
4165 // but the production on the grammar is more concise.
4167 // So we have to enforce these rules here.
4169 // We do not resolve before doing the case 1 test,
4170 // because the grammar is explicit in that the token &
4171 // is present, so we need to test for this particular case.
4175 // Case 1: & object.
4177 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4178 Expression child = ((Unary) e).Expr;
4181 if (child is ParameterReference || child is LocalVariableReference){
4184 "No need to use fixed statement for parameters or " +
4185 "local variable declarations (address is already " +
4194 child = ((Unary) e).Expr;
4196 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4199 data [i].is_object = true;
4201 data [i].converted = null;
4215 if (e.Type.IsArray){
4216 Type array_type = e.Type.GetElementType ();
4220 // Provided that array_type is unmanaged,
4222 if (!TypeManager.VerifyUnManaged (array_type, loc))
4226 // and T* is implicitly convertible to the
4227 // pointer type given in the fixed statement.
4229 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4231 Expression converted = Expression.ConvertImplicitRequired (
4232 ec, array_ptr, vi.VariableType, loc);
4233 if (converted == null)
4236 data [i].is_object = false;
4238 data [i].converted = converted;
4248 if (e.Type == TypeManager.string_type){
4249 data [i].is_object = false;
4251 data [i].converted = null;
4257 return statement.Resolve (ec);
4260 public override bool Emit (EmitContext ec)
4262 ILGenerator ig = ec.ig;
4264 bool is_ret = false;
4266 for (int i = 0; i < data.Length; i++) {
4267 VariableInfo vi = data [i].vi;
4270 // Case 1: & object.
4272 if (data [i].is_object) {
4274 // Store pointer in pinned location
4276 data [i].expr.Emit (ec);
4277 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4279 is_ret = statement.Emit (ec);
4281 // Clear the pinned variable.
4282 ig.Emit (OpCodes.Ldc_I4_0);
4283 ig.Emit (OpCodes.Conv_U);
4284 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4292 if (data [i].expr.Type.IsArray){
4294 // Store pointer in pinned location
4296 data [i].converted.Emit (ec);
4298 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4300 is_ret = statement.Emit (ec);
4302 // Clear the pinned variable.
4303 ig.Emit (OpCodes.Ldc_I4_0);
4304 ig.Emit (OpCodes.Conv_U);
4305 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4313 if (data [i].expr.Type == TypeManager.string_type){
4314 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4315 TypeManager.MakePinned (pinned_string);
4317 data [i].expr.Emit (ec);
4318 ig.Emit (OpCodes.Stloc, pinned_string);
4320 Expression sptr = new StringPtr (pinned_string, loc);
4321 Expression converted = Expression.ConvertImplicitRequired (
4322 ec, sptr, vi.VariableType, loc);
4324 if (converted == null)
4327 converted.Emit (ec);
4328 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4330 is_ret = statement.Emit (ec);
4332 // Clear the pinned variable
4333 ig.Emit (OpCodes.Ldnull);
4334 ig.Emit (OpCodes.Stloc, pinned_string);
4342 public class Catch {
4343 public readonly string Name;
4344 public readonly Block Block;
4345 public readonly Location Location;
4347 Expression type_expr;
4350 public Catch (Expression type, string name, Block block, Location l)
4358 public Type CatchType {
4364 public bool IsGeneral {
4366 return type_expr == null;
4370 public bool Resolve (EmitContext ec)
4372 if (type_expr != null) {
4373 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4377 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4378 Report.Error (155, Location,
4379 "The type caught or thrown must be derived " +
4380 "from System.Exception");
4386 if (!Block.Resolve (ec))
4393 public class Try : Statement {
4394 public readonly Block Fini, Block;
4395 public readonly ArrayList Specific;
4396 public readonly Catch General;
4399 // specific, general and fini might all be null.
4401 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4403 if (specific == null && general == null){
4404 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4408 this.Specific = specific;
4409 this.General = general;
4414 public override bool Resolve (EmitContext ec)
4418 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4420 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4422 bool old_in_try = ec.InTry;
4425 if (!Block.Resolve (ec))
4428 ec.InTry = old_in_try;
4430 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4432 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4434 foreach (Catch c in Specific){
4435 ec.CurrentBranching.CreateSibling ();
4436 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4438 if (c.Name != null) {
4439 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4441 throw new Exception ();
4446 bool old_in_catch = ec.InCatch;
4449 if (!c.Resolve (ec))
4452 ec.InCatch = old_in_catch;
4454 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4456 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4457 vector.AndLocals (current);
4460 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4462 if (General != null){
4463 ec.CurrentBranching.CreateSibling ();
4464 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4466 bool old_in_catch = ec.InCatch;
4469 if (!General.Resolve (ec))
4472 ec.InCatch = old_in_catch;
4474 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4476 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4477 vector.AndLocals (current);
4480 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4483 ec.CurrentBranching.CreateSiblingForFinally ();
4484 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4486 bool old_in_finally = ec.InFinally;
4487 ec.InFinally = true;
4489 if (!Fini.Resolve (ec))
4492 ec.InFinally = old_in_finally;
4495 FlowReturns returns = ec.EndFlowBranching ();
4497 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4499 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4501 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4502 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4505 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4507 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4512 public override bool Emit (EmitContext ec)
4514 ILGenerator ig = ec.ig;
4516 Label finish = ig.DefineLabel ();;
4520 end = ig.BeginExceptionBlock ();
4521 bool old_in_try = ec.InTry;
4523 returns = Block.Emit (ec);
4524 ec.InTry = old_in_try;
4527 // System.Reflection.Emit provides this automatically:
4528 // ig.Emit (OpCodes.Leave, finish);
4530 bool old_in_catch = ec.InCatch;
4532 DeclSpace ds = ec.DeclSpace;
4534 foreach (Catch c in Specific){
4537 ig.BeginCatchBlock (c.CatchType);
4539 if (c.Name != null){
4540 vi = c.Block.GetVariableInfo (c.Name);
4542 throw new Exception ("Variable does not exist in this block");
4544 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4546 ig.Emit (OpCodes.Pop);
4548 if (!c.Block.Emit (ec))
4552 if (General != null){
4553 ig.BeginCatchBlock (TypeManager.object_type);
4554 ig.Emit (OpCodes.Pop);
4555 if (!General.Block.Emit (ec))
4558 ec.InCatch = old_in_catch;
4560 ig.MarkLabel (finish);
4562 ig.BeginFinallyBlock ();
4563 bool old_in_finally = ec.InFinally;
4564 ec.InFinally = true;
4566 ec.InFinally = old_in_finally;
4569 ig.EndExceptionBlock ();
4572 if (!returns || ec.InTry || ec.InCatch)
4575 // Unfortunately, System.Reflection.Emit automatically emits a leave
4576 // to the end of the finally block. This is a problem if `returns'
4577 // is true since we may jump to a point after the end of the method.
4578 // As a workaround, emit an explicit ret here.
4580 if (ec.ReturnType != null)
4581 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4582 ec.ig.Emit (OpCodes.Ret);
4588 public class Using : Statement {
4589 object expression_or_block;
4590 Statement Statement;
4595 Expression [] converted_vars;
4596 ExpressionStatement [] assign;
4598 public Using (object expression_or_block, Statement stmt, Location l)
4600 this.expression_or_block = expression_or_block;
4606 // Resolves for the case of using using a local variable declaration.
4608 bool ResolveLocalVariableDecls (EmitContext ec)
4610 bool need_conv = false;
4611 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4614 if (expr_type == null)
4618 // The type must be an IDisposable or an implicit conversion
4621 converted_vars = new Expression [var_list.Count];
4622 assign = new ExpressionStatement [var_list.Count];
4623 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4624 foreach (DictionaryEntry e in var_list){
4625 Expression var = (Expression) e.Key;
4627 var = var.ResolveLValue (ec, new EmptyExpression ());
4631 converted_vars [i] = Expression.ConvertImplicitRequired (
4632 ec, var, TypeManager.idisposable_type, loc);
4634 if (converted_vars [i] == null)
4642 foreach (DictionaryEntry e in var_list){
4643 LocalVariableReference var = (LocalVariableReference) e.Key;
4644 Expression new_expr = (Expression) e.Value;
4647 a = new Assign (var, new_expr, loc);
4653 converted_vars [i] = var;
4654 assign [i] = (ExpressionStatement) a;
4661 bool ResolveExpression (EmitContext ec)
4663 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4664 conv = Expression.ConvertImplicitRequired (
4665 ec, expr, TypeManager.idisposable_type, loc);
4675 // Emits the code for the case of using using a local variable declaration.
4677 bool EmitLocalVariableDecls (EmitContext ec)
4679 ILGenerator ig = ec.ig;
4682 bool old_in_try = ec.InTry;
4684 for (i = 0; i < assign.Length; i++) {
4685 assign [i].EmitStatement (ec);
4687 ig.BeginExceptionBlock ();
4689 Statement.Emit (ec);
4690 ec.InTry = old_in_try;
4692 bool old_in_finally = ec.InFinally;
4693 ec.InFinally = true;
4694 var_list.Reverse ();
4695 foreach (DictionaryEntry e in var_list){
4696 LocalVariableReference var = (LocalVariableReference) e.Key;
4697 Label skip = ig.DefineLabel ();
4700 ig.BeginFinallyBlock ();
4703 ig.Emit (OpCodes.Brfalse, skip);
4704 converted_vars [i].Emit (ec);
4705 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4706 ig.MarkLabel (skip);
4707 ig.EndExceptionBlock ();
4709 ec.InFinally = old_in_finally;
4714 bool EmitExpression (EmitContext ec)
4717 // Make a copy of the expression and operate on that.
4719 ILGenerator ig = ec.ig;
4720 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4725 ig.Emit (OpCodes.Stloc, local_copy);
4727 bool old_in_try = ec.InTry;
4729 ig.BeginExceptionBlock ();
4730 Statement.Emit (ec);
4731 ec.InTry = old_in_try;
4733 Label skip = ig.DefineLabel ();
4734 bool old_in_finally = ec.InFinally;
4735 ig.BeginFinallyBlock ();
4736 ig.Emit (OpCodes.Ldloc, local_copy);
4737 ig.Emit (OpCodes.Brfalse, skip);
4738 ig.Emit (OpCodes.Ldloc, local_copy);
4739 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4740 ig.MarkLabel (skip);
4741 ec.InFinally = old_in_finally;
4742 ig.EndExceptionBlock ();
4747 public override bool Resolve (EmitContext ec)
4749 if (expression_or_block is DictionaryEntry){
4750 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4751 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4753 if (!ResolveLocalVariableDecls (ec))
4756 } else if (expression_or_block is Expression){
4757 expr = (Expression) expression_or_block;
4759 expr = expr.Resolve (ec);
4763 expr_type = expr.Type;
4765 if (!ResolveExpression (ec))
4769 return Statement.Resolve (ec);
4772 public override bool Emit (EmitContext ec)
4774 if (expression_or_block is DictionaryEntry)
4775 return EmitLocalVariableDecls (ec);
4776 else if (expression_or_block is Expression)
4777 return EmitExpression (ec);
4784 /// Implementation of the foreach C# statement
4786 public class Foreach : Statement {
4788 LocalVariableReference variable;
4790 Statement statement;
4791 ForeachHelperMethods hm;
4792 Expression empty, conv;
4793 Type array_type, element_type;
4796 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4797 Statement stmt, Location l)
4800 this.variable = var;
4806 public override bool Resolve (EmitContext ec)
4808 expr = expr.Resolve (ec);
4812 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4813 if (var_type == null)
4817 // We need an instance variable. Not sure this is the best
4818 // way of doing this.
4820 // FIXME: When we implement propertyaccess, will those turn
4821 // out to return values in ExprClass? I think they should.
4823 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4824 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4825 error1579 (expr.Type);
4829 if (expr.Type.IsArray) {
4830 array_type = expr.Type;
4831 element_type = array_type.GetElementType ();
4833 empty = new EmptyExpression (element_type);
4835 hm = ProbeCollectionType (ec, expr.Type);
4837 error1579 (expr.Type);
4841 array_type = expr.Type;
4842 element_type = hm.element_type;
4844 empty = new EmptyExpression (hm.element_type);
4847 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4848 ec.CurrentBranching.CreateSibling ();
4852 // FIXME: maybe we can apply the same trick we do in the
4853 // array handling to avoid creating empty and conv in some cases.
4855 // Although it is not as important in this case, as the type
4856 // will not likely be object (what the enumerator will return).
4858 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4862 if (variable.ResolveLValue (ec, empty) == null)
4865 if (!statement.Resolve (ec))
4868 FlowReturns returns = ec.EndFlowBranching ();
4874 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4876 static MethodInfo FetchMethodMoveNext (Type t)
4878 MemberList move_next_list;
4880 move_next_list = TypeContainer.FindMembers (
4881 t, MemberTypes.Method,
4882 BindingFlags.Public | BindingFlags.Instance,
4883 Type.FilterName, "MoveNext");
4884 if (move_next_list.Count == 0)
4887 foreach (MemberInfo m in move_next_list){
4888 MethodInfo mi = (MethodInfo) m;
4891 args = TypeManager.GetArgumentTypes (mi);
4892 if (args != null && args.Length == 0){
4893 if (mi.ReturnType == TypeManager.bool_type)
4901 // Retrieves a `public T get_Current ()' method from the Type `t'
4903 static MethodInfo FetchMethodGetCurrent (Type t)
4905 MemberList move_next_list;
4907 move_next_list = TypeContainer.FindMembers (
4908 t, MemberTypes.Method,
4909 BindingFlags.Public | BindingFlags.Instance,
4910 Type.FilterName, "get_Current");
4911 if (move_next_list.Count == 0)
4914 foreach (MemberInfo m in move_next_list){
4915 MethodInfo mi = (MethodInfo) m;
4918 args = TypeManager.GetArgumentTypes (mi);
4919 if (args != null && args.Length == 0)
4926 // This struct records the helper methods used by the Foreach construct
4928 class ForeachHelperMethods {
4929 public EmitContext ec;
4930 public MethodInfo get_enumerator;
4931 public MethodInfo move_next;
4932 public MethodInfo get_current;
4933 public Type element_type;
4934 public Type enumerator_type;
4935 public bool is_disposable;
4937 public ForeachHelperMethods (EmitContext ec)
4940 this.element_type = TypeManager.object_type;
4941 this.enumerator_type = TypeManager.ienumerator_type;
4942 this.is_disposable = true;
4946 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4951 if (!(m is MethodInfo))
4954 if (m.Name != "GetEnumerator")
4957 MethodInfo mi = (MethodInfo) m;
4958 Type [] args = TypeManager.GetArgumentTypes (mi);
4960 if (args.Length != 0)
4963 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4964 EmitContext ec = hm.ec;
4967 // Check whether GetEnumerator is accessible to us
4969 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4971 Type declaring = mi.DeclaringType;
4972 if (prot == MethodAttributes.Private){
4973 if (declaring != ec.ContainerType)
4975 } else if (prot == MethodAttributes.FamANDAssem){
4976 // If from a different assembly, false
4977 if (!(mi is MethodBuilder))
4980 // Are we being invoked from the same class, or from a derived method?
4982 if (ec.ContainerType != declaring){
4983 if (!ec.ContainerType.IsSubclassOf (declaring))
4986 } else if (prot == MethodAttributes.FamORAssem){
4987 if (!(mi is MethodBuilder ||
4988 ec.ContainerType == declaring ||
4989 ec.ContainerType.IsSubclassOf (declaring)))
4991 } if (prot == MethodAttributes.Family){
4992 if (!(ec.ContainerType == declaring ||
4993 ec.ContainerType.IsSubclassOf (declaring)))
4998 // Ok, we can access it, now make sure that we can do something
4999 // with this `GetEnumerator'
5002 if (mi.ReturnType == TypeManager.ienumerator_type ||
5003 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5004 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5005 hm.move_next = TypeManager.bool_movenext_void;
5006 hm.get_current = TypeManager.object_getcurrent_void;
5011 // Ok, so they dont return an IEnumerable, we will have to
5012 // find if they support the GetEnumerator pattern.
5014 Type return_type = mi.ReturnType;
5016 hm.move_next = FetchMethodMoveNext (return_type);
5017 if (hm.move_next == null)
5019 hm.get_current = FetchMethodGetCurrent (return_type);
5020 if (hm.get_current == null)
5023 hm.element_type = hm.get_current.ReturnType;
5024 hm.enumerator_type = return_type;
5025 hm.is_disposable = TypeManager.ImplementsInterface (
5026 hm.enumerator_type, TypeManager.idisposable_type);
5032 /// This filter is used to find the GetEnumerator method
5033 /// on which IEnumerator operates
5035 static MemberFilter FilterEnumerator;
5039 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5042 void error1579 (Type t)
5044 Report.Error (1579, loc,
5045 "foreach statement cannot operate on variables of type `" +
5046 t.FullName + "' because that class does not provide a " +
5047 " GetEnumerator method or it is inaccessible");
5050 static bool TryType (Type t, ForeachHelperMethods hm)
5054 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5055 BindingFlags.Public | BindingFlags.NonPublic |
5056 BindingFlags.Instance,
5057 FilterEnumerator, hm);
5062 hm.get_enumerator = (MethodInfo) mi [0];
5067 // Looks for a usable GetEnumerator in the Type, and if found returns
5068 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5070 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5072 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5074 if (TryType (t, hm))
5078 // Now try to find the method in the interfaces
5081 Type [] ifaces = t.GetInterfaces ();
5083 foreach (Type i in ifaces){
5084 if (TryType (i, hm))
5089 // Since TypeBuilder.GetInterfaces only returns the interface
5090 // types for this type, we have to keep looping, but once
5091 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5092 // done, because it returns all the types
5094 if ((t is TypeBuilder))
5104 // FIXME: possible optimization.
5105 // We might be able to avoid creating `empty' if the type is the sam
5107 bool EmitCollectionForeach (EmitContext ec)
5109 ILGenerator ig = ec.ig;
5110 LocalBuilder enumerator, disposable;
5112 enumerator = ig.DeclareLocal (hm.enumerator_type);
5113 if (hm.is_disposable)
5114 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5119 // Instantiate the enumerator
5121 if (expr.Type.IsValueType){
5122 if (expr is IMemoryLocation){
5123 IMemoryLocation ml = (IMemoryLocation) expr;
5125 ml.AddressOf (ec, AddressOp.Load);
5127 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5128 " does not implement IMemoryLocation");
5129 ig.Emit (OpCodes.Call, hm.get_enumerator);
5132 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5134 ig.Emit (OpCodes.Stloc, enumerator);
5137 // Protect the code in a try/finalize block, so that
5138 // if the beast implement IDisposable, we get rid of it
5141 bool old_in_try = ec.InTry;
5143 if (hm.is_disposable) {
5144 l = ig.BeginExceptionBlock ();
5148 Label end_try = ig.DefineLabel ();
5150 ig.MarkLabel (ec.LoopBegin);
5151 ig.Emit (OpCodes.Ldloc, enumerator);
5152 ig.Emit (OpCodes.Callvirt, hm.move_next);
5153 ig.Emit (OpCodes.Brfalse, end_try);
5154 ig.Emit (OpCodes.Ldloc, enumerator);
5155 ig.Emit (OpCodes.Callvirt, hm.get_current);
5156 variable.EmitAssign (ec, conv);
5157 statement.Emit (ec);
5158 ig.Emit (OpCodes.Br, ec.LoopBegin);
5159 ig.MarkLabel (end_try);
5160 ec.InTry = old_in_try;
5162 // The runtime provides this for us.
5163 // ig.Emit (OpCodes.Leave, end);
5166 // Now the finally block
5168 if (hm.is_disposable) {
5169 Label end_finally = ig.DefineLabel ();
5170 bool old_in_finally = ec.InFinally;
5171 ec.InFinally = true;
5172 ig.BeginFinallyBlock ();
5174 ig.Emit (OpCodes.Ldloc, enumerator);
5175 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5176 ig.Emit (OpCodes.Stloc, disposable);
5177 ig.Emit (OpCodes.Ldloc, disposable);
5178 ig.Emit (OpCodes.Brfalse, end_finally);
5179 ig.Emit (OpCodes.Ldloc, disposable);
5180 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5181 ig.MarkLabel (end_finally);
5182 ec.InFinally = old_in_finally;
5184 // The runtime generates this anyways.
5185 // ig.Emit (OpCodes.Endfinally);
5187 ig.EndExceptionBlock ();
5190 ig.MarkLabel (ec.LoopEnd);
5195 // FIXME: possible optimization.
5196 // We might be able to avoid creating `empty' if the type is the sam
5198 bool EmitArrayForeach (EmitContext ec)
5200 int rank = array_type.GetArrayRank ();
5201 ILGenerator ig = ec.ig;
5203 LocalBuilder copy = ig.DeclareLocal (array_type);
5206 // Make our copy of the array
5209 ig.Emit (OpCodes.Stloc, copy);
5212 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5216 ig.Emit (OpCodes.Ldc_I4_0);
5217 ig.Emit (OpCodes.Stloc, counter);
5218 test = ig.DefineLabel ();
5219 ig.Emit (OpCodes.Br, test);
5221 loop = ig.DefineLabel ();
5222 ig.MarkLabel (loop);
5224 ig.Emit (OpCodes.Ldloc, copy);
5225 ig.Emit (OpCodes.Ldloc, counter);
5226 ArrayAccess.EmitLoadOpcode (ig, var_type);
5228 variable.EmitAssign (ec, conv);
5230 statement.Emit (ec);
5232 ig.MarkLabel (ec.LoopBegin);
5233 ig.Emit (OpCodes.Ldloc, counter);
5234 ig.Emit (OpCodes.Ldc_I4_1);
5235 ig.Emit (OpCodes.Add);
5236 ig.Emit (OpCodes.Stloc, counter);
5238 ig.MarkLabel (test);
5239 ig.Emit (OpCodes.Ldloc, counter);
5240 ig.Emit (OpCodes.Ldloc, copy);
5241 ig.Emit (OpCodes.Ldlen);
5242 ig.Emit (OpCodes.Conv_I4);
5243 ig.Emit (OpCodes.Blt, loop);
5245 LocalBuilder [] dim_len = new LocalBuilder [rank];
5246 LocalBuilder [] dim_count = new LocalBuilder [rank];
5247 Label [] loop = new Label [rank];
5248 Label [] test = new Label [rank];
5251 for (dim = 0; dim < rank; dim++){
5252 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5253 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5254 test [dim] = ig.DefineLabel ();
5255 loop [dim] = ig.DefineLabel ();
5258 for (dim = 0; dim < rank; dim++){
5259 ig.Emit (OpCodes.Ldloc, copy);
5260 IntLiteral.EmitInt (ig, dim);
5261 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5262 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5265 for (dim = 0; dim < rank; dim++){
5266 ig.Emit (OpCodes.Ldc_I4_0);
5267 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5268 ig.Emit (OpCodes.Br, test [dim]);
5269 ig.MarkLabel (loop [dim]);
5272 ig.Emit (OpCodes.Ldloc, copy);
5273 for (dim = 0; dim < rank; dim++)
5274 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5277 // FIXME: Maybe we can cache the computation of `get'?
5279 Type [] args = new Type [rank];
5282 for (int i = 0; i < rank; i++)
5283 args [i] = TypeManager.int32_type;
5285 ModuleBuilder mb = CodeGen.ModuleBuilder;
5286 get = mb.GetArrayMethod (
5288 CallingConventions.HasThis| CallingConventions.Standard,
5290 ig.Emit (OpCodes.Call, get);
5291 variable.EmitAssign (ec, conv);
5292 statement.Emit (ec);
5293 ig.MarkLabel (ec.LoopBegin);
5294 for (dim = rank - 1; dim >= 0; dim--){
5295 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5296 ig.Emit (OpCodes.Ldc_I4_1);
5297 ig.Emit (OpCodes.Add);
5298 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5300 ig.MarkLabel (test [dim]);
5301 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5302 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5303 ig.Emit (OpCodes.Blt, loop [dim]);
5306 ig.MarkLabel (ec.LoopEnd);
5311 public override bool Emit (EmitContext ec)
5315 ILGenerator ig = ec.ig;
5317 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5318 bool old_inloop = ec.InLoop;
5319 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5320 ec.LoopBegin = ig.DefineLabel ();
5321 ec.LoopEnd = ig.DefineLabel ();
5323 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5326 ret_val = EmitCollectionForeach (ec);
5328 ret_val = EmitArrayForeach (ec);
5330 ec.LoopBegin = old_begin;
5331 ec.LoopEnd = old_end;
5332 ec.InLoop = old_inloop;
5333 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;