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;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Diagnostics;
22 // A new instance of this class is created every time a new block is resolved
23 // and if there's branching in the block's control flow.
25 public abstract class FlowBranching
28 // The type of a FlowBranching.
30 public enum BranchingType : byte {
31 // Normal (conditional or toplevel) block.
40 // The statement embedded inside a loop
43 // part of a block headed by a jump target
49 // TryFinally, Using, Lock, CollectionForeach
55 // The toplevel block of a function
63 // The type of one sibling of a branching.
65 public enum SiblingType : byte {
74 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
77 case BranchingType.Exception:
78 case BranchingType.Labeled:
79 case BranchingType.Toplevel:
80 case BranchingType.TryCatch:
81 throw new InvalidOperationException ();
83 case BranchingType.Switch:
84 return new FlowBranchingBreakable (parent, type, SiblingType.SwitchSection, block, loc);
86 case BranchingType.Block:
87 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
89 case BranchingType.Loop:
90 return new FlowBranchingBreakable (parent, type, SiblingType.Conditional, block, loc);
92 case BranchingType.Embedded:
93 return new FlowBranchingContinuable (parent, type, SiblingType.Conditional, block, loc);
96 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
101 // The type of this flow branching.
103 public readonly BranchingType Type;
106 // The block this branching is contained in. This may be null if it's not
107 // a top-level block and it doesn't declare any local variables.
109 public readonly Block Block;
112 // The parent of this branching or null if this is the top-block.
114 public readonly FlowBranching Parent;
117 // Start-Location of this flow branching.
119 public readonly Location Location;
121 static int next_id = 0;
125 // The vector contains a BitArray with information about which local variables
126 // and parameters are already initialized at the current code position.
128 public class UsageVector {
130 // The type of this branching.
132 public readonly SiblingType Type;
135 // Start location of this branching.
137 public Location Location;
140 // This is only valid for SwitchSection, Try, Catch and Finally.
142 public readonly Block Block;
145 // The number of locals in this block.
147 public readonly int CountLocals;
150 // If not null, then we inherit our state from this vector and do a
151 // copy-on-write. If null, then we're the first sibling in a top-level
152 // block and inherit from the empty vector.
154 public readonly UsageVector InheritsFrom;
157 // This is used to construct a list of UsageVector's.
159 public UsageVector Next;
167 static int next_id = 0;
171 // Normally, you should not use any of these constructors.
173 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc, int num_locals)
178 this.InheritsFrom = parent;
179 this.CountLocals = num_locals;
181 locals = num_locals == 0
183 : new MyBitVector (parent == null ? MyBitVector.Empty : parent.locals, num_locals);
186 is_unreachable = parent.is_unreachable;
192 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc)
193 : this (type, parent, block, loc, parent.CountLocals)
196 private UsageVector (MyBitVector locals, bool is_unreachable, Block block, Location loc)
198 this.Type = SiblingType.Block;
202 this.is_unreachable = is_unreachable;
204 this.locals = locals;
211 // This does a deep copy of the usage vector.
213 public UsageVector Clone ()
215 UsageVector retval = new UsageVector (Type, null, Block, Location, CountLocals);
217 retval.locals = locals.Clone ();
218 retval.is_unreachable = is_unreachable;
223 public bool IsAssigned (VariableInfo var, bool ignoreReachability)
225 if (!ignoreReachability && !var.IsParameter && IsUnreachable)
228 return var.IsAssigned (locals);
231 public void SetAssigned (VariableInfo var)
233 if (!var.IsParameter && IsUnreachable)
236 var.SetAssigned (locals);
239 public bool IsFieldAssigned (VariableInfo var, string name)
241 if (!var.IsParameter && IsUnreachable)
244 return var.IsFieldAssigned (locals, name);
247 public void SetFieldAssigned (VariableInfo var, string name)
249 if (!var.IsParameter && IsUnreachable)
252 var.SetFieldAssigned (locals, name);
255 public bool IsUnreachable {
256 get { return is_unreachable; }
259 public void ResetBarrier ()
261 is_unreachable = false;
266 is_unreachable = true;
269 public static UsageVector MergeSiblings (UsageVector sibling_list, Location loc)
271 if (sibling_list.Next == null)
274 MyBitVector locals = null;
275 bool is_unreachable = sibling_list.is_unreachable;
277 if (!sibling_list.IsUnreachable)
278 locals &= sibling_list.locals;
280 for (UsageVector child = sibling_list.Next; child != null; child = child.Next) {
281 is_unreachable &= child.is_unreachable;
283 if (!child.IsUnreachable)
284 locals &= child.locals;
287 return new UsageVector (locals, is_unreachable, null, loc);
291 // Merges a child branching.
293 public UsageVector MergeChild (UsageVector child, bool overwrite)
295 Report.Debug (2, " MERGING CHILD EFFECTS", this, child, Type);
297 bool new_isunr = child.is_unreachable;
300 // We've now either reached the point after the branching or we will
301 // never get there since we always return or always throw an exception.
303 // If we can reach the point after the branching, mark all locals and
304 // parameters as initialized which have been initialized in all branches
305 // we need to look at (see above).
308 if ((Type == SiblingType.SwitchSection) && !new_isunr) {
309 Report.Error (163, Location,
310 "Control cannot fall through from one " +
311 "case label to another");
315 locals |= child.locals;
317 // throw away un-necessary information about variables in child blocks
318 if (locals.Count != CountLocals)
319 locals = new MyBitVector (locals, CountLocals);
322 is_unreachable = new_isunr;
324 is_unreachable |= new_isunr;
329 public void MergeOrigins (UsageVector o_vectors)
331 Report.Debug (1, " MERGING BREAK ORIGINS", this);
333 if (o_vectors == null)
336 if (IsUnreachable && locals != null)
337 locals.SetAll (true);
339 for (UsageVector vector = o_vectors; vector != null; vector = vector.Next) {
340 Report.Debug (1, " MERGING BREAK ORIGIN", vector);
341 if (vector.IsUnreachable)
343 locals &= vector.locals;
344 is_unreachable &= vector.is_unreachable;
347 Report.Debug (1, " MERGING BREAK ORIGINS DONE", this);
354 public override string ToString ()
356 return String.Format ("Vector ({0},{1},{2}-{3})", Type, id, is_unreachable, locals);
361 // Creates a new flow branching which is contained in `parent'.
362 // You should only pass non-null for the `block' argument if this block
363 // introduces any new variables - in this case, we need to create a new
364 // usage vector with a different size than our parent's one.
366 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
367 Block block, Location loc)
377 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
378 vector = new UsageVector (stype, parent_vector, Block, loc, Block.AssignableSlots);
380 vector = new UsageVector (stype, Parent.CurrentUsageVector, null, loc);
386 public abstract UsageVector CurrentUsageVector {
391 // Creates a sibling of the current usage vector.
393 public virtual void CreateSibling (Block block, SiblingType type)
395 UsageVector vector = new UsageVector (
396 type, Parent.CurrentUsageVector, block, Location);
399 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
402 public void CreateSibling ()
404 CreateSibling (null, SiblingType.Conditional);
407 protected abstract void AddSibling (UsageVector uv);
409 protected abstract UsageVector Merge ();
411 public UsageVector MergeChild (FlowBranching child)
413 return CurrentUsageVector.MergeChild (child.Merge (), true);
416 public virtual bool CheckRethrow (Location loc)
418 return Parent.CheckRethrow (loc);
421 public virtual bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
423 return Parent.AddResumePoint (stmt, loc, out pc);
426 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
427 public virtual bool AddBreakOrigin (UsageVector vector, Location loc)
429 return Parent.AddBreakOrigin (vector, loc);
432 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
433 public virtual bool AddContinueOrigin (UsageVector vector, Location loc)
435 return Parent.AddContinueOrigin (vector, loc);
438 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
439 public virtual bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
441 return Parent.AddReturnOrigin (vector, stmt);
444 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
445 public virtual bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
447 return Parent.AddGotoOrigin (vector, goto_stmt);
450 public bool IsAssigned (VariableInfo vi)
452 return CurrentUsageVector.IsAssigned (vi, false);
455 public bool IsFieldAssigned (VariableInfo vi, string field_name)
457 return CurrentUsageVector.IsAssigned (vi, false) || CurrentUsageVector.IsFieldAssigned (vi, field_name);
460 protected static Report Report {
461 get { return RootContext.ToplevelTypes.Compiler.Report; }
464 public void SetAssigned (VariableInfo vi)
466 CurrentUsageVector.SetAssigned (vi);
469 public void SetFieldAssigned (VariableInfo vi, string name)
471 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 ();
500 get { return String.Format ("{0} ({1}:{2}:{3})", GetType (), id, Type, Location); }
504 public class FlowBranchingBlock : FlowBranching
506 UsageVector sibling_list = null;
508 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
509 SiblingType stype, Block block, Location loc)
510 : base (parent, type, stype, block, loc)
513 public override UsageVector CurrentUsageVector {
514 get { return sibling_list; }
517 protected override void AddSibling (UsageVector sibling)
519 if (sibling_list != null && sibling_list.Type == SiblingType.Block)
520 throw new InternalErrorException ("Blocks don't have sibling flow paths");
521 sibling.Next = sibling_list;
522 sibling_list = sibling;
525 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
527 LabeledStatement stmt = Block == null ? null : Block.LookupLabel (goto_stmt.Target);
529 return Parent.AddGotoOrigin (vector, goto_stmt);
532 goto_stmt.SetResolvedTarget (stmt);
533 stmt.AddUsageVector (vector);
537 public static void Error_UnknownLabel (Location loc, string label, Report Report)
539 Report.Error(159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
543 protected override UsageVector Merge ()
545 Report.Debug (2, " MERGING SIBLINGS", Name);
546 UsageVector vector = UsageVector.MergeSiblings (sibling_list, Location);
547 Report.Debug (2, " MERGING SIBLINGS DONE", Name, vector);
552 public class FlowBranchingBreakable : FlowBranchingBlock
554 UsageVector break_origins;
556 public FlowBranchingBreakable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
557 : base (parent, type, stype, block, loc)
560 public override bool AddBreakOrigin (UsageVector vector, Location loc)
562 vector = vector.Clone ();
563 vector.Next = break_origins;
564 break_origins = vector;
568 protected override UsageVector Merge ()
570 UsageVector vector = base.Merge ();
571 vector.MergeOrigins (break_origins);
576 public class FlowBranchingContinuable : FlowBranchingBlock
578 UsageVector continue_origins;
580 public FlowBranchingContinuable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
581 : base (parent, type, stype, block, loc)
584 public override bool AddContinueOrigin (UsageVector vector, Location loc)
586 vector = vector.Clone ();
587 vector.Next = continue_origins;
588 continue_origins = vector;
592 protected override UsageVector Merge ()
594 UsageVector vector = base.Merge ();
595 vector.MergeOrigins (continue_origins);
600 public class FlowBranchingLabeled : FlowBranchingBlock
602 LabeledStatement stmt;
605 public FlowBranchingLabeled (FlowBranching parent, LabeledStatement stmt)
606 : base (parent, BranchingType.Labeled, SiblingType.Conditional, null, stmt.loc)
609 CurrentUsageVector.MergeOrigins (stmt.JumpOrigins);
610 actual = CurrentUsageVector.Clone ();
612 // stand-in for backward jumps
613 CurrentUsageVector.ResetBarrier ();
616 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
618 if (goto_stmt.Target != stmt.Name)
619 return Parent.AddGotoOrigin (vector, goto_stmt);
622 goto_stmt.SetResolvedTarget (stmt);
623 actual.MergeOrigins (vector.Clone ());
628 protected override UsageVector Merge ()
630 UsageVector vector = base.Merge ();
632 if (actual.IsUnreachable)
633 Report.Warning (162, 2, stmt.loc, "Unreachable code detected");
635 actual.MergeChild (vector, false);
640 public class FlowBranchingIterator : FlowBranchingBlock
643 public FlowBranchingIterator (FlowBranching parent, Iterator iterator)
644 : base (parent, BranchingType.Iterator, SiblingType.Block, iterator.Block, iterator.Location)
646 this.iterator = iterator;
649 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
651 pc = iterator.AddResumePoint (stmt);
656 public class FlowBranchingToplevel : FlowBranchingBlock
658 UsageVector return_origins;
660 public FlowBranchingToplevel (FlowBranching parent, ParametersBlock stmt)
661 : base (parent, BranchingType.Toplevel, SiblingType.Conditional, stmt, stmt.loc)
665 public override bool CheckRethrow (Location loc)
667 Report.Error (156, loc, "A throw statement with no arguments is not allowed outside of a catch clause");
671 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
673 throw new InternalErrorException ("A yield in a non-iterator block");
676 public override bool AddBreakOrigin (UsageVector vector, Location loc)
678 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
682 public override bool AddContinueOrigin (UsageVector vector, Location loc)
684 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
688 public override bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
690 vector = vector.Clone ();
691 vector.Location = stmt.loc;
692 vector.Next = return_origins;
693 return_origins = vector;
697 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
699 string name = goto_stmt.Target;
700 LabeledStatement s = Block.LookupLabel (name);
702 throw new InternalErrorException ("Shouldn't get here");
704 if (Parent == null) {
705 Error_UnknownLabel (goto_stmt.loc, name, Report);
709 int errors = Report.Errors;
710 Parent.AddGotoOrigin (vector, goto_stmt);
711 if (errors == Report.Errors)
712 Report.Error (1632, goto_stmt.loc, "Control cannot leave the body of an anonymous method");
716 protected override UsageVector Merge ()
718 for (UsageVector origin = return_origins; origin != null; origin = origin.Next)
719 Block.ParametersBlock.CheckOutParameters (origin, origin.Location);
721 UsageVector vector = base.Merge ();
722 Block.ParametersBlock.CheckOutParameters (vector, Block.loc);
723 // Note: we _do_not_ merge in the return origins
729 return Merge ().IsUnreachable;
733 public class FlowBranchingTryCatch : FlowBranchingBlock
736 public FlowBranchingTryCatch (FlowBranching parent, TryCatch stmt)
737 : base (parent, BranchingType.Block, SiblingType.Try, null, stmt.loc)
742 public override bool CheckRethrow (Location loc)
744 return CurrentUsageVector.Next != null || Parent.CheckRethrow (loc);
747 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
749 int errors = Report.Errors;
750 Parent.AddResumePoint (stmt, loc, out pc);
751 if (errors == Report.Errors) {
752 if (CurrentUsageVector.Next == null)
753 Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
755 Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
760 public override bool AddBreakOrigin (UsageVector vector, Location loc)
762 Parent.AddBreakOrigin (vector, loc);
763 stmt.SomeCodeFollows ();
767 public override bool AddContinueOrigin (UsageVector vector, Location loc)
769 Parent.AddContinueOrigin (vector, loc);
770 stmt.SomeCodeFollows ();
774 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
776 Parent.AddReturnOrigin (vector, exit_stmt);
777 stmt.SomeCodeFollows ();
781 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
783 Parent.AddGotoOrigin (vector, goto_stmt);
788 public class FlowBranchingException : FlowBranching
790 ExceptionStatement stmt;
791 UsageVector current_vector;
792 UsageVector try_vector;
793 UsageVector finally_vector;
795 abstract class SavedOrigin {
796 public readonly SavedOrigin Next;
797 public readonly UsageVector Vector;
799 protected SavedOrigin (SavedOrigin next, UsageVector vector)
802 Vector = vector.Clone ();
805 protected abstract void DoPropagateFinally (FlowBranching parent);
806 public void PropagateFinally (UsageVector finally_vector, FlowBranching parent)
808 if (finally_vector != null)
809 Vector.MergeChild (finally_vector, false);
810 DoPropagateFinally (parent);
814 class BreakOrigin : SavedOrigin {
816 public BreakOrigin (SavedOrigin next, UsageVector vector, Location loc)
817 : base (next, vector)
822 protected override void DoPropagateFinally (FlowBranching parent)
824 parent.AddBreakOrigin (Vector, Loc);
828 class ContinueOrigin : SavedOrigin {
830 public ContinueOrigin (SavedOrigin next, UsageVector vector, Location loc)
831 : base (next, vector)
836 protected override void DoPropagateFinally (FlowBranching parent)
838 parent.AddContinueOrigin (Vector, Loc);
842 class ReturnOrigin : SavedOrigin {
843 public ExitStatement Stmt;
845 public ReturnOrigin (SavedOrigin next, UsageVector vector, ExitStatement stmt)
846 : base (next, vector)
851 protected override void DoPropagateFinally (FlowBranching parent)
853 parent.AddReturnOrigin (Vector, Stmt);
857 class GotoOrigin : SavedOrigin {
860 public GotoOrigin (SavedOrigin next, UsageVector vector, Goto stmt)
861 : base (next, vector)
866 protected override void DoPropagateFinally (FlowBranching parent)
868 parent.AddGotoOrigin (Vector, Stmt);
872 SavedOrigin saved_origins;
874 public FlowBranchingException (FlowBranching parent,
875 ExceptionStatement stmt)
876 : base (parent, BranchingType.Exception, SiblingType.Try,
882 protected override void AddSibling (UsageVector sibling)
884 switch (sibling.Type) {
885 case SiblingType.Try:
886 try_vector = sibling;
888 case SiblingType.Finally:
889 finally_vector = sibling;
892 throw new InvalidOperationException ();
894 current_vector = sibling;
897 public override UsageVector CurrentUsageVector {
898 get { return current_vector; }
901 public override bool CheckRethrow (Location loc)
903 if (!Parent.CheckRethrow (loc))
905 if (finally_vector == null)
907 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");
911 public override bool AddResumePoint (ResumableStatement stmt, Location loc, out int pc)
913 int errors = Report.Errors;
914 Parent.AddResumePoint (this.stmt, loc, out pc);
915 if (errors == Report.Errors) {
916 if (finally_vector == null)
917 this.stmt.AddResumePoint (stmt, pc);
919 Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
924 public override bool AddBreakOrigin (UsageVector vector, Location loc)
926 if (finally_vector != null) {
927 int errors = Report.Errors;
928 Parent.AddBreakOrigin (vector, loc);
929 if (errors == Report.Errors)
930 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
932 saved_origins = new BreakOrigin (saved_origins, vector, loc);
935 // either the loop test or a back jump will follow code
936 stmt.SomeCodeFollows ();
940 public override bool AddContinueOrigin (UsageVector vector, Location loc)
942 if (finally_vector != null) {
943 int errors = Report.Errors;
944 Parent.AddContinueOrigin (vector, loc);
945 if (errors == Report.Errors)
946 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
948 saved_origins = new ContinueOrigin (saved_origins, vector, loc);
951 // either the loop test or a back jump will follow code
952 stmt.SomeCodeFollows ();
956 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
958 if (finally_vector != null) {
959 int errors = Report.Errors;
960 Parent.AddReturnOrigin (vector, exit_stmt);
961 if (errors == Report.Errors)
962 exit_stmt.Error_FinallyClause (Report);
964 saved_origins = new ReturnOrigin (saved_origins, vector, exit_stmt);
967 // sets ec.NeedReturnLabel()
968 stmt.SomeCodeFollows ();
972 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
974 LabeledStatement s = current_vector.Block == null ? null : current_vector.Block.LookupLabel (goto_stmt.Target);
976 throw new InternalErrorException ("Shouldn't get here");
978 if (finally_vector != null) {
979 int errors = Report.Errors;
980 Parent.AddGotoOrigin (vector, goto_stmt);
981 if (errors == Report.Errors)
982 Report.Error (157, goto_stmt.loc, "Control cannot leave the body of a finally clause");
984 saved_origins = new GotoOrigin (saved_origins, vector, goto_stmt);
989 protected override UsageVector Merge ()
991 UsageVector vector = try_vector.Clone ();
993 if (finally_vector != null)
994 vector.MergeChild (finally_vector, false);
996 for (SavedOrigin origin = saved_origins; origin != null; origin = origin.Next)
997 origin.PropagateFinally (finally_vector, Parent);
1004 // This is used by the flow analysis code to keep track of the type of local variables
1007 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1008 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1009 // you can only assign the whole variable as such.
1011 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1012 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1013 // one bit for each of its fields.
1015 // This class computes this `layout' for each type.
1017 public class TypeInfo
1019 public readonly TypeSpec Type;
1022 // Total number of bits a variable of this type consumes in the flow vector.
1024 public readonly int TotalLength;
1027 // Number of bits the simple fields of a variable of this type consume
1028 // in the flow vector.
1030 public readonly int Length;
1033 // This is only used by sub-structs.
1035 public readonly int Offset;
1038 // If this is a struct.
1040 public readonly bool IsStruct;
1043 // If this is a struct, all fields which are structs theirselves.
1045 public TypeInfo[] SubStructInfo;
1047 readonly StructInfo struct_info;
1048 private static Dictionary<TypeSpec, TypeInfo> type_hash;
1055 public static void Reset ()
1057 type_hash = new Dictionary<TypeSpec, TypeInfo> ();
1058 StructInfo.field_type_hash = new Dictionary<TypeSpec, StructInfo> ();
1061 public static TypeInfo GetTypeInfo (TypeSpec type)
1064 if (type_hash.TryGetValue (type, out info))
1067 info = new TypeInfo (type);
1068 type_hash.Add (type, info);
1072 private TypeInfo (TypeSpec type)
1076 struct_info = StructInfo.GetStructInfo (type);
1077 if (struct_info != null) {
1078 Length = struct_info.Length;
1079 TotalLength = struct_info.TotalLength;
1080 SubStructInfo = struct_info.StructFields;
1089 TypeInfo (StructInfo struct_info, int offset)
1091 this.struct_info = struct_info;
1092 this.Offset = offset;
1093 this.Length = struct_info.Length;
1094 this.TotalLength = struct_info.TotalLength;
1095 this.SubStructInfo = struct_info.StructFields;
1096 this.Type = struct_info.Type;
1097 this.IsStruct = true;
1100 public int GetFieldIndex (string name)
1102 if (struct_info == null)
1105 return struct_info [name];
1108 public TypeInfo GetSubStruct (string name)
1110 if (struct_info == null)
1113 return struct_info.GetStructField (name);
1117 // A struct's constructor must always assign all fields.
1118 // This method checks whether it actually does so.
1120 public bool IsFullyInitialized (BlockContext ec, VariableInfo vi, Location loc)
1122 if (struct_info == null)
1126 FlowBranching branching = ec.CurrentBranching;
1127 for (int i = 0; i < struct_info.Count; i++) {
1128 var field = struct_info.Fields [i];
1130 if (!branching.IsFieldAssigned (vi, field.Name)) {
1131 if (field.MemberDefinition is Property.BackingField) {
1132 ec.Report.Error (843, loc,
1133 "An automatically implemented property `{0}' must be fully assigned before control leaves the constructor. Consider calling the default struct contructor from a constructor initializer",
1134 field.GetSignatureForError ());
1136 ec.Report.Error (171, loc,
1137 "Field `{0}' must be fully assigned before control leaves the constructor",
1138 field.GetSignatureForError ());
1147 public override string ToString ()
1149 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1150 Type, Offset, Length, TotalLength);
1154 public readonly TypeSpec Type;
1155 public readonly FieldSpec[] Fields;
1156 public readonly TypeInfo[] StructFields;
1157 public readonly int Count;
1158 public readonly int CountPublic;
1159 public readonly int CountNonPublic;
1160 public readonly int Length;
1161 public readonly int TotalLength;
1162 public readonly bool HasStructFields;
1164 public static Dictionary<TypeSpec, StructInfo> field_type_hash;
1165 private Dictionary<string, TypeInfo> struct_field_hash;
1166 private Dictionary<string, int> field_hash;
1168 protected bool InTransit = false;
1170 // Private constructor. To save memory usage, we only need to create one instance
1171 // of this class per struct type.
1172 private StructInfo (TypeSpec type)
1176 field_type_hash.Add (type, this);
1178 TypeContainer tc = type.MemberDefinition as TypeContainer;
1180 var public_fields = new List<FieldSpec> ();
1181 var non_public_fields = new List<FieldSpec> ();
1184 var fields = tc.Fields;
1186 if (fields != null) {
1187 foreach (FieldBase field in fields) {
1188 if ((field.ModFlags & Modifiers.STATIC) != 0)
1190 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1191 public_fields.Add (field.Spec);
1193 non_public_fields.Add (field.Spec);
1198 CountPublic = public_fields.Count;
1199 CountNonPublic = non_public_fields.Count;
1200 Count = CountPublic + CountNonPublic;
1202 Fields = new FieldSpec[Count];
1203 public_fields.CopyTo (Fields, 0);
1204 non_public_fields.CopyTo (Fields, CountPublic);
1206 struct_field_hash = new Dictionary<string, TypeInfo> ();
1207 field_hash = new Dictionary<string, int> ();
1210 StructFields = new TypeInfo [Count];
1211 StructInfo[] sinfo = new StructInfo [Count];
1215 for (int i = 0; i < Count; i++) {
1216 var field = Fields [i];
1218 sinfo [i] = GetStructInfo (field.MemberType);
1219 if (sinfo [i] == null)
1220 field_hash.Add (field.Name, ++Length);
1221 else if (sinfo [i].InTransit) {
1229 TotalLength = Length + 1;
1230 for (int i = 0; i < Count; i++) {
1231 var field = Fields [i];
1233 if (sinfo [i] == null)
1236 field_hash.Add (field.Name, TotalLength);
1238 HasStructFields = true;
1239 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1240 struct_field_hash.Add (field.Name, StructFields [i]);
1241 TotalLength += sinfo [i].TotalLength;
1245 public int this [string name] {
1248 if (!field_hash.TryGetValue (name, out val))
1255 public TypeInfo GetStructField (string name)
1258 if (struct_field_hash.TryGetValue (name, out ti))
1264 public static StructInfo GetStructInfo (TypeSpec type)
1266 if (!type.IsStruct || TypeManager.IsBuiltinType (type))
1270 if (field_type_hash.TryGetValue (type, out info))
1273 return new StructInfo (type);
1279 // This is used by the flow analysis code to store information about a single local variable
1280 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1281 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1282 // it has been assigned or not, but for structs, we need this information for each of its fields.
1284 public class VariableInfo {
1285 public readonly string Name;
1286 public readonly TypeInfo TypeInfo;
1289 // The bit offset of this variable in the flow vector.
1291 public readonly int Offset;
1294 // The number of bits this variable needs in the flow vector.
1295 // The first bit always specifies whether the variable as such has been assigned while
1296 // the remaining bits contain this information for each of a struct's fields.
1298 public readonly int Length;
1301 // If this is a parameter of local variable.
1303 public readonly bool IsParameter;
1305 public readonly LocalVariable LocalInfo;
1307 readonly VariableInfo Parent;
1308 VariableInfo[] sub_info;
1310 bool is_ever_assigned;
1311 public bool IsEverAssigned {
1312 get { return is_ever_assigned; }
1315 protected VariableInfo (string name, TypeSpec type, int offset)
1318 this.Offset = offset;
1319 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1321 Length = TypeInfo.TotalLength;
1326 protected VariableInfo (VariableInfo parent, TypeInfo type)
1328 this.Name = parent.Name;
1329 this.TypeInfo = type;
1330 this.Offset = parent.Offset + type.Offset;
1331 this.Parent = parent;
1332 this.Length = type.TotalLength;
1334 this.IsParameter = parent.IsParameter;
1335 this.LocalInfo = parent.LocalInfo;
1340 protected void Initialize ()
1342 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1343 if (sub_fields != null) {
1344 sub_info = new VariableInfo [sub_fields.Length];
1345 for (int i = 0; i < sub_fields.Length; i++) {
1346 if (sub_fields [i] != null)
1347 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1350 sub_info = new VariableInfo [0];
1353 public VariableInfo (LocalVariable local_info, int offset)
1354 : this (local_info.Name, local_info.Type, offset)
1356 this.LocalInfo = local_info;
1357 this.IsParameter = false;
1360 public VariableInfo (ParametersCompiled ip, int i, int offset)
1361 : this (ip.FixedParameters [i].Name, ip.Types [i], offset)
1363 this.IsParameter = true;
1366 public bool IsAssigned (ResolveContext ec)
1368 return !ec.DoFlowAnalysis ||
1369 (ec.OmitStructFlowAnalysis && TypeInfo.Type.IsStruct) ||
1370 ec.CurrentBranching.IsAssigned (this);
1373 public bool IsAssigned (ResolveContext ec, Location loc)
1375 if (IsAssigned (ec))
1378 ec.Report.Error (165, loc,
1379 "Use of unassigned local variable `" + Name + "'");
1380 ec.CurrentBranching.SetAssigned (this);
1384 public bool IsAssigned (MyBitVector vector)
1389 if (vector [Offset])
1392 // FIXME: Fix SetFieldAssigned to set the whole range like SetAssigned below. Then, get rid of this stanza
1393 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent) {
1394 if (vector [parent.Offset]) {
1395 // 'parent' is assigned, but someone forgot to note that all its components are assigned too
1396 parent.SetAssigned (vector);
1401 // Return unless this is a struct.
1402 if (!TypeInfo.IsStruct)
1405 // Ok, so each field must be assigned.
1406 for (int i = 0; i < TypeInfo.Length; i++) {
1407 if (!vector [Offset + i + 1])
1411 // Ok, now check all fields which are structs.
1412 for (int i = 0; i < sub_info.Length; i++) {
1413 VariableInfo sinfo = sub_info [i];
1417 if (!sinfo.IsAssigned (vector))
1421 vector [Offset] = true;
1422 is_ever_assigned = true;
1426 public void SetAssigned (ResolveContext ec)
1428 if (ec.DoFlowAnalysis)
1429 ec.CurrentBranching.SetAssigned (this);
1432 public void SetAssigned (MyBitVector vector)
1435 vector [Offset] = true;
1437 vector.SetRange (Offset, Length);
1438 is_ever_assigned = true;
1441 public bool IsFieldAssigned (ResolveContext ec, string name, Location loc)
1443 if (!ec.DoFlowAnalysis ||
1444 ec.OmitStructFlowAnalysis && TypeInfo.IsStruct ||
1445 ec.CurrentBranching.IsFieldAssigned (this, name))
1448 ec.Report.Error (170, loc,
1449 "Use of possibly unassigned field `" + name + "'");
1450 ec.CurrentBranching.SetFieldAssigned (this, name);
1454 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1456 int field_idx = TypeInfo.GetFieldIndex (field_name);
1461 return vector [Offset + field_idx];
1464 public void SetFieldAssigned (ResolveContext ec, string name)
1466 if (ec.DoFlowAnalysis)
1467 ec.CurrentBranching.SetFieldAssigned (this, name);
1470 public void SetFieldAssigned (MyBitVector vector, string field_name)
1472 int field_idx = TypeInfo.GetFieldIndex (field_name);
1477 vector [Offset + field_idx] = true;
1478 is_ever_assigned = true;
1481 public VariableInfo GetSubStruct (string name)
1483 TypeInfo type = TypeInfo.GetSubStruct (name);
1488 return new VariableInfo (this, type);
1491 public override string ToString ()
1493 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1494 Name, TypeInfo, Offset, Length, IsParameter);
1499 // This is a special bit vector which can inherit from another bit vector doing a
1500 // copy-on-write strategy. The inherited vector may have a smaller size than the
1503 public class MyBitVector {
1504 public readonly int Count;
1505 public static readonly MyBitVector Empty = new MyBitVector ();
1507 // Invariant: vector != null => vector.Count == Count
1508 // Invariant: vector == null || shared == null
1509 // i.e., at most one of 'vector' and 'shared' can be non-null. They can both be null -- that means all-ones
1510 // The object in 'shared' cannot be modified, while 'vector' can be freely modified
1511 System.Collections.BitArray vector, shared;
1515 shared = new System.Collections.BitArray (0, false);
1518 public MyBitVector (MyBitVector InheritsFrom, int Count)
1520 if (InheritsFrom != null)
1521 shared = InheritsFrom.MakeShared (Count);
1526 System.Collections.BitArray MakeShared (int new_count)
1528 // Post-condition: vector == null
1530 // ensure we don't leak out dirty bits from the BitVector we inherited from
1531 if (new_count > Count &&
1532 ((shared != null && shared.Count > Count) ||
1533 (shared == null && vector == null)))
1534 initialize_vector ();
1536 if (vector != null) {
1545 // Get/set bit `index' in the bit vector.
1547 public bool this [int index] {
1550 // FIXME: Disabled due to missing anonymous method flow analysis
1551 // throw new ArgumentOutOfRangeException ();
1555 return vector [index];
1558 if (index < shared.Count)
1559 return shared [index];
1564 // Only copy the vector if we're actually modifying it.
1565 if (this [index] != value) {
1567 initialize_vector ();
1568 vector [index] = value;
1574 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1575 // different size than the current one.
1577 private MyBitVector Or (MyBitVector new_vector)
1579 if (Count == 0 || new_vector.Count == 0)
1582 var o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1585 int n = new_vector.Count;
1587 for (int i = 0; i < n; ++i)
1595 if (Count == o.Count) {
1596 if (vector == null) {
1599 initialize_vector ();
1609 for (int i = 0; i < min; i++) {
1618 // Performs an `and' operation on the bit vector. The `new_vector' may have
1619 // a different size than the current one.
1621 private MyBitVector And (MyBitVector new_vector)
1626 var o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1629 for (int i = new_vector.Count; i < Count; ++i)
1639 if (Count == o.Count) {
1640 if (vector == null) {
1641 if (shared == null) {
1642 shared = new_vector.MakeShared (Count);
1645 initialize_vector ();
1655 for (int i = 0; i < min; i++) {
1660 for (int i = min; i < Count; i++)
1666 public static MyBitVector operator & (MyBitVector a, MyBitVector b)
1674 if (a.Count > b.Count)
1675 return a.Clone ().And (b);
1677 return b.Clone ().And (a);
1680 public static MyBitVector operator | (MyBitVector a, MyBitVector b)
1685 return new MyBitVector (null, b.Count);
1687 return new MyBitVector (null, a.Count);
1688 if (a.Count > b.Count)
1689 return a.Clone ().Or (b);
1691 return b.Clone ().Or (a);
1694 public MyBitVector Clone ()
1696 return Count == 0 ? Empty : new MyBitVector (this, Count);
1699 public void SetRange (int offset, int length)
1701 if (offset > Count || offset + length > Count)
1702 throw new ArgumentOutOfRangeException ("flow-analysis");
1704 if (shared == null && vector == null)
1708 if (shared != null) {
1709 if (offset + length <= shared.Count) {
1710 for (; i < length; ++i)
1711 if (!shared [i+offset])
1716 initialize_vector ();
1718 for (; i < length; ++i)
1719 vector [i+offset] = true;
1723 public void SetAll (bool value)
1725 // Don't clobber Empty
1728 shared = value ? null : Empty.MakeShared (Count);
1732 void initialize_vector ()
1734 // Post-condition: vector != null
1735 if (shared == null) {
1736 vector = new System.Collections.BitArray (Count, true);
1740 vector = new System.Collections.BitArray (shared);
1741 if (Count != vector.Count)
1742 vector.Length = Count;
1746 StringBuilder Dump (StringBuilder sb)
1748 var dump = vector == null ? shared : vector;
1750 return sb.Append ("/");
1753 for (int i = 0; i < dump.Count; i++)
1754 sb.Append (dump [i] ? "1" : "0");
1758 public override string ToString ()
1760 return Dump (new StringBuilder ("{")).Append ("}").ToString ();