2 // flowanalyis.cs: The control flow analysis code
5 // Martin Baulig (martin@ximian.com)
6 // Raja R Harinath (rharinath@novell.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
14 using System.Collections.Generic;
19 // A new instance of this class is created every time a new block is resolved
20 // and if there's branching in the block's control flow.
22 public abstract class FlowBranching
25 // The type of a FlowBranching.
27 public enum BranchingType : byte {
28 // Normal (conditional or toplevel) block.
37 // The statement embedded inside a loop
40 // part of a block headed by a jump target
46 // TryFinally, Using, Lock, CollectionForeach
52 // The toplevel block of a function
60 // The type of one sibling of a branching.
62 public enum SiblingType : byte {
71 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
74 case BranchingType.Exception:
75 case BranchingType.Labeled:
76 case BranchingType.Toplevel:
77 case BranchingType.TryCatch:
78 throw new InvalidOperationException ();
80 case BranchingType.Switch:
81 return new FlowBranchingBreakable (parent, type, SiblingType.SwitchSection, block, loc);
83 case BranchingType.Block:
84 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
86 case BranchingType.Loop:
87 return new FlowBranchingBreakable (parent, type, SiblingType.Conditional, block, loc);
89 case BranchingType.Embedded:
90 return new FlowBranchingContinuable (parent, type, SiblingType.Conditional, block, loc);
93 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
98 // The type of this flow branching.
100 public readonly BranchingType Type;
103 // The block this branching is contained in. This may be null if it's not
104 // a top-level block and it doesn't declare any local variables.
106 public readonly Block Block;
109 // The parent of this branching or null if this is the top-block.
111 public readonly FlowBranching Parent;
114 // Start-Location of this flow branching.
116 public readonly Location Location;
118 static int next_id = 0;
122 // The vector contains a BitArray with information about which local variables
123 // and parameters are already initialized at the current code position.
125 public class UsageVector {
127 // The type of this branching.
129 public readonly SiblingType Type;
132 // Start location of this branching.
134 public Location Location;
137 // This is only valid for SwitchSection, Try, Catch and Finally.
139 public readonly Block Block;
142 // The number of locals in this block.
144 public readonly int CountLocals;
147 // If not null, then we inherit our state from this vector and do a
148 // copy-on-write. If null, then we're the first sibling in a top-level
149 // block and inherit from the empty vector.
151 public readonly UsageVector InheritsFrom;
154 // This is used to construct a list of UsageVector's.
156 public UsageVector Next;
164 static int next_id = 0;
168 // Normally, you should not use any of these constructors.
170 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc, int num_locals)
175 this.InheritsFrom = parent;
176 this.CountLocals = num_locals;
178 locals = num_locals == 0
180 : new MyBitVector (parent == null ? MyBitVector.Empty : parent.locals, num_locals);
183 is_unreachable = parent.is_unreachable;
189 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc)
190 : this (type, parent, block, loc, parent.CountLocals)
193 private UsageVector (MyBitVector locals, bool is_unreachable, Block block, Location loc)
195 this.Type = SiblingType.Block;
199 this.is_unreachable = is_unreachable;
201 this.locals = locals;
208 // This does a deep copy of the usage vector.
210 public UsageVector Clone ()
212 UsageVector retval = new UsageVector (Type, null, Block, Location, CountLocals);
214 retval.locals = locals.Clone ();
215 retval.is_unreachable = is_unreachable;
220 public bool IsAssigned (VariableInfo var, bool ignoreReachability)
222 if (!ignoreReachability && !var.IsParameter && IsUnreachable)
225 return var.IsAssigned (locals);
228 public void SetAssigned (VariableInfo var)
230 if (!var.IsParameter && IsUnreachable)
233 var.SetAssigned (locals);
236 public bool IsFieldAssigned (VariableInfo var, string name)
238 if (!var.IsParameter && IsUnreachable)
241 return var.IsFieldAssigned (locals, name);
244 public void SetFieldAssigned (VariableInfo var, string name)
246 if (!var.IsParameter && IsUnreachable)
249 var.SetFieldAssigned (locals, name);
252 public bool IsUnreachable {
253 get { return is_unreachable; }
256 public void ResetBarrier ()
258 is_unreachable = false;
263 is_unreachable = true;
266 public static UsageVector MergeSiblings (UsageVector sibling_list, Location loc)
268 if (sibling_list.Next == null)
271 MyBitVector locals = null;
272 bool is_unreachable = sibling_list.is_unreachable;
274 if (!sibling_list.IsUnreachable)
275 locals &= sibling_list.locals;
277 for (UsageVector child = sibling_list.Next; child != null; child = child.Next) {
278 is_unreachable &= child.is_unreachable;
280 if (!child.IsUnreachable)
281 locals &= child.locals;
284 return new UsageVector (locals, is_unreachable, null, loc);
288 // Merges a child branching.
290 public UsageVector MergeChild (UsageVector child, bool overwrite)
292 Report.Debug (2, " MERGING CHILD EFFECTS", this, child, Type);
294 bool new_isunr = child.is_unreachable;
297 // We've now either reached the point after the branching or we will
298 // never get there since we always return or always throw an exception.
300 // If we can reach the point after the branching, mark all locals and
301 // parameters as initialized which have been initialized in all branches
302 // we need to look at (see above).
305 if ((Type == SiblingType.SwitchSection) && !new_isunr) {
306 Report.Error (163, Location,
307 "Control cannot fall through from one " +
308 "case label to another");
312 locals |= child.locals;
314 // throw away un-necessary information about variables in child blocks
315 if (locals.Count != CountLocals)
316 locals = new MyBitVector (locals, CountLocals);
319 is_unreachable = new_isunr;
321 is_unreachable |= new_isunr;
326 public void MergeOrigins (UsageVector o_vectors)
328 Report.Debug (1, " MERGING BREAK ORIGINS", this);
330 if (o_vectors == null)
333 if (IsUnreachable && locals != null)
334 locals.SetAll (true);
336 for (UsageVector vector = o_vectors; vector != null; vector = vector.Next) {
337 Report.Debug (1, " MERGING BREAK ORIGIN", vector);
338 if (vector.IsUnreachable)
340 locals &= vector.locals;
341 is_unreachable &= vector.is_unreachable;
344 Report.Debug (1, " MERGING BREAK ORIGINS DONE", this);
351 public override string ToString ()
353 return String.Format ("Vector ({0},{1},{2}-{3})", Type, id, is_unreachable, locals);
358 // Creates a new flow branching which is contained in `parent'.
359 // You should only pass non-null for the `block' argument if this block
360 // introduces any new variables - in this case, we need to create a new
361 // usage vector with a different size than our parent's one.
363 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
364 Block block, Location loc)
374 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
375 vector = new UsageVector (stype, parent_vector, Block, loc, Block.AssignableSlots);
377 vector = new UsageVector (stype, Parent.CurrentUsageVector, null, loc);
383 public abstract UsageVector CurrentUsageVector {
388 // Creates a sibling of the current usage vector.
390 public virtual void CreateSibling (Block block, SiblingType type)
392 UsageVector vector = new UsageVector (
393 type, Parent.CurrentUsageVector, block, Location);
396 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
399 public void CreateSibling ()
401 CreateSibling (null, SiblingType.Conditional);
404 protected abstract void AddSibling (UsageVector uv);
406 protected abstract UsageVector Merge ();
408 public UsageVector MergeChild (FlowBranching child)
410 return CurrentUsageVector.MergeChild (child.Merge (), true);
413 public virtual bool CheckRethrow (Location loc)
415 return Parent.CheckRethrow (loc);
418 public virtual bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
420 return Parent.AddResumePoint (stmt, loc, out pc);
423 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
424 public virtual bool AddBreakOrigin (UsageVector vector, Location loc)
426 return Parent.AddBreakOrigin (vector, loc);
429 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
430 public virtual bool AddContinueOrigin (UsageVector vector, Location loc)
432 return Parent.AddContinueOrigin (vector, loc);
435 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
436 public virtual bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
438 return Parent.AddReturnOrigin (vector, stmt);
441 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
442 public virtual bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
444 return Parent.AddGotoOrigin (vector, goto_stmt);
447 public bool IsAssigned (VariableInfo vi)
449 return CurrentUsageVector.IsAssigned (vi, false);
452 public bool IsFieldAssigned (VariableInfo vi, string field_name)
454 return CurrentUsageVector.IsAssigned (vi, false) || CurrentUsageVector.IsFieldAssigned (vi, field_name);
457 protected static Report Report {
458 get { return RootContext.ToplevelTypes.Compiler.Report; }
461 public void SetAssigned (VariableInfo vi)
463 CurrentUsageVector.SetAssigned (vi);
466 public void SetFieldAssigned (VariableInfo vi, string name)
468 CurrentUsageVector.SetFieldAssigned (vi, name);
472 public override string ToString ()
474 StringBuilder sb = new StringBuilder ();
475 sb.Append (GetType ());
483 sb.Append (Block.ID);
485 sb.Append (Block.StartLocation);
488 // sb.Append (Siblings.Length);
489 // sb.Append (" - ");
490 sb.Append (CurrentUsageVector);
492 return sb.ToString ();
497 get { return String.Format ("{0} ({1}:{2}:{3})", GetType (), id, Type, Location); }
501 public class FlowBranchingBlock : FlowBranching
503 UsageVector sibling_list = null;
505 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
506 SiblingType stype, Block block, Location loc)
507 : base (parent, type, stype, block, loc)
510 public override UsageVector CurrentUsageVector {
511 get { return sibling_list; }
514 protected override void AddSibling (UsageVector sibling)
516 if (sibling_list != null && sibling_list.Type == SiblingType.Block)
517 throw new InternalErrorException ("Blocks don't have sibling flow paths");
518 sibling.Next = sibling_list;
519 sibling_list = sibling;
522 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
524 LabeledStatement stmt = Block == null ? null : Block.LookupLabel (goto_stmt.Target);
526 return Parent.AddGotoOrigin (vector, goto_stmt);
529 goto_stmt.SetResolvedTarget (stmt);
530 stmt.AddUsageVector (vector);
534 public static void Error_UnknownLabel (Location loc, string label, Report Report)
536 Report.Error(159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
540 protected override UsageVector Merge ()
542 Report.Debug (2, " MERGING SIBLINGS", Name);
543 UsageVector vector = UsageVector.MergeSiblings (sibling_list, Location);
544 Report.Debug (2, " MERGING SIBLINGS DONE", Name, vector);
549 public class FlowBranchingBreakable : FlowBranchingBlock
551 UsageVector break_origins;
553 public FlowBranchingBreakable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
554 : base (parent, type, stype, block, loc)
557 public override bool AddBreakOrigin (UsageVector vector, Location loc)
559 vector = vector.Clone ();
560 vector.Next = break_origins;
561 break_origins = vector;
565 protected override UsageVector Merge ()
567 UsageVector vector = base.Merge ();
568 vector.MergeOrigins (break_origins);
573 public class FlowBranchingContinuable : FlowBranchingBlock
575 UsageVector continue_origins;
577 public FlowBranchingContinuable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
578 : base (parent, type, stype, block, loc)
581 public override bool AddContinueOrigin (UsageVector vector, Location loc)
583 vector = vector.Clone ();
584 vector.Next = continue_origins;
585 continue_origins = vector;
589 protected override UsageVector Merge ()
591 UsageVector vector = base.Merge ();
592 vector.MergeOrigins (continue_origins);
597 public class FlowBranchingLabeled : FlowBranchingBlock
599 LabeledStatement stmt;
602 public FlowBranchingLabeled (FlowBranching parent, LabeledStatement stmt)
603 : base (parent, BranchingType.Labeled, SiblingType.Conditional, null, stmt.loc)
606 CurrentUsageVector.MergeOrigins (stmt.JumpOrigins);
607 actual = CurrentUsageVector.Clone ();
609 // stand-in for backward jumps
610 CurrentUsageVector.ResetBarrier ();
613 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
615 if (goto_stmt.Target != stmt.Name)
616 return Parent.AddGotoOrigin (vector, goto_stmt);
619 goto_stmt.SetResolvedTarget (stmt);
620 actual.MergeOrigins (vector.Clone ());
625 protected override UsageVector Merge ()
627 UsageVector vector = base.Merge ();
629 if (actual.IsUnreachable)
630 Report.Warning (162, 2, stmt.loc, "Unreachable code detected");
632 actual.MergeChild (vector, false);
637 public class FlowBranchingIterator : FlowBranchingBlock
640 public FlowBranchingIterator (FlowBranching parent, Iterator iterator)
641 : base (parent, BranchingType.Iterator, SiblingType.Block, iterator.Block, iterator.Location)
643 this.iterator = iterator;
646 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
648 pc = iterator.AddResumePoint (stmt);
653 public class FlowBranchingToplevel : FlowBranchingBlock
655 UsageVector return_origins;
657 public FlowBranchingToplevel (FlowBranching parent, ParametersBlock stmt)
658 : base (parent, BranchingType.Toplevel, SiblingType.Conditional, stmt, stmt.loc)
662 public override bool CheckRethrow (Location loc)
664 Report.Error (156, loc, "A throw statement with no arguments is not allowed outside of a catch clause");
668 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
670 throw new InternalErrorException ("A yield in a non-iterator block");
673 public override bool AddBreakOrigin (UsageVector vector, Location loc)
675 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
679 public override bool AddContinueOrigin (UsageVector vector, Location loc)
681 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
685 public override bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
687 vector = vector.Clone ();
688 vector.Location = stmt.loc;
689 vector.Next = return_origins;
690 return_origins = vector;
694 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
696 string name = goto_stmt.Target;
697 LabeledStatement s = Block.LookupLabel (name);
699 throw new InternalErrorException ("Shouldn't get here");
701 if (Parent == null) {
702 Error_UnknownLabel (goto_stmt.loc, name, Report);
706 int errors = Report.Errors;
707 Parent.AddGotoOrigin (vector, goto_stmt);
708 if (errors == Report.Errors)
709 Report.Error (1632, goto_stmt.loc, "Control cannot leave the body of an anonymous method");
713 protected override UsageVector Merge ()
715 for (UsageVector origin = return_origins; origin != null; origin = origin.Next)
716 Block.ParametersBlock.CheckOutParameters (origin, origin.Location);
718 UsageVector vector = base.Merge ();
719 Block.ParametersBlock.CheckOutParameters (vector, Block.loc);
720 // Note: we _do_not_ merge in the return origins
726 return Merge ().IsUnreachable;
730 public class FlowBranchingTryCatch : FlowBranchingBlock
733 public FlowBranchingTryCatch (FlowBranching parent, TryCatch stmt)
734 : base (parent, BranchingType.Block, SiblingType.Try, null, stmt.loc)
739 public override bool CheckRethrow (Location loc)
741 return CurrentUsageVector.Next != null || Parent.CheckRethrow (loc);
744 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
746 int errors = Report.Errors;
747 Parent.AddResumePoint (stmt, loc, out pc);
748 if (errors == Report.Errors) {
749 if (CurrentUsageVector.Next == null)
750 Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
752 Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
757 public override bool AddBreakOrigin (UsageVector vector, Location loc)
759 Parent.AddBreakOrigin (vector, loc);
760 stmt.SomeCodeFollows ();
764 public override bool AddContinueOrigin (UsageVector vector, Location loc)
766 Parent.AddContinueOrigin (vector, loc);
767 stmt.SomeCodeFollows ();
771 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
773 Parent.AddReturnOrigin (vector, exit_stmt);
774 stmt.SomeCodeFollows ();
778 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
780 Parent.AddGotoOrigin (vector, goto_stmt);
785 public class FlowBranchingException : FlowBranching
787 ExceptionStatement stmt;
788 UsageVector current_vector;
789 UsageVector try_vector;
790 UsageVector finally_vector;
792 abstract class SavedOrigin {
793 public readonly SavedOrigin Next;
794 public readonly UsageVector Vector;
796 protected SavedOrigin (SavedOrigin next, UsageVector vector)
799 Vector = vector.Clone ();
802 protected abstract void DoPropagateFinally (FlowBranching parent);
803 public void PropagateFinally (UsageVector finally_vector, FlowBranching parent)
805 if (finally_vector != null)
806 Vector.MergeChild (finally_vector, false);
807 DoPropagateFinally (parent);
811 class BreakOrigin : SavedOrigin {
813 public BreakOrigin (SavedOrigin next, UsageVector vector, Location loc)
814 : base (next, vector)
819 protected override void DoPropagateFinally (FlowBranching parent)
821 parent.AddBreakOrigin (Vector, Loc);
825 class ContinueOrigin : SavedOrigin {
827 public ContinueOrigin (SavedOrigin next, UsageVector vector, Location loc)
828 : base (next, vector)
833 protected override void DoPropagateFinally (FlowBranching parent)
835 parent.AddContinueOrigin (Vector, Loc);
839 class ReturnOrigin : SavedOrigin {
840 public ExitStatement Stmt;
842 public ReturnOrigin (SavedOrigin next, UsageVector vector, ExitStatement stmt)
843 : base (next, vector)
848 protected override void DoPropagateFinally (FlowBranching parent)
850 parent.AddReturnOrigin (Vector, Stmt);
854 class GotoOrigin : SavedOrigin {
857 public GotoOrigin (SavedOrigin next, UsageVector vector, Goto stmt)
858 : base (next, vector)
863 protected override void DoPropagateFinally (FlowBranching parent)
865 parent.AddGotoOrigin (Vector, Stmt);
869 SavedOrigin saved_origins;
871 public FlowBranchingException (FlowBranching parent,
872 ExceptionStatement stmt)
873 : base (parent, BranchingType.Exception, SiblingType.Try,
879 protected override void AddSibling (UsageVector sibling)
881 switch (sibling.Type) {
882 case SiblingType.Try:
883 try_vector = sibling;
885 case SiblingType.Finally:
886 finally_vector = sibling;
889 throw new InvalidOperationException ();
891 current_vector = sibling;
894 public override UsageVector CurrentUsageVector {
895 get { return current_vector; }
898 public override bool CheckRethrow (Location loc)
900 if (!Parent.CheckRethrow (loc))
902 if (finally_vector == null)
904 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");
908 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
910 int errors = Report.Errors;
911 Parent.AddResumePoint (this.stmt, loc, out pc);
912 if (errors == Report.Errors) {
913 if (finally_vector == null)
914 this.stmt.AddResumePoint (stmt, pc);
916 Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
921 public override bool AddBreakOrigin (UsageVector vector, Location loc)
923 if (finally_vector != null) {
924 int errors = Report.Errors;
925 Parent.AddBreakOrigin (vector, loc);
926 if (errors == Report.Errors)
927 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
929 saved_origins = new BreakOrigin (saved_origins, vector, loc);
932 // either the loop test or a back jump will follow code
933 stmt.SomeCodeFollows ();
937 public override bool AddContinueOrigin (UsageVector vector, Location loc)
939 if (finally_vector != null) {
940 int errors = Report.Errors;
941 Parent.AddContinueOrigin (vector, loc);
942 if (errors == Report.Errors)
943 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
945 saved_origins = new ContinueOrigin (saved_origins, vector, loc);
948 // either the loop test or a back jump will follow code
949 stmt.SomeCodeFollows ();
953 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
955 if (finally_vector != null) {
956 int errors = Report.Errors;
957 Parent.AddReturnOrigin (vector, exit_stmt);
958 if (errors == Report.Errors)
959 exit_stmt.Error_FinallyClause (Report);
961 saved_origins = new ReturnOrigin (saved_origins, vector, exit_stmt);
964 // sets ec.NeedReturnLabel()
965 stmt.SomeCodeFollows ();
969 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
971 LabeledStatement s = current_vector.Block == null ? null : current_vector.Block.LookupLabel (goto_stmt.Target);
973 throw new InternalErrorException ("Shouldn't get here");
975 if (finally_vector != null) {
976 int errors = Report.Errors;
977 Parent.AddGotoOrigin (vector, goto_stmt);
978 if (errors == Report.Errors)
979 Report.Error (157, goto_stmt.loc, "Control cannot leave the body of a finally clause");
981 saved_origins = new GotoOrigin (saved_origins, vector, goto_stmt);
986 protected override UsageVector Merge ()
988 UsageVector vector = try_vector.Clone ();
990 if (finally_vector != null)
991 vector.MergeChild (finally_vector, false);
993 for (SavedOrigin origin = saved_origins; origin != null; origin = origin.Next)
994 origin.PropagateFinally (finally_vector, Parent);
1001 // This is used by the flow analysis code to keep track of the type of local variables
1004 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1005 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1006 // you can only assign the whole variable as such.
1008 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1009 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1010 // one bit for each of its fields.
1012 // This class computes this `layout' for each type.
1014 public class TypeInfo
1016 public readonly TypeSpec Type;
1019 // Total number of bits a variable of this type consumes in the flow vector.
1021 public readonly int TotalLength;
1024 // Number of bits the simple fields of a variable of this type consume
1025 // in the flow vector.
1027 public readonly int Length;
1030 // This is only used by sub-structs.
1032 public readonly int Offset;
1035 // If this is a struct.
1037 public readonly bool IsStruct;
1040 // If this is a struct, all fields which are structs theirselves.
1042 public TypeInfo[] SubStructInfo;
1044 readonly StructInfo struct_info;
1045 private static Dictionary<TypeSpec, TypeInfo> type_hash;
1052 public static void Reset ()
1054 type_hash = new Dictionary<TypeSpec, TypeInfo> ();
1055 StructInfo.field_type_hash = new Dictionary<TypeSpec, StructInfo> ();
1058 public static TypeInfo GetTypeInfo (TypeSpec type)
1061 if (type_hash.TryGetValue (type, out info))
1064 info = new TypeInfo (type);
1065 type_hash.Add (type, info);
1069 private TypeInfo (TypeSpec type)
1073 struct_info = StructInfo.GetStructInfo (type);
1074 if (struct_info != null) {
1075 Length = struct_info.Length;
1076 TotalLength = struct_info.TotalLength;
1077 SubStructInfo = struct_info.StructFields;
1086 TypeInfo (StructInfo struct_info, int offset)
1088 this.struct_info = struct_info;
1089 this.Offset = offset;
1090 this.Length = struct_info.Length;
1091 this.TotalLength = struct_info.TotalLength;
1092 this.SubStructInfo = struct_info.StructFields;
1093 this.Type = struct_info.Type;
1094 this.IsStruct = true;
1097 public int GetFieldIndex (string name)
1099 if (struct_info == null)
1102 return struct_info [name];
1105 public TypeInfo GetSubStruct (string name)
1107 if (struct_info == null)
1110 return struct_info.GetStructField (name);
1114 // A struct's constructor must always assign all fields.
1115 // This method checks whether it actually does so.
1117 public bool IsFullyInitialized (BlockContext ec, VariableInfo vi, Location loc)
1119 if (struct_info == null)
1123 FlowBranching branching = ec.CurrentBranching;
1124 for (int i = 0; i < struct_info.Count; i++) {
1125 var field = struct_info.Fields [i];
1127 if (!branching.IsFieldAssigned (vi, field.Name)) {
1128 if (field.MemberDefinition is Property.BackingField) {
1129 ec.Report.Error (843, loc,
1130 "An automatically implemented property `{0}' must be fully assigned before control leaves the constructor. Consider calling the default struct contructor from a constructor initializer",
1131 field.GetSignatureForError ());
1133 ec.Report.Error (171, loc,
1134 "Field `{0}' must be fully assigned before control leaves the constructor",
1135 field.GetSignatureForError ());
1144 public override string ToString ()
1146 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1147 Type, Offset, Length, TotalLength);
1151 public readonly TypeSpec Type;
1152 public readonly FieldSpec[] Fields;
1153 public readonly TypeInfo[] StructFields;
1154 public readonly int Count;
1155 public readonly int CountPublic;
1156 public readonly int CountNonPublic;
1157 public readonly int Length;
1158 public readonly int TotalLength;
1159 public readonly bool HasStructFields;
1161 public static Dictionary<TypeSpec, StructInfo> field_type_hash;
1162 private Dictionary<string, TypeInfo> struct_field_hash;
1163 private Dictionary<string, int> field_hash;
1165 protected bool InTransit = false;
1167 // Private constructor. To save memory usage, we only need to create one instance
1168 // of this class per struct type.
1169 private StructInfo (TypeSpec type)
1173 field_type_hash.Add (type, this);
1175 TypeContainer tc = type.MemberDefinition as TypeContainer;
1177 var public_fields = new List<FieldSpec> ();
1178 var non_public_fields = new List<FieldSpec> ();
1181 var fields = tc.Fields;
1183 if (fields != null) {
1184 foreach (FieldBase field in fields) {
1185 if ((field.ModFlags & Modifiers.STATIC) != 0)
1187 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1188 public_fields.Add (field.Spec);
1190 non_public_fields.Add (field.Spec);
1195 CountPublic = public_fields.Count;
1196 CountNonPublic = non_public_fields.Count;
1197 Count = CountPublic + CountNonPublic;
1199 Fields = new FieldSpec[Count];
1200 public_fields.CopyTo (Fields, 0);
1201 non_public_fields.CopyTo (Fields, CountPublic);
1203 struct_field_hash = new Dictionary<string, TypeInfo> ();
1204 field_hash = new Dictionary<string, int> ();
1207 StructFields = new TypeInfo [Count];
1208 StructInfo[] sinfo = new StructInfo [Count];
1212 for (int i = 0; i < Count; i++) {
1213 var field = Fields [i];
1215 sinfo [i] = GetStructInfo (field.MemberType);
1216 if (sinfo [i] == null)
1217 field_hash.Add (field.Name, ++Length);
1218 else if (sinfo [i].InTransit) {
1226 TotalLength = Length + 1;
1227 for (int i = 0; i < Count; i++) {
1228 var field = Fields [i];
1230 if (sinfo [i] == null)
1233 field_hash.Add (field.Name, TotalLength);
1235 HasStructFields = true;
1236 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1237 struct_field_hash.Add (field.Name, StructFields [i]);
1238 TotalLength += sinfo [i].TotalLength;
1242 public int this [string name] {
1245 if (!field_hash.TryGetValue (name, out val))
1252 public TypeInfo GetStructField (string name)
1255 if (struct_field_hash.TryGetValue (name, out ti))
1261 public static StructInfo GetStructInfo (TypeSpec type)
1263 if (!type.IsStruct || TypeManager.IsBuiltinType (type))
1267 if (field_type_hash.TryGetValue (type, out info))
1270 return new StructInfo (type);
1276 // This is used by the flow analysis code to store information about a single local variable
1277 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1278 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1279 // it has been assigned or not, but for structs, we need this information for each of its fields.
1281 public class VariableInfo {
1282 public readonly string Name;
1283 public readonly TypeInfo TypeInfo;
1286 // The bit offset of this variable in the flow vector.
1288 public readonly int Offset;
1291 // The number of bits this variable needs in the flow vector.
1292 // The first bit always specifies whether the variable as such has been assigned while
1293 // the remaining bits contain this information for each of a struct's fields.
1295 public readonly int Length;
1298 // If this is a parameter of local variable.
1300 public readonly bool IsParameter;
1302 public readonly LocalVariable LocalInfo;
1304 readonly VariableInfo Parent;
1305 VariableInfo[] sub_info;
1307 bool is_ever_assigned;
1308 public bool IsEverAssigned {
1309 get { return is_ever_assigned; }
1312 protected VariableInfo (string name, TypeSpec type, int offset)
1315 this.Offset = offset;
1316 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1318 Length = TypeInfo.TotalLength;
1323 protected VariableInfo (VariableInfo parent, TypeInfo type)
1325 this.Name = parent.Name;
1326 this.TypeInfo = type;
1327 this.Offset = parent.Offset + type.Offset;
1328 this.Parent = parent;
1329 this.Length = type.TotalLength;
1331 this.IsParameter = parent.IsParameter;
1332 this.LocalInfo = parent.LocalInfo;
1337 protected void Initialize ()
1339 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1340 if (sub_fields != null) {
1341 sub_info = new VariableInfo [sub_fields.Length];
1342 for (int i = 0; i < sub_fields.Length; i++) {
1343 if (sub_fields [i] != null)
1344 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1347 sub_info = new VariableInfo [0];
1350 public VariableInfo (LocalVariable local_info, int offset)
1351 : this (local_info.Name, local_info.Type, offset)
1353 this.LocalInfo = local_info;
1354 this.IsParameter = false;
1357 public VariableInfo (ParametersCompiled ip, int i, int offset)
1358 : this (ip.FixedParameters [i].Name, ip.Types [i], offset)
1360 this.IsParameter = true;
1363 public bool IsAssigned (ResolveContext ec)
1365 return !ec.DoFlowAnalysis ||
1366 (ec.OmitStructFlowAnalysis && TypeInfo.Type.IsStruct) ||
1367 ec.CurrentBranching.IsAssigned (this);
1370 public bool IsAssigned (ResolveContext ec, Location loc)
1372 if (IsAssigned (ec))
1375 ec.Report.Error (165, loc,
1376 "Use of unassigned local variable `" + Name + "'");
1377 ec.CurrentBranching.SetAssigned (this);
1381 public bool IsAssigned (MyBitVector vector)
1386 if (vector [Offset])
1389 // FIXME: Fix SetFieldAssigned to set the whole range like SetAssigned below. Then, get rid of this stanza
1390 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent) {
1391 if (vector [parent.Offset]) {
1392 // 'parent' is assigned, but someone forgot to note that all its components are assigned too
1393 parent.SetAssigned (vector);
1398 // Return unless this is a struct.
1399 if (!TypeInfo.IsStruct)
1402 // Ok, so each field must be assigned.
1403 for (int i = 0; i < TypeInfo.Length; i++) {
1404 if (!vector [Offset + i + 1])
1408 // Ok, now check all fields which are structs.
1409 for (int i = 0; i < sub_info.Length; i++) {
1410 VariableInfo sinfo = sub_info [i];
1414 if (!sinfo.IsAssigned (vector))
1418 vector [Offset] = true;
1419 is_ever_assigned = true;
1423 public void SetAssigned (ResolveContext ec)
1425 if (ec.DoFlowAnalysis)
1426 ec.CurrentBranching.SetAssigned (this);
1429 public void SetAssigned (MyBitVector vector)
1432 vector [Offset] = true;
1434 vector.SetRange (Offset, Length);
1435 is_ever_assigned = true;
1438 public bool IsFieldAssigned (ResolveContext ec, string name, Location loc)
1440 if (!ec.DoFlowAnalysis ||
1441 ec.OmitStructFlowAnalysis && TypeInfo.IsStruct ||
1442 ec.CurrentBranching.IsFieldAssigned (this, name))
1445 ec.Report.Error (170, loc,
1446 "Use of possibly unassigned field `" + name + "'");
1447 ec.CurrentBranching.SetFieldAssigned (this, name);
1451 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1453 int field_idx = TypeInfo.GetFieldIndex (field_name);
1458 return vector [Offset + field_idx];
1461 public void SetFieldAssigned (ResolveContext ec, string name)
1463 if (ec.DoFlowAnalysis)
1464 ec.CurrentBranching.SetFieldAssigned (this, name);
1467 public void SetFieldAssigned (MyBitVector vector, string field_name)
1469 int field_idx = TypeInfo.GetFieldIndex (field_name);
1474 vector [Offset + field_idx] = true;
1475 is_ever_assigned = true;
1478 public VariableInfo GetSubStruct (string name)
1480 TypeInfo type = TypeInfo.GetSubStruct (name);
1485 return new VariableInfo (this, type);
1488 public override string ToString ()
1490 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1491 Name, TypeInfo, Offset, Length, IsParameter);
1496 // This is a special bit vector which can inherit from another bit vector doing a
1497 // copy-on-write strategy. The inherited vector may have a smaller size than the
1500 public class MyBitVector {
1501 public readonly int Count;
1502 public static readonly MyBitVector Empty = new MyBitVector ();
1504 // Invariant: vector != null => vector.Count == Count
1505 // Invariant: vector == null || shared == null
1506 // i.e., at most one of 'vector' and 'shared' can be non-null. They can both be null -- that means all-ones
1507 // The object in 'shared' cannot be modified, while 'vector' can be freely modified
1508 System.Collections.BitArray vector, shared;
1512 shared = new System.Collections.BitArray (0, false);
1515 public MyBitVector (MyBitVector InheritsFrom, int Count)
1517 if (InheritsFrom != null)
1518 shared = InheritsFrom.MakeShared (Count);
1523 System.Collections.BitArray MakeShared (int new_count)
1525 // Post-condition: vector == null
1527 // ensure we don't leak out dirty bits from the BitVector we inherited from
1528 if (new_count > Count &&
1529 ((shared != null && shared.Count > Count) ||
1530 (shared == null && vector == null)))
1531 initialize_vector ();
1533 if (vector != null) {
1542 // Get/set bit `index' in the bit vector.
1544 public bool this [int index] {
1547 // FIXME: Disabled due to missing anonymous method flow analysis
1548 // throw new ArgumentOutOfRangeException ();
1552 return vector [index];
1555 if (index < shared.Count)
1556 return shared [index];
1561 // Only copy the vector if we're actually modifying it.
1562 if (this [index] != value) {
1564 initialize_vector ();
1565 vector [index] = value;
1571 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1572 // different size than the current one.
1574 private MyBitVector Or (MyBitVector new_vector)
1576 if (Count == 0 || new_vector.Count == 0)
1579 var o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1582 int n = new_vector.Count;
1584 for (int i = 0; i < n; ++i)
1592 if (Count == o.Count) {
1593 if (vector == null) {
1596 initialize_vector ();
1606 for (int i = 0; i < min; i++) {
1615 // Performs an `and' operation on the bit vector. The `new_vector' may have
1616 // a different size than the current one.
1618 private MyBitVector And (MyBitVector new_vector)
1623 var o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1626 for (int i = new_vector.Count; i < Count; ++i)
1636 if (Count == o.Count) {
1637 if (vector == null) {
1638 if (shared == null) {
1639 shared = new_vector.MakeShared (Count);
1642 initialize_vector ();
1652 for (int i = 0; i < min; i++) {
1657 for (int i = min; i < Count; i++)
1663 public static MyBitVector operator & (MyBitVector a, MyBitVector b)
1671 if (a.Count > b.Count)
1672 return a.Clone ().And (b);
1674 return b.Clone ().And (a);
1677 public static MyBitVector operator | (MyBitVector a, MyBitVector b)
1682 return new MyBitVector (null, b.Count);
1684 return new MyBitVector (null, a.Count);
1685 if (a.Count > b.Count)
1686 return a.Clone ().Or (b);
1688 return b.Clone ().Or (a);
1691 public MyBitVector Clone ()
1693 return Count == 0 ? Empty : new MyBitVector (this, Count);
1696 public void SetRange (int offset, int length)
1698 if (offset > Count || offset + length > Count)
1699 throw new ArgumentOutOfRangeException ("flow-analysis");
1701 if (shared == null && vector == null)
1705 if (shared != null) {
1706 if (offset + length <= shared.Count) {
1707 for (; i < length; ++i)
1708 if (!shared [i+offset])
1713 initialize_vector ();
1715 for (; i < length; ++i)
1716 vector [i+offset] = true;
1720 public void SetAll (bool value)
1722 // Don't clobber Empty
1725 shared = value ? null : Empty.MakeShared (Count);
1729 void initialize_vector ()
1731 // Post-condition: vector != null
1732 if (shared == null) {
1733 vector = new System.Collections.BitArray (Count, true);
1737 vector = new System.Collections.BitArray (shared);
1738 if (Count != vector.Count)
1739 vector.Length = Count;
1743 StringBuilder Dump (StringBuilder sb)
1745 var dump = vector == null ? shared : vector;
1747 return sb.Append ("/");
1750 for (int i = 0; i < dump.Count; i++)
1751 sb.Append (dump [i] ? "1" : "0");
1755 public override string ToString ()
1757 return Dump (new StringBuilder ("{")).Append ("}").ToString ();