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, reachable;
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 FlowReturns Reachable {
97 get { return reachable; }
100 public Reachability (FlowReturns returns, FlowReturns breaks,
101 FlowReturns throws, FlowReturns barrier)
103 this.returns = returns;
104 this.breaks = breaks;
105 this.throws = throws;
106 this.barrier = barrier;
111 public Reachability Clone ()
113 Reachability cloned = new Reachability (returns, breaks, throws, barrier);
114 cloned.reachable = reachable;
119 // Performs an `And' operation on the FlowReturns status
120 // (for instance, a block only returns Always if all its siblings
123 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
125 if (a == FlowReturns.Undefined)
129 case FlowReturns.Never:
130 if (b == FlowReturns.Never)
131 return FlowReturns.Never;
133 return FlowReturns.Sometimes;
135 case FlowReturns.Sometimes:
136 return FlowReturns.Sometimes;
138 case FlowReturns.Always:
139 if (b == FlowReturns.Always)
140 return FlowReturns.Always;
142 return FlowReturns.Sometimes;
145 throw new ArgumentException ();
149 public static FlowReturns OrFlowReturns (FlowReturns a, FlowReturns b)
151 if (a == FlowReturns.Undefined)
155 case FlowReturns.Never:
158 case FlowReturns.Sometimes:
159 if (b == FlowReturns.Always)
160 return FlowReturns.Always;
162 return FlowReturns.Sometimes;
164 case FlowReturns.Always:
165 return FlowReturns.Always;
168 throw new ArgumentException ();
172 public static void And (ref Reachability a, Reachability b, bool do_break)
180 // `break' does not "break" in a Switch or a LoopBlock
182 bool a_breaks = do_break && a.AlwaysBreaks;
183 bool b_breaks = do_break && b.AlwaysBreaks;
185 bool a_has_barrier, b_has_barrier;
188 // This is the normal case: the code following a barrier
189 // cannot be reached.
191 a_has_barrier = a.AlwaysHasBarrier;
192 b_has_barrier = b.AlwaysHasBarrier;
195 // Special case for Switch and LoopBlocks: we can reach the
196 // code after the barrier via the `break'.
198 a_has_barrier = !a.AlwaysBreaks && a.AlwaysHasBarrier;
199 b_has_barrier = !b.AlwaysBreaks && b.AlwaysHasBarrier;
202 bool a_unreachable = a_breaks || a.AlwaysThrows || a_has_barrier;
203 bool b_unreachable = b_breaks || b.AlwaysThrows || b_has_barrier;
206 // Do all code paths always return ?
208 if (a.AlwaysReturns) {
209 if (b.AlwaysReturns || b_unreachable)
210 a.returns = FlowReturns.Always;
212 a.returns = FlowReturns.Sometimes;
213 } else if (b.AlwaysReturns) {
214 if (a.AlwaysReturns || a_unreachable)
215 a.returns = FlowReturns.Always;
217 a.returns = FlowReturns.Sometimes;
218 } else if (!a.MayReturn) {
220 a.returns = FlowReturns.Sometimes;
222 a.returns = FlowReturns.Never;
223 } else if (!b.MayReturn) {
225 a.returns = FlowReturns.Sometimes;
227 a.returns = FlowReturns.Never;
230 a.breaks = AndFlowReturns (a.breaks, b.breaks);
231 a.throws = AndFlowReturns (a.throws, b.throws);
232 a.barrier = AndFlowReturns (a.barrier, b.barrier);
234 a.reachable = AndFlowReturns (a.reachable, b.reachable);
237 public void Or (Reachability b)
239 returns = OrFlowReturns (returns, b.returns);
240 breaks = OrFlowReturns (breaks, b.breaks);
241 throws = OrFlowReturns (throws, b.throws);
242 barrier = OrFlowReturns (barrier, b.barrier);
247 public static Reachability Never ()
249 return new Reachability (
250 FlowReturns.Never, FlowReturns.Never,
251 FlowReturns.Never, FlowReturns.Never);
256 if ((returns == FlowReturns.Always) || (breaks == FlowReturns.Always) ||
257 (throws == FlowReturns.Always) || (barrier == FlowReturns.Always))
258 reachable = FlowReturns.Never;
259 else if ((returns == FlowReturns.Never) && (breaks == FlowReturns.Never) &&
260 (throws == FlowReturns.Never) && (barrier == FlowReturns.Never))
261 reachable = FlowReturns.Always;
263 reachable = 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;
308 public void SetReturnsSometimes ()
310 returns = FlowReturns.Sometimes;
314 public void SetBreaks ()
316 breaks = FlowReturns.Always;
320 public void ResetBreaks ()
322 breaks = FlowReturns.Never;
326 public void SetThrows ()
328 throws = FlowReturns.Always;
332 public void SetBarrier ()
334 barrier = FlowReturns.Always;
338 static string ShortName (FlowReturns returns)
341 case FlowReturns.Never:
343 case FlowReturns.Sometimes:
350 public override string ToString ()
352 return String.Format ("[{0}:{1}:{2}:{3}:{4}]",
353 ShortName (returns), ShortName (breaks),
354 ShortName (throws), ShortName (barrier),
355 ShortName (reachable));
359 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
362 case BranchingType.Exception:
363 return new FlowBranchingException (parent, block, loc);
365 case BranchingType.Switch:
366 return new FlowBranchingBlock (parent, type, SiblingType.SwitchSection, block, loc);
368 case BranchingType.SwitchSection:
369 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
371 case BranchingType.Block:
372 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
375 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
380 // The type of this flow branching.
382 public readonly BranchingType Type;
385 // The block this branching is contained in. This may be null if it's not
386 // a top-level block and it doesn't declare any local variables.
388 public readonly Block Block;
391 // The parent of this branching or null if this is the top-block.
393 public readonly FlowBranching Parent;
396 // Start-Location of this flow branching.
398 public readonly Location Location;
401 // If this is an infinite loop.
403 public bool Infinite;
408 VariableMap param_map, local_map;
410 static int next_id = 0;
414 // The vector contains a BitArray with information about which local variables
415 // and parameters are already initialized at the current code position.
417 public class UsageVector {
419 // The type of this branching.
421 public readonly SiblingType Type;
424 // Start location of this branching.
426 public readonly Location Location;
429 // If this is true, then the usage vector has been modified and must be
430 // merged when we're done with this branching.
435 // The number of parameters in this block.
437 public readonly int CountParameters;
440 // The number of locals in this block.
442 public readonly int CountLocals;
445 // If not null, then we inherit our state from this vector and do a
446 // copy-on-write. If null, then we're the first sibling in a top-level
447 // block and inherit from the empty vector.
449 public readonly UsageVector InheritsFrom;
452 // This is used to construct a list of UsageVector's.
454 public UsageVector Next;
459 MyBitVector locals, parameters;
460 Reachability reachability;
462 static int next_id = 0;
466 // Normally, you should not use any of these constructors.
468 public UsageVector (SiblingType type, UsageVector parent, Location loc, int num_params, int num_locals)
472 this.InheritsFrom = parent;
473 this.CountParameters = num_params;
474 this.CountLocals = num_locals;
476 if (parent != null) {
478 locals = new MyBitVector (parent.locals, CountLocals);
481 parameters = new MyBitVector (parent.parameters, num_params);
483 reachability = parent.Reachability.Clone ();
486 locals = new MyBitVector (null, CountLocals);
489 parameters = new MyBitVector (null, num_params);
491 reachability = Reachability.Never ();
497 public UsageVector (SiblingType type, UsageVector parent, Location loc)
498 : this (type, parent, loc, parent.CountParameters, parent.CountLocals)
501 public UsageVector (MyBitVector parameters, MyBitVector locals,
502 Reachability reachability, Location loc)
504 this.Type = SiblingType.Block;
507 this.reachability = reachability;
508 this.parameters = parameters;
509 this.locals = locals;
515 // This does a deep copy of the usage vector.
517 public UsageVector Clone ()
519 UsageVector retval = new UsageVector (Type, null, Location, CountParameters, CountLocals);
521 if (retval.locals != null)
522 retval.locals = locals.Clone ();
524 if (parameters != null)
525 retval.parameters = parameters.Clone ();
527 retval.reachability = reachability.Clone ();
532 public bool IsAssigned (VariableInfo var)
534 if (!var.IsParameter && Reachability.AlwaysBreaks)
537 return var.IsAssigned (var.IsParameter ? parameters : locals);
540 public void SetAssigned (VariableInfo var)
542 if (!var.IsParameter && Reachability.AlwaysBreaks)
546 var.SetAssigned (var.IsParameter ? parameters : locals);
549 public bool IsFieldAssigned (VariableInfo var, string name)
551 if (!var.IsParameter && Reachability.AlwaysBreaks)
554 return var.IsFieldAssigned (var.IsParameter ? parameters : locals, name);
557 public void SetFieldAssigned (VariableInfo var, string name)
559 if (!var.IsParameter && Reachability.AlwaysBreaks)
563 var.SetFieldAssigned (var.IsParameter ? parameters : locals, name);
566 public Reachability Reachability {
572 public void Return ()
574 if (!reachability.IsUnreachable) {
576 reachability.SetReturns ();
582 if (!reachability.IsUnreachable) {
584 reachability.SetBreaks ();
590 if (!reachability.IsUnreachable) {
592 reachability.SetThrows ();
598 if (!reachability.IsUnreachable) {
600 reachability.SetBarrier ();
605 // Merges a child branching.
607 public UsageVector MergeChild (FlowBranching branching)
609 UsageVector result = branching.Merge ();
611 Report.Debug (2, " MERGING CHILD", this, IsDirty,
612 result.ParameterVector, result.LocalVector,
613 result.Reachability, reachability, Type);
615 Reachability new_r = result.Reachability;
617 if (branching.Type == BranchingType.Loop) {
618 bool may_leave_loop = new_r.MayBreak;
619 new_r.ResetBreaks ();
621 if (branching.Infinite && !may_leave_loop) {
622 if (new_r.Returns == FlowReturns.Sometimes) {
623 // If we're an infinite loop and do not break,
624 // the code after the loop can never be reached.
625 // However, if we may return from the loop,
626 // then we do always return (or stay in the
633 if (new_r.Returns == FlowReturns.Always) {
634 // We're either finite or we may leave the loop.
635 new_r.SetReturnsSometimes ();
638 } else if (branching.Type == BranchingType.Switch)
639 new_r.ResetBreaks ();
642 // We've now either reached the point after the branching or we will
643 // never get there since we always return or always throw an exception.
645 // If we can reach the point after the branching, mark all locals and
646 // parameters as initialized which have been initialized in all branches
647 // we need to look at (see above).
650 if ((Type == SiblingType.SwitchSection) && !new_r.IsUnreachable) {
651 Report.Error (163, Location,
652 "Control cannot fall through from one " +
653 "case label to another");
657 if (locals != null && result.LocalVector != null)
658 locals.Or (result.LocalVector);
660 if (result.ParameterVector != null)
661 parameters.Or (result.ParameterVector);
663 reachability.Or (new_r);
665 Report.Debug (2, " MERGING CHILD DONE", this, result,
666 new_r, reachability);
673 protected void MergeFinally (FlowBranching branching, UsageVector f_origins,
674 MyBitVector f_params)
676 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
677 MyBitVector temp_params = f_params.Clone ();
678 temp_params.Or (vector.Parameters);
682 public void MergeFinally (FlowBranching branching, UsageVector f_vector,
683 UsageVector f_origins)
685 if (parameters != null) {
686 if (f_vector != null) {
687 MergeFinally (branching, f_origins, f_vector.Parameters);
688 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
690 MergeFinally (branching, f_origins, parameters);
693 if (f_vector != null && f_vector.LocalVector != null)
694 MyBitVector.Or (ref locals, f_vector.LocalVector);
698 // Tells control flow analysis that the current code position may be reached with
699 // a forward jump from any of the origins listed in `origin_vectors' which is a
700 // list of UsageVectors.
702 // This is used when resolving forward gotos - in the following example, the
703 // variable `a' is uninitialized in line 8 becase this line may be reached via
704 // the goto in line 4:
714 // 8 Console.WriteLine (a);
717 public void MergeJumpOrigins (ICollection origin_vectors)
719 Report.Debug (1, " MERGING JUMP ORIGINS", this);
721 reachability = Reachability.Never ();
723 if (origin_vectors == null)
728 foreach (UsageVector vector in origin_vectors) {
729 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
732 if (locals != null && vector.Locals != null)
733 locals.Or (vector.locals);
735 if (parameters != null)
736 parameters.Or (vector.parameters);
739 if (locals != null && vector.Locals != null)
740 locals.And (vector.locals);
741 if (parameters != null)
742 parameters.And (vector.parameters);
745 Reachability.And (ref reachability, vector.Reachability, true);
748 Report.Debug (1, " MERGING JUMP ORIGINS DONE", this);
752 // This is used at the beginning of a finally block if there were
753 // any return statements in the try block or one of the catch blocks.
755 public void MergeFinallyOrigins (UsageVector f_origins)
757 Report.Debug (1, " MERGING FINALLY ORIGIN", this);
759 reachability = Reachability.Never ();
761 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
762 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
764 if (parameters != null)
765 parameters.And (vector.parameters);
767 Reachability.And (ref reachability, vector.Reachability, true);
770 Report.Debug (1, " MERGING FINALLY ORIGIN DONE", this);
773 public void CheckOutParameters (FlowBranching branching)
775 if (parameters != null)
776 branching.CheckOutParameters (parameters, branching.Location);
780 // Performs an `or' operation on the locals and the parameters.
782 public void Or (UsageVector new_vector)
785 locals.Or (new_vector.locals);
786 if (parameters != null)
787 parameters.Or (new_vector.parameters);
791 // Performs an `and' operation on the locals.
793 public void AndLocals (UsageVector new_vector)
796 locals.And (new_vector.locals);
799 public bool HasParameters {
801 return parameters != null;
805 public bool HasLocals {
807 return locals != null;
812 // Returns a deep copy of the parameters.
814 public MyBitVector Parameters {
816 if (parameters != null)
817 return parameters.Clone ();
824 // Returns a deep copy of the locals.
826 public MyBitVector Locals {
829 return locals.Clone ();
835 public MyBitVector ParameterVector {
841 public MyBitVector LocalVector {
851 public override string ToString ()
853 StringBuilder sb = new StringBuilder ();
855 sb.Append ("Vector (");
862 sb.Append (reachability);
863 if (parameters != null) {
865 sb.Append (parameters);
871 return sb.ToString ();
876 // Creates a new flow branching which is contained in `parent'.
877 // You should only pass non-null for the `block' argument if this block
878 // introduces any new variables - in this case, we need to create a new
879 // usage vector with a different size than our parent's one.
881 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
882 Block block, Location loc)
892 param_map = Block.ParameterMap;
893 local_map = Block.LocalMap;
895 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
896 vector = new UsageVector (stype, parent_vector, loc, param_map.Length, local_map.Length);
900 param_map = Parent.param_map;
901 local_map = Parent.local_map;
902 vector = new UsageVector (stype, Parent.CurrentUsageVector, loc);
908 public abstract UsageVector CurrentUsageVector {
913 // Creates a sibling of the current usage vector.
915 public virtual void CreateSibling (SiblingType type)
917 AddSibling (new UsageVector (type, Parent.CurrentUsageVector, Location));
919 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
922 protected abstract void AddSibling (UsageVector uv);
924 public abstract void Label (ArrayList origin_vectors);
927 // Check whether all `out' parameters have been assigned.
929 public void CheckOutParameters (MyBitVector parameters, Location loc)
931 for (int i = 0; i < param_map.Count; i++) {
932 VariableInfo var = param_map [i];
937 if (var.IsAssigned (parameters))
940 Report.Error (177, loc, "The out parameter `" +
941 var.Name + "' must be " +
942 "assigned before control leave the current method.");
946 protected UsageVector Merge (UsageVector sibling_list)
948 if (sibling_list.Next == null)
951 MyBitVector locals = null;
952 MyBitVector parameters = null;
954 Reachability reachability = null;
956 Report.Debug (2, " MERGING SIBLINGS", this, Name);
958 for (UsageVector child = sibling_list; child != null; child = child.Next) {
959 bool do_break = (Type != BranchingType.Switch) &&
960 (Type != BranchingType.Loop);
962 Report.Debug (2, " MERGING SIBLING ", child,
963 child.ParameterVector, child.LocalVector,
964 reachability, child.Reachability, do_break);
966 Reachability.And (ref reachability, child.Reachability, do_break);
968 // A local variable is initialized after a flow branching if it
969 // has been initialized in all its branches which do neither
970 // always return or always throw an exception.
972 // If a branch may return, but does not always return, then we
973 // can treat it like a never-returning branch here: control will
974 // only reach the code position after the branching if we did not
977 // It's important to distinguish between always and sometimes
978 // returning branches here:
981 // 2 if (something) {
985 // 6 Console.WriteLine (a);
987 // The if block in lines 3-4 always returns, so we must not look
988 // at the initialization of `a' in line 4 - thus it'll still be
989 // uninitialized in line 6.
991 // On the other hand, the following is allowed:
998 // 6 Console.WriteLine (a);
1000 // Here, `a' is initialized in line 3 and we must not look at
1001 // line 5 since it always returns.
1003 bool do_break_2 = (child.Type != SiblingType.Block) &&
1004 (child.Type != SiblingType.SwitchSection);
1005 bool always_throws = (child.Type != SiblingType.Try) &&
1006 child.Reachability.AlwaysThrows;
1007 bool unreachable = always_throws ||
1008 (do_break_2 && child.Reachability.AlwaysBreaks) ||
1009 child.Reachability.AlwaysReturns ||
1010 child.Reachability.AlwaysHasBarrier;
1012 Report.Debug (2, " MERGING SIBLING #1", reachability,
1013 Type, child.Type, child.Reachability.IsUnreachable,
1014 do_break_2, always_throws, unreachable);
1016 if (!unreachable && (child.LocalVector != null))
1017 MyBitVector.And (ref locals, child.LocalVector);
1019 // An `out' parameter must be assigned in all branches which do
1020 // not always throw an exception.
1021 if ((child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
1022 MyBitVector.And (ref parameters, child.ParameterVector);
1024 Report.Debug (2, " MERGING SIBLING #2", parameters, locals);
1027 if (reachability == null)
1028 reachability = Reachability.Never ();
1030 Report.Debug (2, " MERGING SIBLINGS DONE", parameters, locals,
1031 reachability, Infinite);
1033 return new UsageVector (parameters, locals, reachability, Location);
1036 protected abstract UsageVector Merge ();
1039 // Merge a child branching.
1041 public UsageVector MergeChild (FlowBranching child)
1043 return CurrentUsageVector.MergeChild (child);
1047 // Does the toplevel merging.
1049 public Reachability MergeTopBlock ()
1051 if ((Type != BranchingType.Block) || (Block == null))
1052 throw new NotSupportedException ();
1054 UsageVector vector = new UsageVector (
1055 SiblingType.Conditional, null, Location, param_map.Length, local_map.Length);
1057 UsageVector result = vector.MergeChild (this);
1059 Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1061 if (vector.Reachability.Throws != FlowReturns.Always)
1062 CheckOutParameters (vector.Parameters, Location);
1064 return result.Reachability;
1068 // Checks whether we're in a `try' block.
1070 public virtual bool InTryOrCatch (bool is_return)
1072 if ((Block != null) && Block.IsDestructor)
1074 else if (!is_return &&
1075 ((Type == BranchingType.Loop) || (Type == BranchingType.Switch)))
1077 else if (Parent != null)
1078 return Parent.InTryOrCatch (is_return);
1084 // Checks whether we're in a `catch' block.
1086 public virtual bool InCatch ()
1089 return Parent.InCatch ();
1095 // Checks whether we're in a `finally' block.
1097 public virtual bool InFinally (bool is_return)
1100 ((Type == BranchingType.Loop) || (Type == BranchingType.Switch)))
1102 else if (Parent != null)
1103 return Parent.InFinally (is_return);
1108 public virtual bool InLoop ()
1110 if (Type == BranchingType.Loop)
1112 else if (Parent != null)
1113 return Parent.InLoop ();
1118 public virtual bool InSwitch ()
1120 if (Type == BranchingType.Switch)
1122 else if (Parent != null)
1123 return Parent.InSwitch ();
1128 public virtual bool BreakCrossesTryCatchBoundary ()
1130 if ((Type == BranchingType.Loop) || (Type == BranchingType.Switch))
1132 else if (Parent != null)
1133 return Parent.BreakCrossesTryCatchBoundary ();
1138 public virtual void AddFinallyVector (UsageVector vector)
1141 Parent.AddFinallyVector (vector);
1142 else if ((Block == null) || !Block.IsDestructor)
1143 throw new NotSupportedException ();
1146 public bool IsAssigned (VariableInfo vi)
1148 return CurrentUsageVector.IsAssigned (vi);
1151 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1153 if (CurrentUsageVector.IsAssigned (vi))
1156 return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1159 public void SetAssigned (VariableInfo vi)
1161 CurrentUsageVector.SetAssigned (vi);
1164 public void SetFieldAssigned (VariableInfo vi, string name)
1166 CurrentUsageVector.SetFieldAssigned (vi, name);
1169 public override string ToString ()
1171 StringBuilder sb = new StringBuilder ();
1172 sb.Append (GetType ());
1178 if (Block != null) {
1180 sb.Append (Block.ID);
1182 sb.Append (Block.StartLocation);
1185 // sb.Append (Siblings.Length);
1186 // sb.Append (" - ");
1187 sb.Append (CurrentUsageVector);
1189 return sb.ToString ();
1192 public string Name {
1194 return String.Format ("{0} ({1}:{2}:{3})",
1195 GetType (), id, Type, Location);
1200 public class FlowBranchingBlock : FlowBranching
1202 UsageVector sibling_list = null;
1204 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
1205 SiblingType stype, Block block, Location loc)
1206 : base (parent, type, stype, block, loc)
1209 public override UsageVector CurrentUsageVector {
1210 get { return sibling_list; }
1213 protected override void AddSibling (UsageVector sibling)
1215 sibling.Next = sibling_list;
1216 sibling_list = sibling;
1219 public override void Label (ArrayList origin_vectors)
1221 if (!CurrentUsageVector.Reachability.IsUnreachable) {
1222 if (origin_vectors == null)
1223 origin_vectors = new ArrayList (1);
1224 origin_vectors.Add (CurrentUsageVector.Clone ());
1227 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1230 protected override UsageVector Merge ()
1232 return Merge (sibling_list);
1236 public class FlowBranchingException : FlowBranching
1238 UsageVector current_vector;
1239 UsageVector catch_vectors;
1240 UsageVector finally_vector;
1241 UsageVector finally_origins;
1244 public FlowBranchingException (FlowBranching parent, Block block, Location loc)
1245 : base (parent, BranchingType.Exception, SiblingType.Try, block, loc)
1248 protected override void AddSibling (UsageVector sibling)
1250 if (sibling.Type == SiblingType.Try) {
1251 sibling.Next = catch_vectors;
1252 catch_vectors = sibling;
1254 } else if (sibling.Type == SiblingType.Catch) {
1255 sibling.Next = catch_vectors;
1256 catch_vectors = sibling;
1258 } else if (sibling.Type == SiblingType.Finally) {
1259 sibling.MergeFinallyOrigins (finally_origins);
1260 finally_vector = sibling;
1263 throw new InvalidOperationException ();
1265 current_vector = sibling;
1268 public override UsageVector CurrentUsageVector {
1269 get { return current_vector; }
1272 public override bool InTryOrCatch (bool is_return)
1274 return finally_vector == null;
1277 public override bool InCatch ()
1279 return !in_try && (finally_vector == null);
1282 public override bool InFinally (bool is_return)
1284 return finally_vector != null;
1287 public override bool BreakCrossesTryCatchBoundary ()
1292 public override void AddFinallyVector (UsageVector vector)
1294 vector = vector.Clone ();
1295 vector.Next = finally_origins;
1296 finally_origins = vector;
1299 public override void Label (ArrayList origin_vectors)
1301 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1304 protected override UsageVector Merge ()
1306 UsageVector vector = Merge (catch_vectors);
1308 vector.MergeFinally (this, finally_vector, finally_origins);
1315 // This is used by the flow analysis code to keep track of the type of local variables
1318 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1319 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1320 // you can only assign the whole variable as such.
1322 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1323 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1324 // one bit for each of its fields.
1326 // This class computes this `layout' for each type.
1328 public class TypeInfo
1330 public readonly Type Type;
1333 // Total number of bits a variable of this type consumes in the flow vector.
1335 public readonly int TotalLength;
1338 // Number of bits the simple fields of a variable of this type consume
1339 // in the flow vector.
1341 public readonly int Length;
1344 // This is only used by sub-structs.
1346 public readonly int Offset;
1349 // If this is a struct.
1351 public readonly bool IsStruct;
1354 // If this is a struct, all fields which are structs theirselves.
1356 public TypeInfo[] SubStructInfo;
1358 protected readonly StructInfo struct_info;
1359 private static Hashtable type_hash = new Hashtable ();
1361 public static TypeInfo GetTypeInfo (Type type)
1363 TypeInfo info = (TypeInfo) type_hash [type];
1367 info = new TypeInfo (type);
1368 type_hash.Add (type, info);
1372 public static TypeInfo GetTypeInfo (TypeContainer tc)
1374 TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1378 info = new TypeInfo (tc);
1379 type_hash.Add (tc.TypeBuilder, info);
1383 private TypeInfo (Type type)
1387 struct_info = StructInfo.GetStructInfo (type);
1388 if (struct_info != null) {
1389 Length = struct_info.Length;
1390 TotalLength = struct_info.TotalLength;
1391 SubStructInfo = struct_info.StructFields;
1400 private TypeInfo (TypeContainer tc)
1402 this.Type = tc.TypeBuilder;
1404 struct_info = StructInfo.GetStructInfo (tc);
1405 if (struct_info != null) {
1406 Length = struct_info.Length;
1407 TotalLength = struct_info.TotalLength;
1408 SubStructInfo = struct_info.StructFields;
1417 protected TypeInfo (StructInfo struct_info, int offset)
1419 this.struct_info = struct_info;
1420 this.Offset = offset;
1421 this.Length = struct_info.Length;
1422 this.TotalLength = struct_info.TotalLength;
1423 this.SubStructInfo = struct_info.StructFields;
1424 this.Type = struct_info.Type;
1425 this.IsStruct = true;
1428 public int GetFieldIndex (string name)
1430 if (struct_info == null)
1433 return struct_info [name];
1436 public TypeInfo GetSubStruct (string name)
1438 if (struct_info == null)
1441 return struct_info.GetStructField (name);
1445 // A struct's constructor must always assign all fields.
1446 // This method checks whether it actually does so.
1448 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1450 if (struct_info == null)
1454 for (int i = 0; i < struct_info.Count; i++) {
1455 FieldInfo field = struct_info.Fields [i];
1457 if (!branching.IsFieldAssigned (vi, field.Name)) {
1458 Report.Error (171, loc,
1459 "Field `" + TypeManager.CSharpName (Type) +
1460 "." + field.Name + "' must be fully initialized " +
1461 "before control leaves the constructor");
1469 public override string ToString ()
1471 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1472 Type, Offset, Length, TotalLength);
1475 protected class StructInfo {
1476 public readonly Type Type;
1477 public readonly FieldInfo[] Fields;
1478 public readonly TypeInfo[] StructFields;
1479 public readonly int Count;
1480 public readonly int CountPublic;
1481 public readonly int CountNonPublic;
1482 public readonly int Length;
1483 public readonly int TotalLength;
1484 public readonly bool HasStructFields;
1486 private static Hashtable field_type_hash = new Hashtable ();
1487 private Hashtable struct_field_hash;
1488 private Hashtable field_hash;
1490 protected bool InTransit = false;
1492 // Private constructor. To save memory usage, we only need to create one instance
1493 // of this class per struct type.
1494 private StructInfo (Type type)
1498 field_type_hash.Add (type, this);
1500 if (type is TypeBuilder) {
1501 TypeContainer tc = TypeManager.LookupTypeContainer (type);
1503 ArrayList fields = tc.Fields;
1505 ArrayList public_fields = new ArrayList ();
1506 ArrayList non_public_fields = new ArrayList ();
1508 if (fields != null) {
1509 foreach (Field field in fields) {
1510 if ((field.ModFlags & Modifiers.STATIC) != 0)
1512 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1513 public_fields.Add (field.FieldBuilder);
1515 non_public_fields.Add (field.FieldBuilder);
1519 CountPublic = public_fields.Count;
1520 CountNonPublic = non_public_fields.Count;
1521 Count = CountPublic + CountNonPublic;
1523 Fields = new FieldInfo [Count];
1524 public_fields.CopyTo (Fields, 0);
1525 non_public_fields.CopyTo (Fields, CountPublic);
1527 FieldInfo[] public_fields = type.GetFields (
1528 BindingFlags.Instance|BindingFlags.Public);
1529 FieldInfo[] non_public_fields = type.GetFields (
1530 BindingFlags.Instance|BindingFlags.NonPublic);
1532 CountPublic = public_fields.Length;
1533 CountNonPublic = non_public_fields.Length;
1534 Count = CountPublic + CountNonPublic;
1536 Fields = new FieldInfo [Count];
1537 public_fields.CopyTo (Fields, 0);
1538 non_public_fields.CopyTo (Fields, CountPublic);
1541 struct_field_hash = new Hashtable ();
1542 field_hash = new Hashtable ();
1545 StructFields = new TypeInfo [Count];
1546 StructInfo[] sinfo = new StructInfo [Count];
1550 for (int i = 0; i < Count; i++) {
1551 FieldInfo field = (FieldInfo) Fields [i];
1553 sinfo [i] = GetStructInfo (field.FieldType);
1554 if (sinfo [i] == null)
1555 field_hash.Add (field.Name, ++Length);
1556 else if (sinfo [i].InTransit) {
1557 Report.Error (523, String.Format (
1558 "Struct member '{0}.{1}' of type '{2}' causes " +
1559 "a cycle in the structure layout",
1560 type, field.Name, sinfo [i].Type));
1568 TotalLength = Length + 1;
1569 for (int i = 0; i < Count; i++) {
1570 FieldInfo field = (FieldInfo) Fields [i];
1572 if (sinfo [i] == null)
1575 field_hash.Add (field.Name, TotalLength);
1577 HasStructFields = true;
1578 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1579 struct_field_hash.Add (field.Name, StructFields [i]);
1580 TotalLength += sinfo [i].TotalLength;
1584 public int this [string name] {
1586 if (field_hash.Contains (name))
1587 return (int) field_hash [name];
1593 public TypeInfo GetStructField (string name)
1595 return (TypeInfo) struct_field_hash [name];
1598 public static StructInfo GetStructInfo (Type type)
1600 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1601 TypeManager.IsBuiltinType (type))
1604 StructInfo info = (StructInfo) field_type_hash [type];
1608 return new StructInfo (type);
1611 public static StructInfo GetStructInfo (TypeContainer tc)
1613 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1617 return new StructInfo (tc.TypeBuilder);
1623 // This is used by the flow analysis code to store information about a single local variable
1624 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1625 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1626 // it has been assigned or not, but for structs, we need this information for each of its fields.
1628 public class VariableInfo {
1629 public readonly string Name;
1630 public readonly TypeInfo TypeInfo;
1633 // The bit offset of this variable in the flow vector.
1635 public readonly int Offset;
1638 // The number of bits this variable needs in the flow vector.
1639 // The first bit always specifies whether the variable as such has been assigned while
1640 // the remaining bits contain this information for each of a struct's fields.
1642 public readonly int Length;
1645 // If this is a parameter of local variable.
1647 public readonly bool IsParameter;
1649 public readonly LocalInfo LocalInfo;
1650 public readonly int ParameterIndex;
1652 readonly VariableInfo Parent;
1653 VariableInfo[] sub_info;
1655 protected VariableInfo (string name, Type type, int offset)
1658 this.Offset = offset;
1659 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1661 Length = TypeInfo.TotalLength;
1666 protected VariableInfo (VariableInfo parent, TypeInfo type)
1668 this.Name = parent.Name;
1669 this.TypeInfo = type;
1670 this.Offset = parent.Offset + type.Offset;
1671 this.Parent = parent;
1672 this.Length = type.TotalLength;
1674 this.IsParameter = parent.IsParameter;
1675 this.LocalInfo = parent.LocalInfo;
1676 this.ParameterIndex = parent.ParameterIndex;
1681 protected void Initialize ()
1683 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1684 if (sub_fields != null) {
1685 sub_info = new VariableInfo [sub_fields.Length];
1686 for (int i = 0; i < sub_fields.Length; i++) {
1687 if (sub_fields [i] != null)
1688 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1691 sub_info = new VariableInfo [0];
1694 public VariableInfo (LocalInfo local_info, int offset)
1695 : this (local_info.Name, local_info.VariableType, offset)
1697 this.LocalInfo = local_info;
1698 this.IsParameter = false;
1701 public VariableInfo (string name, Type type, int param_idx, int offset)
1702 : this (name, type, offset)
1704 this.ParameterIndex = param_idx;
1705 this.IsParameter = true;
1708 public bool IsAssigned (EmitContext ec)
1710 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1713 public bool IsAssigned (EmitContext ec, Location loc)
1715 if (IsAssigned (ec))
1718 Report.Error (165, loc,
1719 "Use of unassigned local variable `" + Name + "'");
1720 ec.CurrentBranching.SetAssigned (this);
1724 public bool IsAssigned (MyBitVector vector)
1726 if (vector [Offset])
1729 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1730 if (vector [parent.Offset])
1733 // Return unless this is a struct.
1734 if (!TypeInfo.IsStruct)
1737 // Ok, so each field must be assigned.
1738 for (int i = 0; i < TypeInfo.Length; i++) {
1739 if (!vector [Offset + i + 1])
1743 // Ok, now check all fields which are structs.
1744 for (int i = 0; i < sub_info.Length; i++) {
1745 VariableInfo sinfo = sub_info [i];
1749 if (!sinfo.IsAssigned (vector))
1753 vector [Offset] = true;
1757 public void SetAssigned (EmitContext ec)
1759 if (ec.DoFlowAnalysis)
1760 ec.CurrentBranching.SetAssigned (this);
1763 public void SetAssigned (MyBitVector vector)
1765 vector [Offset] = true;
1768 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1770 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1773 Report.Error (170, loc,
1774 "Use of possibly unassigned field `" + name + "'");
1775 ec.CurrentBranching.SetFieldAssigned (this, name);
1779 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1781 int field_idx = TypeInfo.GetFieldIndex (field_name);
1786 return vector [Offset + field_idx];
1789 public void SetFieldAssigned (EmitContext ec, string name)
1791 if (ec.DoFlowAnalysis)
1792 ec.CurrentBranching.SetFieldAssigned (this, name);
1795 public void SetFieldAssigned (MyBitVector vector, string field_name)
1797 int field_idx = TypeInfo.GetFieldIndex (field_name);
1802 vector [Offset + field_idx] = true;
1805 public VariableInfo GetSubStruct (string name)
1807 TypeInfo type = TypeInfo.GetSubStruct (name);
1812 return new VariableInfo (this, type);
1815 public override string ToString ()
1817 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1818 Name, TypeInfo, Offset, Length, IsParameter);
1823 // This is used by the flow code to hold the `layout' of the flow vector for
1824 // all locals and all parameters (ie. we create one instance of this class for the
1825 // locals and another one for the params).
1827 public class VariableMap {
1829 // The number of variables in the map.
1831 public readonly int Count;
1834 // Total length of the flow vector for this map.
1836 public readonly int Length;
1840 public VariableMap (InternalParameters ip)
1842 Count = ip != null ? ip.Count : 0;
1844 // Dont bother allocating anything!
1850 for (int i = 0; i < Count; i++) {
1851 Parameter.Modifier mod = ip.ParameterModifier (i);
1853 if ((mod & Parameter.Modifier.OUT) == 0)
1856 // Dont allocate till we find an out var.
1858 map = new VariableInfo [Count];
1860 map [i] = new VariableInfo (ip.ParameterName (i),
1861 TypeManager.GetElementType (ip.ParameterType (i)), i, Length);
1863 Length += map [i].Length;
1867 public VariableMap (LocalInfo[] locals)
1868 : this (null, locals)
1871 public VariableMap (VariableMap parent, LocalInfo[] locals)
1873 int offset = 0, start = 0;
1874 if (parent != null && parent.map != null) {
1875 offset = parent.Length;
1876 start = parent.Count;
1879 Count = locals.Length + start;
1884 map = new VariableInfo [Count];
1887 if (parent != null && parent.map != null) {
1888 parent.map.CopyTo (map, 0);
1891 for (int i = start; i < Count; i++) {
1892 LocalInfo li = locals [i-start];
1894 if (li.VariableType == null)
1897 map [i] = li.VariableInfo = new VariableInfo (li, Length);
1898 Length += map [i].Length;
1903 // Returns the VariableInfo for variable @index or null if we don't need to
1904 // compute assignment info for this variable.
1906 public VariableInfo this [int index] {
1915 public override string ToString ()
1917 return String.Format ("VariableMap ({0}:{1})", Count, Length);
1922 // This is a special bit vector which can inherit from another bit vector doing a
1923 // copy-on-write strategy. The inherited vector may have a smaller size than the
1926 public class MyBitVector {
1927 public readonly int Count;
1928 public readonly MyBitVector InheritsFrom;
1933 public MyBitVector (int Count)
1934 : this (null, Count)
1937 public MyBitVector (MyBitVector InheritsFrom, int Count)
1939 this.InheritsFrom = InheritsFrom;
1944 // Checks whether this bit vector has been modified. After setting this to true,
1945 // we won't use the inherited vector anymore, but our own copy of it.
1947 public bool IsDirty {
1954 initialize_vector ();
1959 // Get/set bit `index' in the bit vector.
1961 public bool this [int index]
1965 throw new ArgumentOutOfRangeException ();
1967 // We're doing a "copy-on-write" strategy here; as long
1968 // as nobody writes to the array, we can use our parent's
1969 // copy instead of duplicating the vector.
1972 return vector [index];
1973 else if (InheritsFrom != null) {
1974 BitArray inherited = InheritsFrom.Vector;
1976 if (index < inherited.Count)
1977 return inherited [index];
1986 throw new ArgumentOutOfRangeException ();
1988 // Only copy the vector if we're actually modifying it.
1990 if (this [index] != value) {
1991 initialize_vector ();
1993 vector [index] = value;
1999 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
2000 // copy of the bit vector.
2002 public static explicit operator BitArray (MyBitVector vector)
2004 vector.initialize_vector ();
2005 return vector.Vector;
2009 // Performs an `or' operation on the bit vector. The `new_vector' may have a
2010 // different size than the current one.
2012 public void Or (MyBitVector new_vector)
2014 BitArray new_array = new_vector.Vector;
2016 initialize_vector ();
2019 if (vector.Count < new_array.Count)
2020 upper = vector.Count;
2022 upper = new_array.Count;
2024 for (int i = 0; i < upper; i++)
2025 vector [i] = vector [i] | new_array [i];
2029 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
2030 // a different size than the current one.
2032 public void And (MyBitVector new_vector)
2034 BitArray new_array = new_vector.Vector;
2036 initialize_vector ();
2039 if (vector.Count < new_array.Count)
2040 lower = upper = vector.Count;
2042 lower = new_array.Count;
2043 upper = vector.Count;
2046 for (int i = 0; i < lower; i++)
2047 vector [i] = vector [i] & new_array [i];
2049 for (int i = lower; i < upper; i++)
2053 public static void And (ref MyBitVector target, MyBitVector vector)
2056 target.And (vector);
2058 target = vector.Clone ();
2061 public static void Or (ref MyBitVector target, MyBitVector vector)
2066 target = vector.Clone ();
2070 // This does a deep copy of the bit vector.
2072 public MyBitVector Clone ()
2074 MyBitVector retval = new MyBitVector (Count);
2076 retval.Vector = Vector;
2085 else if (!is_dirty && (InheritsFrom != null))
2086 return InheritsFrom.Vector;
2088 initialize_vector ();
2094 initialize_vector ();
2096 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
2097 vector [i] = value [i];
2101 void initialize_vector ()
2106 vector = new BitArray (Count, false);
2107 if (InheritsFrom != null)
2108 Vector = InheritsFrom.Vector;
2113 public override string ToString ()
2115 StringBuilder sb = new StringBuilder ("{");
2117 BitArray vector = Vector;
2120 for (int i = 0; i < vector.Count; i++) {
2121 sb.Append (vector [i] ? "1" : "0");
2125 return sb.ToString ();