2 // flowanalyis.cs: The control flow analysis code
5 // Martin Baulig (martin@ximian.com)
6 // Raja R Harinath (rharinath@novell.com)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
21 // A new instance of this class is created every time a new block is resolved
22 // and if there's branching in the block's control flow.
24 public abstract class FlowBranching
27 // The type of a FlowBranching.
29 public enum BranchingType : byte {
30 // Normal (conditional or toplevel) block.
39 // The statement embedded inside a loop
42 // part of a block headed by a jump target
48 // TryFinally, Using, Lock, CollectionForeach
54 // The toplevel block of a function
62 // The type of one sibling of a branching.
64 public enum SiblingType : byte {
73 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
76 case BranchingType.Exception:
77 case BranchingType.Labeled:
78 case BranchingType.Toplevel:
79 case BranchingType.TryCatch:
80 throw new InvalidOperationException ();
82 case BranchingType.Switch:
83 return new FlowBranchingBreakable (parent, type, SiblingType.SwitchSection, block, loc);
85 case BranchingType.Block:
86 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
88 case BranchingType.Loop:
89 return new FlowBranchingBreakable (parent, type, SiblingType.Conditional, block, loc);
91 case BranchingType.Embedded:
92 return new FlowBranchingContinuable (parent, type, SiblingType.Conditional, block, loc);
95 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
100 // The type of this flow branching.
102 public readonly BranchingType Type;
105 // The block this branching is contained in. This may be null if it's not
106 // a top-level block and it doesn't declare any local variables.
108 public readonly Block Block;
111 // The parent of this branching or null if this is the top-block.
113 public readonly FlowBranching Parent;
116 // Start-Location of this flow branching.
118 public readonly Location Location;
120 static int next_id = 0;
124 // The vector contains a BitArray with information about which local variables
125 // and parameters are already initialized at the current code position.
127 public class UsageVector {
129 // The type of this branching.
131 public readonly SiblingType Type;
134 // Start location of this branching.
136 public Location Location;
139 // This is only valid for SwitchSection, Try, Catch and Finally.
141 public readonly Block Block;
144 // The number of locals in this block.
146 public readonly int CountLocals;
149 // If not null, then we inherit our state from this vector and do a
150 // copy-on-write. If null, then we're the first sibling in a top-level
151 // block and inherit from the empty vector.
153 public readonly UsageVector InheritsFrom;
156 // This is used to construct a list of UsageVector's.
158 public UsageVector Next;
166 static int next_id = 0;
170 // Normally, you should not use any of these constructors.
172 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc, int num_locals)
177 this.InheritsFrom = parent;
178 this.CountLocals = num_locals;
180 locals = num_locals == 0
182 : new MyBitVector (parent == null ? MyBitVector.Empty : parent.locals, num_locals);
185 is_unreachable = parent.is_unreachable;
191 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc)
192 : this (type, parent, block, loc, parent.CountLocals)
195 private UsageVector (MyBitVector locals, bool is_unreachable, Block block, Location loc)
197 this.Type = SiblingType.Block;
201 this.is_unreachable = is_unreachable;
203 this.locals = locals;
210 // This does a deep copy of the usage vector.
212 public UsageVector Clone ()
214 UsageVector retval = new UsageVector (Type, null, Block, Location, CountLocals);
216 retval.locals = locals.Clone ();
217 retval.is_unreachable = is_unreachable;
222 public bool IsAssigned (VariableInfo var, bool ignoreReachability)
224 if (!ignoreReachability && !var.IsParameter && IsUnreachable)
227 return var.IsAssigned (locals);
230 public void SetAssigned (VariableInfo var)
232 if (!var.IsParameter && IsUnreachable)
235 var.SetAssigned (locals);
238 public bool IsFieldAssigned (VariableInfo var, string name)
240 if (!var.IsParameter && IsUnreachable)
243 return var.IsFieldAssigned (locals, name);
246 public void SetFieldAssigned (VariableInfo var, string name)
248 if (!var.IsParameter && IsUnreachable)
251 var.SetFieldAssigned (locals, name);
254 public bool IsUnreachable {
255 get { return is_unreachable; }
258 public void ResetBarrier ()
260 is_unreachable = false;
265 is_unreachable = true;
268 public static UsageVector MergeSiblings (UsageVector sibling_list, Location loc)
270 if (sibling_list.Next == null)
273 MyBitVector locals = null;
274 bool is_unreachable = sibling_list.is_unreachable;
276 if (!sibling_list.IsUnreachable)
277 locals &= sibling_list.locals;
279 for (UsageVector child = sibling_list.Next; child != null; child = child.Next) {
280 is_unreachable &= child.is_unreachable;
282 if (!child.IsUnreachable)
283 locals &= child.locals;
286 return new UsageVector (locals, is_unreachable, null, loc);
290 // Merges a child branching.
292 public UsageVector MergeChild (UsageVector child, bool overwrite)
294 Report.Debug (2, " MERGING CHILD EFFECTS", this, child, Type);
296 bool new_isunr = child.is_unreachable;
299 // We've now either reached the point after the branching or we will
300 // never get there since we always return or always throw an exception.
302 // If we can reach the point after the branching, mark all locals and
303 // parameters as initialized which have been initialized in all branches
304 // we need to look at (see above).
307 if ((Type == SiblingType.SwitchSection) && !new_isunr) {
308 Report.Error (163, Location,
309 "Control cannot fall through from one " +
310 "case label to another");
314 locals |= child.locals;
317 is_unreachable = new_isunr;
319 is_unreachable |= new_isunr;
324 public void MergeOrigins (UsageVector o_vectors)
326 Report.Debug (1, " MERGING BREAK ORIGINS", this);
328 if (o_vectors == null)
331 if (IsUnreachable && locals != null)
332 locals.SetAll (true);
334 for (UsageVector vector = o_vectors; vector != null; vector = vector.Next) {
335 Report.Debug (1, " MERGING BREAK ORIGIN", vector);
336 if (vector.IsUnreachable)
338 locals &= vector.locals;
339 is_unreachable &= vector.is_unreachable;
342 Report.Debug (1, " MERGING BREAK ORIGINS DONE", this);
349 public override string ToString ()
351 return String.Format ("Vector ({0},{1},{2}-{3})", Type, id, is_unreachable, locals);
356 // Creates a new flow branching which is contained in `parent'.
357 // You should only pass non-null for the `block' argument if this block
358 // introduces any new variables - in this case, we need to create a new
359 // usage vector with a different size than our parent's one.
361 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
362 Block block, Location loc)
372 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
373 vector = new UsageVector (stype, parent_vector, Block, loc, Block.AssignableSlots);
375 vector = new UsageVector (stype, Parent.CurrentUsageVector, null, loc);
381 public abstract UsageVector CurrentUsageVector {
386 // Creates a sibling of the current usage vector.
388 public virtual void CreateSibling (Block block, SiblingType type)
390 UsageVector vector = new UsageVector (
391 type, Parent.CurrentUsageVector, block, Location);
394 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
397 public void CreateSibling ()
399 CreateSibling (null, SiblingType.Conditional);
402 protected abstract void AddSibling (UsageVector uv);
404 protected abstract UsageVector Merge ();
406 public UsageVector MergeChild (FlowBranching child)
408 return CurrentUsageVector.MergeChild (child.Merge (), true);
411 public virtual bool CheckRethrow (Location loc)
413 return Parent.CheckRethrow (loc);
416 public virtual bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
418 return Parent.AddResumePoint (stmt, loc, out pc);
421 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
422 public virtual bool AddBreakOrigin (UsageVector vector, Location loc)
424 return Parent.AddBreakOrigin (vector, loc);
427 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
428 public virtual bool AddContinueOrigin (UsageVector vector, Location loc)
430 return Parent.AddContinueOrigin (vector, loc);
433 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
434 public virtual bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
436 return Parent.AddReturnOrigin (vector, stmt);
439 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
440 public virtual bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
442 return Parent.AddGotoOrigin (vector, goto_stmt);
445 public bool IsAssigned (VariableInfo vi)
447 return CurrentUsageVector.IsAssigned (vi, false);
450 public bool IsFieldAssigned (VariableInfo vi, string field_name)
452 return CurrentUsageVector.IsAssigned (vi, false) || CurrentUsageVector.IsFieldAssigned (vi, field_name);
455 public void SetAssigned (VariableInfo vi)
457 CurrentUsageVector.SetAssigned (vi);
460 public void SetFieldAssigned (VariableInfo vi, string name)
462 CurrentUsageVector.SetFieldAssigned (vi, name);
465 public override string ToString ()
467 StringBuilder sb = new StringBuilder ();
468 sb.Append (GetType ());
476 sb.Append (Block.ID);
478 sb.Append (Block.StartLocation);
481 // sb.Append (Siblings.Length);
482 // sb.Append (" - ");
483 sb.Append (CurrentUsageVector);
485 return sb.ToString ();
489 get { return String.Format ("{0} ({1}:{2}:{3})", GetType (), id, Type, Location); }
493 public class FlowBranchingBlock : FlowBranching
495 UsageVector sibling_list = null;
497 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
498 SiblingType stype, Block block, Location loc)
499 : base (parent, type, stype, block, loc)
502 public override UsageVector CurrentUsageVector {
503 get { return sibling_list; }
506 protected override void AddSibling (UsageVector sibling)
508 if (sibling_list != null && sibling_list.Type == SiblingType.Block)
509 throw new InternalErrorException ("Blocks don't have sibling flow paths");
510 sibling.Next = sibling_list;
511 sibling_list = sibling;
514 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
516 LabeledStatement stmt = Block == null ? null : Block.LookupLabel (goto_stmt.Target);
518 return Parent.AddGotoOrigin (vector, goto_stmt);
521 goto_stmt.SetResolvedTarget (stmt);
522 stmt.AddUsageVector (vector);
526 public static void Error_UnknownLabel (Location loc, string label)
528 Report.Error(159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
532 protected override UsageVector Merge ()
534 Report.Debug (2, " MERGING SIBLINGS", Name);
535 UsageVector vector = UsageVector.MergeSiblings (sibling_list, Location);
536 Report.Debug (2, " MERGING SIBLINGS DONE", Name, vector);
541 public class FlowBranchingBreakable : FlowBranchingBlock
543 UsageVector break_origins;
545 public FlowBranchingBreakable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
546 : base (parent, type, stype, block, loc)
549 public override bool AddBreakOrigin (UsageVector vector, Location loc)
551 vector = vector.Clone ();
552 vector.Next = break_origins;
553 break_origins = vector;
557 protected override UsageVector Merge ()
559 UsageVector vector = base.Merge ();
560 vector.MergeOrigins (break_origins);
565 public class FlowBranchingContinuable : FlowBranchingBlock
567 UsageVector continue_origins;
569 public FlowBranchingContinuable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
570 : base (parent, type, stype, block, loc)
573 public override bool AddContinueOrigin (UsageVector vector, Location loc)
575 vector = vector.Clone ();
576 vector.Next = continue_origins;
577 continue_origins = vector;
581 protected override UsageVector Merge ()
583 UsageVector vector = base.Merge ();
584 vector.MergeOrigins (continue_origins);
589 public class FlowBranchingLabeled : FlowBranchingBlock
591 LabeledStatement stmt;
594 public FlowBranchingLabeled (FlowBranching parent, LabeledStatement stmt)
595 : base (parent, BranchingType.Labeled, SiblingType.Conditional, null, stmt.loc)
598 CurrentUsageVector.MergeOrigins (stmt.JumpOrigins);
599 actual = CurrentUsageVector.Clone ();
601 // stand-in for backward jumps
602 CurrentUsageVector.ResetBarrier ();
605 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
607 if (goto_stmt.Target != stmt.Name)
608 return Parent.AddGotoOrigin (vector, goto_stmt);
611 goto_stmt.SetResolvedTarget (stmt);
612 actual.MergeOrigins (vector.Clone ());
617 protected override UsageVector Merge ()
619 UsageVector vector = base.Merge ();
621 if (actual.IsUnreachable)
622 Report.Warning (162, 2, stmt.loc, "Unreachable code detected");
624 actual.MergeChild (vector, false);
629 public class FlowBranchingIterator : FlowBranchingBlock
632 public FlowBranchingIterator (FlowBranching parent, Iterator iterator)
633 : base (parent, BranchingType.Iterator, SiblingType.Block, null, iterator.Location)
635 this.iterator = iterator;
638 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
640 pc = iterator.AddResumePoint (stmt, loc);
645 public class FlowBranchingToplevel : FlowBranchingBlock
647 UsageVector return_origins;
649 public FlowBranchingToplevel (FlowBranching parent, ToplevelBlock stmt)
650 : base (parent, BranchingType.Toplevel, SiblingType.Conditional, stmt, stmt.loc)
654 public override bool CheckRethrow (Location loc)
656 Report.Error (156, loc, "A throw statement with no arguments is not allowed outside of a catch clause");
660 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
663 Report.Error (-6, loc, "Internal Error: A yield in a non-iterator");
667 public override bool AddBreakOrigin (UsageVector vector, Location loc)
669 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
673 public override bool AddContinueOrigin (UsageVector vector, Location loc)
675 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
679 public override bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
681 vector = vector.Clone ();
682 vector.Location = stmt.loc;
683 vector.Next = return_origins;
684 return_origins = vector;
688 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
690 string name = goto_stmt.Target;
691 LabeledStatement s = Block.LookupLabel (name);
693 throw new InternalErrorException ("Shouldn't get here");
695 if (Parent == null) {
696 Error_UnknownLabel (goto_stmt.loc, name);
700 int errors = Report.Errors;
701 Parent.AddGotoOrigin (vector, goto_stmt);
702 if (errors == Report.Errors)
703 Report.Error (1632, goto_stmt.loc, "Control cannot leave the body of an anonymous method");
707 protected override UsageVector Merge ()
709 for (UsageVector origin = return_origins; origin != null; origin = origin.Next)
710 Block.Toplevel.CheckOutParameters (origin, origin.Location);
712 UsageVector vector = base.Merge ();
713 Block.Toplevel.CheckOutParameters (vector, Block.loc);
714 // Note: we _do_not_ merge in the return origins
720 return Merge ().IsUnreachable;
724 public class FlowBranchingTryCatch : FlowBranchingBlock
727 public FlowBranchingTryCatch (FlowBranching parent, TryCatch stmt)
728 : base (parent, BranchingType.Block, SiblingType.Try, null, stmt.loc)
733 public override bool CheckRethrow (Location loc)
735 return CurrentUsageVector.Next != null || Parent.CheckRethrow (loc);
738 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
740 int errors = Report.Errors;
741 Parent.AddResumePoint (stmt, loc, out pc);
742 if (errors == Report.Errors) {
743 if (CurrentUsageVector.Next == null)
744 Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
746 Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
751 public override bool AddBreakOrigin (UsageVector vector, Location loc)
753 Parent.AddBreakOrigin (vector, loc);
754 stmt.SomeCodeFollows ();
758 public override bool AddContinueOrigin (UsageVector vector, Location loc)
760 Parent.AddContinueOrigin (vector, loc);
761 stmt.SomeCodeFollows ();
765 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
767 Parent.AddReturnOrigin (vector, exit_stmt);
768 stmt.SomeCodeFollows ();
772 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
774 Parent.AddGotoOrigin (vector, goto_stmt);
779 public class FlowBranchingException : FlowBranching
781 ExceptionStatement stmt;
782 UsageVector current_vector;
783 UsageVector try_vector;
784 UsageVector finally_vector;
786 abstract class SavedOrigin {
787 public SavedOrigin Next;
788 public UsageVector Vector;
790 public SavedOrigin (SavedOrigin next, UsageVector vector)
793 Vector = vector.Clone ();
796 protected abstract void DoPropagateFinally (FlowBranching parent);
797 public void PropagateFinally (UsageVector finally_vector, FlowBranching parent)
799 if (finally_vector != null)
800 Vector.MergeChild (finally_vector, false);
801 DoPropagateFinally (parent);
805 class BreakOrigin : SavedOrigin {
807 public BreakOrigin (SavedOrigin next, UsageVector vector, Location loc)
808 : base (next, vector)
813 protected override void DoPropagateFinally (FlowBranching parent)
815 parent.AddBreakOrigin (Vector, Loc);
819 class ContinueOrigin : SavedOrigin {
821 public ContinueOrigin (SavedOrigin next, UsageVector vector, Location loc)
822 : base (next, vector)
827 protected override void DoPropagateFinally (FlowBranching parent)
829 parent.AddContinueOrigin (Vector, Loc);
833 class ReturnOrigin : SavedOrigin {
834 public ExitStatement Stmt;
836 public ReturnOrigin (SavedOrigin next, UsageVector vector, ExitStatement stmt)
837 : base (next, vector)
842 protected override void DoPropagateFinally (FlowBranching parent)
844 parent.AddReturnOrigin (Vector, Stmt);
848 class GotoOrigin : SavedOrigin {
851 public GotoOrigin (SavedOrigin next, UsageVector vector, Goto stmt)
852 : base (next, vector)
857 protected override void DoPropagateFinally (FlowBranching parent)
859 parent.AddGotoOrigin (Vector, Stmt);
863 SavedOrigin saved_origins;
865 public FlowBranchingException (FlowBranching parent,
866 ExceptionStatement stmt)
867 : base (parent, BranchingType.Exception, SiblingType.Try,
873 protected override void AddSibling (UsageVector sibling)
875 switch (sibling.Type) {
876 case SiblingType.Try:
877 try_vector = sibling;
879 case SiblingType.Finally:
880 finally_vector = sibling;
883 throw new InvalidOperationException ();
885 current_vector = sibling;
888 public override UsageVector CurrentUsageVector {
889 get { return current_vector; }
892 public override bool CheckRethrow (Location loc)
894 if (!Parent.CheckRethrow (loc))
896 if (finally_vector == null)
898 Report.Error (724, loc, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
902 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
904 int errors = Report.Errors;
905 Parent.AddResumePoint (this.stmt, loc, out pc);
906 if (errors == Report.Errors) {
907 if (finally_vector == null)
908 this.stmt.AddResumePoint (stmt, loc, pc);
910 Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
915 public override bool AddBreakOrigin (UsageVector vector, Location loc)
917 if (finally_vector != null) {
918 int errors = Report.Errors;
919 Parent.AddBreakOrigin (vector, loc);
920 if (errors == Report.Errors)
921 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
923 saved_origins = new BreakOrigin (saved_origins, vector, loc);
926 // either the loop test or a back jump will follow code
927 stmt.SomeCodeFollows ();
931 public override bool AddContinueOrigin (UsageVector vector, Location loc)
933 if (finally_vector != null) {
934 int errors = Report.Errors;
935 Parent.AddContinueOrigin (vector, loc);
936 if (errors == Report.Errors)
937 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
939 saved_origins = new ContinueOrigin (saved_origins, vector, loc);
942 // either the loop test or a back jump will follow code
943 stmt.SomeCodeFollows ();
947 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
949 if (finally_vector != null) {
950 int errors = Report.Errors;
951 Parent.AddReturnOrigin (vector, exit_stmt);
952 if (errors == Report.Errors)
953 exit_stmt.Error_FinallyClause ();
955 saved_origins = new ReturnOrigin (saved_origins, vector, exit_stmt);
958 // sets ec.NeedReturnLabel()
959 stmt.SomeCodeFollows ();
963 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
965 LabeledStatement s = current_vector.Block == null ? null : current_vector.Block.LookupLabel (goto_stmt.Target);
967 throw new InternalErrorException ("Shouldn't get here");
969 if (finally_vector != null) {
970 int errors = Report.Errors;
971 Parent.AddGotoOrigin (vector, goto_stmt);
972 if (errors == Report.Errors)
973 Report.Error (157, goto_stmt.loc, "Control cannot leave the body of a finally clause");
975 saved_origins = new GotoOrigin (saved_origins, vector, goto_stmt);
980 protected override UsageVector Merge ()
982 UsageVector vector = try_vector.Clone ();
984 if (finally_vector != null)
985 vector.MergeChild (finally_vector, false);
987 for (SavedOrigin origin = saved_origins; origin != null; origin = origin.Next)
988 origin.PropagateFinally (finally_vector, Parent);
995 // This is used by the flow analysis code to keep track of the type of local variables
998 // The flow code uses a BitVector to keep track of whether a variable has been assigned
999 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1000 // you can only assign the whole variable as such.
1002 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1003 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1004 // one bit for each of its fields.
1006 // This class computes this `layout' for each type.
1008 public class TypeInfo
1010 public readonly Type Type;
1013 // Total number of bits a variable of this type consumes in the flow vector.
1015 public readonly int TotalLength;
1018 // Number of bits the simple fields of a variable of this type consume
1019 // in the flow vector.
1021 public readonly int Length;
1024 // This is only used by sub-structs.
1026 public readonly int Offset;
1029 // If this is a struct.
1031 public readonly bool IsStruct;
1034 // If this is a struct, all fields which are structs theirselves.
1036 public TypeInfo[] SubStructInfo;
1038 protected readonly StructInfo struct_info;
1039 private static Hashtable type_hash = new Hashtable ();
1041 public static TypeInfo GetTypeInfo (Type type)
1043 TypeInfo info = (TypeInfo) type_hash [type];
1047 info = new TypeInfo (type);
1048 type_hash.Add (type, info);
1052 public static TypeInfo GetTypeInfo (TypeContainer tc)
1054 TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1058 info = new TypeInfo (tc);
1059 type_hash.Add (tc.TypeBuilder, info);
1063 private TypeInfo (Type type)
1067 struct_info = StructInfo.GetStructInfo (type);
1068 if (struct_info != null) {
1069 Length = struct_info.Length;
1070 TotalLength = struct_info.TotalLength;
1071 SubStructInfo = struct_info.StructFields;
1080 private TypeInfo (TypeContainer tc)
1082 this.Type = tc.TypeBuilder;
1084 struct_info = StructInfo.GetStructInfo (tc);
1085 if (struct_info != null) {
1086 Length = struct_info.Length;
1087 TotalLength = struct_info.TotalLength;
1088 SubStructInfo = struct_info.StructFields;
1097 protected TypeInfo (StructInfo struct_info, int offset)
1099 this.struct_info = struct_info;
1100 this.Offset = offset;
1101 this.Length = struct_info.Length;
1102 this.TotalLength = struct_info.TotalLength;
1103 this.SubStructInfo = struct_info.StructFields;
1104 this.Type = struct_info.Type;
1105 this.IsStruct = true;
1108 public int GetFieldIndex (string name)
1110 if (struct_info == null)
1113 return struct_info [name];
1116 public TypeInfo GetSubStruct (string name)
1118 if (struct_info == null)
1121 return struct_info.GetStructField (name);
1125 // A struct's constructor must always assign all fields.
1126 // This method checks whether it actually does so.
1128 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1130 if (struct_info == null)
1134 for (int i = 0; i < struct_info.Count; i++) {
1135 FieldInfo field = struct_info.Fields [i];
1137 if (!branching.IsFieldAssigned (vi, field.Name)) {
1138 Report.Error (171, loc,
1139 "Field `{0}' must be fully assigned before control leaves the constructor",
1140 TypeManager.GetFullNameSignature (field));
1148 public override string ToString ()
1150 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1151 Type, Offset, Length, TotalLength);
1154 protected class StructInfo {
1155 public readonly Type Type;
1156 public readonly FieldInfo[] Fields;
1157 public readonly TypeInfo[] StructFields;
1158 public readonly int Count;
1159 public readonly int CountPublic;
1160 public readonly int CountNonPublic;
1161 public readonly int Length;
1162 public readonly int TotalLength;
1163 public readonly bool HasStructFields;
1165 private static Hashtable field_type_hash = new Hashtable ();
1166 private Hashtable struct_field_hash;
1167 private Hashtable field_hash;
1169 protected bool InTransit = false;
1171 // Private constructor. To save memory usage, we only need to create one instance
1172 // of this class per struct type.
1173 private StructInfo (Type type)
1177 field_type_hash.Add (type, this);
1179 if (type is TypeBuilder) {
1180 TypeContainer tc = TypeManager.LookupTypeContainer (type);
1182 ArrayList fields = null;
1186 ArrayList public_fields = new ArrayList ();
1187 ArrayList non_public_fields = new ArrayList ();
1189 if (fields != null) {
1190 foreach (FieldBase field in fields) {
1191 if ((field.ModFlags & Modifiers.STATIC) != 0)
1193 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1194 public_fields.Add (field.FieldBuilder);
1196 non_public_fields.Add (field.FieldBuilder);
1200 CountPublic = public_fields.Count;
1201 CountNonPublic = non_public_fields.Count;
1202 Count = CountPublic + CountNonPublic;
1204 Fields = new FieldInfo [Count];
1205 public_fields.CopyTo (Fields, 0);
1206 non_public_fields.CopyTo (Fields, CountPublic);
1208 } else if (type is GenericTypeParameterBuilder) {
1209 CountPublic = CountNonPublic = Count = 0;
1211 Fields = new FieldInfo [0];
1214 FieldInfo[] public_fields = type.GetFields (
1215 BindingFlags.Instance|BindingFlags.Public);
1216 FieldInfo[] non_public_fields = type.GetFields (
1217 BindingFlags.Instance|BindingFlags.NonPublic);
1219 CountPublic = public_fields.Length;
1220 CountNonPublic = non_public_fields.Length;
1221 Count = CountPublic + CountNonPublic;
1223 Fields = new FieldInfo [Count];
1224 public_fields.CopyTo (Fields, 0);
1225 non_public_fields.CopyTo (Fields, CountPublic);
1228 struct_field_hash = new Hashtable ();
1229 field_hash = new Hashtable ();
1232 StructFields = new TypeInfo [Count];
1233 StructInfo[] sinfo = new StructInfo [Count];
1237 for (int i = 0; i < Count; i++) {
1238 FieldInfo field = (FieldInfo) Fields [i];
1240 sinfo [i] = GetStructInfo (field.FieldType);
1241 if (sinfo [i] == null)
1242 field_hash.Add (field.Name, ++Length);
1243 else if (sinfo [i].InTransit) {
1244 Report.Error (523, String.Format (
1245 "Struct member `{0}.{1}' of type `{2}' causes " +
1246 "a cycle in the structure layout",
1247 type, field.Name, sinfo [i].Type));
1255 TotalLength = Length + 1;
1256 for (int i = 0; i < Count; i++) {
1257 FieldInfo field = (FieldInfo) Fields [i];
1259 if (sinfo [i] == null)
1262 field_hash.Add (field.Name, TotalLength);
1264 HasStructFields = true;
1265 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1266 struct_field_hash.Add (field.Name, StructFields [i]);
1267 TotalLength += sinfo [i].TotalLength;
1271 public int this [string name] {
1273 if (field_hash.Contains (name))
1274 return (int) field_hash [name];
1280 public TypeInfo GetStructField (string name)
1282 return (TypeInfo) struct_field_hash [name];
1285 public static StructInfo GetStructInfo (Type type)
1287 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1288 TypeManager.IsBuiltinType (type))
1291 StructInfo info = (StructInfo) field_type_hash [type];
1295 return new StructInfo (type);
1298 public static StructInfo GetStructInfo (TypeContainer tc)
1300 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1304 return new StructInfo (tc.TypeBuilder);
1310 // This is used by the flow analysis code to store information about a single local variable
1311 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1312 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1313 // it has been assigned or not, but for structs, we need this information for each of its fields.
1315 public class VariableInfo {
1316 public readonly string Name;
1317 public readonly TypeInfo TypeInfo;
1320 // The bit offset of this variable in the flow vector.
1322 public readonly int Offset;
1325 // The number of bits this variable needs in the flow vector.
1326 // The first bit always specifies whether the variable as such has been assigned while
1327 // the remaining bits contain this information for each of a struct's fields.
1329 public readonly int Length;
1332 // If this is a parameter of local variable.
1334 public readonly bool IsParameter;
1336 public readonly LocalInfo LocalInfo;
1338 readonly VariableInfo Parent;
1339 VariableInfo[] sub_info;
1341 bool is_ever_assigned;
1342 public bool IsEverAssigned {
1343 get { return is_ever_assigned; }
1346 protected VariableInfo (string name, Type type, int offset)
1349 this.Offset = offset;
1350 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1352 Length = TypeInfo.TotalLength;
1357 protected VariableInfo (VariableInfo parent, TypeInfo type)
1359 this.Name = parent.Name;
1360 this.TypeInfo = type;
1361 this.Offset = parent.Offset + type.Offset;
1362 this.Parent = parent;
1363 this.Length = type.TotalLength;
1365 this.IsParameter = parent.IsParameter;
1366 this.LocalInfo = parent.LocalInfo;
1371 protected void Initialize ()
1373 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1374 if (sub_fields != null) {
1375 sub_info = new VariableInfo [sub_fields.Length];
1376 for (int i = 0; i < sub_fields.Length; i++) {
1377 if (sub_fields [i] != null)
1378 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1381 sub_info = new VariableInfo [0];
1384 public VariableInfo (LocalInfo local_info, int offset)
1385 : this (local_info.Name, local_info.VariableType, offset)
1387 this.LocalInfo = local_info;
1388 this.IsParameter = false;
1391 public VariableInfo (Parameters ip, int i, int offset)
1392 : this (ip.ParameterName (i), TypeManager.GetElementType (ip.ParameterType (i)), offset)
1394 this.IsParameter = true;
1397 public bool IsAssigned (EmitContext ec)
1399 return !ec.DoFlowAnalysis ||
1400 ec.OmitStructFlowAnalysis && TypeInfo.IsStruct ||
1401 ec.CurrentBranching.IsAssigned (this);
1404 public bool IsAssigned (EmitContext ec, Location loc)
1406 if (IsAssigned (ec))
1409 Report.Error (165, loc,
1410 "Use of unassigned local variable `" + Name + "'");
1411 ec.CurrentBranching.SetAssigned (this);
1415 public bool IsAssigned (MyBitVector vector)
1420 if (vector [Offset])
1423 // FIXME: Fix SetFieldAssigned to set the whole range like SetAssigned below. Then, get rid of this stanza
1424 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent) {
1425 if (vector [parent.Offset]) {
1426 // 'parent' is assigned, but someone forgot to note that all its components are assigned too
1427 parent.SetAssigned (vector);
1432 // Return unless this is a struct.
1433 if (!TypeInfo.IsStruct)
1436 // Ok, so each field must be assigned.
1437 for (int i = 0; i < TypeInfo.Length; i++) {
1438 if (!vector [Offset + i + 1])
1442 // Ok, now check all fields which are structs.
1443 for (int i = 0; i < sub_info.Length; i++) {
1444 VariableInfo sinfo = sub_info [i];
1448 if (!sinfo.IsAssigned (vector))
1452 vector [Offset] = true;
1453 is_ever_assigned = true;
1457 public void SetAssigned (EmitContext ec)
1459 if (ec.DoFlowAnalysis)
1460 ec.CurrentBranching.SetAssigned (this);
1463 public void SetAssigned (MyBitVector vector)
1466 vector [Offset] = true;
1468 vector.SetRange (Offset, Length);
1469 is_ever_assigned = true;
1472 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1474 if (!ec.DoFlowAnalysis ||
1475 ec.OmitStructFlowAnalysis && TypeInfo.IsStruct ||
1476 ec.CurrentBranching.IsFieldAssigned (this, name))
1479 Report.Error (170, loc,
1480 "Use of possibly unassigned field `" + name + "'");
1481 ec.CurrentBranching.SetFieldAssigned (this, name);
1485 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1487 int field_idx = TypeInfo.GetFieldIndex (field_name);
1492 return vector [Offset + field_idx];
1495 public void SetFieldAssigned (EmitContext ec, string name)
1497 if (ec.DoFlowAnalysis)
1498 ec.CurrentBranching.SetFieldAssigned (this, name);
1501 public void SetFieldAssigned (MyBitVector vector, string field_name)
1503 int field_idx = TypeInfo.GetFieldIndex (field_name);
1508 vector [Offset + field_idx] = true;
1509 is_ever_assigned = true;
1512 public VariableInfo GetSubStruct (string name)
1514 TypeInfo type = TypeInfo.GetSubStruct (name);
1519 return new VariableInfo (this, type);
1522 public override string ToString ()
1524 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1525 Name, TypeInfo, Offset, Length, IsParameter);
1530 // This is a special bit vector which can inherit from another bit vector doing a
1531 // copy-on-write strategy. The inherited vector may have a smaller size than the
1534 public class MyBitVector {
1535 public readonly int Count;
1536 public static readonly MyBitVector Empty = new MyBitVector ();
1538 // Invariant: vector != null => vector.Count == Count
1539 // Invariant: vector == null || shared == null
1540 // i.e., at most one of 'vector' and 'shared' can be non-null. They can both be null -- that means all-ones
1541 // The object in 'shared' cannot be modified, while 'vector' can be freely modified
1542 BitArray vector, shared;
1546 shared = new BitArray (0, false);
1549 public MyBitVector (MyBitVector InheritsFrom, int Count)
1551 if (InheritsFrom != null)
1552 shared = InheritsFrom.Shared;
1557 // Use this accessor to get a shareable copy of the underlying BitArray representation
1560 // Post-condition: vector == null
1561 if (shared == null) {
1570 // Get/set bit `index' in the bit vector.
1572 public bool this [int index] {
1575 throw new ArgumentOutOfRangeException ();
1578 return vector [index];
1581 if (index < shared.Count)
1582 return shared [index];
1587 // Only copy the vector if we're actually modifying it.
1588 if (this [index] != value) {
1590 initialize_vector ();
1591 vector [index] = value;
1597 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1598 // different size than the current one.
1600 private MyBitVector Or (MyBitVector new_vector)
1602 if (Count == 0 || new_vector.Count == 0)
1605 BitArray o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1608 int n = new_vector.Count;
1610 for (int i = 0; i < n; ++i)
1618 if (Count == o.Count) {
1619 if (vector == null) {
1622 initialize_vector ();
1632 for (int i = 0; i < min; i++) {
1641 // Performs an `and' operation on the bit vector. The `new_vector' may have
1642 // a different size than the current one.
1644 private MyBitVector And (MyBitVector new_vector)
1649 BitArray o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1652 for (int i = new_vector.Count; i < Count; ++i)
1662 if (Count == o.Count) {
1663 if (vector == null) {
1664 if (shared == null) {
1665 shared = new_vector.Shared;
1668 initialize_vector ();
1678 for (int i = 0; i < min; i++) {
1683 for (int i = min; i < Count; i++)
1689 public static MyBitVector operator & (MyBitVector a, MyBitVector b)
1697 if (a.Count > b.Count)
1698 return a.Clone ().And (b);
1700 return b.Clone ().And (a);
1703 public static MyBitVector operator | (MyBitVector a, MyBitVector b)
1708 return new MyBitVector (null, b.Count);
1710 return new MyBitVector (null, a.Count);
1711 if (a.Count > b.Count)
1712 return a.Clone ().Or (b);
1714 return b.Clone ().Or (a);
1717 public MyBitVector Clone ()
1719 return Count == 0 ? Empty : new MyBitVector (this, Count);
1722 public void SetRange (int offset, int length)
1724 if (offset > Count || offset + length > Count)
1725 throw new ArgumentOutOfRangeException ();
1727 if (shared == null && vector == null)
1731 if (shared != null) {
1732 if (offset + length <= shared.Count) {
1733 for (; i < length; ++i)
1734 if (!shared [i+offset])
1739 initialize_vector ();
1741 for (; i < length; ++i)
1742 vector [i+offset] = true;
1746 public void SetAll (bool value)
1748 // Don't clobber Empty
1751 shared = value ? null : Empty.Shared;
1755 void initialize_vector ()
1757 // Post-condition: vector != null
1758 if (shared == null) {
1759 vector = new BitArray (Count, true);
1763 vector = new BitArray (shared);
1764 if (Count != vector.Count)
1765 vector.Length = Count;
1769 StringBuilder Dump (StringBuilder sb)
1771 BitArray dump = vector == null ? shared : vector;
1773 return sb.Append ("/");
1776 for (int i = 0; i < dump.Count; i++)
1777 sb.Append (dump [i] ? "1" : "0");
1781 public override string ToString ()
1783 return Dump (new StringBuilder ("{")).Append ("}").ToString ();