OSDN Git Service

2008-04-08 Hristian Kirtchev <kirtchev@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch11.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ C H 1 1                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2008, 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 Casing;   use Casing;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Exp_Ch7;  use Exp_Ch7;
33 with Exp_Util; use Exp_Util;
34 with Namet;    use Namet;
35 with Nlists;   use Nlists;
36 with Nmake;    use Nmake;
37 with Opt;      use Opt;
38 with Rtsfind;  use Rtsfind;
39 with Restrict; use Restrict;
40 with Rident;   use Rident;
41 with Sem;      use Sem;
42 with Sem_Ch8;  use Sem_Ch8;
43 with Sem_Res;  use Sem_Res;
44 with Sem_Util; use Sem_Util;
45 with Sinfo;    use Sinfo;
46 with Sinput;   use Sinput;
47 with Snames;   use Snames;
48 with Stand;    use Stand;
49 with Stringt;  use Stringt;
50 with Targparm; use Targparm;
51 with Tbuild;   use Tbuild;
52 with Uintp;    use Uintp;
53
54 package body Exp_Ch11 is
55
56    -----------------------
57    -- Local Subprograms --
58    -----------------------
59
60    procedure Warn_No_Exception_Propagation_Active (N : Node_Id);
61    --  Generates warning that pragma Restrictions (No_Exception_Propagation)
62    --  is in effect. Caller then generates appropriate continuation message.
63    --  N is the node on which the warning is placed.
64
65    procedure Warn_If_No_Propagation (N : Node_Id);
66    --  Called for an exception raise that is not a local raise (and thus can
67    --  not be optimized to a goto. Issues warning if No_Exception_Propagation
68    --  restriction is set. N is the node for the raise or equivalent call.
69
70    ---------------------------
71    -- Expand_At_End_Handler --
72    ---------------------------
73
74    --  For a handled statement sequence that has a cleanup (At_End_Proc
75    --  field set), an exception handler of the following form is required:
76
77    --     exception
78    --       when all others =>
79    --          cleanup call
80    --          raise;
81
82    --  Note: this exception handler is treated rather specially by
83    --  subsequent expansion in two respects:
84
85    --    The normal call to Undefer_Abort is omitted
86    --    The raise call does not do Defer_Abort
87
88    --  This is because the current tasking code seems to assume that
89    --  the call to the cleanup routine that is made from an exception
90    --  handler for the abort signal is called with aborts deferred.
91
92    --  This expansion is only done if we have front end exception handling.
93    --  If we have back end exception handling, then the AT END handler is
94    --  left alone, and cleanups (including the exceptional case) are handled
95    --  by the back end.
96
97    --  In the front end case, the exception handler described above handles
98    --  the exceptional case. The AT END handler is left in the generated tree
99    --  and the code generator (e.g. gigi) must still handle proper generation
100    --  of cleanup calls for the non-exceptional case.
101
102    procedure Expand_At_End_Handler (HSS : Node_Id; Block : Node_Id) is
103       Clean   : constant Entity_Id  := Entity (At_End_Proc (HSS));
104       Loc     : constant Source_Ptr := Sloc (Clean);
105       Ohandle : Node_Id;
106       Stmnts  : List_Id;
107
108    begin
109       pragma Assert (Present (Clean));
110       pragma Assert (No (Exception_Handlers (HSS)));
111
112       --  Don't expand if back end exception handling active
113
114       if Exception_Mechanism = Back_End_Exceptions then
115          return;
116       end if;
117
118       --  Don't expand an At End handler if we have already had configurable
119       --  run-time violations, since likely this will just be a matter of
120       --  generating useless cascaded messages
121
122       if Configurable_Run_Time_Violations > 0 then
123          return;
124       end if;
125
126       --  Don't expand an At End handler if we are not allowing exceptions
127       --  or if exceptions are transformed into local gotos, and never
128       --  propagated (No_Exception_Propagation).
129
130       if No_Exception_Handlers_Set then
131          return;
132       end if;
133
134       if Present (Block) then
135          Push_Scope (Block);
136       end if;
137
138       Ohandle :=
139         Make_Others_Choice (Loc);
140       Set_All_Others (Ohandle);
141
142       Stmnts := New_List (
143         Make_Procedure_Call_Statement (Loc,
144           Name => New_Occurrence_Of (Clean, Loc)));
145
146       --  Generate reraise statement as last statement of AT-END handler,
147       --  unless we are under control of No_Exception_Propagation, in which
148       --  case no exception propagation is possible anyway, so we do not need
149       --  a reraise (the AT END handler in this case is only for normal exits
150       --  not for exceptional exits). Also, we flag the Reraise statement as
151       --  being part of an AT END handler to prevent signalling this reraise
152       --  as a violation of the restriction when it is not set.
153
154       if not Restriction_Active (No_Exception_Propagation) then
155          declare
156             Rstm : constant Node_Id := Make_Raise_Statement (Loc);
157          begin
158             Set_From_At_End (Rstm);
159             Append_To (Stmnts, Rstm);
160          end;
161       end if;
162
163       Set_Exception_Handlers (HSS, New_List (
164         Make_Implicit_Exception_Handler (Loc,
165           Exception_Choices => New_List (Ohandle),
166           Statements        => Stmnts)));
167
168       Analyze_List (Stmnts, Suppress => All_Checks);
169       Expand_Exception_Handlers (HSS);
170
171       if Present (Block) then
172          Pop_Scope;
173       end if;
174    end Expand_At_End_Handler;
175
176    -------------------------------
177    -- Expand_Exception_Handlers --
178    -------------------------------
179
180    procedure Expand_Exception_Handlers (HSS : Node_Id) is
181       Handlrs       : constant List_Id    := Exception_Handlers (HSS);
182       Loc           : constant Source_Ptr := Sloc (HSS);
183       Handler       : Node_Id;
184       Others_Choice : Boolean;
185       Obj_Decl      : Node_Id;
186       Next_Handler  : Node_Id;
187
188       procedure Expand_Local_Exception_Handlers;
189       --  This procedure handles the expansion of exception handlers for the
190       --  optimization of local raise statements into goto statements.
191
192       procedure Prepend_Call_To_Handler
193         (Proc : RE_Id;
194          Args : List_Id := No_List);
195       --  Routine to prepend a call to the procedure referenced by Proc at
196       --  the start of the handler code for the current Handler.
197
198       procedure Replace_Raise_By_Goto (Raise_S : Node_Id; Goto_L1 : Node_Id);
199       --  Raise_S is a raise statement (possibly expanded, and possibly of the
200       --  form of a Raise_xxx_Error node with a condition. This procedure is
201       --  called to replace the raise action with the (already analyzed) goto
202       --  statement passed as Goto_L1. This procedure also takes care of the
203       --  requirement of inserting a Local_Raise call where possible.
204
205       -------------------------------------
206       -- Expand_Local_Exception_Handlers --
207       -------------------------------------
208
209       --  There are two cases for this transformation. First the case of
210       --  explicit raise statements. For this case, the transformation we do
211       --  looks like this. Right now we have for example (where L1, L2 are
212       --  exception labels)
213
214       --  begin
215       --     ...
216       --     raise_exception (excep1'identity);  -- was raise excep1
217       --     ...
218       --     raise_exception (excep2'identity);  -- was raise excep2
219       --     ...
220       --  exception
221       --     when excep1 =>
222       --        estmts1
223       --     when excep2 =>
224       --        estmts2
225       --  end;
226
227       --  This gets transformed into:
228
229       --  begin
230       --     L1 : label;                        -- marked Exception_Junk
231       --     L2 : label;                        -- marked Exception_Junk
232       --     L3 : label;                        -- marked Exception_Junk
233
234       --     begin                              -- marked Exception_Junk
235       --        ...
236       --        local_raise (excep1'address);   -- was raise excep1
237       --        goto L1;
238       --        ...
239       --        local_raise (excep2'address);   -- was raise excep2
240       --        goto L2;
241       --        ...
242       --     exception
243       --        when excep1 =>
244       --           goto L1;
245       --        when excep2 =>
246       --           goto L2;
247       --     end;
248
249       --     goto L3;        -- skip handler if no raise, marked Exception_Junk
250
251       --     <<L1>>          -- local excep target label, marked Exception_Junk
252       --        begin        -- marked Exception_Junk
253       --           estmts1
254       --        end;
255       --        goto L3;     -- marked Exception_Junk
256
257       --     <<L2>>          -- marked Exception_Junk
258       --        begin        -- marked Exception_Junk
259       --           estmts2
260       --        end;
261       --        goto L3;     -- marked Exception_Junk
262       --     <<L3>>          -- marked Exception_Junk
263       --  end;
264
265       --  Note: the reason we wrap the original statement sequence in an
266       --  inner block is that there may be raise statements within the
267       --  sequence of statements in the handlers, and we must ensure that
268       --  these are properly handled, and in particular, such raise statements
269       --  must not reenter the same exception handlers.
270
271       --  If the restriction No_Exception_Propagation is in effect, then we
272       --  can omit the exception handlers.
273
274       --  begin
275       --     L1 : label;                        -- marked Exception_Junk
276       --     L2 : label;                        -- marked Exception_Junk
277       --     L3 : label;                        -- marked Exception_Junk
278
279       --     begin                              -- marked Exception_Junk
280       --        ...
281       --        local_raise (excep1'address);   -- was raise excep1
282       --        goto L1;
283       --        ...
284       --        local_raise (excep2'address);   -- was raise excep2
285       --        goto L2;
286       --        ...
287       --     end;
288
289       --     goto L3;        -- skip handler if no raise, marked Exception_Junk
290
291       --     <<L1>>          -- local excep target label, marked Exception_Junk
292       --        begin        -- marked Exception_Junk
293       --           estmts1
294       --        end;
295       --        goto L3;     -- marked Exception_Junk
296
297       --     <<L2>>          -- marked Exception_Junk
298       --        begin        -- marked Exception_Junk
299       --           estmts2
300       --        end;
301
302       --     <<L3>>          -- marked Exception_Junk
303       --  end;
304
305       --  The second case is for exceptions generated by the back end in one
306       --  of three situations:
307
308       --    1. Front end generates N_Raise_xxx_Error node
309       --    2. Front end sets Do_xxx_Check flag in subexpression node
310       --    3. Back end detects a situation where an exception is appropriate
311
312       --  In all these cases, the current processing in gigi is to generate a
313       --  call to the appropriate Rcheck_xx routine (where xx encodes both the
314       --  exception message and the exception to be raised, Constraint_Error,
315       --  Program_Error, or Storage_Error.
316
317       --  We could handle some subcases of 1 using the same front end expansion
318       --  into gotos, but even for case 1, we can't handle all cases, since
319       --  generating gotos in the middle of expressions is not possible (it's
320       --  possible at the gigi/gcc level, but not at the level of the GNAT
321       --  tree).
322
323       --  In any case, it seems easier to have a scheme which handles all three
324       --  cases in a uniform manner. So here is how we proceed in this case.
325
326       --  This procedure detects all handlers for these three exceptions,
327       --  Constraint_Error, Program_Error and Storage_Error (including WHEN
328       --  OTHERS handlers that cover one or more of these cases).
329
330       --  If the handler meets the requirements for being the target of a local
331       --  raise, then the front end does the expansion described previously,
332       --  creating a label to be used as a goto target to raise the exception.
333       --  However, no attempt is made in the front end to convert any related
334       --  raise statements into gotos, e.g. all N_Raise_xxx_Error nodes are
335       --  left unchanged and passed to the back end.
336
337       --  Instead, the front end generates two nodes
338
339       --     N_Push_Constraint_Error_Label
340       --     N_Push_Program_Error_Label
341       --     N_Push_Storage_Error_Label
342
343       --       The Push node is generated at the start of the statements
344       --       covered by the handler, and has as a parameter the label to be
345       --       used as the raise target.
346
347       --     N_Pop_Constraint_Error_Label
348       --     N_Pop_Program_Error_Label
349       --     N_Pop_Storage_Error_Label
350
351       --       The Pop node is generated at the end of the covered statements
352       --       and undoes the effect of the preceding corresponding Push node.
353
354       --  In the case where the handler does NOT meet the requirements, the
355       --  front end will still generate the Push and Pop nodes, but the label
356       --  field in the Push node will be empty signifying that for this region
357       --  of code, no optimization is possible.
358
359       --  The back end must maintain three stacks, one for each exception case,
360       --  the Push node pushes an entry onto the corresponding stack, and Pop
361       --  node pops off the entry. Then instead of calling Rcheck_nn, if the
362       --  corresponding top stack entry has an non-empty label, a goto is
363       --  generated. This goto should be preceded by a call to Local_Raise as
364       --  described above.
365
366       --  An example of this transformation is as follows, given:
367
368       --  declare
369       --    A : Integer range 1 .. 10;
370       --  begin
371       --    A := B + C;
372       --  exception
373       --    when Constraint_Error =>
374       --       estmts
375       --  end;
376
377       --  gets transformed to:
378
379       --  declare
380       --    A : Integer range 1 .. 10;
381
382       --  begin
383       --     L1 : label;
384       --     L2 : label;
385
386       --     begin
387       --        %push_constraint_error_label (L1)
388       --        R1b : constant long_long_integer := long_long_integer?(b) +
389       --          long_long_integer?(c);
390       --        [constraint_error when
391       --          not (R1b in -16#8000_0000# .. 16#7FFF_FFFF#)
392       --          "overflow check failed"]
393       --        a := integer?(R1b);
394       --        %pop_constraint_error_Label
395
396       --     exception
397       --        ...
398       --        when constraint_error =>
399       --           goto L1;
400       --     end;
401
402       --     goto L2;       -- skip handler when exception not raised
403       --     <<L1>>         -- target label for local exception
404       --     estmts
405       --     <<L2>>
406       --  end;
407
408       --  Note: the generated labels and goto statements all have the flag
409       --  Exception_Junk set True, so that Sem_Ch6.Check_Returns will ignore
410       --  this generated exception stuff when checking for missing return
411       --  statements (see circuitry in Check_Statement_Sequence).
412
413       --  Note: All of the processing described above occurs only if
414       --  restriction No_Exception_Propagation applies or debug flag .g is
415       --  enabled.
416
417       CE_Locally_Handled : Boolean := False;
418       SE_Locally_Handled : Boolean := False;
419       PE_Locally_Handled : Boolean := False;
420       --  These three flags indicate whether a handler for the corresponding
421       --  exception (CE=Constraint_Error, SE=Storage_Error, PE=Program_Error)
422       --  is present. If so the switch is set to True, the Exception_Label
423       --  field of the corresponding handler is set, and appropriate Push
424       --  and Pop nodes are inserted into the code.
425
426       Local_Expansion_Required : Boolean := False;
427       --  Set True if we have at least one handler requiring local raise
428       --  expansion as described above.
429
430       procedure Expand_Local_Exception_Handlers is
431
432          procedure Add_Exception_Label (H : Node_Id);
433          --  H is an exception handler. First check for an Exception_Label
434          --  already allocated for H. If none, allocate one, set the field in
435          --  the handler node, add the label declaration, and set the flag
436          --  Local_Expansion_Required. Note: if Local_Raise_Not_OK is set
437          --  the call has no effect and Exception_Label is left empty.
438
439          procedure Add_Label_Declaration (L : Entity_Id);
440          --  Add an implicit declaration of the given label to the declaration
441          --  list in the parent of the current sequence of handled statements.
442
443          generic
444             Exc_Locally_Handled : in out Boolean;
445             --  Flag indicating whether a local handler for this exception
446             --  has already been generated.
447
448             with function Make_Push_Label (Loc : Source_Ptr) return Node_Id;
449             --  Function to create a Push_xxx_Label node
450
451             with function Make_Pop_Label (Loc : Source_Ptr) return Node_Id;
452             --  Function to create a Pop_xxx_Label node
453
454          procedure Generate_Push_Pop (H : Node_Id);
455          --  Common code for Generate_Push_Pop_xxx below, used to generate an
456          --  exception label and Push/Pop nodes for Constraint_Error,
457          --  Program_Error, or Storage_Error.
458
459          -------------------------
460          -- Add_Exception_Label --
461          -------------------------
462
463          procedure Add_Exception_Label (H : Node_Id) is
464          begin
465             if No (Exception_Label (H))
466               and then not Local_Raise_Not_OK (H)
467               and then not Special_Exception_Package_Used
468             then
469                Local_Expansion_Required := True;
470
471                declare
472                   L : constant Entity_Id :=
473                         Make_Defining_Identifier (Sloc (H),
474                           Chars => New_Internal_Name ('L'));
475                begin
476                   Set_Exception_Label (H, L);
477                   Add_Label_Declaration (L);
478                end;
479             end if;
480          end Add_Exception_Label;
481
482          ---------------------------
483          -- Add_Label_Declaration --
484          ---------------------------
485
486          procedure Add_Label_Declaration (L : Entity_Id) is
487             P : constant Node_Id := Parent (HSS);
488
489             Decl_L : constant Node_Id :=
490                        Make_Implicit_Label_Declaration (Loc,
491                          Defining_Identifier => L);
492
493          begin
494             if Declarations (P) = No_List then
495                Set_Declarations (P, Empty_List);
496             end if;
497
498             Append (Decl_L, Declarations (P));
499             Analyze (Decl_L);
500          end Add_Label_Declaration;
501
502          -----------------------
503          -- Generate_Push_Pop --
504          -----------------------
505
506          procedure Generate_Push_Pop (H : Node_Id) is
507          begin
508             if Exc_Locally_Handled then
509                return;
510             else
511                Exc_Locally_Handled := True;
512             end if;
513
514             Add_Exception_Label (H);
515
516             declare
517                F : constant Node_Id := First (Statements (HSS));
518                L : constant Node_Id := Last  (Statements (HSS));
519
520                Push : constant Node_Id := Make_Push_Label (Sloc (F));
521                Pop  : constant Node_Id := Make_Pop_Label  (Sloc (L));
522
523             begin
524                --  We make sure that a call to Get_Local_Raise_Call_Entity is
525                --  made during front end processing, so that when we need it
526                --  in the back end, it will already be available and loaded.
527
528                Discard_Node (Get_Local_Raise_Call_Entity);
529
530                --  Prepare and insert Push and Pop nodes
531
532                Set_Exception_Label (Push, Exception_Label (H));
533                Insert_Before (F, Push);
534                Set_Analyzed (Push);
535
536                Insert_After (L, Pop);
537                Set_Analyzed (Pop);
538             end;
539          end Generate_Push_Pop;
540
541          --  Local declarations
542
543          Loc    : constant Source_Ptr := Sloc (HSS);
544          Stmts  : List_Id := No_List;
545          Choice : Node_Id;
546          Excep  : Entity_Id;
547
548          procedure Generate_Push_Pop_For_Constraint_Error is
549            new Generate_Push_Pop
550              (Exc_Locally_Handled => CE_Locally_Handled,
551               Make_Push_Label     => Make_Push_Constraint_Error_Label,
552               Make_Pop_Label      => Make_Pop_Constraint_Error_Label);
553          --  If no Push/Pop has been generated for CE yet, then set the flag
554          --  CE_Locally_Handled, allocate an Exception_Label for handler H (if
555          --  not already done), and generate Push/Pop nodes for the exception
556          --  label at the start and end of the statements of HSS.
557
558          procedure Generate_Push_Pop_For_Program_Error is
559            new Generate_Push_Pop
560              (Exc_Locally_Handled => PE_Locally_Handled,
561               Make_Push_Label     => Make_Push_Program_Error_Label,
562               Make_Pop_Label      => Make_Pop_Program_Error_Label);
563          --  If no Push/Pop has been generated for PE yet, then set the flag
564          --  PE_Locally_Handled, allocate an Exception_Label for handler H (if
565          --  not already done), and generate Push/Pop nodes for the exception
566          --  label at the start and end of the statements of HSS.
567
568          procedure Generate_Push_Pop_For_Storage_Error is
569            new Generate_Push_Pop
570              (Exc_Locally_Handled => SE_Locally_Handled,
571               Make_Push_Label     => Make_Push_Storage_Error_Label,
572               Make_Pop_Label      => Make_Pop_Storage_Error_Label);
573          --  If no Push/Pop has been generated for SE yet, then set the flag
574          --  SE_Locally_Handled, allocate an Exception_Label for handler H (if
575          --  not already done), and generate Push/Pop nodes for the exception
576          --  label at the start and end of the statements of HSS.
577
578       --  Start of processing for Expand_Local_Exception_Handlers
579
580       begin
581          --  No processing if all exception handlers will get removed
582
583          if Debug_Flag_Dot_X then
584             return;
585          end if;
586
587          --  See for each handler if we have any local raises to expand
588
589          Handler := First_Non_Pragma (Handlrs);
590          while Present (Handler) loop
591
592             --  Note, we do not test Local_Raise_Not_OK here, because in the
593             --  case of Push/Pop generation we want to generate push with a
594             --  null label. The Add_Exception_Label routine has no effect if
595             --  Local_Raise_Not_OK is set, so this works as required.
596
597             if Present (Local_Raise_Statements (Handler)) then
598                Add_Exception_Label (Handler);
599             end if;
600
601             --  If we are doing local raise to goto optimization (restriction
602             --  No_Exception_Propagation set or debug flag .g set), then check
603             --  to see if handler handles CE, PE, SE and if so generate the
604             --  appropriate push/pop sequence for the back end.
605
606             if (Debug_Flag_Dot_G
607                  or else Restriction_Active (No_Exception_Propagation))
608               and then Has_Local_Raise (Handler)
609             then
610                Choice := First (Exception_Choices (Handler));
611                while Present (Choice) loop
612                   if Nkind (Choice) = N_Others_Choice
613                     and then not All_Others (Choice)
614                   then
615                      Generate_Push_Pop_For_Constraint_Error (Handler);
616                      Generate_Push_Pop_For_Program_Error    (Handler);
617                      Generate_Push_Pop_For_Storage_Error    (Handler);
618
619                   elsif Is_Entity_Name (Choice) then
620                      Excep := Get_Renamed_Entity (Entity (Choice));
621
622                      if Excep = Standard_Constraint_Error then
623                         Generate_Push_Pop_For_Constraint_Error (Handler);
624                      elsif Excep = Standard_Program_Error then
625                         Generate_Push_Pop_For_Program_Error    (Handler);
626                      elsif Excep = Standard_Storage_Error then
627                         Generate_Push_Pop_For_Storage_Error    (Handler);
628                      end if;
629                   end if;
630
631                   Next (Choice);
632                end loop;
633             end if;
634
635             Next_Non_Pragma (Handler);
636          end loop;
637
638          --  Nothing to do if no handlers requiring the goto transformation
639
640          if not (Local_Expansion_Required) then
641             return;
642          end if;
643
644          --  Prepare to do the transformation
645
646          declare
647             --  L3 is the label to exit the HSS
648
649             L3_Dent : constant Entity_Id :=
650                         Make_Defining_Identifier (Loc,
651                           Chars => New_Internal_Name ('L'));
652
653             Labl_L3 : constant Node_Id :=
654                         Make_Label (Loc,
655                           Identifier => New_Occurrence_Of (L3_Dent, Loc));
656
657             Blk_Stm : Node_Id;
658             Relmt   : Elmt_Id;
659
660          begin
661             Set_Exception_Junk (Labl_L3);
662             Add_Label_Declaration (L3_Dent);
663
664             --  Wrap existing statements and handlers in an inner block
665
666             Blk_Stm :=
667               Make_Block_Statement (Loc,
668                 Handled_Statement_Sequence => Relocate_Node (HSS));
669             Set_Exception_Junk (Blk_Stm);
670
671             Rewrite (HSS,
672               Make_Handled_Sequence_Of_Statements (Loc,
673                 Statements => New_List (Blk_Stm)));
674
675             --  Set block statement as analyzed, we don't want to actually call
676             --  Analyze on this block, it would cause a recursion in exception
677             --  handler processing which would mess things up.
678
679             Set_Analyzed (Blk_Stm);
680
681             --  Now loop through the exception handlers to deal with those that
682             --  are targets of local raise statements.
683
684             Handler := First_Non_Pragma (Handlrs);
685             while Present (Handler) loop
686                if Present (Exception_Label (Handler)) then
687
688                   --  This handler needs the goto expansion
689
690                   declare
691                      Loc : constant Source_Ptr := Sloc (Handler);
692
693                      --  L1 is the start label for this handler
694
695                      L1_Dent : constant Entity_Id := Exception_Label (Handler);
696
697                      Labl_L1 : constant Node_Id :=
698                                  Make_Label (Loc,
699                                    Identifier =>
700                                      New_Occurrence_Of (L1_Dent, Loc));
701
702                      --  Jump to L1 to be used as replacement for the original
703                      --  handler (used in the case where exception propagation
704                      --  may still occur).
705
706                      Name_L1 : constant Node_Id :=
707                                  New_Occurrence_Of (L1_Dent, Loc);
708
709                      Goto_L1 : constant Node_Id :=
710                                  Make_Goto_Statement (Loc,
711                                    Name => Name_L1);
712
713                      --  Jump to L3 to be used at the end of handler
714
715                      Name_L3 : constant Node_Id :=
716                                  New_Occurrence_Of (L3_Dent, Loc);
717
718                      Goto_L3 : constant Node_Id :=
719                                  Make_Goto_Statement (Loc,
720                                    Name => Name_L3);
721
722                      H_Stmts : constant List_Id := Statements (Handler);
723
724                   begin
725                      Set_Exception_Junk (Labl_L1);
726                      Set_Exception_Junk (Goto_L3);
727
728                      --  Note: we do NOT set Exception_Junk in Goto_L1, since
729                      --  this is a real transfer of control that we want the
730                      --  Sem_Ch6.Check_Returns procedure to recognize properly.
731
732                      --  Replace handler by a goto L1. We can mark this as
733                      --  analyzed since it is fully formed, and we don't
734                      --  want it going through any further checks. We save
735                      --  the last statement location in the goto L1 node for
736                      --  the benefit of Sem_Ch6.Check_Returns.
737
738                      Set_Statements (Handler, New_List (Goto_L1));
739                      Set_Analyzed (Goto_L1);
740                      Set_Etype (Name_L1, Standard_Void_Type);
741
742                      --  Now replace all the raise statements by goto L1
743
744                      if Present (Local_Raise_Statements (Handler)) then
745                         Relmt := First_Elmt (Local_Raise_Statements (Handler));
746                         while Present (Relmt) loop
747                            declare
748                               Raise_S : constant Node_Id := Node (Relmt);
749
750                               Name_L1 : constant Node_Id :=
751                                           New_Occurrence_Of (L1_Dent, Loc);
752
753                               Goto_L1 : constant Node_Id :=
754                                           Make_Goto_Statement (Loc,
755                                             Name => Name_L1);
756
757                            begin
758                               --  Replace raise by goto L1
759
760                               Set_Analyzed (Goto_L1);
761                               Set_Etype (Name_L1, Standard_Void_Type);
762                               Replace_Raise_By_Goto (Raise_S, Goto_L1);
763                            end;
764
765                            Next_Elmt (Relmt);
766                         end loop;
767                      end if;
768
769                      --  Add a goto L3 at end of statement list in block. The
770                      --  first time, this is what skips over the exception
771                      --  handlers in the normal case. Subsequent times, it
772                      --  terminates the execution of the previous handler code,
773                      --  and skips subsequent handlers.
774
775                      Stmts := Statements (HSS);
776
777                      Insert_After (Last (Stmts), Goto_L3);
778                      Set_Analyzed (Goto_L3);
779                      Set_Etype (Name_L3, Standard_Void_Type);
780
781                      --  Now we drop the label that marks the handler start,
782                      --  followed by the statements of the handler.
783
784                      Set_Etype (Identifier (Labl_L1), Standard_Void_Type);
785
786                      Insert_After_And_Analyze (Last (Stmts), Labl_L1);
787
788                      declare
789                         Loc : constant Source_Ptr := Sloc (First (H_Stmts));
790                         Blk : constant Node_Id :=
791                                 Make_Block_Statement (Loc,
792                                   Handled_Statement_Sequence =>
793                                     Make_Handled_Sequence_Of_Statements (Loc,
794                                       Statements => H_Stmts));
795                      begin
796                         Set_Exception_Junk (Blk);
797                         Insert_After_And_Analyze (Last (Stmts), Blk);
798                      end;
799                   end;
800
801                   --  Here if we have local raise statements but the handler is
802                   --  not suitable for processing with a local raise. In this
803                   --  case we have to generate possible diagnostics.
804
805                elsif Has_Local_Raise (Handler)
806                  and then Local_Raise_Statements (Handler) /= No_Elist
807                then
808                   Relmt := First_Elmt (Local_Raise_Statements (Handler));
809                   while Present (Relmt) loop
810                      Warn_If_No_Propagation (Node (Relmt));
811                      Next_Elmt (Relmt);
812                   end loop;
813                end if;
814
815                Next (Handler);
816             end loop;
817
818             --  Only remaining step is to drop the L3 label and we are done
819
820             Set_Etype (Identifier (Labl_L3), Standard_Void_Type);
821
822             --  If we had at least one handler, then we drop the label after
823             --  the last statement of that handler.
824
825             if Stmts /= No_List then
826                Insert_After_And_Analyze (Last (Stmts), Labl_L3);
827
828             --  Otherwise we have removed all the handlers (this results from
829             --  use of pragma Restrictions (No_Exception_Propagation), and we
830             --  drop the label at the end of the statements of the HSS.
831
832             else
833                Insert_After_And_Analyze (Last (Statements (HSS)), Labl_L3);
834             end if;
835
836             return;
837          end;
838       end Expand_Local_Exception_Handlers;
839
840       -----------------------------
841       -- Prepend_Call_To_Handler --
842       -----------------------------
843
844       procedure Prepend_Call_To_Handler
845         (Proc : RE_Id;
846          Args : List_Id := No_List)
847       is
848          Ent : constant Entity_Id := RTE (Proc);
849
850       begin
851          --  If we have no Entity, then we are probably in no run time mode
852          --  or some weird error has occured. In either case do do nothing!
853
854          if Present (Ent) then
855             declare
856                Call : constant Node_Id :=
857                         Make_Procedure_Call_Statement (Loc,
858                           Name => New_Occurrence_Of (RTE (Proc), Loc),
859                           Parameter_Associations => Args);
860
861             begin
862                Prepend_To (Statements (Handler), Call);
863                Analyze (Call, Suppress => All_Checks);
864             end;
865          end if;
866       end Prepend_Call_To_Handler;
867
868       ---------------------------
869       -- Replace_Raise_By_Goto --
870       ---------------------------
871
872       procedure Replace_Raise_By_Goto (Raise_S : Node_Id; Goto_L1 : Node_Id) is
873          Loc   : constant Source_Ptr := Sloc (Raise_S);
874          Excep : Entity_Id;
875          LR    : Node_Id;
876          Cond  : Node_Id;
877          Orig  : Node_Id;
878
879       begin
880          --  If we have a null statement, it means that there is no replacement
881          --  needed (typically this results from a suppressed check).
882
883          if Nkind (Raise_S) = N_Null_Statement then
884             return;
885
886          --  Test for Raise_xxx_Error
887
888          elsif Nkind (Raise_S) = N_Raise_Constraint_Error then
889             Excep := Standard_Constraint_Error;
890             Cond  := Condition (Raise_S);
891
892          elsif Nkind (Raise_S) = N_Raise_Storage_Error then
893             Excep := Standard_Storage_Error;
894             Cond := Condition (Raise_S);
895
896          elsif Nkind (Raise_S) = N_Raise_Program_Error then
897             Excep := Standard_Program_Error;
898             Cond := Condition (Raise_S);
899
900             --  The only other possibility is a node that is or used to be a
901             --  simple raise statement.
902
903          else
904             Orig := Original_Node (Raise_S);
905             pragma Assert (Nkind (Orig) = N_Raise_Statement
906                              and then Present (Name (Orig))
907                              and then No (Expression (Orig)));
908             Excep := Entity (Name (Orig));
909             Cond := Empty;
910          end if;
911
912          --  Here Excep is the exception to raise, and Cond is the condition
913          --  First prepare the call to Local_Raise (excep'address).
914
915          if RTE_Available (RE_Local_Raise) then
916             LR :=
917               Make_Procedure_Call_Statement (Loc,
918                 Name => New_Occurrence_Of (RTE (RE_Local_Raise), Loc),
919                 Parameter_Associations => New_List (
920                   Unchecked_Convert_To (RTE (RE_Address),
921                     Make_Attribute_Reference (Loc,
922                       Prefix         => New_Occurrence_Of (Excep, Loc),
923                       Attribute_Name => Name_Identity))));
924
925             --  Use null statement if Local_Raise not available
926
927          else
928             LR :=
929               Make_Null_Statement (Loc);
930          end if;
931
932          --  If there is no condition, we rewrite as
933
934          --    begin
935          --       Local_Raise (excep'Identity);
936          --       goto L1;
937          --    end;
938
939          if No (Cond) then
940             Rewrite (Raise_S,
941               Make_Block_Statement (Loc,
942                 Handled_Statement_Sequence =>
943                   Make_Handled_Sequence_Of_Statements (Loc,
944                     Statements => New_List (LR, Goto_L1))));
945             Set_Exception_Junk (Raise_S);
946
947          --  If there is a condition, we rewrite as
948
949          --    if condition then
950          --       Local_Raise (excep'Identity);
951          --       goto L1;
952          --    end if;
953
954          else
955             Rewrite (Raise_S,
956               Make_If_Statement (Loc,
957                 Condition       => Cond,
958                 Then_Statements => New_List (LR, Goto_L1)));
959          end if;
960
961          Analyze (Raise_S);
962       end Replace_Raise_By_Goto;
963
964    --  Start of processing for Expand_Exception_Handlers
965
966    begin
967       Expand_Local_Exception_Handlers;
968
969       --  Loop through handlers
970
971       Handler := First_Non_Pragma (Handlrs);
972       Handler_Loop : while Present (Handler) loop
973          Next_Handler := Next_Non_Pragma (Handler);
974
975          --  Remove source handler if gnat debug flag .x is set
976
977          if Debug_Flag_Dot_X and then Comes_From_Source (Handler) then
978             Remove (Handler);
979
980          --  Remove handler if no exception propagation, generating a warning
981          --  if a source generated handler was not the target of a local raise.
982
983          else
984             if Restriction_Active (No_Exception_Propagation)
985               and then not Has_Local_Raise (Handler)
986               and then Comes_From_Source (Handler)
987               and then Warn_On_Non_Local_Exception
988             then
989                Warn_No_Exception_Propagation_Active (Handler);
990                Error_Msg_N
991                  ("\?this handler can never be entered, and has been removed",
992                   Handler);
993             end if;
994
995             if No_Exception_Propagation_Active then
996                Remove (Handler);
997
998             --  Exception handler is active and retained and must be processed
999
1000             else
1001                --  If an exception occurrence is present, then we must declare
1002                --  it and initialize it from the value stored in the TSD
1003
1004                --     declare
1005                --        name : Exception_Occurrence;
1006                --     begin
1007                --        Save_Occurrence (name, Get_Current_Excep.all)
1008                --        ...
1009                --     end;
1010
1011                if Present (Choice_Parameter (Handler)) then
1012                   declare
1013                      Cparm : constant Entity_Id  := Choice_Parameter (Handler);
1014                      Clc   : constant Source_Ptr := Sloc (Cparm);
1015                      Save  : Node_Id;
1016
1017                   begin
1018                      Save :=
1019                        Make_Procedure_Call_Statement (Loc,
1020                          Name =>
1021                            New_Occurrence_Of (RTE (RE_Save_Occurrence), Loc),
1022                          Parameter_Associations => New_List (
1023                            New_Occurrence_Of (Cparm, Clc),
1024                            Make_Explicit_Dereference (Loc,
1025                              Make_Function_Call (Loc,
1026                                Name => Make_Explicit_Dereference (Loc,
1027                                  New_Occurrence_Of
1028                                    (RTE (RE_Get_Current_Excep), Loc))))));
1029
1030                      Mark_Rewrite_Insertion (Save);
1031                      Prepend (Save, Statements (Handler));
1032
1033                      Obj_Decl :=
1034                        Make_Object_Declaration
1035                          (Clc,
1036                           Defining_Identifier => Cparm,
1037                           Object_Definition   =>
1038                             New_Occurrence_Of
1039                               (RTE (RE_Exception_Occurrence), Clc));
1040                      Set_No_Initialization (Obj_Decl, True);
1041
1042                      Rewrite (Handler,
1043                        Make_Implicit_Exception_Handler (Loc,
1044                          Exception_Choices => Exception_Choices (Handler),
1045
1046                          Statements => New_List (
1047                            Make_Block_Statement (Loc,
1048                              Declarations => New_List (Obj_Decl),
1049                              Handled_Statement_Sequence =>
1050                                Make_Handled_Sequence_Of_Statements (Loc,
1051                                  Statements => Statements (Handler))))));
1052
1053                      Analyze_List
1054                        (Statements (Handler), Suppress => All_Checks);
1055                   end;
1056                end if;
1057
1058                --  The processing at this point is rather different for the JVM
1059                --  case, so we completely separate the processing.
1060
1061                --  For the VM case, we unconditionally call Update_Exception,
1062                --  passing a call to the intrinsic Current_Target_Exception
1063                --  (see JVM/.NET versions of Ada.Exceptions for details).
1064
1065                if VM_Target /= No_VM then
1066                   declare
1067                      Arg : constant Node_Id :=
1068                              Make_Function_Call (Loc,
1069                                Name =>
1070                                  New_Occurrence_Of
1071                                    (RTE (RE_Current_Target_Exception), Loc));
1072                   begin
1073                      Prepend_Call_To_Handler
1074                        (RE_Update_Exception, New_List (Arg));
1075                   end;
1076
1077                   --  For the normal case, we have to worry about the state of
1078                   --  abort deferral. Generally, we defer abort during runtime
1079                   --  handling of exceptions. When control is passed to the
1080                   --  handler, then in the normal case we undefer aborts. In
1081                   --  any case this entire handling is relevant only if aborts
1082                   --  are allowed!
1083
1084                elsif Abort_Allowed then
1085
1086                   --  There are some special cases in which we do not do the
1087                   --  undefer. In particular a finalization (AT END) handler
1088                   --  wants to operate with aborts still deferred.
1089
1090                   --  We also suppress the call if this is the special handler
1091                   --  for Abort_Signal, since if we are aborting, we want to
1092                   --  keep aborts deferred (one abort is enough).
1093
1094                   --  If abort really needs to be deferred the expander must
1095                   --  add this call explicitly, see
1096                   --  Expand_N_Asynchronous_Select.
1097
1098                   Others_Choice :=
1099                     Nkind (First (Exception_Choices (Handler))) =
1100                                                          N_Others_Choice;
1101
1102                   if (Others_Choice
1103                        or else Entity (First (Exception_Choices (Handler))) /=
1104                                                          Stand.Abort_Signal)
1105                     and then not
1106                       (Others_Choice
1107                         and then
1108                           All_Others (First (Exception_Choices (Handler))))
1109                     and then Abort_Allowed
1110                   then
1111                      Prepend_Call_To_Handler (RE_Abort_Undefer);
1112                   end if;
1113                end if;
1114             end if;
1115          end if;
1116
1117          Handler := Next_Handler;
1118       end loop Handler_Loop;
1119
1120       --  If all handlers got removed, then remove the list. Note we cannot
1121       --  reference HSS here, since expanding local handlers may have buried
1122       --  the handlers in an inner block.
1123
1124       if Is_Empty_List (Handlrs) then
1125          Set_Exception_Handlers (Parent (Handlrs), No_List);
1126       end if;
1127    end Expand_Exception_Handlers;
1128
1129    ------------------------------------
1130    -- Expand_N_Exception_Declaration --
1131    ------------------------------------
1132
1133    --  Generates:
1134    --     exceptE : constant String := "A.B.EXCEP";   -- static data
1135    --     except : exception_data :=  (
1136    --                    Handled_By_Other => False,
1137    --                    Lang             => 'A',
1138    --                    Name_Length      => exceptE'Length,
1139    --                    Full_Name        => exceptE'Address,
1140    --                    HTable_Ptr       => null,
1141    --                    Import_Code      => 0,
1142    --                    Raise_Hook       => null,
1143    --                    );
1144
1145    --  (protecting test only needed if not at library level)
1146    --
1147    --     exceptF : Boolean := True --  static data
1148    --     if exceptF then
1149    --        exceptF := False;
1150    --        Register_Exception (except'Unchecked_Access);
1151    --     end if;
1152
1153    procedure Expand_N_Exception_Declaration (N : Node_Id) is
1154       Loc     : constant Source_Ptr := Sloc (N);
1155       Id      : constant Entity_Id  := Defining_Identifier (N);
1156       L       : List_Id             := New_List;
1157       Flag_Id : Entity_Id;
1158
1159       Name_Exname : constant Name_Id := New_External_Name (Chars (Id), 'E');
1160       Exname      : constant Node_Id :=
1161                       Make_Defining_Identifier (Loc, Name_Exname);
1162
1163    begin
1164       --  There is no expansion needed when compiling for the JVM since the
1165       --  JVM has a built-in exception mechanism. See 4jexcept.ads for details.
1166
1167       if VM_Target /= No_VM then
1168          return;
1169       end if;
1170
1171       --  Definition of the external name: nam : constant String := "A.B.NAME";
1172
1173       Insert_Action (N,
1174         Make_Object_Declaration (Loc,
1175           Defining_Identifier => Exname,
1176           Constant_Present    => True,
1177           Object_Definition   => New_Occurrence_Of (Standard_String, Loc),
1178           Expression => Make_String_Literal (Loc, Full_Qualified_Name (Id))));
1179
1180       Set_Is_Statically_Allocated (Exname);
1181
1182       --  Create the aggregate list for type Standard.Exception_Type:
1183       --  Handled_By_Other component: False
1184
1185       Append_To (L, New_Occurrence_Of (Standard_False, Loc));
1186
1187       --  Lang component: 'A'
1188
1189       Append_To (L,
1190         Make_Character_Literal (Loc,
1191           Chars              =>  Name_uA,
1192           Char_Literal_Value =>  UI_From_Int (Character'Pos ('A'))));
1193
1194       --  Name_Length component: Nam'Length
1195
1196       Append_To (L,
1197         Make_Attribute_Reference (Loc,
1198           Prefix         => New_Occurrence_Of (Exname, Loc),
1199           Attribute_Name => Name_Length));
1200
1201       --  Full_Name component: Standard.A_Char!(Nam'Address)
1202
1203       Append_To (L, Unchecked_Convert_To (Standard_A_Char,
1204         Make_Attribute_Reference (Loc,
1205           Prefix         => New_Occurrence_Of (Exname, Loc),
1206           Attribute_Name => Name_Address)));
1207
1208       --  HTable_Ptr component: null
1209
1210       Append_To (L, Make_Null (Loc));
1211
1212       --  Import_Code component: 0
1213
1214       Append_To (L, Make_Integer_Literal (Loc, 0));
1215
1216       --  Raise_Hook component: null
1217
1218       Append_To (L, Make_Null (Loc));
1219
1220       Set_Expression (N, Make_Aggregate (Loc, Expressions => L));
1221       Analyze_And_Resolve (Expression (N), Etype (Id));
1222
1223       --  Register_Exception (except'Unchecked_Access);
1224
1225       if not No_Exception_Handlers_Set
1226         and then not Restriction_Active (No_Exception_Registration)
1227       then
1228          L := New_List (
1229                 Make_Procedure_Call_Statement (Loc,
1230                   Name => New_Occurrence_Of (RTE (RE_Register_Exception), Loc),
1231                   Parameter_Associations => New_List (
1232                     Unchecked_Convert_To (RTE (RE_Exception_Data_Ptr),
1233                       Make_Attribute_Reference (Loc,
1234                         Prefix         => New_Occurrence_Of (Id, Loc),
1235                         Attribute_Name => Name_Unrestricted_Access)))));
1236
1237          Set_Register_Exception_Call (Id, First (L));
1238
1239          if not Is_Library_Level_Entity (Id) then
1240             Flag_Id :=  Make_Defining_Identifier (Loc,
1241                           New_External_Name (Chars (Id), 'F'));
1242
1243             Insert_Action (N,
1244               Make_Object_Declaration (Loc,
1245                 Defining_Identifier => Flag_Id,
1246                 Object_Definition   =>
1247                   New_Occurrence_Of (Standard_Boolean, Loc),
1248                 Expression          =>
1249                   New_Occurrence_Of (Standard_True, Loc)));
1250
1251             Set_Is_Statically_Allocated (Flag_Id);
1252
1253             Append_To (L,
1254               Make_Assignment_Statement (Loc,
1255                 Name       => New_Occurrence_Of (Flag_Id, Loc),
1256                 Expression => New_Occurrence_Of (Standard_False, Loc)));
1257
1258             Insert_After_And_Analyze (N,
1259               Make_Implicit_If_Statement (N,
1260                 Condition       => New_Occurrence_Of (Flag_Id, Loc),
1261                 Then_Statements => L));
1262
1263          else
1264             Insert_List_After_And_Analyze (N, L);
1265          end if;
1266       end if;
1267    end Expand_N_Exception_Declaration;
1268
1269    ---------------------------------------------
1270    -- Expand_N_Handled_Sequence_Of_Statements --
1271    ---------------------------------------------
1272
1273    procedure Expand_N_Handled_Sequence_Of_Statements (N : Node_Id) is
1274    begin
1275       --  Expand exception handlers
1276
1277       if Present (Exception_Handlers (N))
1278         and then not Restriction_Active (No_Exception_Handlers)
1279       then
1280          Expand_Exception_Handlers (N);
1281       end if;
1282
1283       --  If local exceptions are being expanded, the previous call will
1284       --  have rewritten the construct as a block and reanalyzed it. No
1285       --  further expansion is needed.
1286
1287       if Analyzed (N) then
1288          return;
1289       end if;
1290
1291       --  Add clean up actions if required
1292
1293       if Nkind (Parent (N)) /= N_Package_Body
1294         and then Nkind (Parent (N)) /= N_Accept_Statement
1295         and then Nkind (Parent (N)) /= N_Extended_Return_Statement
1296         and then not Delay_Cleanups (Current_Scope)
1297       then
1298          Expand_Cleanup_Actions (Parent (N));
1299       else
1300          Set_First_Real_Statement (N, First (Statements (N)));
1301       end if;
1302    end Expand_N_Handled_Sequence_Of_Statements;
1303
1304    -------------------------------------
1305    -- Expand_N_Raise_Constraint_Error --
1306    -------------------------------------
1307
1308    procedure Expand_N_Raise_Constraint_Error (N : Node_Id) is
1309    begin
1310       --  We adjust the condition to deal with the C/Fortran boolean case. This
1311       --  may well not be necessary, as all such conditions are generated by
1312       --  the expander and probably are all standard boolean, but who knows
1313       --  what strange optimization in future may require this adjustment!
1314
1315       Adjust_Condition (Condition (N));
1316
1317       --  Now deal with possible local raise handling
1318
1319       Possible_Local_Raise (N, Standard_Constraint_Error);
1320    end Expand_N_Raise_Constraint_Error;
1321
1322    ----------------------------------
1323    -- Expand_N_Raise_Program_Error --
1324    ----------------------------------
1325
1326    procedure Expand_N_Raise_Program_Error (N : Node_Id) is
1327    begin
1328       --  We adjust the condition to deal with the C/Fortran boolean case. This
1329       --  may well not be necessary, as all such conditions are generated by
1330       --  the expander and probably are all standard boolean, but who knows
1331       --  what strange optimization in future may require this adjustment!
1332
1333       Adjust_Condition (Condition (N));
1334
1335       --  Now deal with possible local raise handling
1336
1337       Possible_Local_Raise (N, Standard_Program_Error);
1338    end Expand_N_Raise_Program_Error;
1339
1340    ------------------------------
1341    -- Expand_N_Raise_Statement --
1342    ------------------------------
1343
1344    procedure Expand_N_Raise_Statement (N : Node_Id) is
1345       Loc   : constant Source_Ptr := Sloc (N);
1346       Ehand : Node_Id;
1347       E     : Entity_Id;
1348       Str   : String_Id;
1349       H     : Node_Id;
1350
1351    begin
1352       --  Processing for locally handled exception (exclude reraise case)
1353
1354       if Present (Name (N)) and then Nkind (Name (N)) = N_Identifier then
1355          if Debug_Flag_Dot_G
1356            or else Restriction_Active (No_Exception_Propagation)
1357          then
1358             --  If we have a local handler, then note that this is potentially
1359             --  able to be transformed into a goto statement.
1360
1361             H := Find_Local_Handler (Entity (Name (N)), N);
1362
1363             if Present (H) then
1364                if Local_Raise_Statements (H) = No_Elist then
1365                   Set_Local_Raise_Statements (H, New_Elmt_List);
1366                end if;
1367
1368                --  Append the new entry if it is not there already. Sometimes
1369                --  we have situations where due to reexpansion, the same node
1370                --  is analyzed twice and would otherwise be added twice.
1371
1372                Append_Unique_Elmt (N, Local_Raise_Statements (H));
1373                Set_Has_Local_Raise (H);
1374
1375             --  If no local handler, then generate no propagation warning
1376
1377             else
1378                Warn_If_No_Propagation (N);
1379             end if;
1380
1381          end if;
1382       end if;
1383
1384       --  If a string expression is present, then the raise statement is
1385       --  converted to a call:
1386
1387       --     Raise_Exception (exception-name'Identity, string);
1388
1389       --  and there is nothing else to do
1390
1391       if Present (Expression (N)) then
1392          Rewrite (N,
1393            Make_Procedure_Call_Statement (Loc,
1394              Name => New_Occurrence_Of (RTE (RE_Raise_Exception), Loc),
1395              Parameter_Associations => New_List (
1396                Make_Attribute_Reference (Loc,
1397                  Prefix => Name (N),
1398                  Attribute_Name => Name_Identity),
1399                Expression (N))));
1400          Analyze (N);
1401          return;
1402       end if;
1403
1404       --  Remaining processing is for the case where no string expression
1405       --  is present.
1406
1407       --  There is no expansion needed for statement "raise <exception>;" when
1408       --  compiling for the JVM since the JVM has a built-in exception
1409       --  mechanism. However we need to keep the expansion for "raise;"
1410       --  statements. See 4jexcept.ads for details.
1411
1412       if Present (Name (N)) and then VM_Target /= No_VM then
1413          return;
1414       end if;
1415
1416       --  Don't expand a raise statement that does not come from source
1417       --  if we have already had configurable run-time violations, since
1418       --  most likely it will be junk cascaded nonsense.
1419
1420       if Configurable_Run_Time_Violations > 0
1421         and then not Comes_From_Source (N)
1422       then
1423          return;
1424       end if;
1425
1426       --  Convert explicit raise of Program_Error, Constraint_Error, and
1427       --  Storage_Error into the corresponding raise (in High_Integrity_Mode
1428       --  all other raises will get normal expansion and be disallowed,
1429       --  but this is also faster in all modes).
1430
1431       if Present (Name (N)) and then Nkind (Name (N)) = N_Identifier then
1432          if Entity (Name (N)) = Standard_Constraint_Error then
1433             Rewrite (N,
1434               Make_Raise_Constraint_Error (Loc,
1435                 Reason => CE_Explicit_Raise));
1436             Analyze (N);
1437             return;
1438
1439          elsif Entity (Name (N)) = Standard_Program_Error then
1440             Rewrite (N,
1441               Make_Raise_Program_Error (Loc,
1442                 Reason => PE_Explicit_Raise));
1443             Analyze (N);
1444             return;
1445
1446          elsif Entity (Name (N)) = Standard_Storage_Error then
1447             Rewrite (N,
1448               Make_Raise_Storage_Error (Loc,
1449                 Reason => SE_Explicit_Raise));
1450             Analyze (N);
1451             return;
1452          end if;
1453       end if;
1454
1455       --  Case of name present, in this case we expand raise name to
1456
1457       --    Raise_Exception (name'Identity, location_string);
1458
1459       --  where location_string identifies the file/line of the raise
1460
1461       if Present (Name (N)) then
1462          declare
1463             Id : Entity_Id := Entity (Name (N));
1464
1465          begin
1466             Name_Len := 0;
1467             Build_Location_String (Loc);
1468
1469             --  If the exception is a renaming, use the exception that it
1470             --  renames (which might be a predefined exception, e.g.).
1471
1472             if Present (Renamed_Object (Id)) then
1473                Id := Renamed_Object (Id);
1474             end if;
1475
1476             --  Build a C-compatible string in case of no exception handlers,
1477             --  since this is what the last chance handler is expecting.
1478
1479             if No_Exception_Handlers_Set then
1480
1481                --  Generate an empty message if configuration pragma
1482                --  Suppress_Exception_Locations is set for this unit.
1483
1484                if Opt.Exception_Locations_Suppressed then
1485                   Name_Len := 1;
1486                else
1487                   Name_Len := Name_Len + 1;
1488                end if;
1489
1490                Name_Buffer (Name_Len) := ASCII.NUL;
1491             end if;
1492
1493             if Opt.Exception_Locations_Suppressed then
1494                Name_Len := 0;
1495             end if;
1496
1497             Str := String_From_Name_Buffer;
1498
1499             --  For VMS exceptions, convert the raise into a call to
1500             --  lib$stop so it will be handled by __gnat_error_handler.
1501
1502             if Is_VMS_Exception (Id) then
1503                declare
1504                   Excep_Image : String_Id;
1505                   Cond        : Node_Id;
1506
1507                begin
1508                   if Present (Interface_Name (Id)) then
1509                      Excep_Image := Strval (Interface_Name (Id));
1510                   else
1511                      Get_Name_String (Chars (Id));
1512                      Set_All_Upper_Case;
1513                      Excep_Image := String_From_Name_Buffer;
1514                   end if;
1515
1516                   if Exception_Code (Id) /= No_Uint then
1517                      Cond :=
1518                        Make_Integer_Literal (Loc, Exception_Code (Id));
1519                   else
1520                      Cond :=
1521                        Unchecked_Convert_To (Standard_Integer,
1522                          Make_Function_Call (Loc,
1523                            Name => New_Occurrence_Of
1524                              (RTE (RE_Import_Value), Loc),
1525                            Parameter_Associations => New_List
1526                              (Make_String_Literal (Loc,
1527                                Strval => Excep_Image))));
1528                   end if;
1529
1530                   Rewrite (N,
1531                     Make_Procedure_Call_Statement (Loc,
1532                       Name =>
1533                         New_Occurrence_Of (RTE (RE_Lib_Stop), Loc),
1534                       Parameter_Associations => New_List (Cond)));
1535                         Analyze_And_Resolve (Cond, Standard_Integer);
1536                end;
1537
1538             --  Not VMS exception case, convert raise to call to the
1539             --  Raise_Exception routine.
1540
1541             else
1542                Rewrite (N,
1543                  Make_Procedure_Call_Statement (Loc,
1544                     Name => New_Occurrence_Of (RTE (RE_Raise_Exception), Loc),
1545                     Parameter_Associations => New_List (
1546                       Make_Attribute_Reference (Loc,
1547                         Prefix => Name (N),
1548                         Attribute_Name => Name_Identity),
1549                       Make_String_Literal (Loc,
1550                         Strval => Str))));
1551             end if;
1552          end;
1553
1554       --  Case of no name present (reraise). We rewrite the raise to:
1555
1556       --    Reraise_Occurrence_Always (EO);
1557
1558       --  where EO is the current exception occurrence. If the current handler
1559       --  does not have a choice parameter specification, then we provide one.
1560
1561       else
1562          --  Find innermost enclosing exception handler (there must be one,
1563          --  since the semantics has already verified that this raise statement
1564          --  is valid, and a raise with no arguments is only permitted in the
1565          --  context of an exception handler.
1566
1567          Ehand := Parent (N);
1568          while Nkind (Ehand) /= N_Exception_Handler loop
1569             Ehand := Parent (Ehand);
1570          end loop;
1571
1572          --  Make exception choice parameter if none present. Note that we do
1573          --  not need to put the entity on the entity chain, since no one will
1574          --  be referencing this entity by normal visibility methods.
1575
1576          if No (Choice_Parameter (Ehand)) then
1577             E := Make_Defining_Identifier (Loc, New_Internal_Name ('E'));
1578             Set_Choice_Parameter (Ehand, E);
1579             Set_Ekind (E, E_Variable);
1580             Set_Etype (E, RTE (RE_Exception_Occurrence));
1581             Set_Scope (E, Current_Scope);
1582          end if;
1583
1584          --  Now rewrite the raise as a call to Reraise. A special case arises
1585          --  if this raise statement occurs in the context of a handler for
1586          --  all others (i.e. an at end handler). in this case we avoid
1587          --  the call to defer abort, cleanup routines are expected to be
1588          --  called in this case with aborts deferred.
1589
1590          declare
1591             Ech : constant Node_Id := First (Exception_Choices (Ehand));
1592             Ent : Entity_Id;
1593
1594          begin
1595             if Nkind (Ech) = N_Others_Choice
1596               and then All_Others (Ech)
1597             then
1598                Ent := RTE (RE_Reraise_Occurrence_No_Defer);
1599             else
1600                Ent := RTE (RE_Reraise_Occurrence_Always);
1601             end if;
1602
1603             Rewrite (N,
1604               Make_Procedure_Call_Statement (Loc,
1605                 Name => New_Occurrence_Of (Ent, Loc),
1606                 Parameter_Associations => New_List (
1607                   New_Occurrence_Of (Choice_Parameter (Ehand), Loc))));
1608          end;
1609       end if;
1610
1611       Analyze (N);
1612    end Expand_N_Raise_Statement;
1613
1614    ----------------------------------
1615    -- Expand_N_Raise_Storage_Error --
1616    ----------------------------------
1617
1618    procedure Expand_N_Raise_Storage_Error (N : Node_Id) is
1619    begin
1620       --  We adjust the condition to deal with the C/Fortran boolean case. This
1621       --  may well not be necessary, as all such conditions are generated by
1622       --  the expander and probably are all standard boolean, but who knows
1623       --  what strange optimization in future may require this adjustment!
1624
1625       Adjust_Condition (Condition (N));
1626
1627       --  Now deal with possible local raise handling
1628
1629       Possible_Local_Raise (N, Standard_Storage_Error);
1630    end Expand_N_Raise_Storage_Error;
1631
1632    --------------------------
1633    -- Possible_Local_Raise --
1634    --------------------------
1635
1636    procedure Possible_Local_Raise (N : Node_Id; E : Entity_Id) is
1637    begin
1638       --  Nothing to do if local raise optimization not active
1639
1640       if not Debug_Flag_Dot_G
1641         and then not Restriction_Active (No_Exception_Propagation)
1642       then
1643          return;
1644       end if;
1645
1646       --  Nothing to do if original node was an explicit raise, because in
1647       --  that case, we already generated the required warning for the raise.
1648
1649       if Nkind (Original_Node (N)) = N_Raise_Statement then
1650          return;
1651       end if;
1652
1653       --  Otherwise see if we have a local handler for the exception
1654
1655       declare
1656          H : constant Node_Id := Find_Local_Handler (E, N);
1657
1658       begin
1659          --  If so, mark that it has a local raise
1660
1661          if Present (H) then
1662             Set_Has_Local_Raise (H, True);
1663
1664          --  Otherwise, if the No_Exception_Propagation restriction is active
1665          --  and the warning is enabled, generate the appropriate warnings.
1666
1667          elsif Warn_On_Non_Local_Exception
1668            and then Restriction_Active (No_Exception_Propagation)
1669          then
1670             Warn_No_Exception_Propagation_Active (N);
1671
1672             if Configurable_Run_Time_Mode then
1673                Error_Msg_NE
1674                  ("\?& may call Last_Chance_Handler", N, E);
1675             else
1676                Error_Msg_NE
1677                  ("\?& may result in unhandled exception", N, E);
1678             end if;
1679          end if;
1680       end;
1681    end Possible_Local_Raise;
1682
1683    ------------------------------
1684    -- Expand_N_Subprogram_Info --
1685    ------------------------------
1686
1687    procedure Expand_N_Subprogram_Info (N : Node_Id) is
1688       Loc : constant Source_Ptr := Sloc (N);
1689
1690    begin
1691       --  For now, we replace an Expand_N_Subprogram_Info node with an
1692       --  attribute reference that gives the address of the procedure.
1693       --  This is because gigi does not yet recognize this node, and
1694       --  for the initial targets, this is the right value anyway.
1695
1696       Rewrite (N,
1697         Make_Attribute_Reference (Loc,
1698           Prefix => Identifier (N),
1699           Attribute_Name => Name_Code_Address));
1700
1701       Analyze_And_Resolve (N, RTE (RE_Code_Loc));
1702    end Expand_N_Subprogram_Info;
1703
1704    ------------------------
1705    -- Find_Local_Handler --
1706    ------------------------
1707
1708    function Find_Local_Handler
1709      (Ename : Entity_Id;
1710       Nod   : Node_Id) return Node_Id
1711    is
1712       N : Node_Id;
1713       P : Node_Id;
1714       H : Node_Id;
1715       C : Node_Id;
1716
1717       SSE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
1718       --  This is used to test for wrapped actions below
1719
1720       ERaise  : Entity_Id;
1721       EHandle : Entity_Id;
1722       --  The entity Id's for the exception we are raising and handling, using
1723       --  the renamed exception if a Renamed_Entity is present.
1724
1725    begin
1726       --  Never any local handler if all handlers removed
1727
1728       if Debug_Flag_Dot_X then
1729          return Empty;
1730       end if;
1731
1732       --  Get the exception we are raising, allowing for renaming
1733
1734       ERaise := Get_Renamed_Entity (Ename);
1735
1736       --  We need to check if the node we are looking at is contained in
1737       --
1738
1739       --  Loop to search up the tree
1740
1741       N := Nod;
1742       loop
1743          P := Parent (N);
1744
1745          --  If we get to the top of the tree, or to a subprogram, task, entry,
1746          --  protected body, or accept statement without having found a
1747          --  matching handler, then there is no local handler.
1748
1749          if No (P)
1750            or else Nkind (P) = N_Subprogram_Body
1751            or else Nkind (P) = N_Task_Body
1752            or else Nkind (P) = N_Protected_Body
1753            or else Nkind (P) = N_Entry_Body
1754            or else Nkind (P) = N_Accept_Statement
1755          then
1756             return Empty;
1757
1758             --  Test for handled sequence of statements with at least one
1759             --  exception handler which might be the one we are looking for.
1760
1761          elsif Nkind (P) = N_Handled_Sequence_Of_Statements
1762            and then Present (Exception_Handlers (P))
1763          then
1764             --  Before we proceed we need to check if the node N is covered
1765             --  by the statement part of P rather than one of its exception
1766             --  handlers (an exception handler obviously does not cover its
1767             --  own statements).
1768
1769             --  This test is more delicate than might be thought. It is not
1770             --  just a matter of checking the Statements (P), because the node
1771             --  might be waiting to be wrapped in a transient scope, in which
1772             --  case it will end up in the block statements, even though it
1773             --  is not there now.
1774
1775             if Is_List_Member (N)
1776               and then (List_Containing (N) = Statements (P)
1777                           or else
1778                         List_Containing (N) = SSE.Actions_To_Be_Wrapped_Before
1779                           or else
1780                         List_Containing (N) = SSE.Actions_To_Be_Wrapped_After)
1781             then
1782                --  Loop through exception handlers
1783
1784                H := First (Exception_Handlers (P));
1785                while Present (H) loop
1786
1787                   --  Loop through choices in one handler
1788
1789                   C := First (Exception_Choices (H));
1790                   while Present (C) loop
1791
1792                      --  Deal with others case
1793
1794                      if Nkind (C) = N_Others_Choice then
1795
1796                         --  Matching others handler, but we need to ensure
1797                         --  there is no choice parameter. If there is, then we
1798                         --  don't have a local handler after all (since we do
1799                         --  not allow choice parameters for local handlers).
1800
1801                         if No (Choice_Parameter (H)) then
1802                            return H;
1803                         else
1804                            return Empty;
1805                         end if;
1806
1807                      --  If not others must be entity name
1808
1809                      elsif Nkind (C) /= N_Others_Choice then
1810                         pragma Assert (Is_Entity_Name (C));
1811                         pragma Assert (Present (Entity (C)));
1812
1813                         --  Get exception being handled, dealing with renaming
1814
1815                         EHandle := Get_Renamed_Entity (Entity (C));
1816
1817                         --  If match, then check choice parameter
1818
1819                         if ERaise = EHandle then
1820                            if No (Choice_Parameter (H)) then
1821                               return H;
1822                            else
1823                               return Empty;
1824                            end if;
1825                         end if;
1826                      end if;
1827
1828                      Next (C);
1829                   end loop;
1830
1831                   Next (H);
1832                end loop;
1833             end if;
1834          end if;
1835
1836          N := P;
1837       end loop;
1838    end Find_Local_Handler;
1839
1840    ---------------------------------
1841    -- Get_Local_Raise_Call_Entity --
1842    ---------------------------------
1843
1844    --  Note: this is primary provided for use by the back end in generating
1845    --  calls to Local_Raise. But it would be too late in the back end to call
1846    --  RTE if this actually caused a load/analyze of the unit. So what we do
1847    --  is to ensure there is a dummy call to this function during front end
1848    --  processing so that the unit gets loaded then, and not later.
1849
1850    Local_Raise_Call_Entity     : Entity_Id;
1851    Local_Raise_Call_Entity_Set : Boolean := False;
1852
1853    function Get_Local_Raise_Call_Entity return Entity_Id is
1854    begin
1855       if not Local_Raise_Call_Entity_Set then
1856          Local_Raise_Call_Entity_Set := True;
1857
1858          if RTE_Available (RE_Local_Raise) then
1859             Local_Raise_Call_Entity := RTE (RE_Local_Raise);
1860          else
1861             Local_Raise_Call_Entity := Empty;
1862          end if;
1863       end if;
1864
1865       return Local_Raise_Call_Entity;
1866    end Get_Local_Raise_Call_Entity;
1867
1868    -----------------------------
1869    -- Get_RT_Exception_Entity --
1870    -----------------------------
1871
1872    function Get_RT_Exception_Entity (R : RT_Exception_Code) return Entity_Id is
1873    begin
1874       case R is
1875          when RT_CE_Exceptions => return Standard_Constraint_Error;
1876          when RT_PE_Exceptions => return Standard_Program_Error;
1877          when RT_SE_Exceptions => return Standard_Storage_Error;
1878       end case;
1879    end Get_RT_Exception_Entity;
1880
1881    ----------------------
1882    -- Is_Non_Ada_Error --
1883    ----------------------
1884
1885    function Is_Non_Ada_Error (E : Entity_Id) return Boolean is
1886    begin
1887       if not OpenVMS_On_Target then
1888          return False;
1889       end if;
1890
1891       Get_Name_String (Chars (E));
1892
1893       --  Note: it is a little irregular for the body of exp_ch11 to know
1894       --  the details of the encoding scheme for names, but on the other
1895       --  hand, gigi knows them, and this is for gigi's benefit anyway!
1896
1897       if Name_Buffer (1 .. 30) /= "system__aux_dec__non_ada_error" then
1898          return False;
1899       end if;
1900
1901       return True;
1902    end Is_Non_Ada_Error;
1903
1904    ----------------------------
1905    -- Warn_If_No_Propagation --
1906    ----------------------------
1907
1908    procedure Warn_If_No_Propagation (N : Node_Id) is
1909    begin
1910       if Restriction_Active (No_Exception_Propagation)
1911         and then Warn_On_Non_Local_Exception
1912       then
1913          Warn_No_Exception_Propagation_Active (N);
1914
1915          if Configurable_Run_Time_Mode then
1916             Error_Msg_N
1917               ("\?Last_Chance_Handler will be called on exception", N);
1918          else
1919             Error_Msg_N
1920               ("\?execution may raise unhandled exception", N);
1921          end if;
1922       end if;
1923    end Warn_If_No_Propagation;
1924
1925    ------------------------------------------
1926    -- Warn_No_Exception_Propagation_Active --
1927    ------------------------------------------
1928
1929    procedure Warn_No_Exception_Propagation_Active (N : Node_Id) is
1930    begin
1931       Error_Msg_N
1932         ("?pragma Restrictions (No_Exception_Propagation) in effect", N);
1933    end Warn_No_Exception_Propagation_Active;
1934
1935 end Exp_Ch11;