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