OSDN Git Service

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