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