OSDN Git Service

2011-08-31 Jose Ruiz <ruiz@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch5.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              S E M _ C H 5                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Einfo;    use Einfo;
30 with Errout;   use Errout;
31 with Expander; use Expander;
32 with Exp_Util; use Exp_Util;
33 with Freeze;   use Freeze;
34 with Lib;      use Lib;
35 with Lib.Xref; use Lib.Xref;
36 with Namet;    use Namet;
37 with Nlists;   use Nlists;
38 with Nmake;    use Nmake;
39 with Opt;      use Opt;
40 with Restrict; use Restrict;
41 with Rident;   use Rident;
42 with Rtsfind;  use Rtsfind;
43 with Sem;      use Sem;
44 with Sem_Aux;  use Sem_Aux;
45 with Sem_Case; use Sem_Case;
46 with Sem_Ch3;  use Sem_Ch3;
47 with Sem_Ch8;  use Sem_Ch8;
48 with Sem_Disp; use Sem_Disp;
49 with Sem_Elab; use Sem_Elab;
50 with Sem_Eval; use Sem_Eval;
51 with Sem_Res;  use Sem_Res;
52 with Sem_Type; use Sem_Type;
53 with Sem_Util; use Sem_Util;
54 with Sem_Warn; use Sem_Warn;
55 with Snames;   use Snames;
56 with Stand;    use Stand;
57 with Sinfo;    use Sinfo;
58 with Targparm; use Targparm;
59 with Tbuild;   use Tbuild;
60 with Uintp;    use Uintp;
61
62 package body Sem_Ch5 is
63
64    Unblocked_Exit_Count : Nat := 0;
65    --  This variable is used when processing if statements, case statements,
66    --  and block statements. It counts the number of exit points that are not
67    --  blocked by unconditional transfer instructions: for IF and CASE, these
68    --  are the branches of the conditional; for a block, they are the statement
69    --  sequence of the block, and the statement sequences of any exception
70    --  handlers that are part of the block. When processing is complete, if
71    --  this count is zero, it means that control cannot fall through the IF,
72    --  CASE or block statement. This is used for the generation of warning
73    --  messages. This variable is recursively saved on entry to processing the
74    --  construct, and restored on exit.
75
76    ------------------------
77    -- Analyze_Assignment --
78    ------------------------
79
80    procedure Analyze_Assignment (N : Node_Id) is
81       Lhs  : constant Node_Id := Name (N);
82       Rhs  : constant Node_Id := Expression (N);
83       T1   : Entity_Id;
84       T2   : Entity_Id;
85       Decl : Node_Id;
86
87       procedure Diagnose_Non_Variable_Lhs (N : Node_Id);
88       --  N is the node for the left hand side of an assignment, and it is not
89       --  a variable. This routine issues an appropriate diagnostic.
90
91       procedure Kill_Lhs;
92       --  This is called to kill current value settings of a simple variable
93       --  on the left hand side. We call it if we find any error in analyzing
94       --  the assignment, and at the end of processing before setting any new
95       --  current values in place.
96
97       procedure Set_Assignment_Type
98         (Opnd      : Node_Id;
99          Opnd_Type : in out Entity_Id);
100       --  Opnd is either the Lhs or Rhs of the assignment, and Opnd_Type is the
101       --  nominal subtype. This procedure is used to deal with cases where the
102       --  nominal subtype must be replaced by the actual subtype.
103
104       -------------------------------
105       -- Diagnose_Non_Variable_Lhs --
106       -------------------------------
107
108       procedure Diagnose_Non_Variable_Lhs (N : Node_Id) is
109       begin
110          --  Not worth posting another error if left hand side already flagged
111          --  as being illegal in some respect.
112
113          if Error_Posted (N) then
114             return;
115
116          --  Some special bad cases of entity names
117
118          elsif Is_Entity_Name (N) then
119             declare
120                Ent : constant Entity_Id := Entity (N);
121
122             begin
123                if Ekind (Ent) = E_In_Parameter then
124                   Error_Msg_N
125                     ("assignment to IN mode parameter not allowed", N);
126
127                --  Renamings of protected private components are turned into
128                --  constants when compiling a protected function. In the case
129                --  of single protected types, the private component appears
130                --  directly.
131
132                elsif (Is_Prival (Ent)
133                         and then
134                           (Ekind (Current_Scope) = E_Function
135                              or else Ekind (Enclosing_Dynamic_Scope
136                                              (Current_Scope)) = E_Function))
137                    or else
138                      (Ekind (Ent) = E_Component
139                         and then Is_Protected_Type (Scope (Ent)))
140                then
141                   Error_Msg_N
142                     ("protected function cannot modify protected object", N);
143
144                elsif Ekind (Ent) = E_Loop_Parameter then
145                   Error_Msg_N
146                     ("assignment to loop parameter not allowed", N);
147
148                else
149                   Error_Msg_N
150                     ("left hand side of assignment must be a variable", N);
151                end if;
152             end;
153
154          --  For indexed components or selected components, test prefix
155
156          elsif Nkind (N) = N_Indexed_Component then
157             Diagnose_Non_Variable_Lhs (Prefix (N));
158
159          --  Another special case for assignment to discriminant
160
161          elsif Nkind (N) = N_Selected_Component then
162             if Present (Entity (Selector_Name (N)))
163               and then Ekind (Entity (Selector_Name (N))) = E_Discriminant
164             then
165                Error_Msg_N
166                  ("assignment to discriminant not allowed", N);
167             else
168                Diagnose_Non_Variable_Lhs (Prefix (N));
169             end if;
170
171          else
172             --  If we fall through, we have no special message to issue!
173
174             Error_Msg_N ("left hand side of assignment must be a variable", N);
175          end if;
176       end Diagnose_Non_Variable_Lhs;
177
178       --------------
179       -- Kill_LHS --
180       --------------
181
182       procedure Kill_Lhs is
183       begin
184          if Is_Entity_Name (Lhs) then
185             declare
186                Ent : constant Entity_Id := Entity (Lhs);
187             begin
188                if Present (Ent) then
189                   Kill_Current_Values (Ent);
190                end if;
191             end;
192          end if;
193       end Kill_Lhs;
194
195       -------------------------
196       -- Set_Assignment_Type --
197       -------------------------
198
199       procedure Set_Assignment_Type
200         (Opnd      : Node_Id;
201          Opnd_Type : in out Entity_Id)
202       is
203       begin
204          Require_Entity (Opnd);
205
206          --  If the assignment operand is an in-out or out parameter, then we
207          --  get the actual subtype (needed for the unconstrained case). If the
208          --  operand is the actual in an entry declaration, then within the
209          --  accept statement it is replaced with a local renaming, which may
210          --  also have an actual subtype.
211
212          if Is_Entity_Name (Opnd)
213            and then (Ekind (Entity (Opnd)) = E_Out_Parameter
214                       or else Ekind (Entity (Opnd)) =
215                            E_In_Out_Parameter
216                       or else Ekind (Entity (Opnd)) =
217                            E_Generic_In_Out_Parameter
218                       or else
219                         (Ekind (Entity (Opnd)) = E_Variable
220                           and then Nkind (Parent (Entity (Opnd))) =
221                              N_Object_Renaming_Declaration
222                           and then Nkind (Parent (Parent (Entity (Opnd)))) =
223                              N_Accept_Statement))
224          then
225             Opnd_Type := Get_Actual_Subtype (Opnd);
226
227          --  If assignment operand is a component reference, then we get the
228          --  actual subtype of the component for the unconstrained case.
229
230          elsif Nkind_In (Opnd, N_Selected_Component, N_Explicit_Dereference)
231            and then not Is_Unchecked_Union (Opnd_Type)
232          then
233             Decl := Build_Actual_Subtype_Of_Component (Opnd_Type, Opnd);
234
235             if Present (Decl) then
236                Insert_Action (N, Decl);
237                Mark_Rewrite_Insertion (Decl);
238                Analyze (Decl);
239                Opnd_Type := Defining_Identifier (Decl);
240                Set_Etype (Opnd, Opnd_Type);
241                Freeze_Itype (Opnd_Type, N);
242
243             elsif Is_Constrained (Etype (Opnd)) then
244                Opnd_Type := Etype (Opnd);
245             end if;
246
247          --  For slice, use the constrained subtype created for the slice
248
249          elsif Nkind (Opnd) = N_Slice then
250             Opnd_Type := Etype (Opnd);
251          end if;
252       end Set_Assignment_Type;
253
254    --  Start of processing for Analyze_Assignment
255
256    begin
257       Mark_Coextensions (N, Rhs);
258
259       Analyze (Rhs);
260       Analyze (Lhs);
261
262       --  Ensure that we never do an assignment on a variable marked as
263       --  as Safe_To_Reevaluate.
264
265       pragma Assert (not Is_Entity_Name (Lhs)
266         or else Ekind (Entity (Lhs)) /= E_Variable
267         or else not Is_Safe_To_Reevaluate (Entity (Lhs)));
268
269       --  Start type analysis for assignment
270
271       T1 := Etype (Lhs);
272
273       --  In the most general case, both Lhs and Rhs can be overloaded, and we
274       --  must compute the intersection of the possible types on each side.
275
276       if Is_Overloaded (Lhs) then
277          declare
278             I  : Interp_Index;
279             It : Interp;
280
281          begin
282             T1 := Any_Type;
283             Get_First_Interp (Lhs, I, It);
284
285             while Present (It.Typ) loop
286                if Has_Compatible_Type (Rhs, It.Typ) then
287                   if T1 /= Any_Type then
288
289                      --  An explicit dereference is overloaded if the prefix
290                      --  is. Try to remove the ambiguity on the prefix, the
291                      --  error will be posted there if the ambiguity is real.
292
293                      if Nkind (Lhs) = N_Explicit_Dereference then
294                         declare
295                            PI    : Interp_Index;
296                            PI1   : Interp_Index := 0;
297                            PIt   : Interp;
298                            Found : Boolean;
299
300                         begin
301                            Found := False;
302                            Get_First_Interp (Prefix (Lhs), PI, PIt);
303
304                            while Present (PIt.Typ) loop
305                               if Is_Access_Type (PIt.Typ)
306                                 and then Has_Compatible_Type
307                                            (Rhs, Designated_Type (PIt.Typ))
308                               then
309                                  if Found then
310                                     PIt :=
311                                       Disambiguate (Prefix (Lhs),
312                                         PI1, PI, Any_Type);
313
314                                     if PIt = No_Interp then
315                                        Error_Msg_N
316                                          ("ambiguous left-hand side"
317                                             & " in assignment", Lhs);
318                                        exit;
319                                     else
320                                        Resolve (Prefix (Lhs), PIt.Typ);
321                                     end if;
322
323                                     exit;
324                                  else
325                                     Found := True;
326                                     PI1 := PI;
327                                  end if;
328                               end if;
329
330                               Get_Next_Interp (PI, PIt);
331                            end loop;
332                         end;
333
334                      else
335                         Error_Msg_N
336                           ("ambiguous left-hand side in assignment", Lhs);
337                         exit;
338                      end if;
339                   else
340                      T1 := It.Typ;
341                   end if;
342                end if;
343
344                Get_Next_Interp (I, It);
345             end loop;
346          end;
347
348          if T1 = Any_Type then
349             Error_Msg_N
350               ("no valid types for left-hand side for assignment", Lhs);
351             Kill_Lhs;
352             return;
353          end if;
354       end if;
355
356       --  The resulting assignment type is T1, so now we will resolve the left
357       --  hand side of the assignment using this determined type.
358
359       Resolve (Lhs, T1);
360
361       --  Cases where Lhs is not a variable
362
363       if not Is_Variable (Lhs) then
364
365          --  Ada 2005 (AI-327): Check assignment to the attribute Priority of a
366          --  protected object.
367
368          declare
369             Ent : Entity_Id;
370             S   : Entity_Id;
371
372          begin
373             if Ada_Version >= Ada_2005 then
374
375                --  Handle chains of renamings
376
377                Ent := Lhs;
378                while Nkind (Ent) in N_Has_Entity
379                  and then Present (Entity (Ent))
380                  and then Present (Renamed_Object (Entity (Ent)))
381                loop
382                   Ent := Renamed_Object (Entity (Ent));
383                end loop;
384
385                if (Nkind (Ent) = N_Attribute_Reference
386                      and then Attribute_Name (Ent) = Name_Priority)
387
388                   --  Renamings of the attribute Priority applied to protected
389                   --  objects have been previously expanded into calls to the
390                   --  Get_Ceiling run-time subprogram.
391
392                  or else
393                   (Nkind (Ent) = N_Function_Call
394                      and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
395                                 or else
396                                Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling)))
397                then
398                   --  The enclosing subprogram cannot be a protected function
399
400                   S := Current_Scope;
401                   while not (Is_Subprogram (S)
402                                and then Convention (S) = Convention_Protected)
403                      and then S /= Standard_Standard
404                   loop
405                      S := Scope (S);
406                   end loop;
407
408                   if Ekind (S) = E_Function
409                     and then Convention (S) = Convention_Protected
410                   then
411                      Error_Msg_N
412                        ("protected function cannot modify protected object",
413                         Lhs);
414                   end if;
415
416                   --  Changes of the ceiling priority of the protected object
417                   --  are only effective if the Ceiling_Locking policy is in
418                   --  effect (AARM D.5.2 (5/2)).
419
420                   if Locking_Policy /= 'C' then
421                      Error_Msg_N ("assignment to the attribute PRIORITY has " &
422                                   "no effect?", Lhs);
423                      Error_Msg_N ("\since no Locking_Policy has been " &
424                                   "specified", Lhs);
425                   end if;
426
427                   return;
428                end if;
429             end if;
430          end;
431
432          Diagnose_Non_Variable_Lhs (Lhs);
433          return;
434
435       --  Error of assigning to limited type. We do however allow this in
436       --  certain cases where the front end generates the assignments.
437
438       elsif Is_Limited_Type (T1)
439         and then not Assignment_OK (Lhs)
440         and then not Assignment_OK (Original_Node (Lhs))
441         and then not Is_Value_Type (T1)
442       then
443          --  CPP constructors can only be called in declarations
444
445          if Is_CPP_Constructor_Call (Rhs) then
446             Error_Msg_N ("invalid use of 'C'P'P constructor", Rhs);
447          else
448             Error_Msg_N
449               ("left hand of assignment must not be limited type", Lhs);
450             Explain_Limited_Type (T1, Lhs);
451          end if;
452          return;
453
454       --  Enforce RM 3.9.3 (8): the target of an assignment operation cannot be
455       --  abstract. This is only checked when the assignment Comes_From_Source,
456       --  because in some cases the expander generates such assignments (such
457       --  in the _assign operation for an abstract type).
458
459       elsif Is_Abstract_Type (T1) and then Comes_From_Source (N) then
460          Error_Msg_N
461            ("target of assignment operation must not be abstract", Lhs);
462       end if;
463
464       --  Resolution may have updated the subtype, in case the left-hand side
465       --  is a private protected component. Use the correct subtype to avoid
466       --  scoping issues in the back-end.
467
468       T1 := Etype (Lhs);
469
470       --  Ada 2005 (AI-50217, AI-326): Check wrong dereference of incomplete
471       --  type. For example:
472
473       --    limited with P;
474       --    package Pkg is
475       --      type Acc is access P.T;
476       --    end Pkg;
477
478       --    with Pkg; use Acc;
479       --    procedure Example is
480       --       A, B : Acc;
481       --    begin
482       --       A.all := B.all;  -- ERROR
483       --    end Example;
484
485       if Nkind (Lhs) = N_Explicit_Dereference
486         and then Ekind (T1) = E_Incomplete_Type
487       then
488          Error_Msg_N ("invalid use of incomplete type", Lhs);
489          Kill_Lhs;
490          return;
491       end if;
492
493       --  Now we can complete the resolution of the right hand side
494
495       Set_Assignment_Type (Lhs, T1);
496       Resolve (Rhs, T1);
497
498       --  This is the point at which we check for an unset reference
499
500       Check_Unset_Reference (Rhs);
501       Check_Unprotected_Access (Lhs, Rhs);
502
503       --  Remaining steps are skipped if Rhs was syntactically in error
504
505       if Rhs = Error then
506          Kill_Lhs;
507          return;
508       end if;
509
510       T2 := Etype (Rhs);
511
512       if not Covers (T1, T2) then
513          Wrong_Type (Rhs, Etype (Lhs));
514          Kill_Lhs;
515          return;
516       end if;
517
518       --  Ada 2005 (AI-326): In case of explicit dereference of incomplete
519       --  types, use the non-limited view if available
520
521       if Nkind (Rhs) = N_Explicit_Dereference
522         and then Ekind (T2) = E_Incomplete_Type
523         and then Is_Tagged_Type (T2)
524         and then Present (Non_Limited_View (T2))
525       then
526          T2 := Non_Limited_View (T2);
527       end if;
528
529       Set_Assignment_Type (Rhs, T2);
530
531       if Total_Errors_Detected /= 0 then
532          if No (T1) then
533             T1 := Any_Type;
534          end if;
535
536          if No (T2) then
537             T2 := Any_Type;
538          end if;
539       end if;
540
541       if T1 = Any_Type or else T2 = Any_Type then
542          Kill_Lhs;
543          return;
544       end if;
545
546       --  If the rhs is class-wide or dynamically tagged, then require the lhs
547       --  to be class-wide. The case where the rhs is a dynamically tagged call
548       --  to a dispatching operation with a controlling access result is
549       --  excluded from this check, since the target has an access type (and
550       --  no tag propagation occurs in that case).
551
552       if (Is_Class_Wide_Type (T2)
553            or else (Is_Dynamically_Tagged (Rhs)
554                      and then not Is_Access_Type (T1)))
555         and then not Is_Class_Wide_Type (T1)
556       then
557          Error_Msg_N ("dynamically tagged expression not allowed!", Rhs);
558
559       elsif Is_Class_Wide_Type (T1)
560         and then not Is_Class_Wide_Type (T2)
561         and then not Is_Tag_Indeterminate (Rhs)
562         and then not Is_Dynamically_Tagged (Rhs)
563       then
564          Error_Msg_N ("dynamically tagged expression required!", Rhs);
565       end if;
566
567       --  Propagate the tag from a class-wide target to the rhs when the rhs
568       --  is a tag-indeterminate call.
569
570       if Is_Tag_Indeterminate (Rhs) then
571          if Is_Class_Wide_Type (T1) then
572             Propagate_Tag (Lhs, Rhs);
573
574          elsif Nkind (Rhs) = N_Function_Call
575               and then Is_Entity_Name (Name (Rhs))
576               and then Is_Abstract_Subprogram (Entity (Name (Rhs)))
577          then
578             Error_Msg_N
579               ("call to abstract function must be dispatching", Name (Rhs));
580
581          elsif Nkind (Rhs) = N_Qualified_Expression
582            and then Nkind (Expression (Rhs)) = N_Function_Call
583               and then Is_Entity_Name (Name (Expression (Rhs)))
584               and then
585                 Is_Abstract_Subprogram (Entity (Name (Expression (Rhs))))
586          then
587             Error_Msg_N
588               ("call to abstract function must be dispatching",
589                 Name (Expression (Rhs)));
590          end if;
591       end if;
592
593       --  Ada 2005 (AI-385): When the lhs type is an anonymous access type,
594       --  apply an implicit conversion of the rhs to that type to force
595       --  appropriate static and run-time accessibility checks. This applies
596       --  as well to anonymous access-to-subprogram types that are component
597       --  subtypes or formal parameters.
598
599       if Ada_Version >= Ada_2005
600         and then Is_Access_Type (T1)
601       then
602          if Is_Local_Anonymous_Access (T1)
603            or else Ekind (T2) = E_Anonymous_Access_Subprogram_Type
604
605            --  Handle assignment to an Ada 2012 stand-alone object
606            --  of an anonymous access type.
607
608            or else (Ekind (T1) = E_Anonymous_Access_Type
609                      and then Nkind (Associated_Node_For_Itype (T1)) =
610                                                        N_Object_Declaration)
611
612          then
613             Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
614             Analyze_And_Resolve (Rhs, T1);
615          end if;
616       end if;
617
618       --  Ada 2005 (AI-231): Assignment to not null variable
619
620       if Ada_Version >= Ada_2005
621         and then Can_Never_Be_Null (T1)
622         and then not Assignment_OK (Lhs)
623       then
624          --  Case where we know the right hand side is null
625
626          if Known_Null (Rhs) then
627             Apply_Compile_Time_Constraint_Error
628               (N   => Rhs,
629                Msg => "(Ada 2005) null not allowed in null-excluding objects?",
630                Reason => CE_Null_Not_Allowed);
631
632             --  We still mark this as a possible modification, that's necessary
633             --  to reset Is_True_Constant, and desirable for xref purposes.
634
635             Note_Possible_Modification (Lhs, Sure => True);
636             return;
637
638          --  If we know the right hand side is non-null, then we convert to the
639          --  target type, since we don't need a run time check in that case.
640
641          elsif not Can_Never_Be_Null (T2) then
642             Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
643             Analyze_And_Resolve (Rhs, T1);
644          end if;
645       end if;
646
647       if Is_Scalar_Type (T1) then
648          Apply_Scalar_Range_Check (Rhs, Etype (Lhs));
649
650       --  For array types, verify that lengths match. If the right hand side
651       --  is a function call that has been inlined, the assignment has been
652       --  rewritten as a block, and the constraint check will be applied to the
653       --  assignment within the block.
654
655       elsif Is_Array_Type (T1)
656         and then
657           (Nkind (Rhs) /= N_Type_Conversion
658             or else Is_Constrained (Etype (Rhs)))
659         and then
660           (Nkind (Rhs) /= N_Function_Call
661             or else Nkind (N) /= N_Block_Statement)
662       then
663          --  Assignment verifies that the length of the Lsh and Rhs are equal,
664          --  but of course the indexes do not have to match. If the right-hand
665          --  side is a type conversion to an unconstrained type, a length check
666          --  is performed on the expression itself during expansion. In rare
667          --  cases, the redundant length check is computed on an index type
668          --  with a different representation, triggering incorrect code in the
669          --  back end.
670
671          Apply_Length_Check (Rhs, Etype (Lhs));
672
673       else
674          --  Discriminant checks are applied in the course of expansion
675
676          null;
677       end if;
678
679       --  Note: modifications of the Lhs may only be recorded after
680       --  checks have been applied.
681
682       Note_Possible_Modification (Lhs, Sure => True);
683       Check_Order_Dependence;
684
685       --  ??? a real accessibility check is needed when ???
686
687       --  Post warning for redundant assignment or variable to itself
688
689       if Warn_On_Redundant_Constructs
690
691          --  We only warn for source constructs
692
693          and then Comes_From_Source (N)
694
695          --  Where the object is the same on both sides
696
697          and then Same_Object (Lhs, Original_Node (Rhs))
698
699          --  But exclude the case where the right side was an operation that
700          --  got rewritten (e.g. JUNK + K, where K was known to be zero). We
701          --  don't want to warn in such a case, since it is reasonable to write
702          --  such expressions especially when K is defined symbolically in some
703          --  other package.
704
705         and then Nkind (Original_Node (Rhs)) not in N_Op
706       then
707          if Nkind (Lhs) in N_Has_Entity then
708             Error_Msg_NE -- CODEFIX
709               ("?useless assignment of & to itself!", N, Entity (Lhs));
710          else
711             Error_Msg_N -- CODEFIX
712               ("?useless assignment of object to itself!", N);
713          end if;
714       end if;
715
716       --  Check for non-allowed composite assignment
717
718       if not Support_Composite_Assign_On_Target
719         and then (Is_Array_Type (T1) or else Is_Record_Type (T1))
720         and then (not Has_Size_Clause (T1) or else Esize (T1) > 64)
721       then
722          Error_Msg_CRT ("composite assignment", N);
723       end if;
724
725       --  Check elaboration warning for left side if not in elab code
726
727       if not In_Subprogram_Or_Concurrent_Unit then
728          Check_Elab_Assign (Lhs);
729       end if;
730
731       --  Set Referenced_As_LHS if appropriate. We only set this flag if the
732       --  assignment is a source assignment in the extended main source unit.
733       --  We are not interested in any reference information outside this
734       --  context, or in compiler generated assignment statements.
735
736       if Comes_From_Source (N)
737         and then In_Extended_Main_Source_Unit (Lhs)
738       then
739          Set_Referenced_Modified (Lhs, Out_Param => False);
740       end if;
741
742       --  Final step. If left side is an entity, then we may be able to reset
743       --  the current tracked values to new safe values. We only have something
744       --  to do if the left side is an entity name, and expansion has not
745       --  modified the node into something other than an assignment, and of
746       --  course we only capture values if it is safe to do so.
747
748       if Is_Entity_Name (Lhs)
749         and then Nkind (N) = N_Assignment_Statement
750       then
751          declare
752             Ent : constant Entity_Id := Entity (Lhs);
753
754          begin
755             if Safe_To_Capture_Value (N, Ent) then
756
757                --  If simple variable on left side, warn if this assignment
758                --  blots out another one (rendering it useless). We only do
759                --  this for source assignments, otherwise we can generate bogus
760                --  warnings when an assignment is rewritten as another
761                --  assignment, and gets tied up with itself.
762
763                if Warn_On_Modified_Unread
764                  and then Is_Assignable (Ent)
765                  and then Comes_From_Source (N)
766                  and then In_Extended_Main_Source_Unit (Ent)
767                then
768                   Warn_On_Useless_Assignment (Ent, N);
769                end if;
770
771                --  If we are assigning an access type and the left side is an
772                --  entity, then make sure that the Is_Known_[Non_]Null flags
773                --  properly reflect the state of the entity after assignment.
774
775                if Is_Access_Type (T1) then
776                   if Known_Non_Null (Rhs) then
777                      Set_Is_Known_Non_Null (Ent, True);
778
779                   elsif Known_Null (Rhs)
780                     and then not Can_Never_Be_Null (Ent)
781                   then
782                      Set_Is_Known_Null (Ent, True);
783
784                   else
785                      Set_Is_Known_Null (Ent, False);
786
787                      if not Can_Never_Be_Null (Ent) then
788                         Set_Is_Known_Non_Null (Ent, False);
789                      end if;
790                   end if;
791
792                --  For discrete types, we may be able to set the current value
793                --  if the value is known at compile time.
794
795                elsif Is_Discrete_Type (T1)
796                  and then Compile_Time_Known_Value (Rhs)
797                then
798                   Set_Current_Value (Ent, Rhs);
799                else
800                   Set_Current_Value (Ent, Empty);
801                end if;
802
803             --  If not safe to capture values, kill them
804
805             else
806                Kill_Lhs;
807             end if;
808          end;
809       end if;
810
811       --  If assigning to an object in whole or in part, note location of
812       --  assignment in case no one references value. We only do this for
813       --  source assignments, otherwise we can generate bogus warnings when an
814       --  assignment is rewritten as another assignment, and gets tied up with
815       --  itself.
816
817       declare
818          Ent : constant Entity_Id := Get_Enclosing_Object (Lhs);
819
820       begin
821          if Present (Ent)
822            and then Safe_To_Capture_Value (N, Ent)
823            and then Nkind (N) = N_Assignment_Statement
824            and then Warn_On_Modified_Unread
825            and then Is_Assignable (Ent)
826            and then Comes_From_Source (N)
827            and then In_Extended_Main_Source_Unit (Ent)
828          then
829             Set_Last_Assignment (Ent, Lhs);
830          end if;
831       end;
832    end Analyze_Assignment;
833
834    -----------------------------
835    -- Analyze_Block_Statement --
836    -----------------------------
837
838    procedure Analyze_Block_Statement (N : Node_Id) is
839       Decls : constant List_Id := Declarations (N);
840       Id    : constant Node_Id := Identifier (N);
841       HSS   : constant Node_Id := Handled_Statement_Sequence (N);
842
843    begin
844       --  In SPARK mode, we reject block statements. Note that the case of
845       --  block statements generated by the expander is fine.
846
847       if Nkind (Original_Node (N)) = N_Block_Statement then
848          Check_SPARK_Restriction ("block statement is not allowed", N);
849       end if;
850
851       --  If no handled statement sequence is present, things are really messed
852       --  up, and we just return immediately (defence against previous errors).
853
854       if No (HSS) then
855          return;
856       end if;
857
858       --  Normal processing with HSS present
859
860       declare
861          EH  : constant List_Id := Exception_Handlers (HSS);
862          Ent : Entity_Id        := Empty;
863          S   : Entity_Id;
864
865          Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
866          --  Recursively save value of this global, will be restored on exit
867
868       begin
869          --  Initialize unblocked exit count for statements of begin block
870          --  plus one for each exception handler that is present.
871
872          Unblocked_Exit_Count := 1;
873
874          if Present (EH) then
875             Unblocked_Exit_Count := Unblocked_Exit_Count + List_Length (EH);
876          end if;
877
878          --  If a label is present analyze it and mark it as referenced
879
880          if Present (Id) then
881             Analyze (Id);
882             Ent := Entity (Id);
883
884             --  An error defense. If we have an identifier, but no entity, then
885             --  something is wrong. If previous errors, then just remove the
886             --  identifier and continue, otherwise raise an exception.
887
888             if No (Ent) then
889                if Total_Errors_Detected /= 0 then
890                   Set_Identifier (N, Empty);
891                else
892                   raise Program_Error;
893                end if;
894
895             else
896                Set_Ekind (Ent, E_Block);
897                Generate_Reference (Ent, N, ' ');
898                Generate_Definition (Ent);
899
900                if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
901                   Set_Label_Construct (Parent (Ent), N);
902                end if;
903             end if;
904          end if;
905
906          --  If no entity set, create a label entity
907
908          if No (Ent) then
909             Ent := New_Internal_Entity (E_Block, Current_Scope, Sloc (N), 'B');
910             Set_Identifier (N, New_Occurrence_Of (Ent, Sloc (N)));
911             Set_Parent (Ent, N);
912          end if;
913
914          Set_Etype (Ent, Standard_Void_Type);
915          Set_Block_Node (Ent, Identifier (N));
916          Push_Scope (Ent);
917
918          if Present (Decls) then
919             Analyze_Declarations (Decls);
920             Check_Completion;
921             Inspect_Deferred_Constant_Completion (Decls);
922          end if;
923
924          Analyze (HSS);
925          Process_End_Label (HSS, 'e', Ent);
926
927          --  If exception handlers are present, then we indicate that enclosing
928          --  scopes contain a block with handlers. We only need to mark non-
929          --  generic scopes.
930
931          if Present (EH) then
932             S := Scope (Ent);
933             loop
934                Set_Has_Nested_Block_With_Handler (S);
935                exit when Is_Overloadable (S)
936                  or else Ekind (S) = E_Package
937                  or else Is_Generic_Unit (S);
938                S := Scope (S);
939             end loop;
940          end if;
941
942          Check_References (Ent);
943          Warn_On_Useless_Assignments (Ent);
944          End_Scope;
945
946          if Unblocked_Exit_Count = 0 then
947             Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
948             Check_Unreachable_Code (N);
949          else
950             Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
951          end if;
952       end;
953    end Analyze_Block_Statement;
954
955    ----------------------------
956    -- Analyze_Case_Statement --
957    ----------------------------
958
959    procedure Analyze_Case_Statement (N : Node_Id) is
960       Exp            : Node_Id;
961       Exp_Type       : Entity_Id;
962       Exp_Btype      : Entity_Id;
963       Last_Choice    : Nat;
964       Dont_Care      : Boolean;
965       Others_Present : Boolean;
966
967       pragma Warnings (Off, Last_Choice);
968       pragma Warnings (Off, Dont_Care);
969       --  Don't care about assigned values
970
971       Statements_Analyzed : Boolean := False;
972       --  Set True if at least some statement sequences get analyzed. If False
973       --  on exit, means we had a serious error that prevented full analysis of
974       --  the case statement, and as a result it is not a good idea to output
975       --  warning messages about unreachable code.
976
977       Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
978       --  Recursively save value of this global, will be restored on exit
979
980       procedure Non_Static_Choice_Error (Choice : Node_Id);
981       --  Error routine invoked by the generic instantiation below when the
982       --  case statement has a non static choice.
983
984       procedure Process_Statements (Alternative : Node_Id);
985       --  Analyzes all the statements associated with a case alternative.
986       --  Needed by the generic instantiation below.
987
988       package Case_Choices_Processing is new
989         Generic_Choices_Processing
990           (Get_Alternatives          => Alternatives,
991            Get_Choices               => Discrete_Choices,
992            Process_Empty_Choice      => No_OP,
993            Process_Non_Static_Choice => Non_Static_Choice_Error,
994            Process_Associated_Node   => Process_Statements);
995       use Case_Choices_Processing;
996       --  Instantiation of the generic choice processing package
997
998       -----------------------------
999       -- Non_Static_Choice_Error --
1000       -----------------------------
1001
1002       procedure Non_Static_Choice_Error (Choice : Node_Id) is
1003       begin
1004          Flag_Non_Static_Expr
1005            ("choice given in case statement is not static!", Choice);
1006       end Non_Static_Choice_Error;
1007
1008       ------------------------
1009       -- Process_Statements --
1010       ------------------------
1011
1012       procedure Process_Statements (Alternative : Node_Id) is
1013          Choices : constant List_Id := Discrete_Choices (Alternative);
1014          Ent     : Entity_Id;
1015
1016       begin
1017          Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1018          Statements_Analyzed := True;
1019
1020          --  An interesting optimization. If the case statement expression
1021          --  is a simple entity, then we can set the current value within an
1022          --  alternative if the alternative has one possible value.
1023
1024          --    case N is
1025          --      when 1      => alpha
1026          --      when 2 | 3  => beta
1027          --      when others => gamma
1028
1029          --  Here we know that N is initially 1 within alpha, but for beta and
1030          --  gamma, we do not know anything more about the initial value.
1031
1032          if Is_Entity_Name (Exp) then
1033             Ent := Entity (Exp);
1034
1035             if Ekind_In (Ent, E_Variable,
1036                               E_In_Out_Parameter,
1037                               E_Out_Parameter)
1038             then
1039                if List_Length (Choices) = 1
1040                  and then Nkind (First (Choices)) in N_Subexpr
1041                  and then Compile_Time_Known_Value (First (Choices))
1042                then
1043                   Set_Current_Value (Entity (Exp), First (Choices));
1044                end if;
1045
1046                Analyze_Statements (Statements (Alternative));
1047
1048                --  After analyzing the case, set the current value to empty
1049                --  since we won't know what it is for the next alternative
1050                --  (unless reset by this same circuit), or after the case.
1051
1052                Set_Current_Value (Entity (Exp), Empty);
1053                return;
1054             end if;
1055          end if;
1056
1057          --  Case where expression is not an entity name of a variable
1058
1059          Analyze_Statements (Statements (Alternative));
1060       end Process_Statements;
1061
1062    --  Start of processing for Analyze_Case_Statement
1063
1064    begin
1065       Unblocked_Exit_Count := 0;
1066       Exp := Expression (N);
1067       Analyze (Exp);
1068
1069       --  The expression must be of any discrete type. In rare cases, the
1070       --  expander constructs a case statement whose expression has a private
1071       --  type whose full view is discrete. This can happen when generating
1072       --  a stream operation for a variant type after the type is frozen,
1073       --  when the partial of view of the type of the discriminant is private.
1074       --  In that case, use the full view to analyze case alternatives.
1075
1076       if not Is_Overloaded (Exp)
1077         and then not Comes_From_Source (N)
1078         and then Is_Private_Type (Etype (Exp))
1079         and then Present (Full_View (Etype (Exp)))
1080         and then Is_Discrete_Type (Full_View (Etype (Exp)))
1081       then
1082          Resolve (Exp, Etype (Exp));
1083          Exp_Type := Full_View (Etype (Exp));
1084
1085       else
1086          Analyze_And_Resolve (Exp, Any_Discrete);
1087          Exp_Type := Etype (Exp);
1088       end if;
1089
1090       Check_Unset_Reference (Exp);
1091       Exp_Btype := Base_Type (Exp_Type);
1092
1093       --  The expression must be of a discrete type which must be determinable
1094       --  independently of the context in which the expression occurs, but
1095       --  using the fact that the expression must be of a discrete type.
1096       --  Moreover, the type this expression must not be a character literal
1097       --  (which is always ambiguous) or, for Ada-83, a generic formal type.
1098
1099       --  If error already reported by Resolve, nothing more to do
1100
1101       if Exp_Btype = Any_Discrete
1102         or else Exp_Btype = Any_Type
1103       then
1104          return;
1105
1106       elsif Exp_Btype = Any_Character then
1107          Error_Msg_N
1108            ("character literal as case expression is ambiguous", Exp);
1109          return;
1110
1111       elsif Ada_Version = Ada_83
1112         and then (Is_Generic_Type (Exp_Btype)
1113                     or else Is_Generic_Type (Root_Type (Exp_Btype)))
1114       then
1115          Error_Msg_N
1116            ("(Ada 83) case expression cannot be of a generic type", Exp);
1117          return;
1118       end if;
1119
1120       --  If the case expression is a formal object of mode in out, then treat
1121       --  it as having a nonstatic subtype by forcing use of the base type
1122       --  (which has to get passed to Check_Case_Choices below). Also use base
1123       --  type when the case expression is parenthesized.
1124
1125       if Paren_Count (Exp) > 0
1126         or else (Is_Entity_Name (Exp)
1127                   and then Ekind (Entity (Exp)) = E_Generic_In_Out_Parameter)
1128       then
1129          Exp_Type := Exp_Btype;
1130       end if;
1131
1132       --  Call instantiated Analyze_Choices which does the rest of the work
1133
1134       Analyze_Choices (N, Exp_Type, Dont_Care, Others_Present);
1135
1136       --  A case statement with a single OTHERS alternative is not allowed
1137       --  in SPARK.
1138
1139       if Others_Present
1140         and then List_Length (Alternatives (N)) = 1
1141       then
1142          Check_SPARK_Restriction
1143            ("OTHERS as unique case alternative is not allowed", N);
1144       end if;
1145
1146       if Exp_Type = Universal_Integer and then not Others_Present then
1147          Error_Msg_N ("case on universal integer requires OTHERS choice", Exp);
1148       end if;
1149
1150       --  If all our exits were blocked by unconditional transfers of control,
1151       --  then the entire CASE statement acts as an unconditional transfer of
1152       --  control, so treat it like one, and check unreachable code. Skip this
1153       --  test if we had serious errors preventing any statement analysis.
1154
1155       if Unblocked_Exit_Count = 0 and then Statements_Analyzed then
1156          Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1157          Check_Unreachable_Code (N);
1158       else
1159          Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1160       end if;
1161
1162       if not Expander_Active
1163         and then Compile_Time_Known_Value (Expression (N))
1164         and then Serious_Errors_Detected = 0
1165       then
1166          declare
1167             Chosen : constant Node_Id := Find_Static_Alternative (N);
1168             Alt    : Node_Id;
1169
1170          begin
1171             Alt := First (Alternatives (N));
1172             while Present (Alt) loop
1173                if Alt /= Chosen then
1174                   Remove_Warning_Messages (Statements (Alt));
1175                end if;
1176
1177                Next (Alt);
1178             end loop;
1179          end;
1180       end if;
1181    end Analyze_Case_Statement;
1182
1183    ----------------------------
1184    -- Analyze_Exit_Statement --
1185    ----------------------------
1186
1187    --  If the exit includes a name, it must be the name of a currently open
1188    --  loop. Otherwise there must be an innermost open loop on the stack, to
1189    --  which the statement implicitly refers.
1190
1191    --  Additionally, in SPARK mode:
1192
1193    --    The exit can only name the closest enclosing loop;
1194
1195    --    An exit with a when clause must be directly contained in a loop;
1196
1197    --    An exit without a when clause must be directly contained in an
1198    --    if-statement with no elsif or else, which is itself directly contained
1199    --    in a loop. The exit must be the last statement in the if-statement.
1200
1201    procedure Analyze_Exit_Statement (N : Node_Id) is
1202       Target   : constant Node_Id := Name (N);
1203       Cond     : constant Node_Id := Condition (N);
1204       Scope_Id : Entity_Id;
1205       U_Name   : Entity_Id;
1206       Kind     : Entity_Kind;
1207
1208    begin
1209       if No (Cond) then
1210          Check_Unreachable_Code (N);
1211       end if;
1212
1213       if Present (Target) then
1214          Analyze (Target);
1215          U_Name := Entity (Target);
1216
1217          if not In_Open_Scopes (U_Name) or else Ekind (U_Name) /= E_Loop then
1218             Error_Msg_N ("invalid loop name in exit statement", N);
1219             return;
1220
1221          else
1222             if Has_Loop_In_Inner_Open_Scopes (U_Name) then
1223                Check_SPARK_Restriction
1224                  ("exit label must name the closest enclosing loop", N);
1225             end if;
1226
1227             Set_Has_Exit (U_Name);
1228          end if;
1229
1230       else
1231          U_Name := Empty;
1232       end if;
1233
1234       for J in reverse 0 .. Scope_Stack.Last loop
1235          Scope_Id := Scope_Stack.Table (J).Entity;
1236          Kind := Ekind (Scope_Id);
1237
1238          if Kind = E_Loop
1239            and then (No (Target) or else Scope_Id = U_Name)
1240          then
1241             Set_Has_Exit (Scope_Id);
1242             exit;
1243
1244          elsif Kind = E_Block
1245            or else Kind = E_Loop
1246            or else Kind = E_Return_Statement
1247          then
1248             null;
1249
1250          else
1251             Error_Msg_N
1252               ("cannot exit from program unit or accept statement", N);
1253             return;
1254          end if;
1255       end loop;
1256
1257       --  Verify that if present the condition is a Boolean expression
1258
1259       if Present (Cond) then
1260          Analyze_And_Resolve (Cond, Any_Boolean);
1261          Check_Unset_Reference (Cond);
1262       end if;
1263
1264       --  In SPARK mode, verify that the exit statement respects the SPARK
1265       --  restrictions.
1266
1267       if Present (Cond) then
1268          if Nkind (Parent (N)) /= N_Loop_Statement then
1269             Check_SPARK_Restriction
1270               ("exit with when clause must be directly in loop", N);
1271          end if;
1272
1273       else
1274          if Nkind (Parent (N)) /= N_If_Statement then
1275             if Nkind (Parent (N)) = N_Elsif_Part then
1276                Check_SPARK_Restriction
1277                  ("exit must be in IF without ELSIF", N);
1278             else
1279                Check_SPARK_Restriction ("exit must be directly in IF", N);
1280             end if;
1281
1282          elsif Nkind (Parent (Parent (N))) /= N_Loop_Statement then
1283             Check_SPARK_Restriction
1284               ("exit must be in IF directly in loop", N);
1285
1286          --  First test the presence of ELSE, so that an exit in an ELSE leads
1287          --  to an error mentioning the ELSE.
1288
1289          elsif Present (Else_Statements (Parent (N))) then
1290             Check_SPARK_Restriction ("exit must be in IF without ELSE", N);
1291
1292          --  An exit in an ELSIF does not reach here, as it would have been
1293          --  detected in the case (Nkind (Parent (N)) /= N_If_Statement).
1294
1295          elsif Present (Elsif_Parts (Parent (N))) then
1296             Check_SPARK_Restriction ("exit must be in IF without ELSIF", N);
1297          end if;
1298       end if;
1299
1300       --  Chain exit statement to associated loop entity
1301
1302       Set_Next_Exit_Statement  (N, First_Exit_Statement (Scope_Id));
1303       Set_First_Exit_Statement (Scope_Id, N);
1304
1305       --  Since the exit may take us out of a loop, any previous assignment
1306       --  statement is not useless, so clear last assignment indications. It
1307       --  is OK to keep other current values, since if the exit statement
1308       --  does not exit, then the current values are still valid.
1309
1310       Kill_Current_Values (Last_Assignment_Only => True);
1311    end Analyze_Exit_Statement;
1312
1313    ----------------------------
1314    -- Analyze_Goto_Statement --
1315    ----------------------------
1316
1317    procedure Analyze_Goto_Statement (N : Node_Id) is
1318       Label       : constant Node_Id := Name (N);
1319       Scope_Id    : Entity_Id;
1320       Label_Scope : Entity_Id;
1321       Label_Ent   : Entity_Id;
1322
1323    begin
1324       Check_SPARK_Restriction ("goto statement is not allowed", N);
1325
1326       --  Actual semantic checks
1327
1328       Check_Unreachable_Code (N);
1329       Kill_Current_Values (Last_Assignment_Only => True);
1330
1331       Analyze (Label);
1332       Label_Ent := Entity (Label);
1333
1334       --  Ignore previous error
1335
1336       if Label_Ent = Any_Id then
1337          return;
1338
1339       --  We just have a label as the target of a goto
1340
1341       elsif Ekind (Label_Ent) /= E_Label then
1342          Error_Msg_N ("target of goto statement must be a label", Label);
1343          return;
1344
1345       --  Check that the target of the goto is reachable according to Ada
1346       --  scoping rules. Note: the special gotos we generate for optimizing
1347       --  local handling of exceptions would violate these rules, but we mark
1348       --  such gotos as analyzed when built, so this code is never entered.
1349
1350       elsif not Reachable (Label_Ent) then
1351          Error_Msg_N ("target of goto statement is not reachable", Label);
1352          return;
1353       end if;
1354
1355       --  Here if goto passes initial validity checks
1356
1357       Label_Scope := Enclosing_Scope (Label_Ent);
1358
1359       for J in reverse 0 .. Scope_Stack.Last loop
1360          Scope_Id := Scope_Stack.Table (J).Entity;
1361
1362          if Label_Scope = Scope_Id
1363            or else (Ekind (Scope_Id) /= E_Block
1364                      and then Ekind (Scope_Id) /= E_Loop
1365                      and then Ekind (Scope_Id) /= E_Return_Statement)
1366          then
1367             if Scope_Id /= Label_Scope then
1368                Error_Msg_N
1369                  ("cannot exit from program unit or accept statement", N);
1370             end if;
1371
1372             return;
1373          end if;
1374       end loop;
1375
1376       raise Program_Error;
1377    end Analyze_Goto_Statement;
1378
1379    --------------------------
1380    -- Analyze_If_Statement --
1381    --------------------------
1382
1383    --  A special complication arises in the analysis of if statements
1384
1385    --  The expander has circuitry to completely delete code that it can tell
1386    --  will not be executed (as a result of compile time known conditions). In
1387    --  the analyzer, we ensure that code that will be deleted in this manner is
1388    --  analyzed but not expanded. This is obviously more efficient, but more
1389    --  significantly, difficulties arise if code is expanded and then
1390    --  eliminated (e.g. exception table entries disappear). Similarly, itypes
1391    --  generated in deleted code must be frozen from start, because the nodes
1392    --  on which they depend will not be available at the freeze point.
1393
1394    procedure Analyze_If_Statement (N : Node_Id) is
1395       E : Node_Id;
1396
1397       Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1398       --  Recursively save value of this global, will be restored on exit
1399
1400       Save_In_Deleted_Code : Boolean;
1401
1402       Del : Boolean := False;
1403       --  This flag gets set True if a True condition has been found, which
1404       --  means that remaining ELSE/ELSIF parts are deleted.
1405
1406       procedure Analyze_Cond_Then (Cnode : Node_Id);
1407       --  This is applied to either the N_If_Statement node itself or to an
1408       --  N_Elsif_Part node. It deals with analyzing the condition and the THEN
1409       --  statements associated with it.
1410
1411       -----------------------
1412       -- Analyze_Cond_Then --
1413       -----------------------
1414
1415       procedure Analyze_Cond_Then (Cnode : Node_Id) is
1416          Cond : constant Node_Id := Condition (Cnode);
1417          Tstm : constant List_Id := Then_Statements (Cnode);
1418
1419       begin
1420          Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1421          Analyze_And_Resolve (Cond, Any_Boolean);
1422          Check_Unset_Reference (Cond);
1423          Set_Current_Value_Condition (Cnode);
1424
1425          --  If already deleting, then just analyze then statements
1426
1427          if Del then
1428             Analyze_Statements (Tstm);
1429
1430          --  Compile time known value, not deleting yet
1431
1432          elsif Compile_Time_Known_Value (Cond) then
1433             Save_In_Deleted_Code := In_Deleted_Code;
1434
1435             --  If condition is True, then analyze the THEN statements and set
1436             --  no expansion for ELSE and ELSIF parts.
1437
1438             if Is_True (Expr_Value (Cond)) then
1439                Analyze_Statements (Tstm);
1440                Del := True;
1441                Expander_Mode_Save_And_Set (False);
1442                In_Deleted_Code := True;
1443
1444             --  If condition is False, analyze THEN with expansion off
1445
1446             else -- Is_False (Expr_Value (Cond))
1447                Expander_Mode_Save_And_Set (False);
1448                In_Deleted_Code := True;
1449                Analyze_Statements (Tstm);
1450                Expander_Mode_Restore;
1451                In_Deleted_Code := Save_In_Deleted_Code;
1452             end if;
1453
1454          --  Not known at compile time, not deleting, normal analysis
1455
1456          else
1457             Analyze_Statements (Tstm);
1458          end if;
1459       end Analyze_Cond_Then;
1460
1461    --  Start of Analyze_If_Statement
1462
1463    begin
1464       --  Initialize exit count for else statements. If there is no else part,
1465       --  this count will stay non-zero reflecting the fact that the uncovered
1466       --  else case is an unblocked exit.
1467
1468       Unblocked_Exit_Count := 1;
1469       Analyze_Cond_Then (N);
1470
1471       --  Now to analyze the elsif parts if any are present
1472
1473       if Present (Elsif_Parts (N)) then
1474          E := First (Elsif_Parts (N));
1475          while Present (E) loop
1476             Analyze_Cond_Then (E);
1477             Next (E);
1478          end loop;
1479       end if;
1480
1481       if Present (Else_Statements (N)) then
1482          Analyze_Statements (Else_Statements (N));
1483       end if;
1484
1485       --  If all our exits were blocked by unconditional transfers of control,
1486       --  then the entire IF statement acts as an unconditional transfer of
1487       --  control, so treat it like one, and check unreachable code.
1488
1489       if Unblocked_Exit_Count = 0 then
1490          Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1491          Check_Unreachable_Code (N);
1492       else
1493          Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1494       end if;
1495
1496       if Del then
1497          Expander_Mode_Restore;
1498          In_Deleted_Code := Save_In_Deleted_Code;
1499       end if;
1500
1501       if not Expander_Active
1502         and then Compile_Time_Known_Value (Condition (N))
1503         and then Serious_Errors_Detected = 0
1504       then
1505          if Is_True (Expr_Value (Condition (N))) then
1506             Remove_Warning_Messages (Else_Statements (N));
1507
1508             if Present (Elsif_Parts (N)) then
1509                E := First (Elsif_Parts (N));
1510                while Present (E) loop
1511                   Remove_Warning_Messages (Then_Statements (E));
1512                   Next (E);
1513                end loop;
1514             end if;
1515
1516          else
1517             Remove_Warning_Messages (Then_Statements (N));
1518          end if;
1519       end if;
1520    end Analyze_If_Statement;
1521
1522    ----------------------------------------
1523    -- Analyze_Implicit_Label_Declaration --
1524    ----------------------------------------
1525
1526    --  An implicit label declaration is generated in the innermost enclosing
1527    --  declarative part. This is done for labels, and block and loop names.
1528
1529    --  Note: any changes in this routine may need to be reflected in
1530    --  Analyze_Label_Entity.
1531
1532    procedure Analyze_Implicit_Label_Declaration (N : Node_Id) is
1533       Id : constant Node_Id := Defining_Identifier (N);
1534    begin
1535       Enter_Name          (Id);
1536       Set_Ekind           (Id, E_Label);
1537       Set_Etype           (Id, Standard_Void_Type);
1538       Set_Enclosing_Scope (Id, Current_Scope);
1539    end Analyze_Implicit_Label_Declaration;
1540
1541    ------------------------------
1542    -- Analyze_Iteration_Scheme --
1543    ------------------------------
1544
1545    procedure Analyze_Iteration_Scheme (N : Node_Id) is
1546
1547       procedure Process_Bounds (R : Node_Id);
1548       --  If the iteration is given by a range, create temporaries and
1549       --  assignment statements block to capture the bounds and perform
1550       --  required finalization actions in case a bound includes a function
1551       --  call that uses the temporary stack. We first pre-analyze a copy of
1552       --  the range in order to determine the expected type, and analyze and
1553       --  resolve the original bounds.
1554
1555       procedure Check_Controlled_Array_Attribute (DS : Node_Id);
1556       --  If the bounds are given by a 'Range reference on a function call
1557       --  that returns a controlled array, introduce an explicit declaration
1558       --  to capture the bounds, so that the function result can be finalized
1559       --  in timely fashion.
1560
1561       function Has_Call_Using_Secondary_Stack (N : Node_Id) return Boolean;
1562       --  N is the node for an arbitrary construct. This function searches the
1563       --  construct N to see if any expressions within it contain function
1564       --  calls that use the secondary stack, returning True if any such call
1565       --  is found, and False otherwise.
1566
1567       procedure Pre_Analyze_Range (R_Copy : Node_Id);
1568       --  Determine expected type of range or domain of iteration of Ada 2012
1569       --  loop by analyzing separate copy. Do the analysis and resolution of
1570       --  the copy of the bound(s) with expansion disabled, to prevent the
1571       --  generation of finalization actions. This prevents memory leaks when
1572       --  the bounds contain calls to functions returning controlled arrays or
1573       --  when the domain of iteration is a container.
1574
1575       -----------------------
1576       -- Pre_Analyze_Range --
1577       -----------------------
1578
1579       procedure Pre_Analyze_Range (R_Copy : Node_Id) is
1580          Save_Analysis : Boolean;
1581       begin
1582          Save_Analysis := Full_Analysis;
1583          Full_Analysis := False;
1584          Expander_Mode_Save_And_Set (False);
1585
1586          Analyze (R_Copy);
1587
1588          if Nkind (R_Copy) in N_Subexpr
1589            and then Is_Overloaded (R_Copy)
1590          then
1591
1592             --  Apply preference rules for range of predefined integer types,
1593             --  or diagnose true ambiguity.
1594
1595             declare
1596                I     : Interp_Index;
1597                It    : Interp;
1598                Found : Entity_Id := Empty;
1599
1600             begin
1601                Get_First_Interp (R_Copy, I, It);
1602                while Present (It.Typ) loop
1603                   if Is_Discrete_Type (It.Typ) then
1604                      if No (Found) then
1605                         Found := It.Typ;
1606                      else
1607                         if Scope (Found) = Standard_Standard then
1608                            null;
1609
1610                         elsif Scope (It.Typ) = Standard_Standard then
1611                            Found := It.Typ;
1612
1613                         else
1614                            --  Both of them are user-defined
1615
1616                            Error_Msg_N
1617                              ("ambiguous bounds in range of iteration",
1618                                R_Copy);
1619                            Error_Msg_N ("\possible interpretations:", R_Copy);
1620                            Error_Msg_NE ("\\} ", R_Copy, Found);
1621                            Error_Msg_NE ("\\} ", R_Copy, It.Typ);
1622                            exit;
1623                         end if;
1624                      end if;
1625                   end if;
1626
1627                   Get_Next_Interp (I, It);
1628                end loop;
1629             end;
1630          end if;
1631
1632          if  Is_Entity_Name (R_Copy)
1633            and then Is_Type (Entity (R_Copy))
1634          then
1635
1636             --  Subtype mark in iteration scheme
1637
1638             null;
1639
1640          elsif Nkind (R_Copy) in N_Subexpr then
1641
1642             --  Expression in range, or Ada 2012 iterator
1643
1644             Resolve (R_Copy);
1645          end if;
1646
1647          Expander_Mode_Restore;
1648          Full_Analysis := Save_Analysis;
1649       end Pre_Analyze_Range;
1650
1651       --------------------
1652       -- Process_Bounds --
1653       --------------------
1654
1655       procedure Process_Bounds (R : Node_Id) is
1656          Loc          : constant Source_Ptr := Sloc (N);
1657          R_Copy       : constant Node_Id := New_Copy_Tree (R);
1658          Lo           : constant Node_Id := Low_Bound  (R);
1659          Hi           : constant Node_Id := High_Bound (R);
1660          New_Lo_Bound : Node_Id;
1661          New_Hi_Bound : Node_Id;
1662          Typ          : Entity_Id;
1663
1664          function One_Bound
1665            (Original_Bound : Node_Id;
1666             Analyzed_Bound : Node_Id) return Node_Id;
1667          --  Capture value of bound and return captured value
1668
1669          ---------------
1670          -- One_Bound --
1671          ---------------
1672
1673          function One_Bound
1674            (Original_Bound : Node_Id;
1675             Analyzed_Bound : Node_Id) return Node_Id
1676          is
1677             Assign : Node_Id;
1678             Id     : Entity_Id;
1679             Decl   : Node_Id;
1680
1681          begin
1682             --  If the bound is a constant or an object, no need for a separate
1683             --  declaration. If the bound is the result of previous expansion
1684             --  it is already analyzed and should not be modified. Note that
1685             --  the Bound will be resolved later, if needed, as part of the
1686             --  call to Make_Index (literal bounds may need to be resolved to
1687             --  type Integer).
1688
1689             if Analyzed (Original_Bound) then
1690                return Original_Bound;
1691
1692             elsif Nkind_In (Analyzed_Bound, N_Integer_Literal,
1693                                             N_Character_Literal)
1694               or else Is_Entity_Name (Analyzed_Bound)
1695             then
1696                Analyze_And_Resolve (Original_Bound, Typ);
1697                return Original_Bound;
1698             end if;
1699
1700             --  Here we need to capture the value
1701
1702             Analyze_And_Resolve (Original_Bound, Typ);
1703
1704             --  Normally, the best approach is simply to generate a constant
1705             --  declaration that captures the bound. However, there is a nasty
1706             --  case where this is wrong. If the bound is complex, and has a
1707             --  possible use of the secondary stack, we need to generate a
1708             --  separate assignment statement to ensure the creation of a block
1709             --  which will release the secondary stack.
1710
1711             --  We prefer the constant declaration, since it leaves us with a
1712             --  proper trace of the value, useful in optimizations that get rid
1713             --  of junk range checks.
1714
1715             if not Has_Call_Using_Secondary_Stack (Original_Bound) then
1716                Force_Evaluation (Original_Bound);
1717                return Original_Bound;
1718             end if;
1719
1720             Id := Make_Temporary (Loc, 'R', Original_Bound);
1721
1722             --  Here we make a declaration with a separate assignment
1723             --  statement, and insert before loop header.
1724
1725             Decl :=
1726               Make_Object_Declaration (Loc,
1727                 Defining_Identifier => Id,
1728                 Object_Definition   => New_Occurrence_Of (Typ, Loc));
1729
1730             Assign :=
1731               Make_Assignment_Statement (Loc,
1732                 Name        => New_Occurrence_Of (Id, Loc),
1733                 Expression  => Relocate_Node (Original_Bound));
1734
1735             --  We must recursively clean in the relocated expression the flag
1736             --  analyzed to ensure that the expression is reanalyzed. Required
1737             --  to ensure that the transient scope is established now (because
1738             --  Establish_Transient_Scope discarded generating transient scopes
1739             --  in the analysis of the iteration scheme).
1740
1741             Reset_Analyzed_Flags (Expression (Assign));
1742
1743             Insert_Actions (Parent (N), New_List (Decl, Assign));
1744
1745             --  Now that this temporary variable is initialized we decorate it
1746             --  as safe-to-reevaluate to inform to the backend that no further
1747             --  asignment will be issued and hence it can be handled as side
1748             --  effect free. Note that this decoration must be done when the
1749             --  assignment has been analyzed because otherwise it will be
1750             --  rejected (see Analyze_Assignment).
1751
1752             Set_Is_Safe_To_Reevaluate (Id);
1753
1754             Rewrite (Original_Bound, New_Occurrence_Of (Id, Loc));
1755
1756             if Nkind (Assign) = N_Assignment_Statement then
1757                return Expression (Assign);
1758             else
1759                return Original_Bound;
1760             end if;
1761          end One_Bound;
1762
1763       --  Start of processing for Process_Bounds
1764
1765       begin
1766          Set_Parent (R_Copy, Parent (R));
1767          Pre_Analyze_Range (R_Copy);
1768          Typ := Etype (R_Copy);
1769
1770          --  If the type of the discrete range is Universal_Integer, then the
1771          --  bound's type must be resolved to Integer, and any object used to
1772          --  hold the bound must also have type Integer, unless the literal
1773          --  bounds are constant-folded expressions with a user-defined type.
1774
1775          if Typ = Universal_Integer then
1776             if Nkind (Lo) = N_Integer_Literal
1777               and then Present (Etype (Lo))
1778               and then Scope (Etype (Lo)) /= Standard_Standard
1779             then
1780                Typ := Etype (Lo);
1781
1782             elsif Nkind (Hi) = N_Integer_Literal
1783               and then Present (Etype (Hi))
1784               and then Scope (Etype (Hi)) /= Standard_Standard
1785             then
1786                Typ := Etype (Hi);
1787
1788             else
1789                Typ := Standard_Integer;
1790             end if;
1791          end if;
1792
1793          Set_Etype (R, Typ);
1794
1795          New_Lo_Bound := One_Bound (Lo, Low_Bound  (R_Copy));
1796          New_Hi_Bound := One_Bound (Hi, High_Bound (R_Copy));
1797
1798          --  Propagate staticness to loop range itself, in case the
1799          --  corresponding subtype is static.
1800
1801          if New_Lo_Bound /= Lo
1802            and then Is_Static_Expression (New_Lo_Bound)
1803          then
1804             Rewrite  (Low_Bound (R), New_Copy (New_Lo_Bound));
1805          end if;
1806
1807          if New_Hi_Bound /= Hi
1808            and then Is_Static_Expression (New_Hi_Bound)
1809          then
1810             Rewrite (High_Bound (R), New_Copy (New_Hi_Bound));
1811          end if;
1812       end Process_Bounds;
1813
1814       --------------------------------------
1815       -- Check_Controlled_Array_Attribute --
1816       --------------------------------------
1817
1818       procedure Check_Controlled_Array_Attribute (DS : Node_Id) is
1819       begin
1820          if Nkind (DS) = N_Attribute_Reference
1821             and then Is_Entity_Name (Prefix (DS))
1822             and then Ekind (Entity (Prefix (DS))) = E_Function
1823             and then Is_Array_Type (Etype (Entity (Prefix (DS))))
1824             and then
1825               Is_Controlled (
1826                 Component_Type (Etype (Entity (Prefix (DS)))))
1827             and then Expander_Active
1828          then
1829             declare
1830                Loc  : constant Source_Ptr := Sloc (N);
1831                Arr  : constant Entity_Id := Etype (Entity (Prefix (DS)));
1832                Indx : constant Entity_Id :=
1833                         Base_Type (Etype (First_Index (Arr)));
1834                Subt : constant Entity_Id := Make_Temporary (Loc, 'S');
1835                Decl : Node_Id;
1836
1837             begin
1838                Decl :=
1839                  Make_Subtype_Declaration (Loc,
1840                    Defining_Identifier => Subt,
1841                    Subtype_Indication  =>
1842                       Make_Subtype_Indication (Loc,
1843                         Subtype_Mark  => New_Reference_To (Indx, Loc),
1844                         Constraint =>
1845                           Make_Range_Constraint (Loc,
1846                             Relocate_Node (DS))));
1847                Insert_Before (Parent (N), Decl);
1848                Analyze (Decl);
1849
1850                Rewrite (DS,
1851                   Make_Attribute_Reference (Loc,
1852                     Prefix => New_Reference_To (Subt, Loc),
1853                     Attribute_Name => Attribute_Name (DS)));
1854                Analyze (DS);
1855             end;
1856          end if;
1857       end Check_Controlled_Array_Attribute;
1858
1859       ------------------------------------
1860       -- Has_Call_Using_Secondary_Stack --
1861       ------------------------------------
1862
1863       function Has_Call_Using_Secondary_Stack (N : Node_Id) return Boolean is
1864
1865          function Check_Call (N : Node_Id) return Traverse_Result;
1866          --  Check if N is a function call which uses the secondary stack
1867
1868          ----------------
1869          -- Check_Call --
1870          ----------------
1871
1872          function Check_Call (N : Node_Id) return Traverse_Result is
1873             Nam        : Node_Id;
1874             Subp       : Entity_Id;
1875             Return_Typ : Entity_Id;
1876
1877          begin
1878             if Nkind (N) = N_Function_Call then
1879                Nam := Name (N);
1880
1881                --  Call using access to subprogram with explicit dereference
1882
1883                if Nkind (Nam) = N_Explicit_Dereference then
1884                   Subp := Etype (Nam);
1885
1886                --  Normal case
1887
1888                else
1889                   Subp := Entity (Nam);
1890                end if;
1891
1892                Return_Typ := Etype (Subp);
1893
1894                if Is_Composite_Type (Return_Typ)
1895                  and then not Is_Constrained (Return_Typ)
1896                then
1897                   return Abandon;
1898
1899                elsif Sec_Stack_Needed_For_Return (Subp) then
1900                   return Abandon;
1901                end if;
1902             end if;
1903
1904             --  Continue traversing the tree
1905
1906             return OK;
1907          end Check_Call;
1908
1909          function Check_Calls is new Traverse_Func (Check_Call);
1910
1911       --  Start of processing for Has_Call_Using_Secondary_Stack
1912
1913       begin
1914          return Check_Calls (N) = Abandon;
1915       end Has_Call_Using_Secondary_Stack;
1916
1917    --  Start of processing for Analyze_Iteration_Scheme
1918
1919    begin
1920       --  If this is a rewritten quantified expression, the iteration scheme
1921       --  has been analyzed already. Do no repeat analysis because the loop
1922       --  variable is already declared.
1923
1924       if Analyzed (N) then
1925          return;
1926       end if;
1927
1928       --  For an infinite loop, there is no iteration scheme
1929
1930       if No (N) then
1931          return;
1932       end if;
1933
1934       --  Iteration scheme is present
1935
1936       declare
1937          Cond : constant Node_Id := Condition (N);
1938
1939       begin
1940          --  For WHILE loop, verify that the condition is a Boolean expression
1941          --  and resolve and check it.
1942
1943          if Present (Cond) then
1944             Analyze_And_Resolve (Cond, Any_Boolean);
1945             Check_Unset_Reference (Cond);
1946             Set_Current_Value_Condition (N);
1947             return;
1948
1949          --  For an iterator specification with "of", pre-analyze range to
1950          --  capture function calls that may require finalization actions.
1951
1952          elsif Present (Iterator_Specification (N)) then
1953             Pre_Analyze_Range (Name (Iterator_Specification (N)));
1954             Analyze_Iterator_Specification (Iterator_Specification (N));
1955
1956          --  Else we have a FOR loop
1957
1958          else
1959             declare
1960                LP : constant Node_Id   := Loop_Parameter_Specification (N);
1961                Id : constant Entity_Id := Defining_Identifier (LP);
1962                DS : constant Node_Id   := Discrete_Subtype_Definition (LP);
1963
1964                D_Copy : Node_Id;
1965
1966             begin
1967                Enter_Name (Id);
1968
1969                --  We always consider the loop variable to be referenced, since
1970                --  the loop may be used just for counting purposes.
1971
1972                Generate_Reference (Id, N, ' ');
1973
1974                --  Check for the case of loop variable hiding a local variable
1975                --  (used later on to give a nice warning if the hidden variable
1976                --  is never assigned).
1977
1978                declare
1979                   H : constant Entity_Id := Homonym (Id);
1980                begin
1981                   if Present (H)
1982                     and then Enclosing_Dynamic_Scope (H) =
1983                     Enclosing_Dynamic_Scope (Id)
1984                     and then Ekind (H) = E_Variable
1985                     and then Is_Discrete_Type (Etype (H))
1986                   then
1987                      Set_Hiding_Loop_Variable (H, Id);
1988                   end if;
1989                end;
1990
1991                --  Loop parameter specification must include subtype mark in
1992                --  SPARK.
1993
1994                if Nkind (DS) = N_Range then
1995                   Check_SPARK_Restriction
1996                     ("loop parameter specification must include subtype mark",
1997                      N);
1998                end if;
1999
2000                --  Now analyze the subtype definition. If it is a range, create
2001                --  temporaries for bounds.
2002
2003                if Nkind (DS) = N_Range
2004                  and then Expander_Active
2005                then
2006                   Process_Bounds (DS);
2007
2008                --  expander not active or else range of iteration is a subtype
2009                --  indication, an entity, or a function call that yields an
2010                --  aggregate or a container.
2011
2012                else
2013                   D_Copy := New_Copy_Tree (DS);
2014                   Set_Parent (D_Copy, Parent (DS));
2015                   Pre_Analyze_Range (D_Copy);
2016
2017                   --  Ada2012: If the domain of iteration is a function call,
2018                   --  it is the new iterator form.
2019
2020                   --  We have also implemented the shorter form : for X in S
2021                   --  for Alfa use. In this case, 'Old and 'Result must be
2022                   --  treated as entity names over which iterators are legal.
2023
2024                   if Nkind (D_Copy) = N_Function_Call
2025                     or else
2026                       (Alfa_Mode
2027                         and then (Nkind (D_Copy) = N_Attribute_Reference
2028                         and then
2029                           (Attribute_Name (D_Copy) = Name_Result
2030                             or else Attribute_Name (D_Copy) = Name_Old)))
2031                     or else
2032                       (Is_Entity_Name (D_Copy)
2033                         and then not Is_Type (Entity (D_Copy)))
2034                   then
2035                      --  This is an iterator specification. Rewrite as such
2036                      --  and analyze, to capture function calls that may
2037                      --  require finalization actions.
2038
2039                      declare
2040                         I_Spec : constant Node_Id :=
2041                                    Make_Iterator_Specification (Sloc (LP),
2042                                      Defining_Identifier =>
2043                                        Relocate_Node (Id),
2044                                      Name                => D_Copy,
2045                                      Subtype_Indication  => Empty,
2046                                      Reverse_Present     =>
2047                                        Reverse_Present (LP));
2048                      begin
2049                         Set_Iterator_Specification (N, I_Spec);
2050                         Set_Loop_Parameter_Specification (N, Empty);
2051                         Analyze_Iterator_Specification (I_Spec);
2052
2053                         --  In a generic context, analyze the original domain
2054                         --  of iteration, for name capture.
2055
2056                         if not Expander_Active then
2057                            Analyze (DS);
2058                         end if;
2059
2060                         return;
2061                      end;
2062
2063                   --  Domain of iteration is not a function call, and is
2064                   --  side-effect free.
2065
2066                   else
2067                      Analyze (DS);
2068                   end if;
2069                end if;
2070
2071                if DS = Error then
2072                   return;
2073                end if;
2074
2075                --  Some additional checks if we are iterating through a type
2076
2077                if Is_Entity_Name (DS)
2078                  and then Present (Entity (DS))
2079                  and then Is_Type (Entity (DS))
2080                then
2081                   --  The subtype indication may denote the completion of an
2082                   --  incomplete type declaration.
2083
2084                   if Ekind (Entity (DS)) = E_Incomplete_Type then
2085                      Set_Entity (DS, Get_Full_View (Entity (DS)));
2086                      Set_Etype  (DS, Entity (DS));
2087                   end if;
2088
2089                   --  Attempt to iterate through non-static predicate
2090
2091                   if Is_Discrete_Type (Entity (DS))
2092                     and then Present (Predicate_Function (Entity (DS)))
2093                     and then No (Static_Predicate (Entity (DS)))
2094                   then
2095                      Bad_Predicated_Subtype_Use
2096                        ("cannot use subtype& with non-static "
2097                         & "predicate for loop iteration", DS, Entity (DS));
2098                   end if;
2099                end if;
2100
2101                --  Error if not discrete type
2102
2103                if not Is_Discrete_Type (Etype (DS)) then
2104                   Wrong_Type (DS, Any_Discrete);
2105                   Set_Etype (DS, Any_Type);
2106                end if;
2107
2108                Check_Controlled_Array_Attribute (DS);
2109
2110                Make_Index (DS, LP, In_Iter_Schm => True);
2111
2112                Set_Ekind (Id, E_Loop_Parameter);
2113
2114                --  If the loop is part of a predicate or precondition, it may
2115                --  be analyzed twice, once in the source and once on the copy
2116                --  used to check conformance. Preserve the original itype
2117                --  because the second one may be created in a different scope,
2118                --  e.g. a precondition procedure, leading to a crash in GIGI.
2119
2120                if No (Etype (Id)) or else Etype (Id) = Any_Type then
2121                   Set_Etype (Id, Etype (DS));
2122                end if;
2123
2124                --  Treat a range as an implicit reference to the type, to
2125                --  inhibit spurious warnings.
2126
2127                Generate_Reference (Base_Type (Etype (DS)), N, ' ');
2128                Set_Is_Known_Valid (Id, True);
2129
2130                --  The loop is not a declarative part, so the only entity
2131                --  declared "within" must be frozen explicitly.
2132
2133                declare
2134                   Flist : constant List_Id := Freeze_Entity (Id, N);
2135                begin
2136                   if Is_Non_Empty_List (Flist) then
2137                      Insert_Actions (N, Flist);
2138                   end if;
2139                end;
2140
2141                --  Check for null or possibly null range and issue warning. We
2142                --  suppress such messages in generic templates and instances,
2143                --  because in practice they tend to be dubious in these cases.
2144
2145                if Nkind (DS) = N_Range and then Comes_From_Source (N) then
2146                   declare
2147                      L : constant Node_Id := Low_Bound  (DS);
2148                      H : constant Node_Id := High_Bound (DS);
2149
2150                   begin
2151                      --  If range of loop is null, issue warning
2152
2153                      if Compile_Time_Compare
2154                           (L, H, Assume_Valid => True) = GT
2155                      then
2156                         --  Suppress the warning if inside a generic template
2157                         --  or instance, since in practice they tend to be
2158                         --  dubious in these cases since they can result from
2159                         --  intended parametrization.
2160
2161                         if not Inside_A_Generic
2162                           and then not In_Instance
2163                         then
2164                            --  Specialize msg if invalid values could make the
2165                            --  loop non-null after all.
2166
2167                            if Compile_Time_Compare
2168                                 (L, H, Assume_Valid => False) = GT
2169                            then
2170                               Error_Msg_N
2171                                 ("?loop range is null, loop will not execute",
2172                                  DS);
2173
2174                               --  Since we know the range of the loop is null,
2175                               --  set the appropriate flag to remove the loop
2176                               --  entirely during expansion.
2177
2178                               Set_Is_Null_Loop (Parent (N));
2179
2180                               --  Here is where the loop could execute because
2181                               --  of invalid values, so issue appropriate
2182                               --  message and in this case we do not set the
2183                               --  Is_Null_Loop flag since the loop may execute.
2184
2185                            else
2186                               Error_Msg_N
2187                                 ("?loop range may be null, "
2188                                  & "loop may not execute",
2189                                  DS);
2190                               Error_Msg_N
2191                                 ("?can only execute if invalid values "
2192                                  & "are present",
2193                                  DS);
2194                            end if;
2195                         end if;
2196
2197                         --  In either case, suppress warnings in the body of
2198                         --  the loop, since it is likely that these warnings
2199                         --  will be inappropriate if the loop never actually
2200                         --  executes, which is likely.
2201
2202                         Set_Suppress_Loop_Warnings (Parent (N));
2203
2204                         --  The other case for a warning is a reverse loop
2205                         --  where the upper bound is the integer literal zero
2206                         --  or one, and the lower bound can be positive.
2207
2208                         --  For example, we have
2209
2210                         --     for J in reverse N .. 1 loop
2211
2212                         --  In practice, this is very likely to be a case of
2213                         --  reversing the bounds incorrectly in the range.
2214
2215                      elsif Reverse_Present (LP)
2216                        and then Nkind (Original_Node (H)) =
2217                                                       N_Integer_Literal
2218                        and then (Intval (Original_Node (H)) = Uint_0
2219                                   or else
2220                                     Intval (Original_Node (H)) = Uint_1)
2221                      then
2222                         Error_Msg_N ("?loop range may be null", DS);
2223                         Error_Msg_N ("\?bounds may be wrong way round", DS);
2224                      end if;
2225                   end;
2226                end if;
2227             end;
2228          end if;
2229       end;
2230    end Analyze_Iteration_Scheme;
2231
2232    -------------------------------------
2233    --  Analyze_Iterator_Specification --
2234    -------------------------------------
2235
2236    procedure Analyze_Iterator_Specification (N : Node_Id) is
2237       Loc       : constant Source_Ptr := Sloc (N);
2238       Def_Id    : constant Node_Id    := Defining_Identifier (N);
2239       Subt      : constant Node_Id    := Subtype_Indication (N);
2240       Iter_Name : constant Node_Id    := Name (N);
2241
2242       Ent : Entity_Id;
2243       Typ : Entity_Id;
2244
2245    begin
2246       Enter_Name (Def_Id);
2247       Set_Ekind (Def_Id, E_Variable);
2248
2249       if Present (Subt) then
2250          Analyze (Subt);
2251       end if;
2252
2253       --  If domain of iteration is an expression, create a declaration for it,
2254       --  so that finalization actions are introduced outside of the loop.
2255
2256       if not Is_Entity_Name (Iter_Name) then
2257          declare
2258             Id   : constant Entity_Id := Make_Temporary (Loc, 'R', Iter_Name);
2259             Decl : Node_Id;
2260
2261          begin
2262             Typ := Etype (Iter_Name);
2263
2264             Decl :=
2265               Make_Object_Declaration (Loc,
2266                 Defining_Identifier => Id,
2267                 Object_Definition   => New_Occurrence_Of (Typ, Loc),
2268                 Expression          => Relocate_Node (Iter_Name));
2269
2270             Insert_Actions (Parent (Parent (N)), New_List (Decl));
2271             Rewrite (Name (N), New_Occurrence_Of (Id, Loc));
2272             Set_Etype (Id, Typ);
2273             Set_Etype (Name (N), Typ);
2274          end;
2275
2276       --  Container is an entity or an array with uncontrolled components, or
2277       --  else it is a container iterator given by a function call, typically
2278       --  called Iterate in the case of predefined containers, even though
2279       --  Iterate is not a reserved name. What matter is that the return type
2280       --  of the function is an iterator type.
2281
2282       else
2283          Analyze (Iter_Name);
2284
2285          if Nkind (Iter_Name) = N_Function_Call then
2286             declare
2287                C  : constant Node_Id := Name (Iter_Name);
2288                I  : Interp_Index;
2289                It : Interp;
2290
2291             begin
2292                if not Is_Overloaded (Iter_Name) then
2293                   Resolve (Iter_Name, Etype (C));
2294
2295                else
2296                   Get_First_Interp (C, I, It);
2297                   while It.Typ /= Empty loop
2298                      if Reverse_Present (N) then
2299                         if Is_Reversible_Iterator (It.Typ) then
2300                            Resolve (Iter_Name, It.Typ);
2301                            exit;
2302                         end if;
2303
2304                      elsif Is_Iterator (It.Typ) then
2305                         Resolve (Iter_Name, It.Typ);
2306                         exit;
2307                      end if;
2308
2309                      Get_Next_Interp (I, It);
2310                   end loop;
2311                end if;
2312             end;
2313
2314          --  Domain of iteration is not overloaded
2315
2316          else
2317             Resolve (Iter_Name, Etype (Iter_Name));
2318          end if;
2319       end if;
2320
2321       Typ := Etype (Iter_Name);
2322
2323       if Is_Array_Type (Typ) then
2324          if Of_Present (N) then
2325             Set_Etype (Def_Id, Component_Type (Typ));
2326          else
2327             Error_Msg_N
2328               ("to iterate over the elements of an array, use OF", N);
2329             Set_Etype (Def_Id, Etype (First_Index (Typ)));
2330          end if;
2331
2332          --  Check for type error in iterator
2333
2334       elsif Typ = Any_Type then
2335          return;
2336
2337       --  Iteration over a container
2338
2339       else
2340          Set_Ekind (Def_Id, E_Loop_Parameter);
2341
2342          if Of_Present (N) then
2343
2344             --  The type of the loop variable is the Iterator_Element aspect of
2345             --  the container type.
2346
2347             Set_Etype (Def_Id,
2348               Entity (Find_Aspect (Typ, Aspect_Iterator_Element)));
2349
2350          else
2351             --  The result type of Iterate function is the classwide type of
2352             --  the interface parent. We need the specific Cursor type defined
2353             --  in the container package.
2354
2355             Ent := First_Entity (Scope (Typ));
2356             while Present (Ent) loop
2357                if Chars (Ent) = Name_Cursor then
2358                   Set_Etype (Def_Id, Etype (Ent));
2359                   exit;
2360                end if;
2361
2362                Next_Entity (Ent);
2363             end loop;
2364          end if;
2365       end if;
2366    end Analyze_Iterator_Specification;
2367
2368    -------------------
2369    -- Analyze_Label --
2370    -------------------
2371
2372    --  Note: the semantic work required for analyzing labels (setting them as
2373    --  reachable) was done in a prepass through the statements in the block,
2374    --  so that forward gotos would be properly handled. See Analyze_Statements
2375    --  for further details. The only processing required here is to deal with
2376    --  optimizations that depend on an assumption of sequential control flow,
2377    --  since of course the occurrence of a label breaks this assumption.
2378
2379    procedure Analyze_Label (N : Node_Id) is
2380       pragma Warnings (Off, N);
2381    begin
2382       Kill_Current_Values;
2383    end Analyze_Label;
2384
2385    --------------------------
2386    -- Analyze_Label_Entity --
2387    --------------------------
2388
2389    procedure Analyze_Label_Entity (E : Entity_Id) is
2390    begin
2391       Set_Ekind           (E, E_Label);
2392       Set_Etype           (E, Standard_Void_Type);
2393       Set_Enclosing_Scope (E, Current_Scope);
2394       Set_Reachable       (E, True);
2395    end Analyze_Label_Entity;
2396
2397    ----------------------------
2398    -- Analyze_Loop_Statement --
2399    ----------------------------
2400
2401    procedure Analyze_Loop_Statement (N : Node_Id) is
2402       Loop_Statement : constant Node_Id := N;
2403
2404       Id   : constant Node_Id := Identifier (Loop_Statement);
2405       Iter : constant Node_Id := Iteration_Scheme (Loop_Statement);
2406       Ent  : Entity_Id;
2407
2408    begin
2409       if Present (Id) then
2410
2411          --  Make name visible, e.g. for use in exit statements. Loop labels
2412          --  are always considered to be referenced.
2413
2414          Analyze (Id);
2415          Ent := Entity (Id);
2416
2417          --  Guard against serious error (typically, a scope mismatch when
2418          --  semantic analysis is requested) by creating loop entity to
2419          --  continue analysis.
2420
2421          if No (Ent) then
2422             if Total_Errors_Detected /= 0 then
2423                Ent :=
2424                  New_Internal_Entity
2425                    (E_Loop, Current_Scope, Sloc (Loop_Statement), 'L');
2426             else
2427                raise Program_Error;
2428             end if;
2429
2430          else
2431             Generate_Reference  (Ent, Loop_Statement, ' ');
2432             Generate_Definition (Ent);
2433
2434             --  If we found a label, mark its type. If not, ignore it, since it
2435             --  means we have a conflicting declaration, which would already
2436             --  have been diagnosed at declaration time. Set Label_Construct
2437             --  of the implicit label declaration, which is not created by the
2438             --  parser for generic units.
2439
2440             if Ekind (Ent) = E_Label then
2441                Set_Ekind (Ent, E_Loop);
2442
2443                if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
2444                   Set_Label_Construct (Parent (Ent), Loop_Statement);
2445                end if;
2446             end if;
2447          end if;
2448
2449       --  Case of no identifier present
2450
2451       else
2452          Ent :=
2453            New_Internal_Entity
2454              (E_Loop, Current_Scope, Sloc (Loop_Statement), 'L');
2455          Set_Etype (Ent,  Standard_Void_Type);
2456          Set_Parent (Ent, Loop_Statement);
2457       end if;
2458
2459       --  Kill current values on entry to loop, since statements in the body of
2460       --  the loop may have been executed before the loop is entered. Similarly
2461       --  we kill values after the loop, since we do not know that the body of
2462       --  the loop was executed.
2463
2464       Kill_Current_Values;
2465       Push_Scope (Ent);
2466       Analyze_Iteration_Scheme (Iter);
2467
2468       --  Analyze the statements of the body except in the case of an Ada 2012
2469       --  iterator with the expander active. In this case the expander will do
2470       --  a rewrite of the loop into a while loop. We will then analyze the
2471       --  loop body when we analyze this while loop.
2472
2473       --  We need to do this delay because if the container is for indefinite
2474       --  types the actual subtype of the components will only be determined
2475       --  when the cursor declaration is analyzed.
2476
2477       --  If the expander is not active, then we want to analyze the loop body
2478       --  now even in the Ada 2012 iterator case, since the rewriting will not
2479       --  be done.
2480
2481       if No (Iter)
2482         or else No (Iterator_Specification (Iter))
2483         or else not Expander_Active
2484       then
2485          Analyze_Statements (Statements (Loop_Statement));
2486       end if;
2487
2488       --  Finish up processing for the loop. We kill all current values, since
2489       --  in general we don't know if the statements in the loop have been
2490       --  executed. We could do a bit better than this with a loop that we
2491       --  know will execute at least once, but it's not worth the trouble and
2492       --  the front end is not in the business of flow tracing.
2493
2494       Process_End_Label (Loop_Statement, 'e', Ent);
2495       End_Scope;
2496       Kill_Current_Values;
2497
2498       --  Check for infinite loop. Skip check for generated code, since it
2499       --  justs waste time and makes debugging the routine called harder.
2500
2501       --  Note that we have to wait till the body of the loop is fully analyzed
2502       --  before making this call, since Check_Infinite_Loop_Warning relies on
2503       --  being able to use semantic visibility information to find references.
2504
2505       if Comes_From_Source (N) then
2506          Check_Infinite_Loop_Warning (N);
2507       end if;
2508
2509       --  Code after loop is unreachable if the loop has no WHILE or FOR and
2510       --  contains no EXIT statements within the body of the loop.
2511
2512       if No (Iter) and then not Has_Exit (Ent) then
2513          Check_Unreachable_Code (N);
2514       end if;
2515    end Analyze_Loop_Statement;
2516
2517    ----------------------------
2518    -- Analyze_Null_Statement --
2519    ----------------------------
2520
2521    --  Note: the semantics of the null statement is implemented by a single
2522    --  null statement, too bad everything isn't as simple as this!
2523
2524    procedure Analyze_Null_Statement (N : Node_Id) is
2525       pragma Warnings (Off, N);
2526    begin
2527       null;
2528    end Analyze_Null_Statement;
2529
2530    ------------------------
2531    -- Analyze_Statements --
2532    ------------------------
2533
2534    procedure Analyze_Statements (L : List_Id) is
2535       S   : Node_Id;
2536       Lab : Entity_Id;
2537
2538    begin
2539       --  The labels declared in the statement list are reachable from
2540       --  statements in the list. We do this as a prepass so that any goto
2541       --  statement will be properly flagged if its target is not reachable.
2542       --  This is not required, but is nice behavior!
2543
2544       S := First (L);
2545       while Present (S) loop
2546          if Nkind (S) = N_Label then
2547             Analyze (Identifier (S));
2548             Lab := Entity (Identifier (S));
2549
2550             --  If we found a label mark it as reachable
2551
2552             if Ekind (Lab) = E_Label then
2553                Generate_Definition (Lab);
2554                Set_Reachable (Lab);
2555
2556                if Nkind (Parent (Lab)) = N_Implicit_Label_Declaration then
2557                   Set_Label_Construct (Parent (Lab), S);
2558                end if;
2559
2560             --  If we failed to find a label, it means the implicit declaration
2561             --  of the label was hidden.  A for-loop parameter can do this to
2562             --  a label with the same name inside the loop, since the implicit
2563             --  label declaration is in the innermost enclosing body or block
2564             --  statement.
2565
2566             else
2567                Error_Msg_Sloc := Sloc (Lab);
2568                Error_Msg_N
2569                  ("implicit label declaration for & is hidden#",
2570                   Identifier (S));
2571             end if;
2572          end if;
2573
2574          Next (S);
2575       end loop;
2576
2577       --  Perform semantic analysis on all statements
2578
2579       Conditional_Statements_Begin;
2580
2581       S := First (L);
2582       while Present (S) loop
2583          Analyze (S);
2584          Next (S);
2585       end loop;
2586
2587       Conditional_Statements_End;
2588
2589       --  Make labels unreachable. Visibility is not sufficient, because labels
2590       --  in one if-branch for example are not reachable from the other branch,
2591       --  even though their declarations are in the enclosing declarative part.
2592
2593       S := First (L);
2594       while Present (S) loop
2595          if Nkind (S) = N_Label then
2596             Set_Reachable (Entity (Identifier (S)), False);
2597          end if;
2598
2599          Next (S);
2600       end loop;
2601    end Analyze_Statements;
2602
2603    ----------------------------
2604    -- Check_Unreachable_Code --
2605    ----------------------------
2606
2607    procedure Check_Unreachable_Code (N : Node_Id) is
2608       Error_Node : Node_Id;
2609       P          : Node_Id;
2610
2611    begin
2612       if Is_List_Member (N)
2613         and then Comes_From_Source (N)
2614       then
2615          declare
2616             Nxt : Node_Id;
2617
2618          begin
2619             Nxt := Original_Node (Next (N));
2620
2621             --  If a label follows us, then we never have dead code, since
2622             --  someone could branch to the label, so we just ignore it, unless
2623             --  we are in formal mode where goto statements are not allowed.
2624
2625             if Nkind (Nxt) = N_Label
2626               and then not Restriction_Check_Required (SPARK)
2627             then
2628                return;
2629
2630             --  Otherwise see if we have a real statement following us
2631
2632             elsif Present (Nxt)
2633               and then Comes_From_Source (Nxt)
2634               and then Is_Statement (Nxt)
2635             then
2636                --  Special very annoying exception. If we have a return that
2637                --  follows a raise, then we allow it without a warning, since
2638                --  the Ada RM annoyingly requires a useless return here!
2639
2640                if Nkind (Original_Node (N)) /= N_Raise_Statement
2641                  or else Nkind (Nxt) /= N_Simple_Return_Statement
2642                then
2643                   --  The rather strange shenanigans with the warning message
2644                   --  here reflects the fact that Kill_Dead_Code is very good
2645                   --  at removing warnings in deleted code, and this is one
2646                   --  warning we would prefer NOT to have removed.
2647
2648                   Error_Node := Nxt;
2649
2650                   --  If we have unreachable code, analyze and remove the
2651                   --  unreachable code, since it is useless and we don't
2652                   --  want to generate junk warnings.
2653
2654                   --  We skip this step if we are not in code generation mode.
2655                   --  This is the one case where we remove dead code in the
2656                   --  semantics as opposed to the expander, and we do not want
2657                   --  to remove code if we are not in code generation mode,
2658                   --  since this messes up the ASIS trees.
2659
2660                   --  Note that one might react by moving the whole circuit to
2661                   --  exp_ch5, but then we lose the warning in -gnatc mode.
2662
2663                   if Operating_Mode = Generate_Code then
2664                      loop
2665                         Nxt := Next (N);
2666
2667                         --  Quit deleting when we have nothing more to delete
2668                         --  or if we hit a label (since someone could transfer
2669                         --  control to a label, so we should not delete it).
2670
2671                         exit when No (Nxt) or else Nkind (Nxt) = N_Label;
2672
2673                         --  Statement/declaration is to be deleted
2674
2675                         Analyze (Nxt);
2676                         Remove (Nxt);
2677                         Kill_Dead_Code (Nxt);
2678                      end loop;
2679                   end if;
2680
2681                   --  Now issue the warning (or error in formal mode)
2682
2683                   if Restriction_Check_Required (SPARK) then
2684                      Check_SPARK_Restriction
2685                        ("unreachable code is not allowed", Error_Node);
2686                   else
2687                      Error_Msg ("?unreachable code!", Sloc (Error_Node));
2688                   end if;
2689                end if;
2690
2691             --  If the unconditional transfer of control instruction is the
2692             --  last statement of a sequence, then see if our parent is one of
2693             --  the constructs for which we count unblocked exits, and if so,
2694             --  adjust the count.
2695
2696             else
2697                P := Parent (N);
2698
2699                --  Statements in THEN part or ELSE part of IF statement
2700
2701                if Nkind (P) = N_If_Statement then
2702                   null;
2703
2704                --  Statements in ELSIF part of an IF statement
2705
2706                elsif Nkind (P) = N_Elsif_Part then
2707                   P := Parent (P);
2708                   pragma Assert (Nkind (P) = N_If_Statement);
2709
2710                --  Statements in CASE statement alternative
2711
2712                elsif Nkind (P) = N_Case_Statement_Alternative then
2713                   P := Parent (P);
2714                   pragma Assert (Nkind (P) = N_Case_Statement);
2715
2716                --  Statements in body of block
2717
2718                elsif Nkind (P) = N_Handled_Sequence_Of_Statements
2719                  and then Nkind (Parent (P)) = N_Block_Statement
2720                then
2721                   null;
2722
2723                --  Statements in exception handler in a block
2724
2725                elsif Nkind (P) = N_Exception_Handler
2726                  and then Nkind (Parent (P)) = N_Handled_Sequence_Of_Statements
2727                  and then Nkind (Parent (Parent (P))) = N_Block_Statement
2728                then
2729                   null;
2730
2731                --  None of these cases, so return
2732
2733                else
2734                   return;
2735                end if;
2736
2737                --  This was one of the cases we are looking for (i.e. the
2738                --  parent construct was IF, CASE or block) so decrement count.
2739
2740                Unblocked_Exit_Count := Unblocked_Exit_Count - 1;
2741             end if;
2742          end;
2743       end if;
2744    end Check_Unreachable_Code;
2745
2746 end Sem_Ch5;