2 // flowanalyis.cs: The control flow analysis code
5 // Martin Baulig (martin@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
20 // A new instance of this class is created every time a new block is resolved
21 // and if there's branching in the block's control flow.
23 public abstract class FlowBranching
26 // The type of a FlowBranching.
28 public enum BranchingType : byte {
29 // Normal (conditional or toplevel) block.
49 // The type of one sibling of a branching.
51 public enum SiblingType : byte {
61 // This is used in the control flow analysis code to specify whether the
62 // current code block may return to its enclosing block before reaching
65 public enum FlowReturns : byte {
68 // It can never return.
71 // This means that the block contains a conditional return statement
75 // The code always returns, ie. there's an unconditional return / break
80 public sealed class Reachability
82 FlowReturns returns, breaks, throws, barrier;
84 public FlowReturns Returns {
85 get { return returns; }
87 public FlowReturns Breaks {
88 get { return breaks; }
90 public FlowReturns Throws {
91 get { return throws; }
93 public FlowReturns Barrier {
94 get { return barrier; }
96 public Reachability (FlowReturns returns, FlowReturns breaks,
97 FlowReturns throws, FlowReturns barrier)
99 this.returns = returns;
100 this.breaks = breaks;
101 this.throws = throws;
102 this.barrier = barrier;
105 public Reachability Clone ()
107 return new Reachability (returns, breaks, throws, barrier);
111 // Performs an `And' operation on the FlowReturns status
112 // (for instance, a block only returns Always if all its siblings
115 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
117 if (a == FlowReturns.Undefined)
121 case FlowReturns.Never:
122 if (b == FlowReturns.Never)
123 return FlowReturns.Never;
125 return FlowReturns.Sometimes;
127 case FlowReturns.Sometimes:
128 return FlowReturns.Sometimes;
130 case FlowReturns.Always:
131 if (b == FlowReturns.Always)
132 return FlowReturns.Always;
134 return FlowReturns.Sometimes;
137 throw new ArgumentException ();
141 public static FlowReturns OrFlowReturns (FlowReturns a, FlowReturns b)
143 if (a == FlowReturns.Undefined)
147 case FlowReturns.Never:
150 case FlowReturns.Sometimes:
151 if (b == FlowReturns.Always)
152 return FlowReturns.Always;
154 return FlowReturns.Sometimes;
156 case FlowReturns.Always:
157 return FlowReturns.Always;
160 throw new ArgumentException ();
164 public static void And (ref Reachability a, Reachability b, bool do_break)
172 // `break' does not "break" in a Switch or a LoopBlock
174 bool a_breaks = do_break && a.AlwaysBreaks;
175 bool b_breaks = do_break && b.AlwaysBreaks;
177 bool a_has_barrier, b_has_barrier;
180 // This is the normal case: the code following a barrier
181 // cannot be reached.
183 a_has_barrier = a.AlwaysHasBarrier;
184 b_has_barrier = b.AlwaysHasBarrier;
187 // Special case for Switch and LoopBlocks: we can reach the
188 // code after the barrier via the `break'.
190 a_has_barrier = !a.AlwaysBreaks && a.AlwaysHasBarrier;
191 b_has_barrier = !b.AlwaysBreaks && b.AlwaysHasBarrier;
194 bool a_unreachable = a_breaks || a.AlwaysThrows || a_has_barrier;
195 bool b_unreachable = b_breaks || b.AlwaysThrows || b_has_barrier;
198 // Do all code paths always return ?
200 if (a.AlwaysReturns) {
201 if (b.AlwaysReturns || b_unreachable)
202 a.returns = FlowReturns.Always;
204 a.returns = FlowReturns.Sometimes;
205 } else if (b.AlwaysReturns) {
206 if (a.AlwaysReturns || a_unreachable)
207 a.returns = FlowReturns.Always;
209 a.returns = FlowReturns.Sometimes;
210 } else if (!a.MayReturn) {
212 a.returns = FlowReturns.Sometimes;
214 a.returns = FlowReturns.Never;
215 } else if (!b.MayReturn) {
217 a.returns = FlowReturns.Sometimes;
219 a.returns = FlowReturns.Never;
222 a.breaks = AndFlowReturns (a.breaks, b.breaks);
223 a.throws = AndFlowReturns (a.throws, b.throws);
224 a.barrier = AndFlowReturns (a.barrier, b.barrier);
226 if (a_unreachable && b_unreachable)
227 a.barrier = FlowReturns.Always;
228 else if (a_unreachable || b_unreachable)
229 a.barrier = FlowReturns.Sometimes;
231 a.barrier = FlowReturns.Never;
234 public void Or (Reachability b)
236 returns = OrFlowReturns (returns, b.returns);
237 breaks = OrFlowReturns (breaks, b.breaks);
238 throws = OrFlowReturns (throws, b.throws);
239 barrier = OrFlowReturns (barrier, b.barrier);
242 public static Reachability Never ()
244 return new Reachability (
245 FlowReturns.Never, FlowReturns.Never,
246 FlowReturns.Never, FlowReturns.Never);
249 public FlowReturns Reachable {
251 if ((returns == FlowReturns.Always) ||
252 (breaks == FlowReturns.Always) ||
253 (throws == FlowReturns.Always) ||
254 (barrier == FlowReturns.Always))
255 return FlowReturns.Never;
256 else if ((returns == FlowReturns.Never) &&
257 (breaks == FlowReturns.Never) &&
258 (throws == FlowReturns.Never) &&
259 (barrier == FlowReturns.Never))
260 return FlowReturns.Always;
262 return FlowReturns.Sometimes;
266 public bool AlwaysBreaks {
267 get { return breaks == FlowReturns.Always; }
270 public bool MayBreak {
271 get { return breaks != FlowReturns.Never; }
274 public bool AlwaysReturns {
275 get { return returns == FlowReturns.Always; }
278 public bool MayReturn {
279 get { return returns != FlowReturns.Never; }
282 public bool AlwaysThrows {
283 get { return throws == FlowReturns.Always; }
286 public bool MayThrow {
287 get { return throws != FlowReturns.Never; }
290 public bool AlwaysHasBarrier {
291 get { return barrier == FlowReturns.Always; }
294 public bool MayHaveBarrier {
295 get { return barrier != FlowReturns.Never; }
298 public bool IsUnreachable {
299 get { return Reachable == FlowReturns.Never; }
302 public void SetReturns ()
304 returns = FlowReturns.Always;
307 public void SetReturnsSometimes ()
309 returns = FlowReturns.Sometimes;
312 public void SetBreaks ()
314 breaks = FlowReturns.Always;
317 public void ResetBreaks ()
319 breaks = FlowReturns.Never;
322 public void SetThrows ()
324 throws = FlowReturns.Always;
327 public void SetThrowsSometimes ()
329 throws = FlowReturns.Sometimes;
332 public void SetBarrier ()
334 barrier = FlowReturns.Always;
337 public void ResetBarrier ()
339 barrier = FlowReturns.Never;
342 static string ShortName (FlowReturns returns)
345 case FlowReturns.Never:
347 case FlowReturns.Sometimes:
354 public override string ToString ()
356 return String.Format ("[{0}:{1}:{2}:{3}:{4}]",
357 ShortName (returns), ShortName (breaks),
358 ShortName (throws), ShortName (barrier),
359 ShortName (Reachable));
363 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
366 case BranchingType.Exception:
367 return new FlowBranchingException (parent, block, loc);
369 case BranchingType.Switch:
370 return new FlowBranchingBlock (parent, type, SiblingType.SwitchSection, block, loc);
372 case BranchingType.SwitchSection:
373 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
375 case BranchingType.Block:
376 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
378 case BranchingType.Loop:
379 return new FlowBranchingLoop (parent, block, loc);
382 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
387 // The type of this flow branching.
389 public readonly BranchingType Type;
392 // The block this branching is contained in. This may be null if it's not
393 // a top-level block and it doesn't declare any local variables.
395 public readonly Block Block;
398 // The parent of this branching or null if this is the top-block.
400 public readonly FlowBranching Parent;
403 // Start-Location of this flow branching.
405 public readonly Location Location;
408 // If this is an infinite loop.
410 public bool Infinite;
415 VariableMap param_map, local_map;
417 static int next_id = 0;
421 // The vector contains a BitArray with information about which local variables
422 // and parameters are already initialized at the current code position.
424 public class UsageVector {
426 // The type of this branching.
428 public readonly SiblingType Type;
431 // Start location of this branching.
433 public readonly Location Location;
436 // This is only valid for SwitchSection, Try, Catch and Finally.
438 public readonly Block Block;
441 // If this is true, then the usage vector has been modified and must be
442 // merged when we're done with this branching.
447 // The number of parameters in this block.
449 public readonly int CountParameters;
452 // The number of locals in this block.
454 public readonly int CountLocals;
457 // If not null, then we inherit our state from this vector and do a
458 // copy-on-write. If null, then we're the first sibling in a top-level
459 // block and inherit from the empty vector.
461 public readonly UsageVector InheritsFrom;
464 // This is used to construct a list of UsageVector's.
466 public UsageVector Next;
471 MyBitVector locals, parameters;
472 Reachability reachability;
474 static int next_id = 0;
478 // Normally, you should not use any of these constructors.
480 public UsageVector (SiblingType type, UsageVector parent,
481 Block block, Location loc,
482 int num_params, int num_locals)
487 this.InheritsFrom = parent;
488 this.CountParameters = num_params;
489 this.CountLocals = num_locals;
491 if (parent != null) {
493 locals = new MyBitVector (parent.locals, CountLocals);
496 parameters = new MyBitVector (parent.parameters, num_params);
498 reachability = parent.Reachability.Clone ();
501 locals = new MyBitVector (null, CountLocals);
504 parameters = new MyBitVector (null, num_params);
506 reachability = Reachability.Never ();
512 public UsageVector (SiblingType type, UsageVector parent,
513 Block block, Location loc)
514 : this (type, parent, block, loc,
515 parent.CountParameters, parent.CountLocals)
518 public UsageVector (MyBitVector parameters, MyBitVector locals,
519 Reachability reachability, Block block,
522 this.Type = SiblingType.Block;
526 this.reachability = reachability;
527 this.parameters = parameters;
528 this.locals = locals;
534 // This does a deep copy of the usage vector.
536 public UsageVector Clone ()
538 UsageVector retval = new UsageVector (
539 Type, null, Block, Location,
540 CountParameters, CountLocals);
542 if (retval.locals != null)
543 retval.locals = locals.Clone ();
545 if (parameters != null)
546 retval.parameters = parameters.Clone ();
548 retval.reachability = reachability.Clone ();
553 public bool IsAssigned (VariableInfo var)
555 if (!var.IsParameter && Reachability.IsUnreachable)
558 return var.IsAssigned (var.IsParameter ? parameters : locals);
561 public void SetAssigned (VariableInfo var)
563 if (!var.IsParameter && Reachability.IsUnreachable)
567 var.SetAssigned (var.IsParameter ? parameters : locals);
570 public bool IsFieldAssigned (VariableInfo var, string name)
572 if (!var.IsParameter && Reachability.IsUnreachable)
575 return var.IsFieldAssigned (var.IsParameter ? parameters : locals, name);
578 public void SetFieldAssigned (VariableInfo var, string name)
580 if (!var.IsParameter && Reachability.IsUnreachable)
584 var.SetFieldAssigned (var.IsParameter ? parameters : locals, name);
587 public Reachability Reachability {
593 public void Return ()
595 if (!reachability.IsUnreachable) {
597 reachability.SetReturns ();
603 if (!reachability.IsUnreachable) {
605 reachability.SetBreaks ();
611 if (!reachability.IsUnreachable) {
613 reachability.SetThrows ();
619 if (!reachability.IsUnreachable) {
621 reachability.SetBarrier ();
626 // Merges a child branching.
628 public UsageVector MergeChild (FlowBranching branching)
630 UsageVector result = branching.Merge ();
632 Report.Debug (2, " MERGING CHILD", this, branching, IsDirty,
633 result.ParameterVector, result.LocalVector,
634 result.Reachability, reachability, Type);
636 Reachability new_r = result.Reachability;
638 if (branching.Type == BranchingType.Loop) {
639 bool may_leave_loop = new_r.MayBreak;
640 new_r.ResetBreaks ();
642 if (branching.Infinite && !may_leave_loop) {
643 if (new_r.Returns == FlowReturns.Sometimes) {
644 // If we're an infinite loop and do not break,
645 // the code after the loop can never be reached.
646 // However, if we may return from the loop,
647 // then we do always return (or stay in the
654 if (new_r.Returns == FlowReturns.Always) {
655 // We're either finite or we may leave the loop.
656 new_r.SetReturnsSometimes ();
658 if (new_r.Throws == FlowReturns.Always) {
659 // We're either finite or we may leave the loop.
660 new_r.SetThrowsSometimes ();
663 if (!new_r.MayReturn && !new_r.MayThrow)
664 new_r.ResetBarrier ();
666 } else if (branching.Type == BranchingType.Switch)
667 new_r.ResetBreaks ();
670 // We've now either reached the point after the branching or we will
671 // never get there since we always return or always throw an exception.
673 // If we can reach the point after the branching, mark all locals and
674 // parameters as initialized which have been initialized in all branches
675 // we need to look at (see above).
678 if ((Type == SiblingType.SwitchSection) && !new_r.IsUnreachable) {
679 Report.Error (163, Location,
680 "Control cannot fall through from one " +
681 "case label to another");
685 if (locals != null && result.LocalVector != null)
686 locals.Or (result.LocalVector);
688 if (result.ParameterVector != null)
689 parameters.Or (result.ParameterVector);
691 reachability.Or (new_r);
693 Report.Debug (2, " MERGING CHILD DONE", this, result,
694 new_r, reachability);
701 protected void MergeFinally (FlowBranching branching, UsageVector f_origins,
702 MyBitVector f_params)
704 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
705 MyBitVector temp_params = f_params.Clone ();
706 temp_params.Or (vector.Parameters);
710 public void MergeFinally (FlowBranching branching, UsageVector f_vector,
711 UsageVector f_origins)
713 if (parameters != null) {
714 if (f_vector != null) {
715 MergeFinally (branching, f_origins, f_vector.Parameters);
716 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
718 MergeFinally (branching, f_origins, parameters);
721 if (f_vector != null && f_vector.LocalVector != null)
722 MyBitVector.Or (ref locals, f_vector.LocalVector);
726 // Tells control flow analysis that the current code position may be reached with
727 // a forward jump from any of the origins listed in `origin_vectors' which is a
728 // list of UsageVectors.
730 // This is used when resolving forward gotos - in the following example, the
731 // variable `a' is uninitialized in line 8 becase this line may be reached via
732 // the goto in line 4:
742 // 8 Console.WriteLine (a);
745 public void MergeJumpOrigins (UsageVector o_vectors)
747 Report.Debug (1, " MERGING JUMP ORIGINS", this);
749 reachability = Reachability.Never ();
751 if (o_vectors == null)
756 for (UsageVector vector = o_vectors; vector != null;
757 vector = vector.Next) {
758 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
761 if (locals != null && vector.Locals != null)
762 locals.Or (vector.locals);
764 if (parameters != null)
765 parameters.Or (vector.parameters);
768 if (locals != null && vector.Locals != null)
769 locals.And (vector.locals);
770 if (parameters != null)
771 parameters.And (vector.parameters);
774 Reachability.And (ref reachability, vector.Reachability, true);
777 Report.Debug (1, " MERGING JUMP ORIGINS DONE", this);
781 // This is used at the beginning of a finally block if there were
782 // any return statements in the try block or one of the catch blocks.
784 public void MergeFinallyOrigins (UsageVector f_origins)
786 Report.Debug (1, " MERGING FINALLY ORIGIN", this);
788 reachability = Reachability.Never ();
790 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
791 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
793 if (parameters != null)
794 parameters.And (vector.parameters);
796 Reachability.And (ref reachability, vector.Reachability, true);
799 Report.Debug (1, " MERGING FINALLY ORIGIN DONE", this);
802 public void MergeBreakOrigins (UsageVector o_vectors)
804 Report.Debug (1, " MERGING BREAK ORIGINS", this);
806 if (o_vectors == null)
811 for (UsageVector vector = o_vectors; vector != null;
812 vector = vector.Next) {
813 Report.Debug (1, " MERGING BREAK ORIGIN", vector);
816 if (locals != null && vector.Locals != null)
817 locals.Or (vector.locals);
819 if (parameters != null)
820 parameters.Or (vector.parameters);
823 if (locals != null && vector.Locals != null)
824 locals.And (vector.locals);
825 if (parameters != null)
826 parameters.And (vector.parameters);
830 Report.Debug (1, " MERGING BREAK ORIGINS DONE", this);
833 public void CheckOutParameters (FlowBranching branching)
835 if (parameters != null)
836 branching.CheckOutParameters (parameters, branching.Location);
840 // Performs an `or' operation on the locals and the parameters.
842 public void Or (UsageVector new_vector)
845 locals.Or (new_vector.locals);
846 if (parameters != null)
847 parameters.Or (new_vector.parameters);
851 // Performs an `and' operation on the locals.
853 public void AndLocals (UsageVector new_vector)
856 locals.And (new_vector.locals);
859 public bool HasParameters {
861 return parameters != null;
865 public bool HasLocals {
867 return locals != null;
872 // Returns a deep copy of the parameters.
874 public MyBitVector Parameters {
876 if (parameters != null)
877 return parameters.Clone ();
884 // Returns a deep copy of the locals.
886 public MyBitVector Locals {
889 return locals.Clone ();
895 public MyBitVector ParameterVector {
901 public MyBitVector LocalVector {
911 public override string ToString ()
913 StringBuilder sb = new StringBuilder ();
915 sb.Append ("Vector (");
922 sb.Append (reachability);
923 if (parameters != null) {
925 sb.Append (parameters);
931 return sb.ToString ();
936 // Creates a new flow branching which is contained in `parent'.
937 // You should only pass non-null for the `block' argument if this block
938 // introduces any new variables - in this case, we need to create a new
939 // usage vector with a different size than our parent's one.
941 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
942 Block block, Location loc)
952 param_map = Block.ParameterMap;
953 local_map = Block.LocalMap;
955 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
956 vector = new UsageVector (
957 stype, parent_vector, Block, loc,
958 param_map.Length, local_map.Length);
960 param_map = Parent.param_map;
961 local_map = Parent.local_map;
962 vector = new UsageVector (
963 stype, Parent.CurrentUsageVector, null, loc);
969 public abstract UsageVector CurrentUsageVector {
974 // Creates a sibling of the current usage vector.
976 public virtual void CreateSibling (Block block, SiblingType type)
978 UsageVector vector = new UsageVector (
979 type, Parent.CurrentUsageVector, block, Location);
982 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
985 public void CreateSibling ()
987 CreateSibling (null, SiblingType.Conditional);
990 protected abstract void AddSibling (UsageVector uv);
992 public virtual LabeledStatement LookupLabel (string name, Location loc)
995 return Parent.LookupLabel (name, loc);
999 "No such label `" + name + "' in this scope");
1003 public abstract void Label (UsageVector origin_vectors);
1006 // Check whether all `out' parameters have been assigned.
1008 public void CheckOutParameters (MyBitVector parameters, Location loc)
1010 for (int i = 0; i < param_map.Count; i++) {
1011 VariableInfo var = param_map [i];
1016 if (var.IsAssigned (parameters))
1019 Report.Error (177, loc, "The out parameter `" +
1020 var.Name + "' must be " +
1021 "assigned before control leaves the current method.");
1025 protected UsageVector Merge (UsageVector sibling_list)
1027 if (sibling_list.Next == null)
1028 return sibling_list;
1030 MyBitVector locals = null;
1031 MyBitVector parameters = null;
1033 Reachability reachability = null;
1035 Report.Debug (2, " MERGING SIBLINGS", this, Name);
1037 for (UsageVector child = sibling_list; child != null; child = child.Next) {
1038 bool do_break = (Type != BranchingType.Switch) &&
1039 (Type != BranchingType.Loop);
1041 Report.Debug (2, " MERGING SIBLING ", child,
1042 child.ParameterVector, child.LocalVector,
1043 reachability, child.Reachability, do_break);
1045 Reachability.And (ref reachability, child.Reachability, do_break);
1047 // A local variable is initialized after a flow branching if it
1048 // has been initialized in all its branches which do neither
1049 // always return or always throw an exception.
1051 // If a branch may return, but does not always return, then we
1052 // can treat it like a never-returning branch here: control will
1053 // only reach the code position after the branching if we did not
1056 // It's important to distinguish between always and sometimes
1057 // returning branches here:
1060 // 2 if (something) {
1064 // 6 Console.WriteLine (a);
1066 // The if block in lines 3-4 always returns, so we must not look
1067 // at the initialization of `a' in line 4 - thus it'll still be
1068 // uninitialized in line 6.
1070 // On the other hand, the following is allowed:
1077 // 6 Console.WriteLine (a);
1079 // Here, `a' is initialized in line 3 and we must not look at
1080 // line 5 since it always returns.
1082 bool do_break_2 = (child.Type != SiblingType.Block) &&
1083 (child.Type != SiblingType.SwitchSection);
1084 bool always_throws = (child.Type != SiblingType.Try) &&
1085 child.Reachability.AlwaysThrows;
1086 bool unreachable = always_throws ||
1087 (do_break_2 && child.Reachability.AlwaysBreaks) ||
1088 child.Reachability.AlwaysReturns ||
1089 child.Reachability.AlwaysHasBarrier;
1091 Report.Debug (2, " MERGING SIBLING #1", reachability,
1092 Type, child.Type, child.Reachability.IsUnreachable,
1093 do_break_2, always_throws, unreachable);
1095 if (!unreachable && (child.LocalVector != null))
1096 MyBitVector.And (ref locals, child.LocalVector);
1098 // An `out' parameter must be assigned in all branches which do
1099 // not always throw an exception.
1100 if ((child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
1101 MyBitVector.And (ref parameters, child.ParameterVector);
1103 Report.Debug (2, " MERGING SIBLING #2", parameters, locals);
1106 if (reachability == null)
1107 reachability = Reachability.Never ();
1109 Report.Debug (2, " MERGING SIBLINGS DONE", parameters, locals,
1110 reachability, Infinite);
1112 return new UsageVector (
1113 parameters, locals, reachability, null, Location);
1116 protected abstract UsageVector Merge ();
1119 // Merge a child branching.
1121 public UsageVector MergeChild (FlowBranching child)
1123 return CurrentUsageVector.MergeChild (child);
1127 // Does the toplevel merging.
1129 public Reachability MergeTopBlock ()
1131 if ((Type != BranchingType.Block) || (Block == null))
1132 throw new NotSupportedException ();
1134 UsageVector vector = new UsageVector (
1135 SiblingType.Conditional, null, Block, Location,
1136 param_map.Length, local_map.Length);
1138 UsageVector result = vector.MergeChild (this);
1140 Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1142 if ((vector.Reachability.Throws != FlowReturns.Always) &&
1143 (vector.Reachability.Barrier != FlowReturns.Always))
1144 CheckOutParameters (vector.Parameters, Location);
1146 return result.Reachability;
1150 // Checks whether we're in a `try' block.
1152 public virtual bool InTryOrCatch (bool is_return)
1154 if ((Block != null) && Block.IsDestructor)
1156 else if (!is_return &&
1157 ((Type == BranchingType.Loop) || (Type == BranchingType.Switch)))
1159 else if (Parent != null)
1160 return Parent.InTryOrCatch (is_return);
1166 // Checks whether we're in a `catch' block.
1168 public virtual bool InCatch ()
1171 return Parent.InCatch ();
1177 // Checks whether we're in a `finally' block.
1179 public virtual bool InFinally (bool is_return)
1182 ((Type == BranchingType.Loop) || (Type == BranchingType.Switch)))
1184 else if (Parent != null)
1185 return Parent.InFinally (is_return);
1190 public virtual bool InLoop ()
1192 if (Type == BranchingType.Loop)
1194 else if (Parent != null)
1195 return Parent.InLoop ();
1200 public virtual bool InSwitch ()
1202 if (Type == BranchingType.Switch)
1204 else if (Parent != null)
1205 return Parent.InSwitch ();
1210 public virtual bool BreakCrossesTryCatchBoundary ()
1212 if ((Type == BranchingType.Loop) || (Type == BranchingType.Switch))
1214 else if (Parent != null)
1215 return Parent.BreakCrossesTryCatchBoundary ();
1220 public virtual void AddFinallyVector (UsageVector vector)
1223 Parent.AddFinallyVector (vector);
1224 else if ((Block == null) || !Block.IsDestructor)
1225 throw new NotSupportedException ();
1228 public virtual void AddBreakVector (UsageVector vector)
1231 Parent.AddBreakVector (vector);
1232 else if ((Block == null) || !Block.IsDestructor)
1233 throw new NotSupportedException ();
1236 public bool IsAssigned (VariableInfo vi)
1238 return CurrentUsageVector.IsAssigned (vi);
1241 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1243 if (CurrentUsageVector.IsAssigned (vi))
1246 return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1249 public void SetAssigned (VariableInfo vi)
1251 CurrentUsageVector.SetAssigned (vi);
1254 public void SetFieldAssigned (VariableInfo vi, string name)
1256 CurrentUsageVector.SetFieldAssigned (vi, name);
1259 public override string ToString ()
1261 StringBuilder sb = new StringBuilder ();
1262 sb.Append (GetType ());
1268 if (Block != null) {
1270 sb.Append (Block.ID);
1272 sb.Append (Block.StartLocation);
1275 // sb.Append (Siblings.Length);
1276 // sb.Append (" - ");
1277 sb.Append (CurrentUsageVector);
1279 return sb.ToString ();
1282 public string Name {
1284 return String.Format ("{0} ({1}:{2}:{3})",
1285 GetType (), id, Type, Location);
1290 public class FlowBranchingBlock : FlowBranching
1292 UsageVector sibling_list = null;
1294 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
1295 SiblingType stype, Block block, Location loc)
1296 : base (parent, type, stype, block, loc)
1299 public override UsageVector CurrentUsageVector {
1300 get { return sibling_list; }
1303 protected override void AddSibling (UsageVector sibling)
1305 sibling.Next = sibling_list;
1306 sibling_list = sibling;
1309 public override LabeledStatement LookupLabel (string name, Location loc)
1312 return base.LookupLabel (name, loc);
1314 LabeledStatement s = Block.LookupLabel (name);
1318 return base.LookupLabel (name, loc);
1321 public override void Label (UsageVector origin_vectors)
1323 if (!CurrentUsageVector.Reachability.IsUnreachable) {
1324 UsageVector vector = CurrentUsageVector.Clone ();
1325 vector.Next = origin_vectors;
1326 origin_vectors = vector;
1329 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1332 protected override UsageVector Merge ()
1334 return Merge (sibling_list);
1338 public class FlowBranchingLoop : FlowBranchingBlock
1340 UsageVector break_origins;
1342 public FlowBranchingLoop (FlowBranching parent, Block block, Location loc)
1343 : base (parent, BranchingType.Loop, SiblingType.Conditional, block, loc)
1346 public override void AddBreakVector (UsageVector vector)
1348 vector = vector.Clone ();
1349 vector.Next = break_origins;
1350 break_origins = vector;
1353 protected override UsageVector Merge ()
1355 UsageVector vector = base.Merge ();
1357 vector.MergeBreakOrigins (break_origins);
1363 public class FlowBranchingException : FlowBranching
1365 UsageVector current_vector;
1366 UsageVector catch_vectors;
1367 UsageVector finally_vector;
1368 UsageVector finally_origins;
1371 public FlowBranchingException (FlowBranching parent, Block block, Location loc)
1372 : base (parent, BranchingType.Exception, SiblingType.Try, block, loc)
1375 protected override void AddSibling (UsageVector sibling)
1377 if (sibling.Type == SiblingType.Try) {
1378 sibling.Next = catch_vectors;
1379 catch_vectors = sibling;
1381 } else if (sibling.Type == SiblingType.Catch) {
1382 sibling.Next = catch_vectors;
1383 catch_vectors = sibling;
1385 } else if (sibling.Type == SiblingType.Finally) {
1386 sibling.MergeFinallyOrigins (finally_origins);
1387 finally_vector = sibling;
1390 throw new InvalidOperationException ();
1392 current_vector = sibling;
1395 public override UsageVector CurrentUsageVector {
1396 get { return current_vector; }
1399 public override bool InTryOrCatch (bool is_return)
1401 return finally_vector == null;
1404 public override bool InCatch ()
1406 return !in_try && (finally_vector == null);
1409 public override bool InFinally (bool is_return)
1411 return finally_vector != null;
1414 public override bool BreakCrossesTryCatchBoundary ()
1419 public override void AddFinallyVector (UsageVector vector)
1421 vector = vector.Clone ();
1422 vector.Next = finally_origins;
1423 finally_origins = vector;
1426 public override LabeledStatement LookupLabel (string name, Location loc)
1428 if (current_vector.Block == null)
1429 return base.LookupLabel (name, loc);
1431 LabeledStatement s = current_vector.Block.LookupLabel (name);
1435 if (finally_vector != null) {
1437 157, loc, "Control can not leave the body " +
1438 "of the finally block");
1442 return base.LookupLabel (name, loc);
1445 public override void Label (UsageVector origin_vectors)
1447 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1450 protected override UsageVector Merge ()
1452 UsageVector vector = Merge (catch_vectors);
1454 vector.MergeFinally (this, finally_vector, finally_origins);
1461 // This is used by the flow analysis code to keep track of the type of local variables
1464 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1465 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1466 // you can only assign the whole variable as such.
1468 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1469 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1470 // one bit for each of its fields.
1472 // This class computes this `layout' for each type.
1474 public class TypeInfo
1476 public readonly Type Type;
1479 // Total number of bits a variable of this type consumes in the flow vector.
1481 public readonly int TotalLength;
1484 // Number of bits the simple fields of a variable of this type consume
1485 // in the flow vector.
1487 public readonly int Length;
1490 // This is only used by sub-structs.
1492 public readonly int Offset;
1495 // If this is a struct.
1497 public readonly bool IsStruct;
1500 // If this is a struct, all fields which are structs theirselves.
1502 public TypeInfo[] SubStructInfo;
1504 protected readonly StructInfo struct_info;
1505 private static Hashtable type_hash = new Hashtable ();
1507 public static TypeInfo GetTypeInfo (Type type)
1509 TypeInfo info = (TypeInfo) type_hash [type];
1513 info = new TypeInfo (type);
1514 type_hash.Add (type, info);
1518 public static TypeInfo GetTypeInfo (TypeContainer tc)
1520 TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1524 info = new TypeInfo (tc);
1525 type_hash.Add (tc.TypeBuilder, info);
1529 private TypeInfo (Type type)
1533 struct_info = StructInfo.GetStructInfo (type);
1534 if (struct_info != null) {
1535 Length = struct_info.Length;
1536 TotalLength = struct_info.TotalLength;
1537 SubStructInfo = struct_info.StructFields;
1546 private TypeInfo (TypeContainer tc)
1548 this.Type = tc.TypeBuilder;
1550 struct_info = StructInfo.GetStructInfo (tc);
1551 if (struct_info != null) {
1552 Length = struct_info.Length;
1553 TotalLength = struct_info.TotalLength;
1554 SubStructInfo = struct_info.StructFields;
1563 protected TypeInfo (StructInfo struct_info, int offset)
1565 this.struct_info = struct_info;
1566 this.Offset = offset;
1567 this.Length = struct_info.Length;
1568 this.TotalLength = struct_info.TotalLength;
1569 this.SubStructInfo = struct_info.StructFields;
1570 this.Type = struct_info.Type;
1571 this.IsStruct = true;
1574 public int GetFieldIndex (string name)
1576 if (struct_info == null)
1579 return struct_info [name];
1582 public TypeInfo GetSubStruct (string name)
1584 if (struct_info == null)
1587 return struct_info.GetStructField (name);
1591 // A struct's constructor must always assign all fields.
1592 // This method checks whether it actually does so.
1594 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1596 if (struct_info == null)
1600 for (int i = 0; i < struct_info.Count; i++) {
1601 FieldInfo field = struct_info.Fields [i];
1603 if (!branching.IsFieldAssigned (vi, field.Name)) {
1604 Report.Error (171, loc,
1605 "Field `" + TypeManager.CSharpName (Type) +
1606 "." + field.Name + "' must be fully initialized " +
1607 "before control leaves the constructor");
1615 public override string ToString ()
1617 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1618 Type, Offset, Length, TotalLength);
1621 protected class StructInfo {
1622 public readonly Type Type;
1623 public readonly FieldInfo[] Fields;
1624 public readonly TypeInfo[] StructFields;
1625 public readonly int Count;
1626 public readonly int CountPublic;
1627 public readonly int CountNonPublic;
1628 public readonly int Length;
1629 public readonly int TotalLength;
1630 public readonly bool HasStructFields;
1632 private static Hashtable field_type_hash = new Hashtable ();
1633 private Hashtable struct_field_hash;
1634 private Hashtable field_hash;
1636 protected bool InTransit = false;
1638 // Private constructor. To save memory usage, we only need to create one instance
1639 // of this class per struct type.
1640 private StructInfo (Type type)
1644 field_type_hash.Add (type, this);
1646 if (type is TypeBuilder) {
1647 TypeContainer tc = TypeManager.LookupTypeContainer (type);
1649 ArrayList fields = tc.Fields;
1651 ArrayList public_fields = new ArrayList ();
1652 ArrayList non_public_fields = new ArrayList ();
1654 if (fields != null) {
1655 foreach (Field field in fields) {
1656 if ((field.ModFlags & Modifiers.STATIC) != 0)
1658 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1659 public_fields.Add (field.FieldBuilder);
1661 non_public_fields.Add (field.FieldBuilder);
1665 CountPublic = public_fields.Count;
1666 CountNonPublic = non_public_fields.Count;
1667 Count = CountPublic + CountNonPublic;
1669 Fields = new FieldInfo [Count];
1670 public_fields.CopyTo (Fields, 0);
1671 non_public_fields.CopyTo (Fields, CountPublic);
1673 FieldInfo[] public_fields = type.GetFields (
1674 BindingFlags.Instance|BindingFlags.Public);
1675 FieldInfo[] non_public_fields = type.GetFields (
1676 BindingFlags.Instance|BindingFlags.NonPublic);
1678 CountPublic = public_fields.Length;
1679 CountNonPublic = non_public_fields.Length;
1680 Count = CountPublic + CountNonPublic;
1682 Fields = new FieldInfo [Count];
1683 public_fields.CopyTo (Fields, 0);
1684 non_public_fields.CopyTo (Fields, CountPublic);
1687 struct_field_hash = new Hashtable ();
1688 field_hash = new Hashtable ();
1691 StructFields = new TypeInfo [Count];
1692 StructInfo[] sinfo = new StructInfo [Count];
1696 for (int i = 0; i < Count; i++) {
1697 FieldInfo field = (FieldInfo) Fields [i];
1699 sinfo [i] = GetStructInfo (field.FieldType);
1700 if (sinfo [i] == null)
1701 field_hash.Add (field.Name, ++Length);
1702 else if (sinfo [i].InTransit) {
1703 Report.Error (523, String.Format (
1704 "Struct member '{0}.{1}' of type '{2}' causes " +
1705 "a cycle in the structure layout",
1706 type, field.Name, sinfo [i].Type));
1714 TotalLength = Length + 1;
1715 for (int i = 0; i < Count; i++) {
1716 FieldInfo field = (FieldInfo) Fields [i];
1718 if (sinfo [i] == null)
1721 field_hash.Add (field.Name, TotalLength);
1723 HasStructFields = true;
1724 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1725 struct_field_hash.Add (field.Name, StructFields [i]);
1726 TotalLength += sinfo [i].TotalLength;
1730 public int this [string name] {
1732 if (field_hash.Contains (name))
1733 return (int) field_hash [name];
1739 public TypeInfo GetStructField (string name)
1741 return (TypeInfo) struct_field_hash [name];
1744 public static StructInfo GetStructInfo (Type type)
1746 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1747 TypeManager.IsBuiltinType (type))
1750 StructInfo info = (StructInfo) field_type_hash [type];
1754 return new StructInfo (type);
1757 public static StructInfo GetStructInfo (TypeContainer tc)
1759 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1763 return new StructInfo (tc.TypeBuilder);
1769 // This is used by the flow analysis code to store information about a single local variable
1770 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1771 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1772 // it has been assigned or not, but for structs, we need this information for each of its fields.
1774 public class VariableInfo {
1775 public readonly string Name;
1776 public readonly TypeInfo TypeInfo;
1779 // The bit offset of this variable in the flow vector.
1781 public readonly int Offset;
1784 // The number of bits this variable needs in the flow vector.
1785 // The first bit always specifies whether the variable as such has been assigned while
1786 // the remaining bits contain this information for each of a struct's fields.
1788 public readonly int Length;
1791 // If this is a parameter of local variable.
1793 public readonly bool IsParameter;
1795 public readonly LocalInfo LocalInfo;
1796 public readonly int ParameterIndex;
1798 readonly VariableInfo Parent;
1799 VariableInfo[] sub_info;
1801 protected VariableInfo (string name, Type type, int offset)
1804 this.Offset = offset;
1805 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1807 Length = TypeInfo.TotalLength;
1812 protected VariableInfo (VariableInfo parent, TypeInfo type)
1814 this.Name = parent.Name;
1815 this.TypeInfo = type;
1816 this.Offset = parent.Offset + type.Offset;
1817 this.Parent = parent;
1818 this.Length = type.TotalLength;
1820 this.IsParameter = parent.IsParameter;
1821 this.LocalInfo = parent.LocalInfo;
1822 this.ParameterIndex = parent.ParameterIndex;
1827 protected void Initialize ()
1829 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1830 if (sub_fields != null) {
1831 sub_info = new VariableInfo [sub_fields.Length];
1832 for (int i = 0; i < sub_fields.Length; i++) {
1833 if (sub_fields [i] != null)
1834 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1837 sub_info = new VariableInfo [0];
1840 public VariableInfo (LocalInfo local_info, int offset)
1841 : this (local_info.Name, local_info.VariableType, offset)
1843 this.LocalInfo = local_info;
1844 this.IsParameter = false;
1847 public VariableInfo (string name, Type type, int param_idx, int offset)
1848 : this (name, type, offset)
1850 this.ParameterIndex = param_idx;
1851 this.IsParameter = true;
1854 public bool IsAssigned (EmitContext ec)
1856 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1859 public bool IsAssigned (EmitContext ec, Location loc)
1861 if (IsAssigned (ec))
1864 Report.Error (165, loc,
1865 "Use of unassigned local variable `" + Name + "'");
1866 ec.CurrentBranching.SetAssigned (this);
1870 public bool IsAssigned (MyBitVector vector)
1872 if (vector [Offset])
1875 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1876 if (vector [parent.Offset])
1879 // Return unless this is a struct.
1880 if (!TypeInfo.IsStruct)
1883 // Ok, so each field must be assigned.
1884 for (int i = 0; i < TypeInfo.Length; i++) {
1885 if (!vector [Offset + i + 1])
1889 // Ok, now check all fields which are structs.
1890 for (int i = 0; i < sub_info.Length; i++) {
1891 VariableInfo sinfo = sub_info [i];
1895 if (!sinfo.IsAssigned (vector))
1899 vector [Offset] = true;
1903 public void SetAssigned (EmitContext ec)
1905 if (ec.DoFlowAnalysis)
1906 ec.CurrentBranching.SetAssigned (this);
1909 public void SetAssigned (MyBitVector vector)
1911 vector [Offset] = true;
1914 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1916 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1919 Report.Error (170, loc,
1920 "Use of possibly unassigned field `" + name + "'");
1921 ec.CurrentBranching.SetFieldAssigned (this, name);
1925 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1927 int field_idx = TypeInfo.GetFieldIndex (field_name);
1932 return vector [Offset + field_idx];
1935 public void SetFieldAssigned (EmitContext ec, string name)
1937 if (ec.DoFlowAnalysis)
1938 ec.CurrentBranching.SetFieldAssigned (this, name);
1941 public void SetFieldAssigned (MyBitVector vector, string field_name)
1943 int field_idx = TypeInfo.GetFieldIndex (field_name);
1948 vector [Offset + field_idx] = true;
1951 public VariableInfo GetSubStruct (string name)
1953 TypeInfo type = TypeInfo.GetSubStruct (name);
1958 return new VariableInfo (this, type);
1961 public override string ToString ()
1963 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1964 Name, TypeInfo, Offset, Length, IsParameter);
1969 // This is used by the flow code to hold the `layout' of the flow vector for
1970 // all locals and all parameters (ie. we create one instance of this class for the
1971 // locals and another one for the params).
1973 public class VariableMap {
1975 // The number of variables in the map.
1977 public readonly int Count;
1980 // Total length of the flow vector for this map.
1982 public readonly int Length;
1986 public VariableMap (InternalParameters ip)
1988 Count = ip != null ? ip.Count : 0;
1990 // Dont bother allocating anything!
1996 for (int i = 0; i < Count; i++) {
1997 Parameter.Modifier mod = ip.ParameterModifier (i);
1999 if ((mod & Parameter.Modifier.OUT) == 0)
2002 // Dont allocate till we find an out var.
2004 map = new VariableInfo [Count];
2006 map [i] = new VariableInfo (ip.ParameterName (i),
2007 TypeManager.GetElementType (ip.ParameterType (i)), i, Length);
2009 Length += map [i].Length;
2013 public VariableMap (LocalInfo[] locals)
2014 : this (null, locals)
2017 public VariableMap (VariableMap parent, LocalInfo[] locals)
2019 int offset = 0, start = 0;
2020 if (parent != null && parent.map != null) {
2021 offset = parent.Length;
2022 start = parent.Count;
2025 Count = locals.Length + start;
2030 map = new VariableInfo [Count];
2033 if (parent != null && parent.map != null) {
2034 parent.map.CopyTo (map, 0);
2037 for (int i = start; i < Count; i++) {
2038 LocalInfo li = locals [i-start];
2040 if (li.VariableType == null)
2043 map [i] = li.VariableInfo = new VariableInfo (li, Length);
2044 Length += map [i].Length;
2049 // Returns the VariableInfo for variable @index or null if we don't need to
2050 // compute assignment info for this variable.
2052 public VariableInfo this [int index] {
2061 public override string ToString ()
2063 return String.Format ("VariableMap ({0}:{1})", Count, Length);
2068 // This is a special bit vector which can inherit from another bit vector doing a
2069 // copy-on-write strategy. The inherited vector may have a smaller size than the
2072 public class MyBitVector {
2073 public readonly int Count;
2074 public readonly MyBitVector InheritsFrom;
2079 public MyBitVector (int Count)
2080 : this (null, Count)
2083 public MyBitVector (MyBitVector InheritsFrom, int Count)
2085 this.InheritsFrom = InheritsFrom;
2090 // Checks whether this bit vector has been modified. After setting this to true,
2091 // we won't use the inherited vector anymore, but our own copy of it.
2093 public bool IsDirty {
2100 initialize_vector ();
2105 // Get/set bit `index' in the bit vector.
2107 public bool this [int index]
2111 throw new ArgumentOutOfRangeException ();
2113 // We're doing a "copy-on-write" strategy here; as long
2114 // as nobody writes to the array, we can use our parent's
2115 // copy instead of duplicating the vector.
2118 return vector [index];
2119 else if (InheritsFrom != null) {
2120 BitArray inherited = InheritsFrom.Vector;
2122 if (index < inherited.Count)
2123 return inherited [index];
2132 throw new ArgumentOutOfRangeException ();
2134 // Only copy the vector if we're actually modifying it.
2136 if (this [index] != value) {
2137 initialize_vector ();
2139 vector [index] = value;
2145 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
2146 // copy of the bit vector.
2148 public static explicit operator BitArray (MyBitVector vector)
2150 vector.initialize_vector ();
2151 return vector.Vector;
2155 // Performs an `or' operation on the bit vector. The `new_vector' may have a
2156 // different size than the current one.
2158 public void Or (MyBitVector new_vector)
2160 BitArray new_array = new_vector.Vector;
2162 initialize_vector ();
2165 if (vector.Count < new_array.Count)
2166 upper = vector.Count;
2168 upper = new_array.Count;
2170 for (int i = 0; i < upper; i++)
2171 vector [i] = vector [i] | new_array [i];
2175 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
2176 // a different size than the current one.
2178 public void And (MyBitVector new_vector)
2180 BitArray new_array = new_vector.Vector;
2182 initialize_vector ();
2185 if (vector.Count < new_array.Count)
2186 lower = upper = vector.Count;
2188 lower = new_array.Count;
2189 upper = vector.Count;
2192 for (int i = 0; i < lower; i++)
2193 vector [i] = vector [i] & new_array [i];
2195 for (int i = lower; i < upper; i++)
2199 public static void And (ref MyBitVector target, MyBitVector vector)
2202 target.And (vector);
2204 target = vector.Clone ();
2207 public static void Or (ref MyBitVector target, MyBitVector vector)
2212 target = vector.Clone ();
2216 // This does a deep copy of the bit vector.
2218 public MyBitVector Clone ()
2220 MyBitVector retval = new MyBitVector (Count);
2222 retval.Vector = Vector;
2231 else if (!is_dirty && (InheritsFrom != null))
2232 return InheritsFrom.Vector;
2234 initialize_vector ();
2240 initialize_vector ();
2242 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
2243 vector [i] = value [i];
2247 void initialize_vector ()
2252 vector = new BitArray (Count, false);
2253 if (InheritsFrom != null)
2254 Vector = InheritsFrom.Vector;
2259 public override string ToString ()
2261 StringBuilder sb = new StringBuilder ("{");
2263 BitArray vector = Vector;
2266 for (int i = 0; i < vector.Count; i++) {
2267 sb.Append (vector [i] ? "1" : "0");
2271 return sb.ToString ();