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;
15 using System.Collections.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Diagnostics;
23 // A new instance of this class is created every time a new block is resolved
24 // and if there's branching in the block's control flow.
26 public abstract class FlowBranching
29 // The type of a FlowBranching.
31 public enum BranchingType : byte {
32 // Normal (conditional or toplevel) block.
41 // The statement embedded inside a loop
44 // part of a block headed by a jump target
50 // TryFinally, Using, Lock, CollectionForeach
56 // The toplevel block of a function
64 // The type of one sibling of a branching.
66 public enum SiblingType : byte {
75 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
78 case BranchingType.Exception:
79 case BranchingType.Labeled:
80 case BranchingType.Toplevel:
81 case BranchingType.TryCatch:
82 throw new InvalidOperationException ();
84 case BranchingType.Switch:
85 return new FlowBranchingBreakable (parent, type, SiblingType.SwitchSection, block, loc);
87 case BranchingType.Block:
88 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
90 case BranchingType.Loop:
91 return new FlowBranchingBreakable (parent, type, SiblingType.Conditional, block, loc);
93 case BranchingType.Embedded:
94 return new FlowBranchingContinuable (parent, type, SiblingType.Conditional, block, loc);
97 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
102 // The type of this flow branching.
104 public readonly BranchingType Type;
107 // The block this branching is contained in. This may be null if it's not
108 // a top-level block and it doesn't declare any local variables.
110 public readonly Block Block;
113 // The parent of this branching or null if this is the top-block.
115 public readonly FlowBranching Parent;
118 // Start-Location of this flow branching.
120 public readonly Location Location;
122 static int next_id = 0;
126 // The vector contains a BitArray with information about which local variables
127 // and parameters are already initialized at the current code position.
129 public class UsageVector {
131 // The type of this branching.
133 public readonly SiblingType Type;
136 // Start location of this branching.
138 public Location Location;
141 // This is only valid for SwitchSection, Try, Catch and Finally.
143 public readonly Block Block;
146 // The number of locals in this block.
148 public readonly int CountLocals;
151 // If not null, then we inherit our state from this vector and do a
152 // copy-on-write. If null, then we're the first sibling in a top-level
153 // block and inherit from the empty vector.
155 public readonly UsageVector InheritsFrom;
158 // This is used to construct a list of UsageVector's.
160 public UsageVector Next;
168 static int next_id = 0;
172 // Normally, you should not use any of these constructors.
174 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc, int num_locals)
179 this.InheritsFrom = parent;
180 this.CountLocals = num_locals;
182 locals = num_locals == 0
184 : new MyBitVector (parent == null ? MyBitVector.Empty : parent.locals, num_locals);
187 is_unreachable = parent.is_unreachable;
193 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc)
194 : this (type, parent, block, loc, parent.CountLocals)
197 private UsageVector (MyBitVector locals, bool is_unreachable, Block block, Location loc)
199 this.Type = SiblingType.Block;
203 this.is_unreachable = is_unreachable;
205 this.locals = locals;
212 // This does a deep copy of the usage vector.
214 public UsageVector Clone ()
216 UsageVector retval = new UsageVector (Type, null, Block, Location, CountLocals);
218 retval.locals = locals.Clone ();
219 retval.is_unreachable = is_unreachable;
224 public bool IsAssigned (VariableInfo var, bool ignoreReachability)
226 if (!ignoreReachability && !var.IsParameter && IsUnreachable)
229 return var.IsAssigned (locals);
232 public void SetAssigned (VariableInfo var)
234 if (!var.IsParameter && IsUnreachable)
237 var.SetAssigned (locals);
240 public bool IsFieldAssigned (VariableInfo var, string name)
242 if (!var.IsParameter && IsUnreachable)
245 return var.IsFieldAssigned (locals, name);
248 public void SetFieldAssigned (VariableInfo var, string name)
250 if (!var.IsParameter && IsUnreachable)
253 var.SetFieldAssigned (locals, name);
256 public bool IsUnreachable {
257 get { return is_unreachable; }
260 public void ResetBarrier ()
262 is_unreachable = false;
267 is_unreachable = true;
270 public static UsageVector MergeSiblings (UsageVector sibling_list, Location loc)
272 if (sibling_list.Next == null)
275 MyBitVector locals = null;
276 bool is_unreachable = sibling_list.is_unreachable;
278 if (!sibling_list.IsUnreachable)
279 locals &= sibling_list.locals;
281 for (UsageVector child = sibling_list.Next; child != null; child = child.Next) {
282 is_unreachable &= child.is_unreachable;
284 if (!child.IsUnreachable)
285 locals &= child.locals;
288 return new UsageVector (locals, is_unreachable, null, loc);
292 // Merges a child branching.
294 public UsageVector MergeChild (UsageVector child, bool overwrite)
296 Report.Debug (2, " MERGING CHILD EFFECTS", this, child, Type);
298 bool new_isunr = child.is_unreachable;
301 // We've now either reached the point after the branching or we will
302 // never get there since we always return or always throw an exception.
304 // If we can reach the point after the branching, mark all locals and
305 // parameters as initialized which have been initialized in all branches
306 // we need to look at (see above).
309 if ((Type == SiblingType.SwitchSection) && !new_isunr) {
310 Report.Error (163, Location,
311 "Control cannot fall through from one " +
312 "case label to another");
316 locals |= child.locals;
318 // throw away un-necessary information about variables in child blocks
319 if (locals.Count != CountLocals)
320 locals = new MyBitVector (locals, CountLocals);
323 is_unreachable = new_isunr;
325 is_unreachable |= new_isunr;
330 public void MergeOrigins (UsageVector o_vectors)
332 Report.Debug (1, " MERGING BREAK ORIGINS", this);
334 if (o_vectors == null)
337 if (IsUnreachable && locals != null)
338 locals.SetAll (true);
340 for (UsageVector vector = o_vectors; vector != null; vector = vector.Next) {
341 Report.Debug (1, " MERGING BREAK ORIGIN", vector);
342 if (vector.IsUnreachable)
344 locals &= vector.locals;
345 is_unreachable &= vector.is_unreachable;
348 Report.Debug (1, " MERGING BREAK ORIGINS DONE", this);
355 public override string ToString ()
357 return String.Format ("Vector ({0},{1},{2}-{3})", Type, id, is_unreachable, locals);
362 // Creates a new flow branching which is contained in `parent'.
363 // You should only pass non-null for the `block' argument if this block
364 // introduces any new variables - in this case, we need to create a new
365 // usage vector with a different size than our parent's one.
367 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
368 Block block, Location loc)
378 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
379 vector = new UsageVector (stype, parent_vector, Block, loc, Block.AssignableSlots);
381 vector = new UsageVector (stype, Parent.CurrentUsageVector, null, loc);
387 public abstract UsageVector CurrentUsageVector {
392 // Creates a sibling of the current usage vector.
394 public virtual void CreateSibling (Block block, SiblingType type)
396 UsageVector vector = new UsageVector (
397 type, Parent.CurrentUsageVector, block, Location);
400 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
403 public void CreateSibling ()
405 CreateSibling (null, SiblingType.Conditional);
408 protected abstract void AddSibling (UsageVector uv);
410 protected abstract UsageVector Merge ();
412 public UsageVector MergeChild (FlowBranching child)
414 return CurrentUsageVector.MergeChild (child.Merge (), true);
417 public virtual bool CheckRethrow (Location loc)
419 return Parent.CheckRethrow (loc);
422 public virtual bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
424 return Parent.AddResumePoint (stmt, loc, out pc);
427 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
428 public virtual bool AddBreakOrigin (UsageVector vector, Location loc)
430 return Parent.AddBreakOrigin (vector, loc);
433 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
434 public virtual bool AddContinueOrigin (UsageVector vector, Location loc)
436 return Parent.AddContinueOrigin (vector, loc);
439 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
440 public virtual bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
442 return Parent.AddReturnOrigin (vector, stmt);
445 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
446 public virtual bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
448 return Parent.AddGotoOrigin (vector, goto_stmt);
451 public bool IsAssigned (VariableInfo vi)
453 return CurrentUsageVector.IsAssigned (vi, false);
456 public bool IsFieldAssigned (VariableInfo vi, string field_name)
458 return CurrentUsageVector.IsAssigned (vi, false) || CurrentUsageVector.IsFieldAssigned (vi, field_name);
461 protected static Report Report {
462 get { return RootContext.ToplevelTypes.Compiler.Report; }
465 public void SetAssigned (VariableInfo vi)
467 CurrentUsageVector.SetAssigned (vi);
470 public void SetFieldAssigned (VariableInfo vi, string name)
472 CurrentUsageVector.SetFieldAssigned (vi, name);
475 public override string ToString ()
477 StringBuilder sb = new StringBuilder ();
478 sb.Append (GetType ());
486 sb.Append (Block.ID);
488 sb.Append (Block.StartLocation);
491 // sb.Append (Siblings.Length);
492 // sb.Append (" - ");
493 sb.Append (CurrentUsageVector);
495 return sb.ToString ();
499 get { return String.Format ("{0} ({1}:{2}:{3})", GetType (), id, Type, Location); }
503 public class FlowBranchingBlock : FlowBranching
505 UsageVector sibling_list = null;
507 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
508 SiblingType stype, Block block, Location loc)
509 : base (parent, type, stype, block, loc)
512 public override UsageVector CurrentUsageVector {
513 get { return sibling_list; }
516 protected override void AddSibling (UsageVector sibling)
518 if (sibling_list != null && sibling_list.Type == SiblingType.Block)
519 throw new InternalErrorException ("Blocks don't have sibling flow paths");
520 sibling.Next = sibling_list;
521 sibling_list = sibling;
524 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
526 LabeledStatement stmt = Block == null ? null : Block.LookupLabel (goto_stmt.Target);
528 return Parent.AddGotoOrigin (vector, goto_stmt);
531 goto_stmt.SetResolvedTarget (stmt);
532 stmt.AddUsageVector (vector);
536 public static void Error_UnknownLabel (Location loc, string label, Report Report)
538 Report.Error(159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
542 protected override UsageVector Merge ()
544 Report.Debug (2, " MERGING SIBLINGS", Name);
545 UsageVector vector = UsageVector.MergeSiblings (sibling_list, Location);
546 Report.Debug (2, " MERGING SIBLINGS DONE", Name, vector);
551 public class FlowBranchingBreakable : FlowBranchingBlock
553 UsageVector break_origins;
555 public FlowBranchingBreakable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
556 : base (parent, type, stype, block, loc)
559 public override bool AddBreakOrigin (UsageVector vector, Location loc)
561 vector = vector.Clone ();
562 vector.Next = break_origins;
563 break_origins = vector;
567 protected override UsageVector Merge ()
569 UsageVector vector = base.Merge ();
570 vector.MergeOrigins (break_origins);
575 public class FlowBranchingContinuable : FlowBranchingBlock
577 UsageVector continue_origins;
579 public FlowBranchingContinuable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
580 : base (parent, type, stype, block, loc)
583 public override bool AddContinueOrigin (UsageVector vector, Location loc)
585 vector = vector.Clone ();
586 vector.Next = continue_origins;
587 continue_origins = vector;
591 protected override UsageVector Merge ()
593 UsageVector vector = base.Merge ();
594 vector.MergeOrigins (continue_origins);
599 public class FlowBranchingLabeled : FlowBranchingBlock
601 LabeledStatement stmt;
604 public FlowBranchingLabeled (FlowBranching parent, LabeledStatement stmt)
605 : base (parent, BranchingType.Labeled, SiblingType.Conditional, null, stmt.loc)
608 CurrentUsageVector.MergeOrigins (stmt.JumpOrigins);
609 actual = CurrentUsageVector.Clone ();
611 // stand-in for backward jumps
612 CurrentUsageVector.ResetBarrier ();
615 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
617 if (goto_stmt.Target != stmt.Name)
618 return Parent.AddGotoOrigin (vector, goto_stmt);
621 goto_stmt.SetResolvedTarget (stmt);
622 actual.MergeOrigins (vector.Clone ());
627 protected override UsageVector Merge ()
629 UsageVector vector = base.Merge ();
631 if (actual.IsUnreachable)
632 Report.Warning (162, 2, stmt.loc, "Unreachable code detected");
634 actual.MergeChild (vector, false);
639 public class FlowBranchingIterator : FlowBranchingBlock
642 public FlowBranchingIterator (FlowBranching parent, Iterator iterator)
643 : base (parent, BranchingType.Iterator, SiblingType.Block, null, iterator.Location)
645 this.iterator = iterator;
648 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
650 pc = iterator.AddResumePoint (stmt);
655 public class FlowBranchingToplevel : FlowBranchingBlock
657 UsageVector return_origins;
659 public FlowBranchingToplevel (FlowBranching parent, ToplevelBlock stmt)
660 : base (parent, BranchingType.Toplevel, SiblingType.Conditional, stmt, stmt.loc)
664 public override bool CheckRethrow (Location loc)
666 Report.Error (156, loc, "A throw statement with no arguments is not allowed outside of a catch clause");
670 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
672 throw new InternalErrorException ("A yield in a non-iterator block");
675 public override bool AddBreakOrigin (UsageVector vector, Location loc)
677 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
681 public override bool AddContinueOrigin (UsageVector vector, Location loc)
683 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
687 public override bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
689 vector = vector.Clone ();
690 vector.Location = stmt.loc;
691 vector.Next = return_origins;
692 return_origins = vector;
696 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
698 string name = goto_stmt.Target;
699 LabeledStatement s = Block.LookupLabel (name);
701 throw new InternalErrorException ("Shouldn't get here");
703 if (Parent == null) {
704 Error_UnknownLabel (goto_stmt.loc, name, Report);
708 int errors = Report.Errors;
709 Parent.AddGotoOrigin (vector, goto_stmt);
710 if (errors == Report.Errors)
711 Report.Error (1632, goto_stmt.loc, "Control cannot leave the body of an anonymous method");
715 protected override UsageVector Merge ()
717 for (UsageVector origin = return_origins; origin != null; origin = origin.Next)
718 Block.Toplevel.CheckOutParameters (origin, origin.Location);
720 UsageVector vector = base.Merge ();
721 Block.Toplevel.CheckOutParameters (vector, Block.loc);
722 // Note: we _do_not_ merge in the return origins
728 return Merge ().IsUnreachable;
732 public class FlowBranchingTryCatch : FlowBranchingBlock
735 public FlowBranchingTryCatch (FlowBranching parent, TryCatch stmt)
736 : base (parent, BranchingType.Block, SiblingType.Try, null, stmt.loc)
741 public override bool CheckRethrow (Location loc)
743 return CurrentUsageVector.Next != null || Parent.CheckRethrow (loc);
746 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
748 int errors = Report.Errors;
749 Parent.AddResumePoint (stmt, loc, out pc);
750 if (errors == Report.Errors) {
751 if (CurrentUsageVector.Next == null)
752 Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
754 Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
759 public override bool AddBreakOrigin (UsageVector vector, Location loc)
761 Parent.AddBreakOrigin (vector, loc);
762 stmt.SomeCodeFollows ();
766 public override bool AddContinueOrigin (UsageVector vector, Location loc)
768 Parent.AddContinueOrigin (vector, loc);
769 stmt.SomeCodeFollows ();
773 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
775 Parent.AddReturnOrigin (vector, exit_stmt);
776 stmt.SomeCodeFollows ();
780 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
782 Parent.AddGotoOrigin (vector, goto_stmt);
787 public class FlowBranchingException : FlowBranching
789 ExceptionStatement stmt;
790 UsageVector current_vector;
791 UsageVector try_vector;
792 UsageVector finally_vector;
794 abstract class SavedOrigin {
795 public readonly SavedOrigin Next;
796 public readonly UsageVector Vector;
798 protected SavedOrigin (SavedOrigin next, UsageVector vector)
801 Vector = vector.Clone ();
804 protected abstract void DoPropagateFinally (FlowBranching parent);
805 public void PropagateFinally (UsageVector finally_vector, FlowBranching parent)
807 if (finally_vector != null)
808 Vector.MergeChild (finally_vector, false);
809 DoPropagateFinally (parent);
813 class BreakOrigin : SavedOrigin {
815 public BreakOrigin (SavedOrigin next, UsageVector vector, Location loc)
816 : base (next, vector)
821 protected override void DoPropagateFinally (FlowBranching parent)
823 parent.AddBreakOrigin (Vector, Loc);
827 class ContinueOrigin : SavedOrigin {
829 public ContinueOrigin (SavedOrigin next, UsageVector vector, Location loc)
830 : base (next, vector)
835 protected override void DoPropagateFinally (FlowBranching parent)
837 parent.AddContinueOrigin (Vector, Loc);
841 class ReturnOrigin : SavedOrigin {
842 public ExitStatement Stmt;
844 public ReturnOrigin (SavedOrigin next, UsageVector vector, ExitStatement stmt)
845 : base (next, vector)
850 protected override void DoPropagateFinally (FlowBranching parent)
852 parent.AddReturnOrigin (Vector, Stmt);
856 class GotoOrigin : SavedOrigin {
859 public GotoOrigin (SavedOrigin next, UsageVector vector, Goto stmt)
860 : base (next, vector)
865 protected override void DoPropagateFinally (FlowBranching parent)
867 parent.AddGotoOrigin (Vector, Stmt);
871 SavedOrigin saved_origins;
873 public FlowBranchingException (FlowBranching parent,
874 ExceptionStatement stmt)
875 : base (parent, BranchingType.Exception, SiblingType.Try,
881 protected override void AddSibling (UsageVector sibling)
883 switch (sibling.Type) {
884 case SiblingType.Try:
885 try_vector = sibling;
887 case SiblingType.Finally:
888 finally_vector = sibling;
891 throw new InvalidOperationException ();
893 current_vector = sibling;
896 public override UsageVector CurrentUsageVector {
897 get { return current_vector; }
900 public override bool CheckRethrow (Location loc)
902 if (!Parent.CheckRethrow (loc))
904 if (finally_vector == null)
906 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");
910 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
912 int errors = Report.Errors;
913 Parent.AddResumePoint (this.stmt, loc, out pc);
914 if (errors == Report.Errors) {
915 if (finally_vector == null)
916 this.stmt.AddResumePoint (stmt, pc);
918 Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
923 public override bool AddBreakOrigin (UsageVector vector, Location loc)
925 if (finally_vector != null) {
926 int errors = Report.Errors;
927 Parent.AddBreakOrigin (vector, loc);
928 if (errors == Report.Errors)
929 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
931 saved_origins = new BreakOrigin (saved_origins, vector, loc);
934 // either the loop test or a back jump will follow code
935 stmt.SomeCodeFollows ();
939 public override bool AddContinueOrigin (UsageVector vector, Location loc)
941 if (finally_vector != null) {
942 int errors = Report.Errors;
943 Parent.AddContinueOrigin (vector, loc);
944 if (errors == Report.Errors)
945 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
947 saved_origins = new ContinueOrigin (saved_origins, vector, loc);
950 // either the loop test or a back jump will follow code
951 stmt.SomeCodeFollows ();
955 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
957 if (finally_vector != null) {
958 int errors = Report.Errors;
959 Parent.AddReturnOrigin (vector, exit_stmt);
960 if (errors == Report.Errors)
961 exit_stmt.Error_FinallyClause (Report);
963 saved_origins = new ReturnOrigin (saved_origins, vector, exit_stmt);
966 // sets ec.NeedReturnLabel()
967 stmt.SomeCodeFollows ();
971 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
973 LabeledStatement s = current_vector.Block == null ? null : current_vector.Block.LookupLabel (goto_stmt.Target);
975 throw new InternalErrorException ("Shouldn't get here");
977 if (finally_vector != null) {
978 int errors = Report.Errors;
979 Parent.AddGotoOrigin (vector, goto_stmt);
980 if (errors == Report.Errors)
981 Report.Error (157, goto_stmt.loc, "Control cannot leave the body of a finally clause");
983 saved_origins = new GotoOrigin (saved_origins, vector, goto_stmt);
988 protected override UsageVector Merge ()
990 UsageVector vector = try_vector.Clone ();
992 if (finally_vector != null)
993 vector.MergeChild (finally_vector, false);
995 for (SavedOrigin origin = saved_origins; origin != null; origin = origin.Next)
996 origin.PropagateFinally (finally_vector, Parent);
1003 // This is used by the flow analysis code to keep track of the type of local variables
1006 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1007 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1008 // you can only assign the whole variable as such.
1010 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1011 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1012 // one bit for each of its fields.
1014 // This class computes this `layout' for each type.
1016 public class TypeInfo
1018 public readonly Type Type;
1021 // Total number of bits a variable of this type consumes in the flow vector.
1023 public readonly int TotalLength;
1026 // Number of bits the simple fields of a variable of this type consume
1027 // in the flow vector.
1029 public readonly int Length;
1032 // This is only used by sub-structs.
1034 public readonly int Offset;
1037 // If this is a struct.
1039 public readonly bool IsStruct;
1042 // If this is a struct, all fields which are structs theirselves.
1044 public TypeInfo[] SubStructInfo;
1046 readonly StructInfo struct_info;
1047 private static Dictionary<Type, TypeInfo> type_hash;
1054 public static void Reset ()
1056 type_hash = new Dictionary<Type, TypeInfo> ();
1057 StructInfo.field_type_hash = new Dictionary<Type, StructInfo> ();
1060 public static TypeInfo GetTypeInfo (Type type)
1063 if (type_hash.TryGetValue (type, out info))
1066 info = new TypeInfo (type);
1067 type_hash.Add (type, info);
1071 public static TypeInfo GetTypeInfo (TypeContainer tc)
1074 if (type_hash.TryGetValue (tc.TypeBuilder, out info))
1077 info = new TypeInfo (tc);
1078 type_hash.Add (tc.TypeBuilder, info);
1082 private TypeInfo (Type type)
1086 struct_info = StructInfo.GetStructInfo (type);
1087 if (struct_info != null) {
1088 Length = struct_info.Length;
1089 TotalLength = struct_info.TotalLength;
1090 SubStructInfo = struct_info.StructFields;
1099 private TypeInfo (TypeContainer tc)
1101 this.Type = tc.TypeBuilder;
1103 struct_info = StructInfo.GetStructInfo (tc);
1104 if (struct_info != null) {
1105 Length = struct_info.Length;
1106 TotalLength = struct_info.TotalLength;
1107 SubStructInfo = struct_info.StructFields;
1116 TypeInfo (StructInfo struct_info, int offset)
1118 this.struct_info = struct_info;
1119 this.Offset = offset;
1120 this.Length = struct_info.Length;
1121 this.TotalLength = struct_info.TotalLength;
1122 this.SubStructInfo = struct_info.StructFields;
1123 this.Type = struct_info.Type;
1124 this.IsStruct = true;
1127 public int GetFieldIndex (string name)
1129 if (struct_info == null)
1132 return struct_info [name];
1135 public TypeInfo GetSubStruct (string name)
1137 if (struct_info == null)
1140 return struct_info.GetStructField (name);
1144 // A struct's constructor must always assign all fields.
1145 // This method checks whether it actually does so.
1147 public bool IsFullyInitialized (BlockContext ec, VariableInfo vi, Location loc)
1149 if (struct_info == null)
1153 FlowBranching branching = ec.CurrentBranching;
1154 for (int i = 0; i < struct_info.Count; i++) {
1155 FieldInfo field = struct_info.Fields [i];
1157 if (!branching.IsFieldAssigned (vi, field.Name)) {
1158 FieldBase fb = TypeManager.GetField (field);
1159 if (fb is Property.BackingField) {
1160 ec.Report.Error (843, loc,
1161 "An automatically implemented property `{0}' must be fully assigned before control leaves the constructor. Consider calling default contructor",
1162 fb.GetSignatureForError ());
1164 ec.Report.Error (171, loc,
1165 "Field `{0}' must be fully assigned before control leaves the constructor",
1166 TypeManager.GetFullNameSignature (field));
1175 public override string ToString ()
1177 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1178 Type, Offset, Length, TotalLength);
1182 public readonly Type Type;
1183 public readonly FieldInfo[] Fields;
1184 public readonly TypeInfo[] StructFields;
1185 public readonly int Count;
1186 public readonly int CountPublic;
1187 public readonly int CountNonPublic;
1188 public readonly int Length;
1189 public readonly int TotalLength;
1190 public readonly bool HasStructFields;
1192 public static Dictionary<Type, StructInfo> field_type_hash;
1193 private Dictionary<string, TypeInfo> struct_field_hash;
1194 private Dictionary<string, int> field_hash;
1196 protected bool InTransit = false;
1198 // Private constructor. To save memory usage, we only need to create one instance
1199 // of this class per struct type.
1200 private StructInfo (Type type)
1204 field_type_hash.Add (type, this);
1206 if (TypeManager.IsBeingCompiled (type)) {
1207 TypeContainer tc = TypeManager.LookupTypeContainer (TypeManager.DropGenericTypeArguments (type));
1209 ArrayList public_fields = new ArrayList ();
1210 ArrayList non_public_fields = new ArrayList ();
1213 // TODO: tc != null is needed because FixedBuffers are not cached
1216 var fields = tc.Fields;
1218 if (fields != null) {
1219 foreach (FieldBase field in fields) {
1220 if ((field.ModFlags & Modifiers.STATIC) != 0)
1222 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1223 public_fields.Add (field.FieldBuilder);
1225 non_public_fields.Add (field.FieldBuilder);
1230 CountPublic = public_fields.Count;
1231 CountNonPublic = non_public_fields.Count;
1232 Count = CountPublic + CountNonPublic;
1234 Fields = new FieldInfo [Count];
1235 public_fields.CopyTo (Fields, 0);
1236 non_public_fields.CopyTo (Fields, CountPublic);
1237 } else if (type is GenericTypeParameterBuilder) {
1238 CountPublic = CountNonPublic = Count = 0;
1240 Fields = new FieldInfo [0];
1242 FieldInfo[] public_fields = type.GetFields (
1243 BindingFlags.Instance|BindingFlags.Public);
1244 FieldInfo[] non_public_fields = type.GetFields (
1245 BindingFlags.Instance|BindingFlags.NonPublic);
1247 CountPublic = public_fields.Length;
1248 CountNonPublic = non_public_fields.Length;
1249 Count = CountPublic + CountNonPublic;
1251 Fields = new FieldInfo [Count];
1252 public_fields.CopyTo (Fields, 0);
1253 non_public_fields.CopyTo (Fields, CountPublic);
1256 struct_field_hash = new Dictionary<string, TypeInfo> ();
1257 field_hash = new Dictionary<string, int> ();
1260 StructFields = new TypeInfo [Count];
1261 StructInfo[] sinfo = new StructInfo [Count];
1265 for (int i = 0; i < Count; i++) {
1266 FieldInfo field = (FieldInfo) Fields [i];
1268 sinfo [i] = GetStructInfo (field.FieldType);
1269 if (sinfo [i] == null)
1270 field_hash.Add (field.Name, ++Length);
1271 else if (sinfo [i].InTransit) {
1272 RootContext.ToplevelTypes.Compiler.Report.Error (523, String.Format (
1273 "Struct member `{0}.{1}' of type `{2}' causes " +
1274 "a cycle in the structure layout",
1275 type, field.Name, sinfo [i].Type));
1283 TotalLength = Length + 1;
1284 for (int i = 0; i < Count; i++) {
1285 FieldInfo field = (FieldInfo) Fields [i];
1287 if (sinfo [i] == null)
1290 field_hash.Add (field.Name, TotalLength);
1292 HasStructFields = true;
1293 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1294 struct_field_hash.Add (field.Name, StructFields [i]);
1295 TotalLength += sinfo [i].TotalLength;
1299 public int this [string name] {
1302 if (!field_hash.TryGetValue (name, out val))
1309 public TypeInfo GetStructField (string name)
1312 if (struct_field_hash.TryGetValue (name, out ti))
1318 public static StructInfo GetStructInfo (Type type)
1320 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1321 TypeManager.IsBuiltinType (type))
1324 if (TypeManager.IsGenericParameter (type))
1328 if (field_type_hash.TryGetValue (type, out info))
1331 return new StructInfo (type);
1334 public static StructInfo GetStructInfo (TypeContainer tc)
1337 if (field_type_hash.TryGetValue (tc.TypeBuilder, out info))
1340 return new StructInfo (tc.TypeBuilder);
1346 // This is used by the flow analysis code to store information about a single local variable
1347 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1348 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1349 // it has been assigned or not, but for structs, we need this information for each of its fields.
1351 public class VariableInfo {
1352 public readonly string Name;
1353 public readonly TypeInfo TypeInfo;
1356 // The bit offset of this variable in the flow vector.
1358 public readonly int Offset;
1361 // The number of bits this variable needs in the flow vector.
1362 // The first bit always specifies whether the variable as such has been assigned while
1363 // the remaining bits contain this information for each of a struct's fields.
1365 public readonly int Length;
1368 // If this is a parameter of local variable.
1370 public readonly bool IsParameter;
1372 public readonly LocalInfo LocalInfo;
1374 readonly VariableInfo Parent;
1375 VariableInfo[] sub_info;
1377 bool is_ever_assigned;
1378 public bool IsEverAssigned {
1379 get { return is_ever_assigned; }
1382 protected VariableInfo (string name, Type type, int offset)
1385 this.Offset = offset;
1386 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1388 Length = TypeInfo.TotalLength;
1393 protected VariableInfo (VariableInfo parent, TypeInfo type)
1395 this.Name = parent.Name;
1396 this.TypeInfo = type;
1397 this.Offset = parent.Offset + type.Offset;
1398 this.Parent = parent;
1399 this.Length = type.TotalLength;
1401 this.IsParameter = parent.IsParameter;
1402 this.LocalInfo = parent.LocalInfo;
1407 protected void Initialize ()
1409 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1410 if (sub_fields != null) {
1411 sub_info = new VariableInfo [sub_fields.Length];
1412 for (int i = 0; i < sub_fields.Length; i++) {
1413 if (sub_fields [i] != null)
1414 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1417 sub_info = new VariableInfo [0];
1420 public VariableInfo (LocalInfo local_info, int offset)
1421 : this (local_info.Name, local_info.VariableType, offset)
1423 this.LocalInfo = local_info;
1424 this.IsParameter = false;
1427 public VariableInfo (ParametersCompiled ip, int i, int offset)
1428 : this (ip.FixedParameters [i].Name, ip.Types [i], offset)
1430 this.IsParameter = true;
1433 public bool IsAssigned (ResolveContext ec)
1435 return !ec.DoFlowAnalysis ||
1436 ec.OmitStructFlowAnalysis && TypeInfo.IsStruct ||
1437 ec.CurrentBranching.IsAssigned (this);
1440 public bool IsAssigned (ResolveContext ec, Location loc)
1442 if (IsAssigned (ec))
1445 ec.Report.Error (165, loc,
1446 "Use of unassigned local variable `" + Name + "'");
1447 ec.CurrentBranching.SetAssigned (this);
1451 public bool IsAssigned (MyBitVector vector)
1456 if (vector [Offset])
1459 // FIXME: Fix SetFieldAssigned to set the whole range like SetAssigned below. Then, get rid of this stanza
1460 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent) {
1461 if (vector [parent.Offset]) {
1462 // 'parent' is assigned, but someone forgot to note that all its components are assigned too
1463 parent.SetAssigned (vector);
1468 // Return unless this is a struct.
1469 if (!TypeInfo.IsStruct)
1472 // Ok, so each field must be assigned.
1473 for (int i = 0; i < TypeInfo.Length; i++) {
1474 if (!vector [Offset + i + 1])
1478 // Ok, now check all fields which are structs.
1479 for (int i = 0; i < sub_info.Length; i++) {
1480 VariableInfo sinfo = sub_info [i];
1484 if (!sinfo.IsAssigned (vector))
1488 vector [Offset] = true;
1489 is_ever_assigned = true;
1493 public void SetAssigned (ResolveContext ec)
1495 if (ec.DoFlowAnalysis)
1496 ec.CurrentBranching.SetAssigned (this);
1499 public void SetAssigned (MyBitVector vector)
1502 vector [Offset] = true;
1504 vector.SetRange (Offset, Length);
1505 is_ever_assigned = true;
1508 public bool IsFieldAssigned (ResolveContext ec, string name, Location loc)
1510 if (!ec.DoFlowAnalysis ||
1511 ec.OmitStructFlowAnalysis && TypeInfo.IsStruct ||
1512 ec.CurrentBranching.IsFieldAssigned (this, name))
1515 ec.Report.Error (170, loc,
1516 "Use of possibly unassigned field `" + name + "'");
1517 ec.CurrentBranching.SetFieldAssigned (this, name);
1521 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1523 int field_idx = TypeInfo.GetFieldIndex (field_name);
1528 return vector [Offset + field_idx];
1531 public void SetFieldAssigned (ResolveContext ec, string name)
1533 if (ec.DoFlowAnalysis)
1534 ec.CurrentBranching.SetFieldAssigned (this, name);
1537 public void SetFieldAssigned (MyBitVector vector, string field_name)
1539 int field_idx = TypeInfo.GetFieldIndex (field_name);
1544 vector [Offset + field_idx] = true;
1545 is_ever_assigned = true;
1548 public VariableInfo GetSubStruct (string name)
1550 TypeInfo type = TypeInfo.GetSubStruct (name);
1555 return new VariableInfo (this, type);
1558 public override string ToString ()
1560 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1561 Name, TypeInfo, Offset, Length, IsParameter);
1566 // This is a special bit vector which can inherit from another bit vector doing a
1567 // copy-on-write strategy. The inherited vector may have a smaller size than the
1570 public class MyBitVector {
1571 public readonly int Count;
1572 public static readonly MyBitVector Empty = new MyBitVector ();
1574 // Invariant: vector != null => vector.Count == Count
1575 // Invariant: vector == null || shared == null
1576 // i.e., at most one of 'vector' and 'shared' can be non-null. They can both be null -- that means all-ones
1577 // The object in 'shared' cannot be modified, while 'vector' can be freely modified
1578 BitArray vector, shared;
1582 shared = new BitArray (0, false);
1585 public MyBitVector (MyBitVector InheritsFrom, int Count)
1587 if (InheritsFrom != null)
1588 shared = InheritsFrom.MakeShared (Count);
1593 BitArray MakeShared (int new_count)
1595 // Post-condition: vector == null
1597 // ensure we don't leak out dirty bits from the BitVector we inherited from
1598 if (new_count > Count &&
1599 ((shared != null && shared.Count > Count) ||
1600 (shared == null && vector == null)))
1601 initialize_vector ();
1603 if (vector != null) {
1612 // Get/set bit `index' in the bit vector.
1614 public bool this [int index] {
1617 // FIXME: Disabled due to missing anonymous method flow analysis
1618 // throw new ArgumentOutOfRangeException ();
1622 return vector [index];
1625 if (index < shared.Count)
1626 return shared [index];
1631 // Only copy the vector if we're actually modifying it.
1632 if (this [index] != value) {
1634 initialize_vector ();
1635 vector [index] = value;
1641 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1642 // different size than the current one.
1644 private MyBitVector Or (MyBitVector new_vector)
1646 if (Count == 0 || new_vector.Count == 0)
1649 BitArray o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1652 int n = new_vector.Count;
1654 for (int i = 0; i < n; ++i)
1662 if (Count == o.Count) {
1663 if (vector == null) {
1666 initialize_vector ();
1676 for (int i = 0; i < min; i++) {
1685 // Performs an `and' operation on the bit vector. The `new_vector' may have
1686 // a different size than the current one.
1688 private MyBitVector And (MyBitVector new_vector)
1693 BitArray o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1696 for (int i = new_vector.Count; i < Count; ++i)
1706 if (Count == o.Count) {
1707 if (vector == null) {
1708 if (shared == null) {
1709 shared = new_vector.MakeShared (Count);
1712 initialize_vector ();
1722 for (int i = 0; i < min; i++) {
1727 for (int i = min; i < Count; i++)
1733 public static MyBitVector operator & (MyBitVector a, MyBitVector b)
1741 if (a.Count > b.Count)
1742 return a.Clone ().And (b);
1744 return b.Clone ().And (a);
1747 public static MyBitVector operator | (MyBitVector a, MyBitVector b)
1752 return new MyBitVector (null, b.Count);
1754 return new MyBitVector (null, a.Count);
1755 if (a.Count > b.Count)
1756 return a.Clone ().Or (b);
1758 return b.Clone ().Or (a);
1761 public MyBitVector Clone ()
1763 return Count == 0 ? Empty : new MyBitVector (this, Count);
1766 public void SetRange (int offset, int length)
1768 if (offset > Count || offset + length > Count)
1769 throw new ArgumentOutOfRangeException ();
1771 if (shared == null && vector == null)
1775 if (shared != null) {
1776 if (offset + length <= shared.Count) {
1777 for (; i < length; ++i)
1778 if (!shared [i+offset])
1783 initialize_vector ();
1785 for (; i < length; ++i)
1786 vector [i+offset] = true;
1790 public void SetAll (bool value)
1792 // Don't clobber Empty
1795 shared = value ? null : Empty.MakeShared (Count);
1799 void initialize_vector ()
1801 // Post-condition: vector != null
1802 if (shared == null) {
1803 vector = new BitArray (Count, true);
1807 vector = new BitArray (shared);
1808 if (Count != vector.Count)
1809 vector.Length = Count;
1813 StringBuilder Dump (StringBuilder sb)
1815 BitArray dump = vector == null ? shared : vector;
1817 return sb.Append ("/");
1820 for (int i = 0; i < dump.Count; i++)
1821 sb.Append (dump [i] ? "1" : "0");
1825 public override string ToString ()
1827 return Dump (new StringBuilder ("{")).Append ("}").ToString ();