Improved debugging info.
[mono.git] / mcs / mcs / flowanalysis.cs
1 //
2 // flowanalyis.cs: The control flow analysis code
3 //
4 // Author:
5 //   Martin Baulig (martin@ximian.com)
6 //
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 //
9
10 using System;
11 using System.Text;
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
16
17 namespace Mono.CSharp
18 {
19         // <summary>
20         //   A new instance of this class is created every time a new block is resolved
21         //   and if there's branching in the block's control flow.
22         // </summary>
23         public abstract class FlowBranching
24         {
25                 // <summary>
26                 //   The type of a FlowBranching.
27                 // </summary>
28                 public enum BranchingType {
29                         // Normal (conditional or toplevel) block.
30                         Block,
31
32                         // Conditional.
33                         Conditional,
34
35                         // A loop block.
36                         LoopBlock,
37
38                         // Try/Catch block.
39                         Exception,
40
41                         // Switch block.
42                         Switch,
43
44                         // Switch section.
45                         SwitchSection
46                 }
47
48                 // <summary>
49                 //   The type of one sibling of a branching.
50                 // </summary>
51                 public enum SiblingType {
52                         Block,
53                         Conditional,
54                         SwitchSection,
55                         Try,
56                         Catch,
57                         Finally
58                 }
59
60                 // <summary>
61                 //   This is used in the control flow analysis code to specify whether the
62                 //   current code block may return to its enclosing block before reaching
63                 //   its end.
64                 // </summary>
65                 public enum FlowReturns {
66                         Undefined = 0,
67
68                         // It can never return.
69                         Never,
70
71                         // This means that the block contains a conditional return statement
72                         // somewhere.
73                         Sometimes,
74
75                         // The code always returns, ie. there's an unconditional return / break
76                         // statement in it.
77                         Always
78                 }
79
80                 public sealed class Reachability
81                 {
82                         FlowReturns returns, breaks, throws, barrier, reachable;
83
84                         public FlowReturns Returns {
85                                 get { return returns; }
86                         }
87                         public FlowReturns Breaks {
88                                 get { return breaks; }
89                         }
90                         public FlowReturns Throws {
91                                 get { return throws; }
92                         }
93                         public FlowReturns Barrier {
94                                 get { return barrier; }
95                         }
96                         public FlowReturns Reachable {
97                                 get { return reachable; }
98                         }
99
100                         public Reachability (FlowReturns returns, FlowReturns breaks,
101                                              FlowReturns throws, FlowReturns barrier)
102                         {
103                                 this.returns = returns;
104                                 this.breaks = breaks;
105                                 this.throws = throws;
106                                 this.barrier = barrier;
107
108                                 update ();
109                         }
110
111                         public Reachability Clone ()
112                         {
113                                 Reachability cloned = new Reachability (returns, breaks, throws, barrier);
114                                 cloned.reachable = reachable;
115                                 return cloned;
116                         }
117
118                         public static void And (ref Reachability a, Reachability b, bool do_break)
119                         {
120                                 if (a == null) {
121                                         a = b.Clone ();
122                                         return;
123                                 }
124
125                                 //
126                                 // `break' does not "break" in a Switch or a LoopBlock
127                                 //
128                                 bool a_breaks = do_break && a.AlwaysBreaks;
129                                 bool b_breaks = do_break && b.AlwaysBreaks;
130
131                                 bool a_has_barrier, b_has_barrier;
132                                 if (do_break) {
133                                         //
134                                         // This is the normal case: the code following a barrier
135                                         // cannot be reached.
136                                         //
137                                         a_has_barrier = a.AlwaysHasBarrier;
138                                         b_has_barrier = b.AlwaysHasBarrier;
139                                 } else {
140                                         //
141                                         // Special case for Switch and LoopBlocks: we can reach the
142                                         // code after the barrier via the `break'.
143                                         //
144                                         a_has_barrier = !a.AlwaysBreaks && a.AlwaysHasBarrier;
145                                         b_has_barrier = !b.AlwaysBreaks && b.AlwaysHasBarrier;
146                                 }
147
148                                 bool a_unreachable = a_breaks || a.AlwaysThrows || a_has_barrier;
149                                 bool b_unreachable = b_breaks || b.AlwaysThrows || b_has_barrier;
150
151                                 //
152                                 // Do all code paths always return ?
153                                 //
154                                 if (a.AlwaysReturns) {
155                                         if (b.AlwaysReturns || b_unreachable)
156                                                 a.returns = FlowReturns.Always;
157                                         else
158                                                 a.returns = FlowReturns.Sometimes;
159                                 } else if (b.AlwaysReturns) {
160                                         if (a.AlwaysReturns || a_unreachable)
161                                                 a.returns = FlowReturns.Always;
162                                         else
163                                                 a.returns = FlowReturns.Sometimes;
164                                 } else if (!a.MayReturn) {
165                                         if (b.MayReturn)
166                                                 a.returns = FlowReturns.Sometimes;
167                                         else
168                                                 a.returns = FlowReturns.Never;
169                                 } else if (!b.MayReturn) {
170                                         if (a.MayReturn)
171                                                 a.returns = FlowReturns.Sometimes;
172                                         else
173                                                 a.returns = FlowReturns.Never;
174                                 }
175
176                                 a.breaks = AndFlowReturns (a.breaks, b.breaks);
177                                 a.throws = AndFlowReturns (a.throws, b.throws);
178                                 a.barrier = AndFlowReturns (a.barrier, b.barrier);
179
180                                 a.reachable = AndFlowReturns (a.reachable, b.reachable);
181                         }
182
183                         public static Reachability Never ()
184                         {
185                                 return new Reachability (
186                                         FlowReturns.Never, FlowReturns.Never,
187                                         FlowReturns.Never, FlowReturns.Never);
188                         }
189
190                         void update ()
191                         {
192                                 if ((returns == FlowReturns.Always) || (breaks == FlowReturns.Always) ||
193                                     (throws == FlowReturns.Always) || (barrier == FlowReturns.Always))
194                                         reachable = FlowReturns.Never;
195                                 else if ((returns == FlowReturns.Never) && (breaks == FlowReturns.Never) &&
196                                          (throws == FlowReturns.Never) && (barrier == FlowReturns.Never))
197                                         reachable = FlowReturns.Always;
198                                 else
199                                         reachable = FlowReturns.Sometimes;
200                         }
201
202                         public bool AlwaysBreaks {
203                                 get { return breaks == FlowReturns.Always; }
204                         }
205
206                         public bool MayBreak {
207                                 get { return breaks != FlowReturns.Never; }
208                         }
209
210                         public bool AlwaysReturns {
211                                 get { return returns == FlowReturns.Always; }
212                         }
213
214                         public bool MayReturn {
215                                 get { return returns != FlowReturns.Never; }
216                         }
217
218                         public bool AlwaysThrows {
219                                 get { return throws == FlowReturns.Always; }
220                         }
221
222                         public bool MayThrow {
223                                 get { return throws != FlowReturns.Never; }
224                         }
225
226                         public bool AlwaysHasBarrier {
227                                 get { return barrier == FlowReturns.Always; }
228                         }
229
230                         public bool MayHaveBarrier {
231                                 get { return barrier != FlowReturns.Never; }
232                         }
233
234                         public bool IsUnreachable {
235                                 get { return reachable == FlowReturns.Never; }
236                         }
237
238                         public void SetReturns ()
239                         {
240                                 returns = FlowReturns.Always;
241                                 update ();
242                         }
243
244                         public void SetReturnsSometimes ()
245                         {
246                                 returns = FlowReturns.Sometimes;
247                                 update ();
248                         }
249
250                         public void SetBreaks ()
251                         {
252                                 breaks = FlowReturns.Always;
253                                 update ();
254                         }
255
256                         public void ResetBreaks ()
257                         {
258                                 breaks = FlowReturns.Never;
259                                 update ();
260                         }
261
262                         public void SetThrows ()
263                         {
264                                 throws = FlowReturns.Always;
265                                 update ();
266                         }
267
268                         public void SetBarrier ()
269                         {
270                                 barrier = FlowReturns.Always;
271                                 update ();
272                         }
273
274                         static string ShortName (FlowReturns returns)
275                         {
276                                 switch (returns) {
277                                 case FlowReturns.Never:
278                                         return "N";
279                                 case FlowReturns.Sometimes:
280                                         return "S";
281                                 default:
282                                         return "A";
283                                 }
284                         }
285
286                         public override string ToString ()
287                         {
288                                 return String.Format ("[{0}:{1}:{2}:{3}:{4}]",
289                                                       ShortName (returns), ShortName (breaks),
290                                                       ShortName (throws), ShortName (barrier),
291                                                       ShortName (reachable));
292                         }
293                 }
294
295                 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
296                 {
297                         switch (type) {
298                         case BranchingType.Exception:
299                                 return new FlowBranchingException (parent, type, block, loc);
300
301                         case BranchingType.Switch:
302                                 return new FlowBranchingBlock (parent, type, SiblingType.SwitchSection, block, loc);
303
304                         case BranchingType.SwitchSection:
305                                 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
306
307                         case BranchingType.Block:
308                                 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
309
310                         default:
311                                 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
312                         }
313                 }
314
315                 // <summary>
316                 //   The type of this flow branching.
317                 // </summary>
318                 public readonly BranchingType Type;
319
320                 // <summary>
321                 //   The block this branching is contained in.  This may be null if it's not
322                 //   a top-level block and it doesn't declare any local variables.
323                 // </summary>
324                 public readonly Block Block;
325
326                 // <summary>
327                 //   The parent of this branching or null if this is the top-block.
328                 // </summary>
329                 public readonly FlowBranching Parent;
330
331                 // <summary>
332                 //   Start-Location of this flow branching.
333                 // </summary>
334                 public readonly Location Location;
335
336                 // <summary>
337                 //   If this is an infinite loop.
338                 // </summary>
339                 public bool Infinite;
340
341                 //
342                 // Private
343                 //
344                 VariableMap param_map, local_map;
345
346                 static int next_id = 0;
347                 int id;
348
349                 // <summary>
350                 //   Performs an `And' operation on the FlowReturns status
351                 //   (for instance, a block only returns Always if all its siblings
352                 //   always return).
353                 // </summary>
354                 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
355                 {
356                         if (a == FlowReturns.Undefined)
357                                 return b;
358
359                         switch (a) {
360                         case FlowReturns.Never:
361                                 if (b == FlowReturns.Never)
362                                         return FlowReturns.Never;
363                                 else
364                                         return FlowReturns.Sometimes;
365
366                         case FlowReturns.Sometimes:
367                                 return FlowReturns.Sometimes;
368
369                         case FlowReturns.Always:
370                                 if (b == FlowReturns.Always)
371                                         return FlowReturns.Always;
372                                 else
373                                         return FlowReturns.Sometimes;
374
375                         default:
376                                 throw new ArgumentException ();
377                         }
378                 }
379
380                 // <summary>
381                 //   The vector contains a BitArray with information about which local variables
382                 //   and parameters are already initialized at the current code position.
383                 // </summary>
384                 public class UsageVector {
385                         // <summary>
386                         //   The type of this branching.
387                         // </summary>
388                         public readonly SiblingType Type;
389
390                         // <summary>
391                         //   Start location of this branching.
392                         // </summary>
393                         public readonly Location Location;
394
395                         // <summary>
396                         //   If this is true, then the usage vector has been modified and must be
397                         //   merged when we're done with this branching.
398                         // </summary>
399                         public bool IsDirty;
400
401                         // <summary>
402                         //   The number of parameters in this block.
403                         // </summary>
404                         public readonly int CountParameters;
405
406                         // <summary>
407                         //   The number of locals in this block.
408                         // </summary>
409                         public readonly int CountLocals;
410
411                         // <summary>
412                         //   If not null, then we inherit our state from this vector and do a
413                         //   copy-on-write.  If null, then we're the first sibling in a top-level
414                         //   block and inherit from the empty vector.
415                         // </summary>
416                         public readonly UsageVector InheritsFrom;
417
418                         // <summary>
419                         //   This is used to construct a list of UsageVector's.
420                         // </summary>
421                         public UsageVector Next;
422
423                         //
424                         // Private.
425                         //
426                         MyBitVector locals, parameters;
427                         Reachability reachability;
428                         bool is_finally;
429
430                         static int next_id = 0;
431                         int id;
432
433                         //
434                         // Normally, you should not use any of these constructors.
435                         //
436                         public UsageVector (SiblingType type, UsageVector parent, Location loc, int num_params, int num_locals)
437                         {
438                                 this.Type = type;
439                                 this.Location = loc;
440                                 this.InheritsFrom = parent;
441                                 this.CountParameters = num_params;
442                                 this.CountLocals = num_locals;
443
444                                 if (parent != null) {
445                                         locals = new MyBitVector (parent.locals, CountLocals);
446                                         if (num_params > 0)
447                                                 parameters = new MyBitVector (parent.parameters, num_params);
448
449                                         reachability = parent.Reachability.Clone ();
450                                 } else {
451                                         locals = new MyBitVector (null, CountLocals);
452                                         if (num_params > 0)
453                                                 parameters = new MyBitVector (null, num_params);
454
455                                         reachability = Reachability.Never ();
456                                 }
457
458                                 id = ++next_id;
459                         }
460
461                         public UsageVector (SiblingType type, UsageVector parent, Location loc)
462                                 : this (type, parent, loc, parent.CountParameters, parent.CountLocals)
463                         { }
464
465                         public UsageVector (MyBitVector parameters, MyBitVector locals,
466                                             Reachability reachability, Location loc)
467                         {
468                                 this.Type = SiblingType.Block;
469                                 this.Location = loc;
470
471                                 this.reachability = reachability;
472                                 this.parameters = parameters;
473                                 this.locals = locals;
474
475                                 id = ++next_id;
476                         }
477
478                         // <summary>
479                         //   This does a deep copy of the usage vector.
480                         // </summary>
481                         public UsageVector Clone ()
482                         {
483                                 UsageVector retval = new UsageVector (Type, null, Location, CountParameters, CountLocals);
484
485                                 retval.locals = locals.Clone ();
486                                 if (parameters != null)
487                                         retval.parameters = parameters.Clone ();
488                                 retval.reachability = reachability.Clone ();
489
490                                 return retval;
491                         }
492
493                         public bool IsAssigned (VariableInfo var)
494                         {
495                                 if (!var.IsParameter && Reachability.AlwaysBreaks)
496                                         return true;
497
498                                 return var.IsAssigned (var.IsParameter ? parameters : locals);
499                         }
500
501                         public void SetAssigned (VariableInfo var)
502                         {
503                                 if (!var.IsParameter && Reachability.AlwaysBreaks)
504                                         return;
505
506                                 IsDirty = true;
507                                 var.SetAssigned (var.IsParameter ? parameters : locals);
508                         }
509
510                         public bool IsFieldAssigned (VariableInfo var, string name)
511                         {
512                                 if (!var.IsParameter && Reachability.AlwaysBreaks)
513                                         return true;
514
515                                 return var.IsFieldAssigned (var.IsParameter ? parameters : locals, name);
516                         }
517
518                         public void SetFieldAssigned (VariableInfo var, string name)
519                         {
520                                 if (!var.IsParameter && Reachability.AlwaysBreaks)
521                                         return;
522
523                                 IsDirty = true;
524                                 var.SetFieldAssigned (var.IsParameter ? parameters : locals, name);
525                         }
526
527                         public Reachability Reachability {
528                                 get {
529                                         return reachability;
530                                 }
531                         }
532
533                         public void Return ()
534                         {
535                                 if (!reachability.IsUnreachable) {
536                                         IsDirty = true;
537                                         reachability.SetReturns ();
538                                 }
539                         }
540
541                         public void Break ()
542                         {
543                                 if (!reachability.IsUnreachable) {
544                                         IsDirty = true;
545                                         reachability.SetBreaks ();
546                                 }
547                         }
548
549                         public void Throw ()
550                         {
551                                 if (!reachability.IsUnreachable) {
552                                         IsDirty = true;
553                                         reachability.SetThrows ();
554                                 }
555                         }
556
557                         public void Goto ()
558                         {
559                                 if (!reachability.IsUnreachable) {
560                                         IsDirty = true;
561                                         reachability.SetBarrier ();
562                                 }
563                         }
564
565                         // <summary>
566                         //   Merges a child branching.
567                         // </summary>
568                         public UsageVector MergeChild (FlowBranching branching)
569                         {
570                                 UsageVector result = branching.Merge ();
571
572                                 Report.Debug (2, "  MERGING CHILD", this, IsDirty,
573                                               result.ParameterVector, result.LocalVector,
574                                               result.Reachability, Type);
575
576                                 reachability = result.Reachability;
577
578                                 if (branching.Type == BranchingType.LoopBlock) {
579                                         bool may_leave_loop = reachability.MayBreak;
580                                         reachability.ResetBreaks ();
581
582                                         if (branching.Infinite && !may_leave_loop) {
583                                                 if (reachability.Returns == FlowReturns.Sometimes) {
584                                                         // If we're an infinite loop and do not break,
585                                                         // the code after the loop can never be reached.
586                                                         // However, if we may return from the loop,
587                                                         // then we do always return (or stay in the
588                                                         // loop forever).
589                                                         reachability.SetReturns ();
590                                                 }
591
592                                                 reachability.SetBarrier ();
593                                         } else {
594                                                 if (reachability.Returns == FlowReturns.Always) {
595                                                         // We're either finite or we may leave the loop.
596                                                         reachability.SetReturnsSometimes ();
597                                                 }
598                                         }
599                                 } else if (branching.Type == BranchingType.Switch)
600                                         reachability.ResetBreaks ();
601
602                                 //
603                                 // We've now either reached the point after the branching or we will
604                                 // never get there since we always return or always throw an exception.
605                                 //
606                                 // If we can reach the point after the branching, mark all locals and
607                                 // parameters as initialized which have been initialized in all branches
608                                 // we need to look at (see above).
609                                 //
610
611                                 if ((Type == SiblingType.SwitchSection) && !reachability.IsUnreachable) {
612                                         Report.Error (163, Location,
613                                                       "Control cannot fall through from one " +
614                                                       "case label to another");
615                                         return result;
616                                 }
617
618                                 if (result.LocalVector != null)
619                                         locals.Or (result.LocalVector);
620
621                                 if (result.ParameterVector != null)
622                                         parameters.Or (result.ParameterVector);
623
624                                 Report.Debug (2, "  MERGING CHILD DONE", this);
625
626                                 IsDirty = true;
627
628                                 return result;
629                         }
630
631                         protected void MergeFinally (FlowBranching branching, UsageVector f_origins,
632                                                      MyBitVector f_params)
633                         {
634                                 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
635                                         MyBitVector temp_params = f_params.Clone ();
636                                         temp_params.Or (vector.Parameters);
637
638                                         branching.CheckOutParameters (temp_params, branching.Location);
639                                 }
640                         }
641
642                         public void MergeFinally (FlowBranching branching, UsageVector f_vector,
643                                                   UsageVector f_origins)
644                         {
645                                 if (parameters != null) {
646                                         if (f_vector != null) {
647                                                 MergeFinally (branching, f_origins, f_vector.Parameters);
648                                                 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
649                                         } else
650                                                 MergeFinally (branching, f_origins, parameters);
651                                 }
652
653                                 if (f_vector != null)
654                                         MyBitVector.Or (ref locals, f_vector.LocalVector);
655                         }
656
657                         // <summary>
658                         //   Tells control flow analysis that the current code position may be reached with
659                         //   a forward jump from any of the origins listed in `origin_vectors' which is a
660                         //   list of UsageVectors.
661                         //
662                         //   This is used when resolving forward gotos - in the following example, the
663                         //   variable `a' is uninitialized in line 8 becase this line may be reached via
664                         //   the goto in line 4:
665                         //
666                         //      1     int a;
667                         //
668                         //      3     if (something)
669                         //      4        goto World;
670                         //
671                         //      6     a = 5;
672                         //
673                         //      7  World:
674                         //      8     Console.WriteLine (a);
675                         //
676                         // </summary>
677                         public void MergeJumpOrigins (ICollection origin_vectors)
678                         {
679                                 Report.Debug (1, "  MERGING JUMP ORIGIN", this);
680
681                                 reachability = Reachability.Never ();
682
683                                 if (origin_vectors == null)
684                                         return;
685
686                                 foreach (UsageVector vector in origin_vectors) {
687                                         Report.Debug (1, "    MERGING JUMP ORIGIN", vector);
688
689                                         locals.And (vector.locals);
690                                         if (parameters != null)
691                                                 parameters.And (vector.parameters);
692
693                                         Reachability.And (ref reachability, vector.Reachability, true);
694                                 }
695
696                                 Report.Debug (1, "  MERGING JUMP ORIGIN DONE", this);
697                         }
698
699                         // <summary>
700                         //   This is used at the beginning of a finally block if there were
701                         //   any return statements in the try block or one of the catch blocks.
702                         // </summary>
703                         public void MergeFinallyOrigins (ICollection finally_vectors)
704                         {
705                                 Report.Debug (1, "  MERGING FINALLY ORIGIN", this);
706
707 #if FIXME
708                                 RealBreaks = FlowReturns.Never;
709 #endif
710
711                                 foreach (UsageVector vector in finally_vectors) {
712                                         Report.Debug (1, "    MERGING FINALLY ORIGIN", vector);
713
714                                         if (parameters != null)
715                                                 parameters.And (vector.parameters);
716
717 #if FIXME
718                                         RealBreaks = AndFlowReturns (Breaks, vector.Breaks);
719 #endif
720                                 }
721
722                                 is_finally = true;
723
724                                 Report.Debug (1, "  MERGING FINALLY ORIGIN DONE", this);
725                         }
726
727                         public void CheckOutParameters (FlowBranching branching)
728                         {
729                                 if (parameters != null)
730                                         branching.CheckOutParameters (parameters, branching.Location);
731                         }
732
733                         // <summary>
734                         //   Performs an `or' operation on the locals and the parameters.
735                         // </summary>
736                         public void Or (UsageVector new_vector)
737                         {
738                                 IsDirty = true;
739                                 locals.Or (new_vector.locals);
740                                 if (parameters != null)
741                                         parameters.Or (new_vector.parameters);
742                         }
743
744                         // <summary>
745                         //   Performs an `and' operation on the locals.
746                         // </summary>
747                         public void AndLocals (UsageVector new_vector)
748                         {
749                                 IsDirty = true;
750                                 locals.And (new_vector.locals);
751                         }
752
753                         public bool HasParameters {
754                                 get {
755                                         return parameters != null;
756                                 }
757                         }
758
759                         public bool HasLocals {
760                                 get {
761                                         return locals != null;
762                                 }
763                         }
764
765                         // <summary>
766                         //   Returns a deep copy of the parameters.
767                         // </summary>
768                         public MyBitVector Parameters {
769                                 get {
770                                         if (parameters != null)
771                                                 return parameters.Clone ();
772                                         else
773                                                 return null;
774                                 }
775                         }
776
777                         // <summary>
778                         //   Returns a deep copy of the locals.
779                         // </summary>
780                         public MyBitVector Locals {
781                                 get {
782                                         return locals.Clone ();
783                                 }
784                         }
785
786                         public MyBitVector ParameterVector {
787                                 get {
788                                         return parameters;
789                                 }
790                         }
791
792                         public MyBitVector LocalVector {
793                                 get {
794                                         return locals;
795                                 }
796                         }
797
798                         //
799                         // Debugging stuff.
800                         //
801
802                         public override string ToString ()
803                         {
804                                 StringBuilder sb = new StringBuilder ();
805
806                                 sb.Append ("Vector (");
807                                 sb.Append (id);
808                                 sb.Append (",");
809                                 sb.Append (IsDirty);
810                                 sb.Append (",");
811                                 sb.Append (reachability);
812                                 if (parameters != null) {
813                                         sb.Append (" - ");
814                                         sb.Append (parameters);
815                                 }
816                                 sb.Append (" - ");
817                                 sb.Append (locals);
818                                 sb.Append (")");
819
820                                 return sb.ToString ();
821                         }
822                 }
823
824                 // <summary>
825                 //   Creates a new flow branching which is contained in `parent'.
826                 //   You should only pass non-null for the `block' argument if this block
827                 //   introduces any new variables - in this case, we need to create a new
828                 //   usage vector with a different size than our parent's one.
829                 // </summary>
830                 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
831                                          Block block, Location loc)
832                 {
833                         Parent = parent;
834                         Block = block;
835                         Location = loc;
836                         Type = type;
837                         id = ++next_id;
838
839                         UsageVector vector;
840                         if (Block != null) {
841                                 param_map = Block.ParameterMap;
842                                 local_map = Block.LocalMap;
843
844                                 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
845                                 vector = new UsageVector (stype, parent_vector, loc, param_map.Length, local_map.Length);
846                         } else {
847                                 param_map = Parent.param_map;
848                                 local_map = Parent.local_map;
849                                 vector = new UsageVector (stype, Parent.CurrentUsageVector, loc);
850                         }
851
852                         AddSibling (vector);
853                 }
854
855                 public abstract UsageVector CurrentUsageVector {
856                         get;
857                 }                               
858
859                 // <summary>
860                 //   Creates a sibling of the current usage vector.
861                 // </summary>
862                 public virtual void CreateSibling (SiblingType type)
863                 {
864                         AddSibling (new UsageVector (type, Parent.CurrentUsageVector, Location));
865
866                         Report.Debug (1, "  CREATED SIBLING", CurrentUsageVector);
867                 }
868
869                 protected abstract void AddSibling (UsageVector uv);
870
871                 public abstract void Label (ArrayList origin_vectors);
872
873                 // <summary>
874                 //   Check whether all `out' parameters have been assigned.
875                 // </summary>
876                 public void CheckOutParameters (MyBitVector parameters, Location loc)
877                 {
878                         for (int i = 0; i < param_map.Count; i++) {
879                                 VariableInfo var = param_map [i];
880
881                                 if (var == null)
882                                         continue;
883
884                                 if (var.IsAssigned (parameters))
885                                         continue;
886
887                                 Report.Error (177, loc, "The out parameter `" +
888                                               param_map.VariableNames [i] + "' must be " +
889                                               "assigned before control leave the current method.");
890                         }
891                 }
892
893                 protected UsageVector Merge (UsageVector sibling_list)
894                 {
895                         if (sibling_list.Next == null)
896                                 return sibling_list;
897
898                         MyBitVector locals = null;
899                         MyBitVector parameters = null;
900
901                         Reachability reachability = null;
902
903                         Report.Debug (2, "  MERGING SIBLINGS", this, Name);
904
905                         for (UsageVector child = sibling_list; child != null; child = child.Next) {
906                                 bool do_break = (Type != BranchingType.Switch) &&
907                                         (Type != BranchingType.LoopBlock);
908
909                                 Report.Debug (2, "    MERGING SIBLING   ", child,
910                                               child.Locals, child.Parameters,
911                                               reachability, child.Reachability, do_break);
912
913                                 Reachability.And (ref reachability, child.Reachability, do_break);
914
915                                 // A local variable is initialized after a flow branching if it
916                                 // has been initialized in all its branches which do neither
917                                 // always return or always throw an exception.
918                                 //
919                                 // If a branch may return, but does not always return, then we
920                                 // can treat it like a never-returning branch here: control will
921                                 // only reach the code position after the branching if we did not
922                                 // return here.
923                                 //
924                                 // It's important to distinguish between always and sometimes
925                                 // returning branches here:
926                                 //
927                                 //    1   int a;
928                                 //    2   if (something) {
929                                 //    3      return;
930                                 //    4      a = 5;
931                                 //    5   }
932                                 //    6   Console.WriteLine (a);
933                                 //
934                                 // The if block in lines 3-4 always returns, so we must not look
935                                 // at the initialization of `a' in line 4 - thus it'll still be
936                                 // uninitialized in line 6.
937                                 //
938                                 // On the other hand, the following is allowed:
939                                 //
940                                 //    1   int a;
941                                 //    2   if (something)
942                                 //    3      a = 5;
943                                 //    4   else
944                                 //    5      return;
945                                 //    6   Console.WriteLine (a);
946                                 //
947                                 // Here, `a' is initialized in line 3 and we must not look at
948                                 // line 5 since it always returns.
949                                 // 
950                                 bool do_break_2 = (child.Type != SiblingType.Block) &&
951                                         (child.Type != SiblingType.SwitchSection);
952                                 bool unreachable = (do_break_2 && child.Reachability.AlwaysBreaks) ||
953                                         child.Reachability.AlwaysThrows ||
954                                         child.Reachability.AlwaysReturns ||
955                                         child.Reachability.AlwaysHasBarrier;
956
957                                 Report.Debug (2, "    MERGING SIBLING #1", reachability,
958                                               Type, child.Type, child.Reachability.IsUnreachable,
959                                               do_break_2, unreachable);
960
961                                 if (!unreachable)
962                                         MyBitVector.And (ref locals, child.LocalVector);
963
964                                 // An `out' parameter must be assigned in all branches which do
965                                 // not always throw an exception.
966                                 if ((child.Type != SiblingType.Catch) &&
967                                     (child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
968                                         MyBitVector.And (ref parameters, child.ParameterVector);
969                         }
970
971                         if (reachability == null)
972                                 reachability = Reachability.Never ();
973
974                         Report.Debug (2, "  MERGING SIBLINGS DONE", parameters, locals,
975                                       reachability, Infinite);
976
977                         return new UsageVector (parameters, locals, reachability, Location);
978                 }
979
980                 protected abstract UsageVector Merge ();
981
982                 // <summary>
983                 //   Merge a child branching.
984                 // </summary>
985                 public Reachability MergeChild (FlowBranching child)
986                 {
987                         UsageVector result = CurrentUsageVector.MergeChild (child);
988
989                         return result.Reachability;
990                 }
991
992                 // <summary>
993                 //   Does the toplevel merging.
994                 // </summary>
995                 public Reachability MergeTopBlock ()
996                 {
997                         if ((Type != BranchingType.Block) || (Block == null))
998                                 throw new NotSupportedException ();
999
1000                         UsageVector vector = new UsageVector (
1001                                 SiblingType.Conditional, null, Location, param_map.Length, local_map.Length);
1002
1003                         UsageVector result = vector.MergeChild (this);
1004
1005                         Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1006
1007                         if (vector.Reachability.Throws != FlowReturns.Always)
1008                                 CheckOutParameters (vector.Parameters, Location);
1009
1010                         return result.Reachability;
1011                 }
1012
1013                 public virtual bool InTryBlock ()
1014                 {
1015                         if (Parent != null)
1016                                 return Parent.InTryBlock ();
1017                         else
1018                                 return false;
1019                 }
1020
1021                 public virtual void AddFinallyVector (UsageVector vector)
1022                 {
1023                         if (Parent != null)
1024                                 Parent.AddFinallyVector (vector);
1025                         else
1026                                 throw new NotSupportedException ();
1027                 }
1028
1029                 public bool IsAssigned (VariableInfo vi)
1030                 {
1031                         return CurrentUsageVector.IsAssigned (vi);
1032                 }
1033
1034                 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1035                 {
1036                         if (CurrentUsageVector.IsAssigned (vi))
1037                                 return true;
1038
1039                         return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1040                 }
1041
1042                 public void SetAssigned (VariableInfo vi)
1043                 {
1044                         CurrentUsageVector.SetAssigned (vi);
1045                 }
1046
1047                 public void SetFieldAssigned (VariableInfo vi, string name)
1048                 {
1049                         CurrentUsageVector.SetFieldAssigned (vi, name);
1050                 }
1051
1052                 public override string ToString ()
1053                 {
1054                         StringBuilder sb = new StringBuilder ();
1055                         sb.Append (GetType ());
1056                         sb.Append (" (");
1057
1058                         sb.Append (id);
1059                         sb.Append (",");
1060                         sb.Append (Type);
1061                         if (Block != null) {
1062                                 sb.Append (" - ");
1063                                 sb.Append (Block.ID);
1064                                 sb.Append (" - ");
1065                                 sb.Append (Block.StartLocation);
1066                         }
1067                         sb.Append (" - ");
1068                         // sb.Append (Siblings.Length);
1069                         // sb.Append (" - ");
1070                         sb.Append (CurrentUsageVector);
1071                         sb.Append (")");
1072                         return sb.ToString ();
1073                 }
1074
1075                 public string Name {
1076                         get {
1077                                 return String.Format ("{0} ({1}:{2}:{3})",
1078                                                       GetType (), id, Type, Location);
1079                         }
1080                 }
1081         }
1082
1083         public class FlowBranchingBlock : FlowBranching
1084         {
1085                 UsageVector sibling_list = null;
1086
1087                 public FlowBranchingBlock (FlowBranching parent, BranchingType type, SiblingType stype,
1088                                            Block block, Location loc)
1089                         : base (parent, type, stype, block, loc)
1090                 { }
1091
1092                 public override UsageVector CurrentUsageVector {
1093                         get { return sibling_list; }
1094                 }
1095
1096                 protected override void AddSibling (UsageVector sibling)
1097                 {
1098                         sibling.Next = sibling_list;
1099                         sibling_list = sibling;
1100                 }
1101
1102                 public override void Label (ArrayList origin_vectors)
1103                 {
1104                         CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1105                 }
1106
1107                 protected override UsageVector Merge ()
1108                 {
1109                         return Merge (sibling_list);
1110                 }
1111         }
1112
1113         public class FlowBranchingException : FlowBranching
1114         {
1115                 UsageVector current_vector;
1116                 UsageVector try_vector;
1117                 UsageVector catch_vectors;
1118                 UsageVector finally_vector;
1119                 UsageVector finally_origins;
1120
1121                 public FlowBranchingException (FlowBranching parent, BranchingType type, Block block, Location loc)
1122                         : base (parent, type, SiblingType.Try, block, loc)
1123                 { }
1124
1125                 protected override void AddSibling (UsageVector sibling)
1126                 {
1127                         if (sibling.Type == SiblingType.Try) {
1128                                 try_vector = sibling;
1129                                 sibling.Next = catch_vectors;
1130                                 catch_vectors = sibling;
1131                         } else if (sibling.Type == SiblingType.Catch) {
1132                                 sibling.Next = catch_vectors;
1133                                 catch_vectors = sibling;
1134                         } else if (sibling.Type == SiblingType.Finally) {
1135                                 // sibling.MergeFinallyOrigins (finally_vectors);
1136                                 finally_vector = sibling;
1137                         } else
1138                                 throw new InvalidOperationException ();
1139
1140                         current_vector = sibling;
1141                 }
1142
1143                 public override UsageVector CurrentUsageVector {
1144                         get { return current_vector; }
1145                 }
1146
1147                 public override bool InTryBlock ()
1148                 {
1149                         return true;
1150                 }
1151
1152                 public override void AddFinallyVector (UsageVector vector)
1153                 {
1154                         vector = vector.Clone ();
1155                         vector.Next = finally_origins;
1156                         finally_origins = vector;
1157                 }
1158
1159                 public override void Label (ArrayList origin_vectors)
1160                 {
1161                         CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1162                 }
1163
1164                 protected override UsageVector Merge ()
1165                 {
1166                         UsageVector vector = Merge (catch_vectors);
1167
1168                         vector.MergeFinally (this, finally_vector, finally_origins);
1169
1170                         return vector;
1171                 }
1172         }
1173
1174         // <summary>
1175         //   This is used by the flow analysis code to keep track of the type of local variables
1176         //   and variables.
1177         //
1178         //   The flow code uses a BitVector to keep track of whether a variable has been assigned
1179         //   or not.  This is easy for fundamental types (int, char etc.) or reference types since
1180         //   you can only assign the whole variable as such.
1181         //
1182         //   For structs, we also need to keep track of all its fields.  To do this, we allocate one
1183         //   bit for the struct itself (it's used if you assign/access the whole struct) followed by
1184         //   one bit for each of its fields.
1185         //
1186         //   This class computes this `layout' for each type.
1187         // </summary>
1188         public class TypeInfo
1189         {
1190                 public readonly Type Type;
1191
1192                 // <summary>
1193                 //   Total number of bits a variable of this type consumes in the flow vector.
1194                 // </summary>
1195                 public readonly int TotalLength;
1196
1197                 // <summary>
1198                 //   Number of bits the simple fields of a variable of this type consume
1199                 //   in the flow vector.
1200                 // </summary>
1201                 public readonly int Length;
1202
1203                 // <summary>
1204                 //   This is only used by sub-structs.
1205                 // </summary>
1206                 public readonly int Offset;
1207
1208                 // <summary>
1209                 //   If this is a struct.
1210                 // </summary>
1211                 public readonly bool IsStruct;       
1212
1213                 // <summary>
1214                 //   If this is a struct, all fields which are structs theirselves.
1215                 // </summary>
1216                 public TypeInfo[] SubStructInfo;
1217
1218                 protected readonly StructInfo struct_info;
1219                 private static Hashtable type_hash = new Hashtable ();
1220
1221                 public static TypeInfo GetTypeInfo (Type type)
1222                 {
1223                         TypeInfo info = (TypeInfo) type_hash [type];
1224                         if (info != null)
1225                                 return info;
1226
1227                         info = new TypeInfo (type);
1228                         type_hash.Add (type, info);
1229                         return info;
1230                 }
1231
1232                 public static TypeInfo GetTypeInfo (TypeContainer tc)
1233                 {
1234                         TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1235                         if (info != null)
1236                                 return info;
1237
1238                         info = new TypeInfo (tc);
1239                         type_hash.Add (tc.TypeBuilder, info);
1240                         return info;
1241                 }
1242
1243                 private TypeInfo (Type type)
1244                 {
1245                         this.Type = type;
1246
1247                         struct_info = StructInfo.GetStructInfo (type);
1248                         if (struct_info != null) {
1249                                 Length = struct_info.Length;
1250                                 TotalLength = struct_info.TotalLength;
1251                                 SubStructInfo = struct_info.StructFields;
1252                                 IsStruct = true;
1253                         } else {
1254                                 Length = 0;
1255                                 TotalLength = 1;
1256                                 IsStruct = false;
1257                         }
1258                 }
1259
1260                 private TypeInfo (TypeContainer tc)
1261                 {
1262                         this.Type = tc.TypeBuilder;
1263
1264                         struct_info = StructInfo.GetStructInfo (tc);
1265                         if (struct_info != null) {
1266                                 Length = struct_info.Length;
1267                                 TotalLength = struct_info.TotalLength;
1268                                 SubStructInfo = struct_info.StructFields;
1269                                 IsStruct = true;
1270                         } else {
1271                                 Length = 0;
1272                                 TotalLength = 1;
1273                                 IsStruct = false;
1274                         }
1275                 }
1276
1277                 protected TypeInfo (StructInfo struct_info, int offset)
1278                 {
1279                         this.struct_info = struct_info;
1280                         this.Offset = offset;
1281                         this.Length = struct_info.Length;
1282                         this.TotalLength = struct_info.TotalLength;
1283                         this.SubStructInfo = struct_info.StructFields;
1284                         this.Type = struct_info.Type;
1285                         this.IsStruct = true;
1286                 }
1287
1288                 public int GetFieldIndex (string name)
1289                 {
1290                         if (struct_info == null)
1291                                 return 0;
1292
1293                         return struct_info [name];
1294                 }
1295
1296                 public TypeInfo GetSubStruct (string name)
1297                 {
1298                         if (struct_info == null)
1299                                 return null;
1300
1301                         return struct_info.GetStructField (name);
1302                 }
1303
1304                 // <summary>
1305                 //   A struct's constructor must always assign all fields.
1306                 //   This method checks whether it actually does so.
1307                 // </summary>
1308                 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1309                 {
1310                         if (struct_info == null)
1311                                 return true;
1312
1313                         bool ok = true;
1314                         for (int i = 0; i < struct_info.Count; i++) {
1315                                 FieldInfo field = struct_info.Fields [i];
1316
1317                                 if (!branching.IsFieldAssigned (vi, field.Name)) {
1318                                         Report.Error (171, loc,
1319                                                       "Field `" + TypeManager.CSharpName (Type) +
1320                                                       "." + field.Name + "' must be fully initialized " +
1321                                                       "before control leaves the constructor");
1322                                         ok = false;
1323                                 }
1324                         }
1325
1326                         return ok;
1327                 }
1328
1329                 public override string ToString ()
1330                 {
1331                         return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1332                                               Type, Offset, Length, TotalLength);
1333                 }
1334
1335                 protected class StructInfo {
1336                         public readonly Type Type;
1337                         public readonly FieldInfo[] Fields;
1338                         public readonly TypeInfo[] StructFields;
1339                         public readonly int Count;
1340                         public readonly int CountPublic;
1341                         public readonly int CountNonPublic;
1342                         public readonly int Length;
1343                         public readonly int TotalLength;
1344                         public readonly bool HasStructFields;
1345
1346                         private static Hashtable field_type_hash = new Hashtable ();
1347                         private Hashtable struct_field_hash;
1348                         private Hashtable field_hash;
1349
1350                         protected bool InTransit = false;
1351
1352                         // Private constructor.  To save memory usage, we only need to create one instance
1353                         // of this class per struct type.
1354                         private StructInfo (Type type)
1355                         {
1356                                 this.Type = type;
1357
1358                                 field_type_hash.Add (type, this);
1359
1360                                 if (type is TypeBuilder) {
1361                                         TypeContainer tc = TypeManager.LookupTypeContainer (type);
1362
1363                                         ArrayList fields = tc.Fields;
1364
1365                                         ArrayList public_fields = new ArrayList ();
1366                                         ArrayList non_public_fields = new ArrayList ();
1367
1368                                         if (fields != null) {
1369                                                 foreach (Field field in fields) {
1370                                                         if ((field.ModFlags & Modifiers.STATIC) != 0)
1371                                                                 continue;
1372                                                         if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1373                                                                 public_fields.Add (field.FieldBuilder);
1374                                                         else
1375                                                                 non_public_fields.Add (field.FieldBuilder);
1376                                                 }
1377                                         }
1378
1379                                         CountPublic = public_fields.Count;
1380                                         CountNonPublic = non_public_fields.Count;
1381                                         Count = CountPublic + CountNonPublic;
1382
1383                                         Fields = new FieldInfo [Count];
1384                                         public_fields.CopyTo (Fields, 0);
1385                                         non_public_fields.CopyTo (Fields, CountPublic);
1386                                 } else {
1387                                         FieldInfo[] public_fields = type.GetFields (
1388                                                 BindingFlags.Instance|BindingFlags.Public);
1389                                         FieldInfo[] non_public_fields = type.GetFields (
1390                                                 BindingFlags.Instance|BindingFlags.NonPublic);
1391
1392                                         CountPublic = public_fields.Length;
1393                                         CountNonPublic = non_public_fields.Length;
1394                                         Count = CountPublic + CountNonPublic;
1395
1396                                         Fields = new FieldInfo [Count];
1397                                         public_fields.CopyTo (Fields, 0);
1398                                         non_public_fields.CopyTo (Fields, CountPublic);
1399                                 }
1400
1401                                 struct_field_hash = new Hashtable ();
1402                                 field_hash = new Hashtable ();
1403
1404                                 Length = 0;
1405                                 StructFields = new TypeInfo [Count];
1406                                 StructInfo[] sinfo = new StructInfo [Count];
1407
1408                                 InTransit = true;
1409
1410                                 for (int i = 0; i < Count; i++) {
1411                                         FieldInfo field = (FieldInfo) Fields [i];
1412
1413                                         sinfo [i] = GetStructInfo (field.FieldType);
1414                                         if (sinfo [i] == null)
1415                                                 field_hash.Add (field.Name, ++Length);
1416                                         else if (sinfo [i].InTransit) {
1417                                                 Report.Error (523, String.Format (
1418                                                                       "Struct member '{0}.{1}' of type '{2}' causes " +
1419                                                                       "a cycle in the structure layout",
1420                                                                       type, field.Name, sinfo [i].Type));
1421                                                 sinfo [i] = null;
1422                                                 return;
1423                                         }
1424                                 }
1425
1426                                 InTransit = false;
1427
1428                                 TotalLength = Length + 1;
1429                                 for (int i = 0; i < Count; i++) {
1430                                         FieldInfo field = (FieldInfo) Fields [i];
1431
1432                                         if (sinfo [i] == null)
1433                                                 continue;
1434
1435                                         field_hash.Add (field.Name, TotalLength);
1436
1437                                         HasStructFields = true;
1438                                         StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1439                                         struct_field_hash.Add (field.Name, StructFields [i]);
1440                                         TotalLength += sinfo [i].TotalLength;
1441                                 }
1442                         }
1443
1444                         public int this [string name] {
1445                                 get {
1446                                         if (field_hash.Contains (name))
1447                                                 return (int) field_hash [name];
1448                                         else
1449                                                 return 0;
1450                                 }
1451                         }
1452
1453                         public TypeInfo GetStructField (string name)
1454                         {
1455                                 return (TypeInfo) struct_field_hash [name];
1456                         }
1457
1458                         public static StructInfo GetStructInfo (Type type)
1459                         {
1460                                 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1461                                     TypeManager.IsBuiltinType (type))
1462                                         return null;
1463
1464                                 StructInfo info = (StructInfo) field_type_hash [type];
1465                                 if (info != null)
1466                                         return info;
1467
1468                                 return new StructInfo (type);
1469                         }
1470
1471                         public static StructInfo GetStructInfo (TypeContainer tc)
1472                         {
1473                                 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1474                                 if (info != null)
1475                                         return info;
1476
1477                                 return new StructInfo (tc.TypeBuilder);
1478                         }
1479                 }
1480         }
1481
1482         // <summary>
1483         //   This is used by the flow analysis code to store information about a single local variable
1484         //   or parameter.  Depending on the variable's type, we need to allocate one or more elements
1485         //   in the BitVector - if it's a fundamental or reference type, we just need to know whether
1486         //   it has been assigned or not, but for structs, we need this information for each of its fields.
1487         // </summary>
1488         public class VariableInfo {
1489                 public readonly string Name;
1490                 public readonly TypeInfo TypeInfo;
1491
1492                 // <summary>
1493                 //   The bit offset of this variable in the flow vector.
1494                 // </summary>
1495                 public readonly int Offset;
1496
1497                 // <summary>
1498                 //   The number of bits this variable needs in the flow vector.
1499                 //   The first bit always specifies whether the variable as such has been assigned while
1500                 //   the remaining bits contain this information for each of a struct's fields.
1501                 // </summary>
1502                 public readonly int Length;
1503
1504                 // <summary>
1505                 //   If this is a parameter of local variable.
1506                 // </summary>
1507                 public readonly bool IsParameter;
1508
1509                 public readonly LocalInfo LocalInfo;
1510                 public readonly int ParameterIndex;
1511
1512                 readonly VariableInfo Parent;
1513                 VariableInfo[] sub_info;
1514
1515                 protected VariableInfo (string name, Type type, int offset)
1516                 {
1517                         this.Name = name;
1518                         this.Offset = offset;
1519                         this.TypeInfo = TypeInfo.GetTypeInfo (type);
1520
1521                         Length = TypeInfo.TotalLength;
1522
1523                         Initialize ();
1524                 }
1525
1526                 protected VariableInfo (VariableInfo parent, TypeInfo type)
1527                 {
1528                         this.Name = parent.Name;
1529                         this.TypeInfo = type;
1530                         this.Offset = parent.Offset + type.Offset;
1531                         this.Parent = parent;
1532                         this.Length = type.TotalLength;
1533
1534                         this.IsParameter = parent.IsParameter;
1535                         this.LocalInfo = parent.LocalInfo;
1536                         this.ParameterIndex = parent.ParameterIndex;
1537
1538                         Initialize ();
1539                 }
1540
1541                 protected void Initialize ()
1542                 {
1543                         TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1544                         if (sub_fields != null) {
1545                                 sub_info = new VariableInfo [sub_fields.Length];
1546                                 for (int i = 0; i < sub_fields.Length; i++) {
1547                                         if (sub_fields [i] != null)
1548                                                 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1549                                 }
1550                         } else
1551                                 sub_info = new VariableInfo [0];
1552                 }
1553
1554                 public VariableInfo (LocalInfo local_info, int offset)
1555                         : this (local_info.Name, local_info.VariableType, offset)
1556                 {
1557                         this.LocalInfo = local_info;
1558                         this.IsParameter = false;
1559                 }
1560
1561                 public VariableInfo (string name, Type type, int param_idx, int offset)
1562                         : this (name, type, offset)
1563                 {
1564                         this.ParameterIndex = param_idx;
1565                         this.IsParameter = true;
1566                 }
1567
1568                 public bool IsAssigned (EmitContext ec)
1569                 {
1570                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1571                 }
1572
1573                 public bool IsAssigned (EmitContext ec, Location loc)
1574                 {
1575                         if (IsAssigned (ec))
1576                                 return true;
1577
1578                         Report.Error (165, loc,
1579                                       "Use of unassigned local variable `" + Name + "'");
1580                         ec.CurrentBranching.SetAssigned (this);
1581                         return false;
1582                 }
1583
1584                 public bool IsAssigned (MyBitVector vector)
1585                 {
1586                         if (vector [Offset])
1587                                 return true;
1588
1589                         for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1590                                 if (vector [parent.Offset])
1591                                         return true;
1592
1593                         // Return unless this is a struct.
1594                         if (!TypeInfo.IsStruct)
1595                                 return false;
1596
1597                         // Ok, so each field must be assigned.
1598                         for (int i = 0; i < TypeInfo.Length; i++) {
1599                                 if (!vector [Offset + i + 1])
1600                                         return false;
1601                         }
1602
1603                         // Ok, now check all fields which are structs.
1604                         for (int i = 0; i < sub_info.Length; i++) {
1605                                 VariableInfo sinfo = sub_info [i];
1606                                 if (sinfo == null)
1607                                         continue;
1608
1609                                 if (!sinfo.IsAssigned (vector))
1610                                         return false;
1611                         }
1612
1613                         vector [Offset] = true;
1614                         return true;
1615                 }
1616
1617                 public void SetAssigned (EmitContext ec)
1618                 {
1619                         if (ec.DoFlowAnalysis)
1620                                 ec.CurrentBranching.SetAssigned (this);
1621                 }
1622
1623                 public void SetAssigned (MyBitVector vector)
1624                 {
1625                         vector [Offset] = true;
1626                 }
1627
1628                 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1629                 {
1630                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1631                                 return true;
1632
1633                         Report.Error (170, loc,
1634                                       "Use of possibly unassigned field `" + name + "'");
1635                         ec.CurrentBranching.SetFieldAssigned (this, name);
1636                         return false;
1637                 }
1638
1639                 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1640                 {
1641                         int field_idx = TypeInfo.GetFieldIndex (field_name);
1642
1643                         if (field_idx == 0)
1644                                 return true;
1645
1646                         return vector [Offset + field_idx];
1647                 }
1648
1649                 public void SetFieldAssigned (EmitContext ec, string name)
1650                 {
1651                         if (ec.DoFlowAnalysis)
1652                                 ec.CurrentBranching.SetFieldAssigned (this, name);
1653                 }
1654
1655                 public void SetFieldAssigned (MyBitVector vector, string field_name)
1656                 {
1657                         int field_idx = TypeInfo.GetFieldIndex (field_name);
1658
1659                         if (field_idx == 0)
1660                                 return;
1661
1662                         vector [Offset + field_idx] = true;
1663                 }
1664
1665                 public VariableInfo GetSubStruct (string name)
1666                 {
1667                         TypeInfo type = TypeInfo.GetSubStruct (name);
1668
1669                         if (type == null)
1670                                 return null;
1671
1672                         return new VariableInfo (this, type);
1673                 }
1674
1675                 public override string ToString ()
1676                 {
1677                         return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1678                                               Name, TypeInfo, Offset, Length, IsParameter);
1679                 }
1680         }
1681
1682         // <summary>
1683         //   This is used by the flow code to hold the `layout' of the flow vector for
1684         //   all locals and all parameters (ie. we create one instance of this class for the
1685         //   locals and another one for the params).
1686         // </summary>
1687         public class VariableMap {
1688                 // <summary>
1689                 //   The number of variables in the map.
1690                 // </summary>
1691                 public readonly int Count;
1692
1693                 // <summary>
1694                 //   Total length of the flow vector for this map.
1695                 // <summary>
1696                 public readonly int Length;
1697
1698                 // <summary>
1699                 //   Type and name of all the variables.
1700                 //   Note that this is null for variables for which we do not need to compute
1701                 //   assignment info.
1702                 // </summary>
1703                 public readonly Type[] VariableTypes;
1704                 public readonly string[] VariableNames;
1705
1706                 VariableInfo[] map;
1707
1708                 public VariableMap (InternalParameters ip)
1709                 {
1710                         Count = ip != null ? ip.Count : 0;
1711                         map = new VariableInfo [Count];
1712                         VariableNames = new string [Count];
1713                         VariableTypes = new Type [Count];
1714                         Length = 0;
1715
1716                         for (int i = 0; i < Count; i++) {
1717                                 Parameter.Modifier mod = ip.ParameterModifier (i);
1718
1719                                 if ((mod & Parameter.Modifier.OUT) == 0)
1720                                         continue;
1721
1722                                 VariableNames [i] = ip.ParameterName (i);
1723                                 VariableTypes [i] = TypeManager.GetElementType (ip.ParameterType (i));
1724
1725                                 map [i] = new VariableInfo (VariableNames [i], VariableTypes [i], i, Length);
1726                                 Length += map [i].Length;
1727                         }
1728                 }
1729
1730                 public VariableMap (LocalInfo[] locals)
1731                         : this (null, locals)
1732                 { }
1733
1734                 public VariableMap (VariableMap parent, LocalInfo[] locals)
1735                 {
1736                         int offset = 0, start = 0;
1737                         if (parent != null) {
1738                                 offset = parent.Length;
1739                                 start = parent.Count;
1740                         }
1741
1742                         Count = locals.Length + start;
1743                         map = new VariableInfo [Count];
1744                         VariableNames = new string [Count];
1745                         VariableTypes = new Type [Count];
1746                         Length = offset;
1747
1748                         if (parent != null) {
1749                                 parent.map.CopyTo (map, 0);
1750                                 parent.VariableNames.CopyTo (VariableNames, 0);
1751                                 parent.VariableTypes.CopyTo (VariableTypes, 0);
1752                         }
1753
1754                         for (int i = start; i < Count; i++) {
1755                                 LocalInfo li = locals [i-start];
1756
1757                                 if (li.VariableType == null)
1758                                         continue;
1759
1760                                 VariableNames [i] = li.Name;
1761                                 VariableTypes [i] = li.VariableType;
1762
1763                                 map [i] = li.VariableInfo = new VariableInfo (li, Length);
1764                                 Length += map [i].Length;
1765                         }
1766                 }
1767
1768                 // <summary>
1769                 //   Returns the VariableInfo for variable @index or null if we don't need to
1770                 //   compute assignment info for this variable.
1771                 // </summary>
1772                 public VariableInfo this [int index] {
1773                         get {
1774                                 return map [index];
1775                         }
1776                 }
1777
1778                 public override string ToString ()
1779                 {
1780                         return String.Format ("VariableMap ({0}:{1})", Count, Length);
1781                 }
1782         }
1783
1784         // <summary>
1785         //   This is a special bit vector which can inherit from another bit vector doing a
1786         //   copy-on-write strategy.  The inherited vector may have a smaller size than the
1787         //   current one.
1788         // </summary>
1789         public class MyBitVector {
1790                 public readonly int Count;
1791                 public readonly MyBitVector InheritsFrom;
1792
1793                 bool is_dirty;
1794                 BitArray vector;
1795
1796                 public MyBitVector (int Count)
1797                         : this (null, Count)
1798                 { }
1799
1800                 public MyBitVector (MyBitVector InheritsFrom, int Count)
1801                 {
1802                         this.InheritsFrom = InheritsFrom;
1803                         this.Count = Count;
1804                 }
1805
1806                 // <summary>
1807                 //   Checks whether this bit vector has been modified.  After setting this to true,
1808                 //   we won't use the inherited vector anymore, but our own copy of it.
1809                 // </summary>
1810                 public bool IsDirty {
1811                         get {
1812                                 return is_dirty;
1813                         }
1814
1815                         set {
1816                                 if (!is_dirty)
1817                                         initialize_vector ();
1818                         }
1819                 }
1820
1821                 // <summary>
1822                 //   Get/set bit `index' in the bit vector.
1823                 // </summary>
1824                 public bool this [int index]
1825                 {
1826                         get {
1827                                 if (index > Count)
1828                                         throw new ArgumentOutOfRangeException ();
1829
1830                                 // We're doing a "copy-on-write" strategy here; as long
1831                                 // as nobody writes to the array, we can use our parent's
1832                                 // copy instead of duplicating the vector.
1833
1834                                 if (vector != null)
1835                                         return vector [index];
1836                                 else if (InheritsFrom != null) {
1837                                         BitArray inherited = InheritsFrom.Vector;
1838
1839                                         if (index < inherited.Count)
1840                                                 return inherited [index];
1841                                         else
1842                                                 return false;
1843                                 } else
1844                                         return false;
1845                         }
1846
1847                         set {
1848                                 if (index > Count)
1849                                         throw new ArgumentOutOfRangeException ();
1850
1851                                 // Only copy the vector if we're actually modifying it.
1852
1853                                 if (this [index] != value) {
1854                                         initialize_vector ();
1855
1856                                         vector [index] = value;
1857                                 }
1858                         }
1859                 }
1860
1861                 // <summary>
1862                 //   If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1863                 //   copy of the bit vector.
1864                 // </summary>
1865                 public static explicit operator BitArray (MyBitVector vector)
1866                 {
1867                         vector.initialize_vector ();
1868                         return vector.Vector;
1869                 }
1870
1871                 // <summary>
1872                 //   Performs an `or' operation on the bit vector.  The `new_vector' may have a
1873                 //   different size than the current one.
1874                 // </summary>
1875                 public void Or (MyBitVector new_vector)
1876                 {
1877                         BitArray new_array = new_vector.Vector;
1878
1879                         initialize_vector ();
1880
1881                         int upper;
1882                         if (vector.Count < new_array.Count)
1883                                 upper = vector.Count;
1884                         else
1885                                 upper = new_array.Count;
1886
1887                         for (int i = 0; i < upper; i++)
1888                                 vector [i] = vector [i] | new_array [i];
1889                 }
1890
1891                 // <summary>
1892                 //   Perfonrms an `and' operation on the bit vector.  The `new_vector' may have
1893                 //   a different size than the current one.
1894                 // </summary>
1895                 public void And (MyBitVector new_vector)
1896                 {
1897                         BitArray new_array = new_vector.Vector;
1898
1899                         initialize_vector ();
1900
1901                         int lower, upper;
1902                         if (vector.Count < new_array.Count)
1903                                 lower = upper = vector.Count;
1904                         else {
1905                                 lower = new_array.Count;
1906                                 upper = vector.Count;
1907                         }
1908
1909                         for (int i = 0; i < lower; i++)
1910                                 vector [i] = vector [i] & new_array [i];
1911
1912                         for (int i = lower; i < upper; i++)
1913                                 vector [i] = false;
1914                 }
1915
1916                 public static void And (ref MyBitVector target, MyBitVector vector)
1917                 {
1918                         if (target != null)
1919                                 target.And (vector);
1920                         else
1921                                 target = vector.Clone ();
1922                 }
1923
1924                 public static void Or (ref MyBitVector target, MyBitVector vector)
1925                 {
1926                         if (target != null)
1927                                 target.Or (vector);
1928                         else
1929                                 target = vector.Clone ();
1930                 }
1931
1932                 // <summary>
1933                 //   This does a deep copy of the bit vector.
1934                 // </summary>
1935                 public MyBitVector Clone ()
1936                 {
1937                         MyBitVector retval = new MyBitVector (Count);
1938
1939                         retval.Vector = Vector;
1940
1941                         return retval;
1942                 }
1943
1944                 BitArray Vector {
1945                         get {
1946                                 if (vector != null)
1947                                         return vector;
1948                                 else if (!is_dirty && (InheritsFrom != null))
1949                                         return InheritsFrom.Vector;
1950
1951                                 initialize_vector ();
1952
1953                                 return vector;
1954                         }
1955
1956                         set {
1957                                 initialize_vector ();
1958
1959                                 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1960                                         vector [i] = value [i];
1961                         }
1962                 }
1963
1964                 void initialize_vector ()
1965                 {
1966                         if (vector != null)
1967                                 return;
1968
1969                         vector = new BitArray (Count, false);
1970                         if (InheritsFrom != null)
1971                                 Vector = InheritsFrom.Vector;
1972
1973                         is_dirty = true;
1974                 }
1975
1976                 public override string ToString ()
1977                 {
1978                         StringBuilder sb = new StringBuilder ("{");
1979
1980                         BitArray vector = Vector;
1981                         if (!IsDirty)
1982                                 sb.Append ("=");
1983                         for (int i = 0; i < vector.Count; i++) {
1984                                 sb.Append (vector [i] ? "1" : "0");
1985                         }
1986                         
1987                         sb.Append ("}");
1988                         return sb.ToString ();
1989                 }
1990         }
1991 }