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