OSDN Git Service

2006-10-31 Javier Miranda <miranda@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_intr.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ I N T R                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2006, 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 2,  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 COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Einfo;    use Einfo;
29 with Elists;   use Elists;
30 with Errout;   use Errout;
31 with Exp_Ch4;  use Exp_Ch4;
32 with Exp_Ch7;  use Exp_Ch7;
33 with Exp_Ch11; use Exp_Ch11;
34 with Exp_Code; use Exp_Code;
35 with Exp_Disp; use Exp_Disp;
36 with Exp_Fixd; use Exp_Fixd;
37 with Exp_Util; use Exp_Util;
38 with Freeze;   use Freeze;
39 with Namet;    use Namet;
40 with Nmake;    use Nmake;
41 with Nlists;   use Nlists;
42 with Restrict; use Restrict;
43 with Rtsfind;  use Rtsfind;
44 with Sem;      use Sem;
45 with Sem_Eval; use Sem_Eval;
46 with Sem_Res;  use Sem_Res;
47 with Sem_Util; use Sem_Util;
48 with Sinfo;    use Sinfo;
49 with Sinput;   use Sinput;
50 with Snames;   use Snames;
51 with Stand;    use Stand;
52 with Stringt;  use Stringt;
53 with Tbuild;   use Tbuild;
54 with Uintp;    use Uintp;
55 with Urealp;   use Urealp;
56
57 package body Exp_Intr is
58
59    -----------------------
60    -- Local Subprograms --
61    -----------------------
62
63    procedure Expand_Is_Negative (N : Node_Id);
64    --  Expand a call to the intrinsic Is_Negative function
65
66    procedure Expand_Dispatching_Constructor_Call (N : Node_Id);
67    --  Expand a call to an instantiation of Generic_Dispatching_Constructor
68    --  into a dispatching call to the actual subprogram associated with the
69    --  Constructor formal subprogram, passing it the Parameters actual of
70    --  the call to the instantiation and dispatching based on call's Tag
71    --  parameter.
72
73    procedure Expand_Exception_Call (N : Node_Id; Ent : RE_Id);
74    --  Expand a call to Exception_Information/Message/Name. The first
75    --  parameter, N, is the node for the function call, and Ent is the
76    --  entity for the corresponding routine in the Ada.Exceptions package.
77
78    procedure Expand_Import_Call (N : Node_Id);
79    --  Expand a call to Import_Address/Longest_Integer/Value. The parameter
80    --  N is the node for the function call.
81
82    procedure Expand_Shift (N : Node_Id; E : Entity_Id; K : Node_Kind);
83    --  Expand an intrinsic shift operation, N and E are from the call to
84    --  Expand_Intrinsic_Call (call node and subprogram spec entity) and
85    --  K is the kind for the shift node
86
87    procedure Expand_Unc_Conversion (N : Node_Id; E : Entity_Id);
88    --  Expand a call to an instantiation of Unchecked_Convertion into a node
89    --  N_Unchecked_Type_Conversion.
90
91    procedure Expand_Unc_Deallocation (N : Node_Id);
92    --  Expand a call to an instantiation of Unchecked_Deallocation into a node
93    --  N_Free_Statement and appropriate context.
94
95    procedure Expand_To_Address (N : Node_Id);
96    procedure Expand_To_Pointer (N : Node_Id);
97    --  Expand a call to corresponding function, declared in an instance of
98    --  System.Addess_To_Access_Conversions.
99
100    procedure Expand_Source_Info (N : Node_Id; Nam : Name_Id);
101    --  Rewrite the node by the appropriate string or positive constant.
102    --  Nam can be one of the following:
103    --    Name_File             - expand string that is the name of source file
104    --    Name_Line             - expand integer line number
105    --    Name_Source_Location  - expand string of form file:line
106    --    Name_Enclosing_Entity - expand string  with name of enclosing entity
107
108    -----------------------------------------
109    -- Expand_Dispatching_Constructor_Call --
110    -----------------------------------------
111
112    --  Transform a call to an instantiation of Generic_Dispatching_Constructor
113    --  of the form:
114
115    --     GDC_Instance (The_Tag, Parameters'Access)
116
117    --  to a class-wide conversion of a dispatching call to the actual
118    --  associated with the formal subprogram Construct, designating
119    --  The_Tag as the controlling tag of the call:
120
121    --     T'Class (Construct'Actual (Params)) -- Controlling tag is The_Tag
122
123    --  which will eventually be expanded to the following:
124
125    --     T'Class (The_Tag.all (Construct'Actual'Index).all (Params))
126
127    --  A class-wide membership test is also generated, preceding the call,
128    --  to ensure that the controlling tag denotes a type in T'Class.
129
130    procedure Expand_Dispatching_Constructor_Call (N : Node_Id) is
131       Loc        : constant Source_Ptr := Sloc (N);
132       Tag_Arg    : constant Node_Id    := First_Actual (N);
133       Param_Arg  : constant Node_Id    := Next_Actual (Tag_Arg);
134       Subp_Decl  : constant Node_Id    := Parent (Parent (Entity (Name (N))));
135       Inst_Pkg   : constant Node_Id    := Parent (Subp_Decl);
136       Act_Rename : Node_Id;
137       Act_Constr : Entity_Id;
138       Result_Typ : Entity_Id;
139       Cnstr_Call : Node_Id;
140
141    begin
142       --  The subprogram is the third actual in the instantiation, and is
143       --  retrieved from the corresponding renaming declaration. However,
144       --  freeze nodes may appear before, so we retrieve the declaration
145       --  with an explicit loop.
146
147       Act_Rename := First (Visible_Declarations (Inst_Pkg));
148       while Nkind (Act_Rename) /= N_Subprogram_Renaming_Declaration loop
149          Next (Act_Rename);
150       end loop;
151
152       Act_Constr := Entity (Name (Act_Rename));
153       Result_Typ := Class_Wide_Type (Etype (Act_Constr));
154
155       --  Create the call to the actual Constructor function
156
157       Cnstr_Call :=
158         Make_Function_Call (Loc,
159           Name                   => New_Occurrence_Of (Act_Constr, Loc),
160           Parameter_Associations => New_List (Relocate_Node (Param_Arg)));
161
162       --  Establish its controlling tag from the tag passed to the instance
163
164       Set_Controlling_Argument (Cnstr_Call, Relocate_Node (Tag_Arg));
165
166       --  Rewrite and analyze the call to the instance as a class-wide
167       --  conversion of the call to the actual constructor.
168
169       Rewrite (N, Convert_To (Result_Typ, Cnstr_Call));
170       Analyze_And_Resolve (N, Etype (Act_Constr));
171
172       --  Generate a class-wide membership test to ensure that the call's tag
173       --  argument denotes a type within the class.
174
175       Insert_Action (N,
176         Make_Implicit_If_Statement (N,
177           Condition =>
178             Make_Op_Not (Loc,
179               Make_DT_Access_Action (Result_Typ,
180                  Action => CW_Membership,
181                  Args   => New_List (
182                    Duplicate_Subexpr (Tag_Arg),
183                    New_Reference_To (
184                      Node (First_Elmt (Access_Disp_Table (
185                                          Root_Type (Result_Typ)))), Loc)))),
186           Then_Statements =>
187             New_List (Make_Raise_Statement (Loc,
188                         New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
189    end Expand_Dispatching_Constructor_Call;
190
191    ---------------------------
192    -- Expand_Exception_Call --
193    ---------------------------
194
195    --  If the function call is not within an exception handler, then the
196    --  call is replaced by a null string. Otherwise the appropriate routine
197    --  in Ada.Exceptions is called passing the choice parameter specification
198    --  from the enclosing handler. If the enclosing handler lacks a choice
199    --  parameter, then one is supplied.
200
201    procedure Expand_Exception_Call (N : Node_Id; Ent : RE_Id) is
202       Loc : constant Source_Ptr := Sloc (N);
203       P   : Node_Id;
204       E   : Entity_Id;
205
206    begin
207       --  Climb up parents to see if we are in exception handler
208
209       P := Parent (N);
210       loop
211          --  Case of not in exception handler, replace by null string
212
213          if No (P) then
214             Rewrite (N,
215               Make_String_Literal (Loc,
216                 Strval => ""));
217             exit;
218
219          --  Case of in exception handler
220
221          elsif Nkind (P) = N_Exception_Handler then
222             if No (Choice_Parameter (P)) then
223
224                --  If no choice parameter present, then put one there. Note
225                --  that we do not need to put it on the entity chain, since
226                --  no one will be referencing it by normal visibility methods.
227
228                E := Make_Defining_Identifier (Loc, New_Internal_Name ('E'));
229                Set_Choice_Parameter (P, E);
230                Set_Ekind (E, E_Variable);
231                Set_Etype (E, RTE (RE_Exception_Occurrence));
232                Set_Scope (E, Current_Scope);
233             end if;
234
235             Rewrite (N,
236               Make_Function_Call (Loc,
237                 Name => New_Occurrence_Of (RTE (Ent), Loc),
238                 Parameter_Associations => New_List (
239                   New_Occurrence_Of (Choice_Parameter (P), Loc))));
240             exit;
241
242          --  Keep climbing!
243
244          else
245             P := Parent (P);
246          end if;
247       end loop;
248
249       Analyze_And_Resolve (N, Standard_String);
250    end Expand_Exception_Call;
251
252    ------------------------
253    -- Expand_Import_Call --
254    ------------------------
255
256    --  The function call must have a static string as its argument. We create
257    --  a dummy variable which uses this string as the external name in an
258    --  Import pragma. The result is then obtained as the address of this
259    --  dummy variable, converted to the appropriate target type.
260
261    procedure Expand_Import_Call (N : Node_Id) is
262       Loc : constant Source_Ptr := Sloc (N);
263       Ent : constant Entity_Id  := Entity (Name (N));
264       Str : constant Node_Id    := First_Actual (N);
265       Dum : Entity_Id;
266
267    begin
268       Dum := Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
269
270       Insert_Actions (N, New_List (
271         Make_Object_Declaration (Loc,
272           Defining_Identifier => Dum,
273           Object_Definition   =>
274             New_Occurrence_Of (Standard_Character, Loc)),
275
276         Make_Pragma (Loc,
277           Chars => Name_Import,
278           Pragma_Argument_Associations => New_List (
279             Make_Pragma_Argument_Association (Loc,
280               Expression => Make_Identifier (Loc, Name_Ada)),
281
282             Make_Pragma_Argument_Association (Loc,
283               Expression => Make_Identifier (Loc, Chars (Dum))),
284
285             Make_Pragma_Argument_Association (Loc,
286               Chars => Name_Link_Name,
287               Expression => Relocate_Node (Str))))));
288
289       Rewrite (N,
290         Unchecked_Convert_To (Etype (Ent),
291           Make_Attribute_Reference (Loc,
292             Attribute_Name => Name_Address,
293             Prefix => Make_Identifier (Loc, Chars (Dum)))));
294
295       Analyze_And_Resolve (N, Etype (Ent));
296    end Expand_Import_Call;
297
298    ---------------------------
299    -- Expand_Intrinsic_Call --
300    ---------------------------
301
302    procedure Expand_Intrinsic_Call (N : Node_Id; E : Entity_Id) is
303       Nam : Name_Id;
304
305    begin
306       --  If the intrinsic subprogram is generic, gets its original name
307
308       if Present (Parent (E))
309         and then Present (Generic_Parent (Parent (E)))
310       then
311          Nam := Chars (Generic_Parent (Parent (E)));
312       else
313          Nam := Chars (E);
314       end if;
315
316       if Nam = Name_Asm then
317          Expand_Asm_Call (N);
318
319       elsif Nam = Name_Divide then
320          Expand_Decimal_Divide_Call (N);
321
322       elsif Nam = Name_Exception_Information then
323          Expand_Exception_Call (N, RE_Exception_Information);
324
325       elsif Nam = Name_Exception_Message then
326          Expand_Exception_Call (N, RE_Exception_Message);
327
328       elsif Nam = Name_Exception_Name then
329          Expand_Exception_Call (N, RE_Exception_Name_Simple);
330
331       elsif Nam = Name_Generic_Dispatching_Constructor then
332          Expand_Dispatching_Constructor_Call (N);
333
334       elsif Nam = Name_Import_Address
335               or else
336             Nam = Name_Import_Largest_Value
337               or else
338             Nam = Name_Import_Value
339       then
340          Expand_Import_Call (N);
341
342       elsif Nam = Name_Is_Negative then
343          Expand_Is_Negative (N);
344
345       elsif Nam = Name_Rotate_Left then
346          Expand_Shift (N, E, N_Op_Rotate_Left);
347
348       elsif Nam = Name_Rotate_Right then
349          Expand_Shift (N, E, N_Op_Rotate_Right);
350
351       elsif Nam = Name_Shift_Left then
352          Expand_Shift (N, E, N_Op_Shift_Left);
353
354       elsif Nam = Name_Shift_Right then
355          Expand_Shift (N, E, N_Op_Shift_Right);
356
357       elsif Nam = Name_Shift_Right_Arithmetic then
358          Expand_Shift (N, E, N_Op_Shift_Right_Arithmetic);
359
360       elsif Nam = Name_Unchecked_Conversion then
361          Expand_Unc_Conversion (N, E);
362
363       elsif Nam = Name_Unchecked_Deallocation then
364          Expand_Unc_Deallocation (N);
365
366       elsif Nam = Name_To_Address then
367          Expand_To_Address (N);
368
369       elsif Nam = Name_To_Pointer then
370          Expand_To_Pointer (N);
371
372       elsif Nam = Name_File
373         or else Nam = Name_Line
374         or else Nam = Name_Source_Location
375         or else Nam = Name_Enclosing_Entity
376       then
377          Expand_Source_Info (N, Nam);
378
379          --  If we have a renaming, expand the call to the original operation,
380          --  which must itself be intrinsic, since renaming requires matching
381          --  conventions and this has already been checked.
382
383       elsif Present (Alias (E)) then
384          Expand_Intrinsic_Call (N,  Alias (E));
385
386          --  The only other case is where an external name was specified,
387          --  since this is the only way that an otherwise unrecognized
388          --  name could escape the checking in Sem_Prag. Nothing needs
389          --  to be done in such a case, since we pass such a call to the
390          --  back end unchanged.
391
392       else
393          null;
394       end if;
395    end Expand_Intrinsic_Call;
396
397    ------------------------
398    -- Expand_Is_Negative --
399    ------------------------
400
401    procedure Expand_Is_Negative (N : Node_Id) is
402       Loc   : constant Source_Ptr := Sloc (N);
403       Opnd  : constant Node_Id    := Relocate_Node (First_Actual (N));
404
405    begin
406
407       --  We replace the function call by the following expression
408
409       --    if Opnd < 0.0 then
410       --       True
411       --    else
412       --       if Opnd > 0.0 then
413       --          False;
414       --       else
415       --          Float_Unsigned!(Float (Opnd)) /= 0
416       --       end if;
417       --    end if;
418
419       Rewrite (N,
420         Make_Conditional_Expression (Loc,
421           Expressions => New_List (
422             Make_Op_Lt (Loc,
423               Left_Opnd  => Duplicate_Subexpr (Opnd),
424               Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
425
426             New_Occurrence_Of (Standard_True, Loc),
427
428             Make_Conditional_Expression (Loc,
429              Expressions => New_List (
430                Make_Op_Gt (Loc,
431                  Left_Opnd  => Duplicate_Subexpr_No_Checks (Opnd),
432                  Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
433
434                New_Occurrence_Of (Standard_False, Loc),
435
436                 Make_Op_Ne (Loc,
437                   Left_Opnd =>
438                     Unchecked_Convert_To
439                       (RTE (RE_Float_Unsigned),
440                        Convert_To
441                          (Standard_Float,
442                           Duplicate_Subexpr_No_Checks (Opnd))),
443                   Right_Opnd =>
444                     Make_Integer_Literal (Loc, 0)))))));
445
446       Analyze_And_Resolve (N, Standard_Boolean);
447    end Expand_Is_Negative;
448
449    ------------------
450    -- Expand_Shift --
451    ------------------
452
453    --  This procedure is used to convert a call to a shift function to the
454    --  corresponding operator node. This conversion is not done by the usual
455    --  circuit for converting calls to operator functions (e.g. "+"(1,2)) to
456    --  operator nodes, because shifts are not predefined operators.
457
458    --  As a result, whenever a shift is used in the source program, it will
459    --  remain as a call until converted by this routine to the operator node
460    --  form which Gigi is expecting to see.
461
462    --  Note: it is possible for the expander to generate shift operator nodes
463    --  directly, which will be analyzed in the normal manner by calling Analyze
464    --  and Resolve. Such shift operator nodes will not be seen by Expand_Shift.
465
466    procedure Expand_Shift (N : Node_Id; E : Entity_Id; K : Node_Kind) is
467       Loc   : constant Source_Ptr := Sloc (N);
468       Typ   : constant Entity_Id  := Etype (N);
469       Left  : constant Node_Id    := First_Actual (N);
470       Right : constant Node_Id    := Next_Actual (Left);
471       Ltyp  : constant Node_Id    := Etype (Left);
472       Rtyp  : constant Node_Id    := Etype (Right);
473       Snode : Node_Id;
474
475    begin
476       Snode := New_Node (K, Loc);
477       Set_Left_Opnd  (Snode, Relocate_Node (Left));
478       Set_Right_Opnd (Snode, Relocate_Node (Right));
479       Set_Chars      (Snode, Chars (E));
480       Set_Etype      (Snode, Base_Type (Typ));
481       Set_Entity     (Snode, E);
482
483       if Compile_Time_Known_Value (Type_High_Bound (Rtyp))
484         and then Expr_Value (Type_High_Bound (Rtyp)) < Esize (Ltyp)
485       then
486          Set_Shift_Count_OK (Snode, True);
487       end if;
488
489       --  Do the rewrite. Note that we don't call Analyze and Resolve on
490       --  this node, because it already got analyzed and resolved when
491       --  it was a function call!
492
493       Rewrite (N, Snode);
494       Set_Analyzed (N);
495    end Expand_Shift;
496
497    ------------------------
498    -- Expand_Source_Info --
499    ------------------------
500
501    procedure Expand_Source_Info (N : Node_Id; Nam : Name_Id) is
502       Loc : constant Source_Ptr := Sloc (N);
503       Ent : Entity_Id;
504
505       procedure Write_Entity_Name (E : Entity_Id);
506       --  Recursive procedure to construct string for qualified name of
507       --  enclosing program unit. The qualification stops at an enclosing
508       --  scope has no source name (block or loop). If entity is a subprogram
509       --  instance, skip enclosing wrapper package.
510
511       -----------------------
512       -- Write_Entity_Name --
513       -----------------------
514
515       procedure Write_Entity_Name (E : Entity_Id) is
516          SDef : Source_Ptr;
517          TDef : constant Source_Buffer_Ptr :=
518                   Source_Text (Get_Source_File_Index (Sloc (E)));
519
520       begin
521          --  Nothing to do if at outer level
522
523          if Scope (E) = Standard_Standard then
524             null;
525
526          --  If scope comes from source, write its name
527
528          elsif Comes_From_Source (Scope (E)) then
529             Write_Entity_Name (Scope (E));
530             Add_Char_To_Name_Buffer ('.');
531
532          --  If in wrapper package skip past it
533
534          elsif Is_Wrapper_Package (Scope (E)) then
535             Write_Entity_Name (Scope (Scope (E)));
536             Add_Char_To_Name_Buffer ('.');
537
538          --  Otherwise nothing to output (happens in unnamed block statements)
539
540          else
541             null;
542          end if;
543
544          --  Loop to output the name
545
546          --  is this right wrt wide char encodings ??? (no!)
547
548          SDef := Sloc (E);
549          while TDef (SDef) in '0' .. '9'
550            or else TDef (SDef) >= 'A'
551            or else TDef (SDef) = ASCII.ESC
552          loop
553             Add_Char_To_Name_Buffer (TDef (SDef));
554             SDef := SDef + 1;
555          end loop;
556       end Write_Entity_Name;
557
558    --  Start of processing for Expand_Source_Info
559
560    begin
561       --  Integer cases
562
563       if Nam = Name_Line then
564          Rewrite (N,
565            Make_Integer_Literal (Loc,
566              Intval => UI_From_Int (Int (Get_Logical_Line_Number (Loc)))));
567          Analyze_And_Resolve (N, Standard_Positive);
568
569       --  String cases
570
571       else
572          case Nam is
573             when Name_File =>
574                Get_Decoded_Name_String
575                  (Reference_Name (Get_Source_File_Index (Loc)));
576
577             when Name_Source_Location =>
578                Build_Location_String (Loc);
579
580             when Name_Enclosing_Entity =>
581                Name_Len := 0;
582
583                Ent := Current_Scope;
584
585                --  Skip enclosing blocks to reach enclosing unit
586
587                while Present (Ent) loop
588                   exit when Ekind (Ent) /= E_Block
589                     and then Ekind (Ent) /= E_Loop;
590                   Ent := Scope (Ent);
591                end loop;
592
593                --  Ent now points to the relevant defining entity
594
595                Name_Len := 0;
596                Write_Entity_Name (Ent);
597
598             when others =>
599                raise Program_Error;
600          end case;
601
602          Rewrite (N,
603            Make_String_Literal (Loc, Strval => String_From_Name_Buffer));
604          Analyze_And_Resolve (N, Standard_String);
605       end if;
606
607       Set_Is_Static_Expression (N);
608    end Expand_Source_Info;
609
610    ---------------------------
611    -- Expand_Unc_Conversion --
612    ---------------------------
613
614    procedure Expand_Unc_Conversion (N : Node_Id; E : Entity_Id) is
615       Func : constant Entity_Id  := Entity (Name (N));
616       Conv : Node_Id;
617       Ftyp : Entity_Id;
618       Ttyp : Entity_Id;
619
620    begin
621       --  Rewrite as unchecked conversion node. Note that we must convert
622       --  the operand to the formal type of the input parameter of the
623       --  function, so that the resulting N_Unchecked_Type_Conversion
624       --  call indicates the correct types for Gigi.
625
626       --  Right now, we only do this if a scalar type is involved. It is
627       --  not clear if it is needed in other cases. If we do attempt to
628       --  do the conversion unconditionally, it crashes 3411-018. To be
629       --  investigated further ???
630
631       Conv := Relocate_Node (First_Actual (N));
632       Ftyp := Etype (First_Formal (Func));
633
634       if Is_Scalar_Type (Ftyp) then
635          Conv := Convert_To (Ftyp, Conv);
636          Set_Parent (Conv, N);
637          Analyze_And_Resolve (Conv);
638       end if;
639
640       --  The instantiation of Unchecked_Conversion creates a wrapper package,
641       --  and the target type is declared as a subtype of the actual. Recover
642       --  the actual, which is the subtype indic. in the subtype declaration
643       --  for the target type. This is semantically correct, and avoids
644       --  anomalies with access subtypes. For entities, leave type as is.
645
646       --  We do the analysis here, because we do not want the compiler
647       --  to try to optimize or otherwise reorganize the unchecked
648       --  conversion node.
649
650       Ttyp := Etype (E);
651
652       if Is_Entity_Name (Conv) then
653          null;
654
655       elsif Nkind (Parent (Ttyp)) = N_Subtype_Declaration then
656          Ttyp := Entity (Subtype_Indication (Parent (Etype (E))));
657
658       elsif Is_Itype (Ttyp) then
659          Ttyp :=
660            Entity (Subtype_Indication (Associated_Node_For_Itype (Ttyp)));
661       else
662          raise Program_Error;
663       end if;
664
665       Rewrite (N, Unchecked_Convert_To (Ttyp, Conv));
666       Set_Etype (N, Ttyp);
667       Set_Analyzed (N);
668
669       if Nkind (N) = N_Unchecked_Type_Conversion then
670          Expand_N_Unchecked_Type_Conversion (N);
671       end if;
672    end Expand_Unc_Conversion;
673
674    -----------------------------
675    -- Expand_Unc_Deallocation --
676    -----------------------------
677
678    --  Generate the following Code :
679
680    --    if Arg /= null then
681    --     <Finalize_Call> (.., T'Class(Arg.all), ..);  -- for controlled types
682    --       Free (Arg);
683    --       Arg := Null;
684    --    end if;
685
686    --  For a task, we also generate a call to Free_Task to ensure that the
687    --  task itself is freed if it is terminated, ditto for a simple protected
688    --  object, with a call to Finalize_Protection. For composite types that
689    --  have tasks or simple protected objects as components, we traverse the
690    --  structures to find and terminate those components.
691
692    procedure Expand_Unc_Deallocation (N : Node_Id) is
693       Loc   : constant Source_Ptr := Sloc (N);
694       Arg   : constant Node_Id    := First_Actual (N);
695       Typ   : constant Entity_Id  := Etype (Arg);
696       Stmts : constant List_Id    := New_List;
697       Rtyp  : constant Entity_Id  := Underlying_Type (Root_Type (Typ));
698       Pool  : constant Entity_Id  := Associated_Storage_Pool (Rtyp);
699
700       Desig_T   : constant Entity_Id  := Designated_Type (Typ);
701       Gen_Code  : Node_Id;
702       Free_Node : Node_Id;
703       Deref     : Node_Id;
704       Free_Arg  : Node_Id;
705       Free_Cod  : List_Id;
706       Blk       : Node_Id;
707
708       Arg_Known_Non_Null : constant Boolean := Known_Non_Null (N);
709       --  This captures whether we know the argument to be non-null so that
710       --  we can avoid the test. The reason that we need to capture this is
711       --  that we analyze some generated statements before properly attaching
712       --  them to the tree, and that can disturb current value settings.
713
714    begin
715       if No_Pool_Assigned (Rtyp) then
716          Error_Msg_N ("?deallocation from empty storage pool", N);
717       end if;
718
719       --  Nothing to do if we know the argument is null
720
721       if Known_Null (N) then
722          return;
723       end if;
724
725       --  Processing for pointer to controlled type
726
727       if Controlled_Type (Desig_T) then
728          Deref :=
729            Make_Explicit_Dereference (Loc,
730              Prefix => Duplicate_Subexpr_No_Checks (Arg));
731
732          --  If the type is tagged, then we must force dispatching on the
733          --  finalization call because the designated type may not be the
734          --  actual type of the object.
735
736          if Is_Tagged_Type (Desig_T)
737            and then not Is_Class_Wide_Type (Desig_T)
738          then
739             Deref := Unchecked_Convert_To (Class_Wide_Type (Desig_T), Deref);
740
741          elsif not Is_Tagged_Type (Desig_T) then
742
743             --  Set type of result, to force a conversion when needed (see
744             --  exp_ch7, Convert_View), given that Deep_Finalize may be
745             --  inherited from the parent type, and we need the type of the
746             --  expression to see whether the conversion is in fact needed.
747
748             Set_Etype (Deref, Desig_T);
749          end if;
750
751          Free_Cod :=
752            Make_Final_Call
753             (Ref         => Deref,
754              Typ         => Desig_T,
755              With_Detach => New_Reference_To (Standard_True, Loc));
756
757          if Abort_Allowed then
758             Prepend_To (Free_Cod,
759               Build_Runtime_Call (Loc, RE_Abort_Defer));
760
761             Blk :=
762               Make_Block_Statement (Loc, Handled_Statement_Sequence =>
763                 Make_Handled_Sequence_Of_Statements (Loc,
764                   Statements  => Free_Cod,
765                   At_End_Proc =>
766                     New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc)));
767
768             --  We now expand the exception (at end) handler. We set a
769             --  temporary parent pointer since we have not attached Blk
770             --  to the tree yet.
771
772             Set_Parent (Blk, N);
773             Analyze (Blk);
774             Expand_At_End_Handler
775               (Handled_Statement_Sequence (Blk), Entity (Identifier (Blk)));
776             Append (Blk, Stmts);
777
778             --  We kill saved current values, since analyzing statements not
779             --  properly attached to the tree can set wrong current values.
780
781             Kill_Current_Values;
782
783          else
784             Append_List_To (Stmts, Free_Cod);
785          end if;
786       end if;
787
788       --  For a task type, call Free_Task before freeing the ATCB
789
790       if Is_Task_Type (Desig_T) then
791          declare
792             Stat : Node_Id := Prev (N);
793             Nam1 : Node_Id;
794             Nam2 : Node_Id;
795
796          begin
797             --  An Abort followed by a Free will not do what the user
798             --  expects, because the abort is not immediate. This is
799             --  worth a friendly warning.
800
801             while Present (Stat)
802               and then not Comes_From_Source (Original_Node (Stat))
803             loop
804                Prev (Stat);
805             end loop;
806
807             if Present (Stat)
808               and then Nkind (Original_Node (Stat)) = N_Abort_Statement
809             then
810                Stat := Original_Node (Stat);
811                Nam1 := First (Names (Stat));
812                Nam2 := Original_Node (First (Parameter_Associations (N)));
813
814                if Nkind (Nam1) = N_Explicit_Dereference
815                  and then Is_Entity_Name (Prefix (Nam1))
816                  and then Is_Entity_Name (Nam2)
817                  and then Entity (Prefix (Nam1)) = Entity (Nam2)
818                then
819                   Error_Msg_N ("abort may take time to complete?", N);
820                   Error_Msg_N ("\deallocation might have no effect?", N);
821                   Error_Msg_N ("\safer to wait for termination.?", N);
822                end if;
823             end if;
824          end;
825
826          Append_To
827            (Stmts, Cleanup_Task (N, Duplicate_Subexpr_No_Checks (Arg)));
828
829       --  For composite types that contain tasks, recurse over the structure
830       --  to build the selectors for the task subcomponents.
831
832       elsif Has_Task (Desig_T) then
833          if Is_Record_Type (Desig_T) then
834             Append_List_To (Stmts, Cleanup_Record (N, Arg, Desig_T));
835
836          elsif Is_Array_Type (Desig_T) then
837             Append_List_To (Stmts, Cleanup_Array (N, Arg, Desig_T));
838          end if;
839       end if;
840
841       --  Same for simple protected types. Eventually call Finalize_Protection
842       --  before freeing the PO for each protected component.
843
844       if Is_Simple_Protected_Type (Desig_T) then
845          Append_To (Stmts,
846            Cleanup_Protected_Object (N, Duplicate_Subexpr_No_Checks (Arg)));
847
848       elsif Has_Simple_Protected_Object (Desig_T) then
849          if Is_Record_Type (Desig_T) then
850             Append_List_To (Stmts, Cleanup_Record (N, Arg, Desig_T));
851          elsif Is_Array_Type (Desig_T) then
852             Append_List_To (Stmts, Cleanup_Array (N, Arg, Desig_T));
853          end if;
854       end if;
855
856       --  Normal processing for non-controlled types
857
858       Free_Arg := Duplicate_Subexpr_No_Checks (Arg);
859       Free_Node := Make_Free_Statement (Loc, Empty);
860       Append_To (Stmts, Free_Node);
861       Set_Storage_Pool (Free_Node, Pool);
862
863       --  Deal with storage pool
864
865       if Present (Pool) then
866
867          --  Freeing the secondary stack is meaningless
868
869          if Is_RTE (Pool, RE_SS_Pool) then
870             null;
871
872          elsif Is_Class_Wide_Type (Etype (Pool)) then
873
874             --  Case of a class-wide pool type: make a dispatching call
875             --  to Deallocate through the class-wide Deallocate_Any.
876
877             Set_Procedure_To_Call (Free_Node,
878               RTE (RE_Deallocate_Any));
879
880          else
881             --  Case of a specific pool type: make a statically bound call
882
883             Set_Procedure_To_Call (Free_Node,
884               Find_Prim_Op (Etype (Pool), Name_Deallocate));
885          end if;
886       end if;
887
888       if Present (Procedure_To_Call (Free_Node)) then
889
890          --  For all cases of a Deallocate call, the back-end needs to be
891          --  able to compute the size of the object being freed. This may
892          --  require some adjustments for objects of dynamic size.
893          --
894          --  If the type is class wide, we generate an implicit type with the
895          --  right dynamic size, so that the deallocate call gets the right
896          --  size parameter computed by GIGI. Same for an access to
897          --  unconstrained packed array.
898
899          if Is_Class_Wide_Type (Desig_T)
900            or else
901             (Is_Array_Type (Desig_T)
902                and then not Is_Constrained (Desig_T)
903                and then Is_Packed (Desig_T))
904          then
905             declare
906                Deref    : constant Node_Id :=
907                             Make_Explicit_Dereference (Loc,
908                               Duplicate_Subexpr_No_Checks (Arg));
909                D_Subtyp : Node_Id;
910                D_Type   : Entity_Id;
911
912             begin
913                Set_Etype  (Deref, Typ);
914                Set_Parent (Deref, Free_Node);
915                D_Subtyp := Make_Subtype_From_Expr (Deref, Desig_T);
916
917                if Nkind (D_Subtyp) in N_Has_Entity then
918                   D_Type := Entity (D_Subtyp);
919
920                else
921                   D_Type := Make_Defining_Identifier (Loc,
922                               New_Internal_Name ('A'));
923                   Insert_Action (N,
924                     Make_Subtype_Declaration (Loc,
925                       Defining_Identifier => D_Type,
926                       Subtype_Indication  => D_Subtyp));
927                   Freeze_Itype (D_Type, N);
928
929                end if;
930
931                Set_Actual_Designated_Subtype (Free_Node, D_Type);
932             end;
933
934          end if;
935       end if;
936
937       Set_Expression (Free_Node, Free_Arg);
938
939       --  Only remaining step is to set result to null, or generate a
940       --  raise of constraint error if the target object is "not null".
941
942       if Can_Never_Be_Null (Etype (Arg)) then
943          Append_To (Stmts,
944            Make_Raise_Constraint_Error (Loc,
945              Reason => CE_Access_Check_Failed));
946
947       else
948          declare
949             Lhs : constant Node_Id := Duplicate_Subexpr_No_Checks (Arg);
950          begin
951             Set_Assignment_OK (Lhs);
952             Append_To (Stmts,
953               Make_Assignment_Statement (Loc,
954                 Name       => Lhs,
955                 Expression => Make_Null (Loc)));
956          end;
957       end if;
958
959       --  If we know the argument is non-null, then make a block statement
960       --  that contains the required statements, no need for a test.
961
962       if Arg_Known_Non_Null then
963          Gen_Code :=
964            Make_Block_Statement (Loc,
965              Handled_Statement_Sequence =>
966                Make_Handled_Sequence_Of_Statements (Loc,
967              Statements => Stmts));
968
969       --  If the argument may be null, wrap the statements inside an IF that
970       --  does an explicit test to exclude the null case.
971
972       else
973          Gen_Code :=
974            Make_Implicit_If_Statement (N,
975              Condition =>
976                Make_Op_Ne (Loc,
977                  Left_Opnd  => Duplicate_Subexpr (Arg),
978                  Right_Opnd => Make_Null (Loc)),
979              Then_Statements => Stmts);
980       end if;
981
982       --  Rewrite the call
983
984       Rewrite (N, Gen_Code);
985       Analyze (N);
986    end Expand_Unc_Deallocation;
987
988    -----------------------
989    -- Expand_To_Address --
990    -----------------------
991
992    procedure Expand_To_Address (N : Node_Id) is
993       Loc : constant Source_Ptr := Sloc (N);
994       Arg : constant Node_Id := First_Actual (N);
995       Obj : Node_Id;
996
997    begin
998       Remove_Side_Effects (Arg);
999
1000       Obj := Make_Explicit_Dereference (Loc, Relocate_Node (Arg));
1001
1002       Rewrite (N,
1003         Make_Conditional_Expression (Loc,
1004           Expressions => New_List (
1005             Make_Op_Eq (Loc,
1006               Left_Opnd => New_Copy_Tree (Arg),
1007               Right_Opnd => Make_Null (Loc)),
1008             New_Occurrence_Of (RTE (RE_Null_Address), Loc),
1009             Make_Attribute_Reference (Loc,
1010               Attribute_Name => Name_Address,
1011               Prefix => Obj))));
1012
1013       Analyze_And_Resolve (N, RTE (RE_Address));
1014    end Expand_To_Address;
1015
1016    -----------------------
1017    -- Expand_To_Pointer --
1018    -----------------------
1019
1020    procedure Expand_To_Pointer (N : Node_Id) is
1021       Arg : constant Node_Id := First_Actual (N);
1022
1023    begin
1024       Rewrite (N, Unchecked_Convert_To (Etype (N), Arg));
1025       Analyze (N);
1026    end Expand_To_Pointer;
1027
1028 end Exp_Intr;