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-2015, 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
26with Atree;    use Atree;
27with Checks;   use Checks;
28with Einfo;    use Einfo;
29with Elists;   use Elists;
30with Errout;   use Errout;
31with Expander; use Expander;
32with Exp_Atag; use Exp_Atag;
33with Exp_Ch4;  use Exp_Ch4;
34with Exp_Ch7;  use Exp_Ch7;
35with Exp_Ch11; use Exp_Ch11;
36with Exp_Code; use Exp_Code;
37with Exp_Fixd; use Exp_Fixd;
38with Exp_Util; use Exp_Util;
39with Freeze;   use Freeze;
40with Inline;   use Inline;
41with Nmake;    use Nmake;
42with Nlists;   use Nlists;
43with Opt;      use Opt;
44with Restrict; use Restrict;
45with Rident;   use Rident;
46with Rtsfind;  use Rtsfind;
47with Sem;      use Sem;
48with Sem_Aux;  use Sem_Aux;
49with Sem_Eval; use Sem_Eval;
50with Sem_Res;  use Sem_Res;
51with Sem_Type; use Sem_Type;
52with Sem_Util; use Sem_Util;
53with Sinfo;    use Sinfo;
54with Sinput;   use Sinput;
55with Snames;   use Snames;
56with Stand;    use Stand;
57with Stringt;  use Stringt;
58with Tbuild;   use Tbuild;
59with Uintp;    use Uintp;
60with Urealp;   use Urealp;
61
62package body Exp_Intr is
63
64   -----------------------
65   -- Local Subprograms --
66   -----------------------
67
68   procedure Expand_Binary_Operator_Call (N : Node_Id);
69   --  Expand a call to an intrinsic arithmetic operator when the operand
70   --  types or sizes are not identical.
71
72   procedure Expand_Is_Negative (N : Node_Id);
73   --  Expand a call to the intrinsic Is_Negative function
74
75   procedure Expand_Dispatching_Constructor_Call (N : Node_Id);
76   --  Expand a call to an instantiation of Generic_Dispatching_Constructor
77   --  into a dispatching call to the actual subprogram associated with the
78   --  Constructor formal subprogram, passing it the Parameters actual of
79   --  the call to the instantiation and dispatching based on call's Tag
80   --  parameter.
81
82   procedure Expand_Exception_Call (N : Node_Id; Ent : RE_Id);
83   --  Expand a call to Exception_Information/Message/Name. The first
84   --  parameter, N, is the node for the function call, and Ent is the
85   --  entity for the corresponding routine in the Ada.Exceptions package.
86
87   procedure Expand_Import_Call (N : Node_Id);
88   --  Expand a call to Import_Address/Longest_Integer/Value. The parameter
89   --  N is the node for the function call.
90
91   procedure Expand_Shift (N : Node_Id; E : Entity_Id; K : Node_Kind);
92   --  Expand an intrinsic shift operation, N and E are from the call to
93   --  Expand_Intrinsic_Call (call node and subprogram spec entity) and
94   --  K is the kind for the shift node
95
96   procedure Expand_Unc_Conversion (N : Node_Id; E : Entity_Id);
97   --  Expand a call to an instantiation of Unchecked_Conversion into a node
98   --  N_Unchecked_Type_Conversion.
99
100   procedure Expand_Unc_Deallocation (N : Node_Id);
101   --  Expand a call to an instantiation of Unchecked_Deallocation into a node
102   --  N_Free_Statement and appropriate context.
103
104   procedure Expand_To_Address (N : Node_Id);
105   procedure Expand_To_Pointer (N : Node_Id);
106   --  Expand a call to corresponding function, declared in an instance of
107   --  System.Address_To_Access_Conversions.
108
109   procedure Expand_Source_Info (N : Node_Id; Nam : Name_Id);
110   --  Rewrite the node by the appropriate string or positive constant.
111   --  Nam can be one of the following:
112   --    Name_File                  - expand string name of source file
113   --    Name_Line                  - expand integer line number
114   --    Name_Source_Location       - expand string of form file:line
115   --    Name_Enclosing_Entity      - expand string name of enclosing entity
116   --    Name_Compilation_Date      - expand string with compilation date
117   --    Name_Compilation_Time      - expand string with compilation time
118
119   procedure Write_Entity_Name (E : Entity_Id);
120   --  Recursive procedure to construct string for qualified name of enclosing
121   --  program unit. The qualification stops at an enclosing scope has no
122   --  source name (block or loop). If entity is a subprogram instance, skip
123   --  enclosing wrapper package. The name is appended to the current contents
124   --  of Name_Buffer, incrementing Name_Len.
125
126   ---------------------
127   -- Add_Source_Info --
128   ---------------------
129
130   procedure Add_Source_Info (Loc : Source_Ptr; Nam : Name_Id) is
131      Ent : Entity_Id;
132
133      Save_NB : constant String  := Name_Buffer (1 .. Name_Len);
134      Save_NL : constant Natural := Name_Len;
135      --  Save current Name_Buffer contents
136
137   begin
138      Name_Len := 0;
139
140      --  Line
141
142      case Nam is
143
144         when Name_Line =>
145            Add_Nat_To_Name_Buffer (Nat (Get_Logical_Line_Number (Loc)));
146
147         when Name_File =>
148            Get_Decoded_Name_String
149              (Reference_Name (Get_Source_File_Index (Loc)));
150
151         when Name_Source_Location =>
152            Build_Location_String (Loc);
153
154         when Name_Enclosing_Entity =>
155
156            --  Skip enclosing blocks to reach enclosing unit
157
158            Ent := Current_Scope;
159            while Present (Ent) loop
160               exit when not Ekind_In (Ent, E_Block, E_Loop);
161               Ent := Scope (Ent);
162            end loop;
163
164            --  Ent now points to the relevant defining entity
165
166            Write_Entity_Name (Ent);
167
168         when Name_Compilation_Date =>
169            declare
170               subtype S13 is String (1 .. 3);
171               Months : constant array (1 .. 12) of S13 :=
172                          ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
173                           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
174
175               M1 : constant Character := Opt.Compilation_Time (6);
176               M2 : constant Character := Opt.Compilation_Time (7);
177
178               MM : constant Natural range 1 .. 12 :=
179                      (Character'Pos (M1) - Character'Pos ('0')) * 10 +
180                 (Character'Pos (M2) - Character'Pos ('0'));
181
182            begin
183               --  Reformat ISO date into MMM DD YYYY (__DATE__) format
184
185               Name_Buffer (1 .. 3)  := Months (MM);
186               Name_Buffer (4)       := ' ';
187               Name_Buffer (5 .. 6)  := Opt.Compilation_Time (9 .. 10);
188               Name_Buffer (7)       := ' ';
189               Name_Buffer (8 .. 11) := Opt.Compilation_Time (1 .. 4);
190               Name_Len := 11;
191            end;
192
193         when Name_Compilation_Time =>
194            Name_Buffer (1 .. 8) := Opt.Compilation_Time (12 .. 19);
195            Name_Len := 8;
196
197         when others =>
198            raise Program_Error;
199      end case;
200
201      --  Prepend original Name_Buffer contents
202
203      Name_Buffer (Save_NL + 1 .. Save_NL + Name_Len) :=
204        Name_Buffer (1 .. Name_Len);
205      Name_Buffer (1 .. Save_NL) := Save_NB;
206      Name_Len := Name_Len + Save_NL;
207   end Add_Source_Info;
208
209   ---------------------------------
210   -- Expand_Binary_Operator_Call --
211   ---------------------------------
212
213   procedure Expand_Binary_Operator_Call (N : Node_Id) is
214      T1  : constant Entity_Id := Underlying_Type (Etype (Left_Opnd  (N)));
215      T2  : constant Entity_Id := Underlying_Type (Etype (Right_Opnd (N)));
216      TR  : constant Entity_Id := Etype (N);
217      T3  : Entity_Id;
218      Res : Node_Id;
219
220      Siz : constant Uint := UI_Max (RM_Size (T1), RM_Size (T2));
221      --  Maximum of operand sizes
222
223   begin
224      --  Nothing to do if the operands have the same modular type
225
226      if Base_Type (T1) = Base_Type (T2)
227        and then Is_Modular_Integer_Type (T1)
228      then
229         return;
230      end if;
231
232      --  Use Unsigned_32 for sizes of 32 or below, else Unsigned_64
233
234      if Siz > 32 then
235         T3 := RTE (RE_Unsigned_64);
236      else
237         T3 := RTE (RE_Unsigned_32);
238      end if;
239
240      --  Copy operator node, and reset type and entity fields, for
241      --  subsequent reanalysis.
242
243      Res := New_Copy (N);
244      Set_Etype (Res, T3);
245
246      case Nkind (N) is
247         when N_Op_And =>
248            Set_Entity (Res, Standard_Op_And);
249         when N_Op_Or =>
250            Set_Entity (Res, Standard_Op_Or);
251         when N_Op_Xor =>
252            Set_Entity (Res, Standard_Op_Xor);
253         when others =>
254            raise Program_Error;
255      end case;
256
257      --  Convert operands to large enough intermediate type
258
259      Set_Left_Opnd (Res,
260        Unchecked_Convert_To (T3, Relocate_Node (Left_Opnd (N))));
261      Set_Right_Opnd (Res,
262        Unchecked_Convert_To (T3, Relocate_Node (Right_Opnd (N))));
263
264      --  Analyze and resolve result formed by conversion to target type
265
266      Rewrite (N, Unchecked_Convert_To (TR, Res));
267      Analyze_And_Resolve (N, TR);
268   end Expand_Binary_Operator_Call;
269
270   -----------------------------------------
271   -- Expand_Dispatching_Constructor_Call --
272   -----------------------------------------
273
274   --  Transform a call to an instantiation of Generic_Dispatching_Constructor
275   --  of the form:
276
277   --     GDC_Instance (The_Tag, Parameters'Access)
278
279   --  to a class-wide conversion of a dispatching call to the actual
280   --  associated with the formal subprogram Construct, designating The_Tag
281   --  as the controlling tag of the call:
282
283   --     T'Class (Construct'Actual (Params)) -- Controlling tag is The_Tag
284
285   --  which will eventually be expanded to the following:
286
287   --     T'Class (The_Tag.all (Construct'Actual'Index).all (Params))
288
289   --  A class-wide membership test is also generated, preceding the call, to
290   --  ensure that the controlling tag denotes a type in T'Class.
291
292   procedure Expand_Dispatching_Constructor_Call (N : Node_Id) is
293      Loc        : constant Source_Ptr := Sloc (N);
294      Tag_Arg    : constant Node_Id    := First_Actual (N);
295      Param_Arg  : constant Node_Id    := Next_Actual (Tag_Arg);
296      Subp_Decl  : constant Node_Id    := Parent (Parent (Entity (Name (N))));
297      Inst_Pkg   : constant Node_Id    := Parent (Subp_Decl);
298      Act_Rename : Node_Id;
299      Act_Constr : Entity_Id;
300      Iface_Tag  : Node_Id := Empty;
301      Cnstr_Call : Node_Id;
302      Result_Typ : Entity_Id;
303
304   begin
305      --  Remove side effects from tag argument early, before rewriting
306      --  the dispatching constructor call, as Remove_Side_Effects relies
307      --  on Tag_Arg's Parent link properly attached to the tree (once the
308      --  call is rewritten, the Parent is inconsistent as it points to the
309      --  rewritten node, which is not the syntactic parent of the Tag_Arg
310      --  anymore).
311
312      Remove_Side_Effects (Tag_Arg);
313
314      --  Check that we have a proper tag
315
316      Insert_Action (N,
317        Make_Implicit_If_Statement (N,
318          Condition       => Make_Op_Eq (Loc,
319            Left_Opnd  => New_Copy_Tree (Tag_Arg),
320            Right_Opnd => New_Occurrence_Of (RTE (RE_No_Tag), Loc)),
321
322          Then_Statements => New_List (
323            Make_Raise_Statement (Loc,
324              New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
325
326      --  Check that it is not the tag of an abstract type
327
328      Insert_Action (N,
329        Make_Implicit_If_Statement (N,
330          Condition       => Make_Function_Call (Loc,
331             Name                   =>
332               New_Occurrence_Of (RTE (RE_Type_Is_Abstract), Loc),
333             Parameter_Associations => New_List (New_Copy_Tree (Tag_Arg))),
334
335          Then_Statements => New_List (
336            Make_Raise_Statement (Loc,
337              New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
338
339      --  The subprogram is the third actual in the instantiation, and is
340      --  retrieved from the corresponding renaming declaration. However,
341      --  freeze nodes may appear before, so we retrieve the declaration
342      --  with an explicit loop.
343
344      Act_Rename := First (Visible_Declarations (Inst_Pkg));
345      while Nkind (Act_Rename) /= N_Subprogram_Renaming_Declaration loop
346         Next (Act_Rename);
347      end loop;
348
349      Act_Constr := Entity (Name (Act_Rename));
350      Result_Typ := Class_Wide_Type (Etype (Act_Constr));
351
352      --  Check that the accessibility level of the tag is no deeper than that
353      --  of the constructor function.
354
355      Insert_Action (N,
356        Make_Implicit_If_Statement (N,
357          Condition       =>
358            Make_Op_Gt (Loc,
359              Left_Opnd  =>
360                Build_Get_Access_Level (Loc, New_Copy_Tree (Tag_Arg)),
361              Right_Opnd =>
362                Make_Integer_Literal (Loc, Scope_Depth (Act_Constr))),
363
364          Then_Statements => New_List (
365            Make_Raise_Statement (Loc,
366              New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
367
368      if Is_Interface (Etype (Act_Constr)) then
369
370         --  If the result type is not known to be a parent of Tag_Arg then we
371         --  need to locate the tag of the secondary dispatch table.
372
373         if not Is_Ancestor (Etype (Result_Typ), Etype (Tag_Arg),
374                             Use_Full_View => True)
375           and then Tagged_Type_Expansion
376         then
377            --  Obtain the reference to the Ada.Tags service before generating
378            --  the Object_Declaration node to ensure that if this service is
379            --  not available in the runtime then we generate a clear error.
380
381            declare
382               Fname : constant Node_Id :=
383                         New_Occurrence_Of (RTE (RE_Secondary_Tag), Loc);
384
385            begin
386               pragma Assert (not Is_Interface (Etype (Tag_Arg)));
387
388               --  The tag is the first entry in the dispatch table of the
389               --  return type of the constructor.
390
391               Iface_Tag :=
392                 Make_Object_Declaration (Loc,
393                   Defining_Identifier => Make_Temporary (Loc, 'V'),
394                   Object_Definition   =>
395                     New_Occurrence_Of (RTE (RE_Tag), Loc),
396                   Expression          =>
397                     Make_Function_Call (Loc,
398                       Name                   => Fname,
399                       Parameter_Associations => New_List (
400                         Relocate_Node (Tag_Arg),
401                         New_Occurrence_Of
402                           (Node (First_Elmt
403                                    (Access_Disp_Table (Etype (Act_Constr)))),
404                            Loc))));
405               Insert_Action (N, Iface_Tag);
406            end;
407         end if;
408      end if;
409
410      --  Create the call to the actual Constructor function
411
412      Cnstr_Call :=
413        Make_Function_Call (Loc,
414          Name                   => New_Occurrence_Of (Act_Constr, Loc),
415          Parameter_Associations => New_List (Relocate_Node (Param_Arg)));
416
417      --  Establish its controlling tag from the tag passed to the instance
418      --  The tag may be given by a function call, in which case a temporary
419      --  should be generated now, to prevent out-of-order insertions during
420      --  the expansion of that call when stack-checking is enabled.
421
422      if Present (Iface_Tag) then
423         Set_Controlling_Argument (Cnstr_Call,
424           New_Occurrence_Of (Defining_Identifier (Iface_Tag), Loc));
425      else
426         Set_Controlling_Argument (Cnstr_Call,
427           Relocate_Node (Tag_Arg));
428      end if;
429
430      --  Rewrite and analyze the call to the instance as a class-wide
431      --  conversion of the call to the actual constructor.
432
433      Rewrite (N, Convert_To (Result_Typ, Cnstr_Call));
434
435      --  Do not generate a run-time check on the built object if tag
436      --  checks are suppressed for the result type or tagged type expansion
437      --  is disabled.
438
439      if Tag_Checks_Suppressed (Etype (Result_Typ))
440        or else not Tagged_Type_Expansion
441      then
442         null;
443
444      --  Generate a class-wide membership test to ensure that the call's tag
445      --  argument denotes a type within the class. We must keep separate the
446      --  case in which the Result_Type of the constructor function is a tagged
447      --  type from the case in which it is an abstract interface because the
448      --  run-time subprogram required to check these cases differ (and have
449      --  one difference in their parameters profile).
450
451      --  Call CW_Membership if the Result_Type is a tagged type to look for
452      --  the tag in the table of ancestor tags.
453
454      elsif not Is_Interface (Result_Typ) then
455         declare
456            Obj_Tag_Node : Node_Id := New_Copy_Tree (Tag_Arg);
457            CW_Test_Node : Node_Id;
458
459         begin
460            Build_CW_Membership (Loc,
461              Obj_Tag_Node => Obj_Tag_Node,
462              Typ_Tag_Node =>
463                New_Occurrence_Of (
464                   Node (First_Elmt (Access_Disp_Table (
465                                       Root_Type (Result_Typ)))), Loc),
466              Related_Nod => N,
467              New_Node    => CW_Test_Node);
468
469            Insert_Action (N,
470              Make_Implicit_If_Statement (N,
471                Condition =>
472                  Make_Op_Not (Loc, CW_Test_Node),
473                Then_Statements =>
474                  New_List (Make_Raise_Statement (Loc,
475                              New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
476         end;
477
478      --  Call IW_Membership test if the Result_Type is an abstract interface
479      --  to look for the tag in the table of interface tags.
480
481      else
482         Insert_Action (N,
483           Make_Implicit_If_Statement (N,
484             Condition =>
485               Make_Op_Not (Loc,
486                 Make_Function_Call (Loc,
487                    Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
488                    Parameter_Associations => New_List (
489                      Make_Attribute_Reference (Loc,
490                        Prefix         => New_Copy_Tree (Tag_Arg),
491                        Attribute_Name => Name_Address),
492
493                      New_Occurrence_Of (
494                        Node (First_Elmt (Access_Disp_Table (
495                                            Root_Type (Result_Typ)))), Loc)))),
496             Then_Statements =>
497               New_List (
498                 Make_Raise_Statement (Loc,
499                   Name => New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
500      end if;
501
502      Analyze_And_Resolve (N, Etype (Act_Constr));
503   end Expand_Dispatching_Constructor_Call;
504
505   ---------------------------
506   -- Expand_Exception_Call --
507   ---------------------------
508
509   --  If the function call is not within an exception handler, then the call
510   --  is replaced by a null string. Otherwise the appropriate routine in
511   --  Ada.Exceptions is called passing the choice parameter specification
512   --  from the enclosing handler. If the enclosing handler lacks a choice
513   --  parameter, then one is supplied.
514
515   procedure Expand_Exception_Call (N : Node_Id; Ent : RE_Id) is
516      Loc : constant Source_Ptr := Sloc (N);
517      P   : Node_Id;
518      E   : Entity_Id;
519
520   begin
521      --  Climb up parents to see if we are in exception handler
522
523      P := Parent (N);
524      loop
525         --  Case of not in exception handler, replace by null string
526
527         if No (P) then
528            Rewrite (N,
529              Make_String_Literal (Loc,
530                Strval => ""));
531            exit;
532
533         --  Case of in exception handler
534
535         elsif Nkind (P) = N_Exception_Handler then
536
537            --  Handler cannot be used for a local raise, and furthermore, this
538            --  is a violation of the No_Exception_Propagation restriction.
539
540            Set_Local_Raise_Not_OK (P);
541            Check_Restriction (No_Exception_Propagation, N);
542
543            --  If no choice parameter present, then put one there. Note that
544            --  we do not need to put it on the entity chain, since no one will
545            --  be referencing it by normal visibility methods.
546
547            if No (Choice_Parameter (P)) then
548               E := Make_Temporary (Loc, 'E');
549               Set_Choice_Parameter (P, E);
550               Set_Ekind (E, E_Variable);
551               Set_Etype (E, RTE (RE_Exception_Occurrence));
552               Set_Scope (E, Current_Scope);
553            end if;
554
555            Rewrite (N,
556              Make_Function_Call (Loc,
557                Name => New_Occurrence_Of (RTE (Ent), Loc),
558                Parameter_Associations => New_List (
559                  New_Occurrence_Of (Choice_Parameter (P), Loc))));
560            exit;
561
562         --  Keep climbing
563
564         else
565            P := Parent (P);
566         end if;
567      end loop;
568
569      Analyze_And_Resolve (N, Standard_String);
570   end Expand_Exception_Call;
571
572   ------------------------
573   -- Expand_Import_Call --
574   ------------------------
575
576   --  The function call must have a static string as its argument. We create
577   --  a dummy variable which uses this string as the external name in an
578   --  Import pragma. The result is then obtained as the address of this
579   --  dummy variable, converted to the appropriate target type.
580
581   procedure Expand_Import_Call (N : Node_Id) is
582      Loc : constant Source_Ptr := Sloc (N);
583      Ent : constant Entity_Id  := Entity (Name (N));
584      Str : constant Node_Id    := First_Actual (N);
585      Dum : constant Entity_Id  := Make_Temporary (Loc, 'D');
586
587   begin
588      Insert_Actions (N, New_List (
589        Make_Object_Declaration (Loc,
590          Defining_Identifier => Dum,
591          Object_Definition   =>
592            New_Occurrence_Of (Standard_Character, Loc)),
593
594        Make_Pragma (Loc,
595          Chars                        => Name_Import,
596          Pragma_Argument_Associations => New_List (
597            Make_Pragma_Argument_Association (Loc,
598              Expression => Make_Identifier (Loc, Name_Ada)),
599
600            Make_Pragma_Argument_Association (Loc,
601              Expression => Make_Identifier (Loc, Chars (Dum))),
602
603            Make_Pragma_Argument_Association (Loc,
604              Chars => Name_Link_Name,
605              Expression => Relocate_Node (Str))))));
606
607      Rewrite (N,
608        Unchecked_Convert_To (Etype (Ent),
609          Make_Attribute_Reference (Loc,
610            Prefix         => Make_Identifier (Loc, Chars (Dum)),
611            Attribute_Name => Name_Address)));
612
613      Analyze_And_Resolve (N, Etype (Ent));
614   end Expand_Import_Call;
615
616   ---------------------------
617   -- Expand_Intrinsic_Call --
618   ---------------------------
619
620   procedure Expand_Intrinsic_Call (N : Node_Id; E : Entity_Id) is
621      Nam : Name_Id;
622
623   begin
624      --  If an external name is specified for the intrinsic, it is handled
625      --  by the back-end: leave the call node unchanged for now.
626
627      if Present (Interface_Name (E)) then
628         return;
629      end if;
630
631      --  If the intrinsic subprogram is generic, gets its original name
632
633      if Present (Parent (E))
634        and then Present (Generic_Parent (Parent (E)))
635      then
636         Nam := Chars (Generic_Parent (Parent (E)));
637      else
638         Nam := Chars (E);
639      end if;
640
641      if Nam = Name_Asm then
642         Expand_Asm_Call (N);
643
644      elsif Nam = Name_Divide then
645         Expand_Decimal_Divide_Call (N);
646
647      elsif Nam = Name_Exception_Information then
648         Expand_Exception_Call (N, RE_Exception_Information);
649
650      elsif Nam = Name_Exception_Message then
651         Expand_Exception_Call (N, RE_Exception_Message);
652
653      elsif Nam = Name_Exception_Name then
654         Expand_Exception_Call (N, RE_Exception_Name_Simple);
655
656      elsif Nam = Name_Generic_Dispatching_Constructor then
657         Expand_Dispatching_Constructor_Call (N);
658
659      elsif Nam_In (Nam, Name_Import_Address,
660                         Name_Import_Largest_Value,
661                         Name_Import_Value)
662      then
663         Expand_Import_Call (N);
664
665      elsif Nam = Name_Is_Negative then
666         Expand_Is_Negative (N);
667
668      elsif Nam = Name_Rotate_Left then
669         Expand_Shift (N, E, N_Op_Rotate_Left);
670
671      elsif Nam = Name_Rotate_Right then
672         Expand_Shift (N, E, N_Op_Rotate_Right);
673
674      elsif Nam = Name_Shift_Left then
675         Expand_Shift (N, E, N_Op_Shift_Left);
676
677      elsif Nam = Name_Shift_Right then
678         Expand_Shift (N, E, N_Op_Shift_Right);
679
680      elsif Nam = Name_Shift_Right_Arithmetic then
681         Expand_Shift (N, E, N_Op_Shift_Right_Arithmetic);
682
683      elsif Nam = Name_Unchecked_Conversion then
684         Expand_Unc_Conversion (N, E);
685
686      elsif Nam = Name_Unchecked_Deallocation then
687         Expand_Unc_Deallocation (N);
688
689      elsif Nam = Name_To_Address then
690         Expand_To_Address (N);
691
692      elsif Nam = Name_To_Pointer then
693         Expand_To_Pointer (N);
694
695      elsif Nam_In (Nam, Name_File,
696                         Name_Line,
697                         Name_Source_Location,
698                         Name_Enclosing_Entity,
699                         Name_Compilation_Date,
700                         Name_Compilation_Time)
701      then
702         Expand_Source_Info (N, Nam);
703
704         --  If we have a renaming, expand the call to the original operation,
705         --  which must itself be intrinsic, since renaming requires matching
706         --  conventions and this has already been checked.
707
708      elsif Present (Alias (E)) then
709         Expand_Intrinsic_Call (N, Alias (E));
710
711      elsif Nkind (N) in N_Binary_Op then
712         Expand_Binary_Operator_Call (N);
713
714         --  The only other case is where an external name was specified, since
715         --  this is the only way that an otherwise unrecognized name could
716         --  escape the checking in Sem_Prag. Nothing needs to be done in such
717         --  a case, since we pass such a call to the back end unchanged.
718
719      else
720         null;
721      end if;
722   end Expand_Intrinsic_Call;
723
724   ------------------------
725   -- Expand_Is_Negative --
726   ------------------------
727
728   procedure Expand_Is_Negative (N : Node_Id) is
729      Loc   : constant Source_Ptr := Sloc (N);
730      Opnd  : constant Node_Id    := Relocate_Node (First_Actual (N));
731
732   begin
733
734      --  We replace the function call by the following expression
735
736      --    if Opnd < 0.0 then
737      --       True
738      --    else
739      --       if Opnd > 0.0 then
740      --          False;
741      --       else
742      --          Float_Unsigned!(Float (Opnd)) /= 0
743      --       end if;
744      --    end if;
745
746      Rewrite (N,
747        Make_If_Expression (Loc,
748          Expressions => New_List (
749            Make_Op_Lt (Loc,
750              Left_Opnd  => Duplicate_Subexpr (Opnd),
751              Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
752
753            New_Occurrence_Of (Standard_True, Loc),
754
755            Make_If_Expression (Loc,
756             Expressions => New_List (
757               Make_Op_Gt (Loc,
758                 Left_Opnd  => Duplicate_Subexpr_No_Checks (Opnd),
759                 Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
760
761               New_Occurrence_Of (Standard_False, Loc),
762
763                Make_Op_Ne (Loc,
764                  Left_Opnd =>
765                    Unchecked_Convert_To
766                      (RTE (RE_Float_Unsigned),
767                       Convert_To
768                         (Standard_Float,
769                          Duplicate_Subexpr_No_Checks (Opnd))),
770                  Right_Opnd =>
771                    Make_Integer_Literal (Loc, 0)))))));
772
773      Analyze_And_Resolve (N, Standard_Boolean);
774   end Expand_Is_Negative;
775
776   ------------------
777   -- Expand_Shift --
778   ------------------
779
780   --  This procedure is used to convert a call to a shift function to the
781   --  corresponding operator node. This conversion is not done by the usual
782   --  circuit for converting calls to operator functions (e.g. "+"(1,2)) to
783   --  operator nodes, because shifts are not predefined operators.
784
785   --  As a result, whenever a shift is used in the source program, it will
786   --  remain as a call until converted by this routine to the operator node
787   --  form which the back end is expecting to see.
788
789   --  Note: it is possible for the expander to generate shift operator nodes
790   --  directly, which will be analyzed in the normal manner by calling Analyze
791   --  and Resolve. Such shift operator nodes will not be seen by Expand_Shift.
792
793   procedure Expand_Shift (N : Node_Id; E : Entity_Id; K : Node_Kind) is
794      Entyp : constant Entity_Id  := Etype (E);
795      Left  : constant Node_Id    := First_Actual (N);
796      Loc   : constant Source_Ptr := Sloc (N);
797      Right : constant Node_Id    := Next_Actual (Left);
798      Ltyp  : constant Node_Id    := Etype (Left);
799      Rtyp  : constant Node_Id    := Etype (Right);
800      Typ   : constant Entity_Id  := Etype (N);
801      Snode : Node_Id;
802
803   begin
804      Snode := New_Node (K, Loc);
805      Set_Right_Opnd (Snode, Relocate_Node (Right));
806      Set_Chars      (Snode, Chars (E));
807      Set_Etype      (Snode, Base_Type (Entyp));
808      Set_Entity     (Snode, E);
809
810      if Compile_Time_Known_Value (Type_High_Bound (Rtyp))
811        and then Expr_Value (Type_High_Bound (Rtyp)) < Esize (Ltyp)
812      then
813         Set_Shift_Count_OK (Snode, True);
814      end if;
815
816      if Typ = Entyp then
817
818         --  Note that we don't call Analyze and Resolve on this node, because
819         --  it already got analyzed and resolved when it was a function call.
820
821         Set_Left_Opnd (Snode, Relocate_Node (Left));
822         Rewrite (N, Snode);
823         Set_Analyzed (N);
824
825         --  However, we do call the expander, so that the expansion for
826         --  rotates and shift_right_arithmetic happens if Modify_Tree_For_C
827         --  is set.
828
829         if Expander_Active then
830            Expand (N);
831         end if;
832
833      else
834         --  If the context type is not the type of the operator, it is an
835         --  inherited operator for a derived type. Wrap the node in a
836         --  conversion so that it is type-consistent for possible further
837         --  expansion (e.g. within a lock-free protected type).
838
839         Set_Left_Opnd (Snode,
840           Unchecked_Convert_To (Base_Type (Entyp), Relocate_Node (Left)));
841         Rewrite (N, Unchecked_Convert_To (Typ, Snode));
842
843         --  Analyze and resolve result formed by conversion to target type
844
845         Analyze_And_Resolve (N, Typ);
846      end if;
847   end Expand_Shift;
848
849   ------------------------
850   -- Expand_Source_Info --
851   ------------------------
852
853   procedure Expand_Source_Info (N : Node_Id; Nam : Name_Id) is
854      Loc : constant Source_Ptr := Sloc (N);
855      Ent : Entity_Id;
856
857   begin
858      --  Integer cases
859
860      if Nam = Name_Line then
861         Rewrite (N,
862           Make_Integer_Literal (Loc,
863             Intval => UI_From_Int (Int (Get_Logical_Line_Number (Loc)))));
864         Analyze_And_Resolve (N, Standard_Positive);
865
866      --  String cases
867
868      else
869         Name_Len := 0;
870
871         case Nam is
872            when Name_File =>
873               Get_Decoded_Name_String
874                 (Reference_Name (Get_Source_File_Index (Loc)));
875
876            when Name_Source_Location =>
877               Build_Location_String (Loc);
878
879            when Name_Enclosing_Entity =>
880
881               --  Skip enclosing blocks to reach enclosing unit
882
883               Ent := Current_Scope;
884               while Present (Ent) loop
885                  exit when Ekind (Ent) /= E_Block
886                    and then Ekind (Ent) /= E_Loop;
887                  Ent := Scope (Ent);
888               end loop;
889
890               --  Ent now points to the relevant defining entity
891
892               Write_Entity_Name (Ent);
893
894            when Name_Compilation_Date =>
895               declare
896                  subtype S13 is String (1 .. 3);
897                  Months : constant array (1 .. 12) of S13 :=
898                    ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
899                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
900
901                  M1 : constant Character := Opt.Compilation_Time (6);
902                  M2 : constant Character := Opt.Compilation_Time (7);
903
904                  MM : constant Natural range 1 .. 12 :=
905                    (Character'Pos (M1) - Character'Pos ('0')) * 10 +
906                    (Character'Pos (M2) - Character'Pos ('0'));
907
908               begin
909                  --  Reformat ISO date into MMM DD YYYY (__DATE__) format
910
911                  Name_Buffer (1 .. 3)  := Months (MM);
912                  Name_Buffer (4)       := ' ';
913                  Name_Buffer (5 .. 6)  := Opt.Compilation_Time (9 .. 10);
914                  Name_Buffer (7)       := ' ';
915                  Name_Buffer (8 .. 11) := Opt.Compilation_Time (1 .. 4);
916                  Name_Len := 11;
917               end;
918
919            when Name_Compilation_Time =>
920               Name_Buffer (1 .. 8) := Opt.Compilation_Time (12 .. 19);
921               Name_Len := 8;
922
923            when others =>
924               raise Program_Error;
925         end case;
926
927         Rewrite (N,
928           Make_String_Literal (Loc,
929             Strval => String_From_Name_Buffer));
930         Analyze_And_Resolve (N, Standard_String);
931      end if;
932
933      Set_Is_Static_Expression (N);
934   end Expand_Source_Info;
935
936   ---------------------------
937   -- Expand_Unc_Conversion --
938   ---------------------------
939
940   procedure Expand_Unc_Conversion (N : Node_Id; E : Entity_Id) is
941      Func : constant Entity_Id  := Entity (Name (N));
942      Conv : Node_Id;
943      Ftyp : Entity_Id;
944      Ttyp : Entity_Id;
945
946   begin
947      --  Rewrite as unchecked conversion node. Note that we must convert
948      --  the operand to the formal type of the input parameter of the
949      --  function, so that the resulting N_Unchecked_Type_Conversion
950      --  call indicates the correct types for Gigi.
951
952      --  Right now, we only do this if a scalar type is involved. It is
953      --  not clear if it is needed in other cases. If we do attempt to
954      --  do the conversion unconditionally, it crashes 3411-018. To be
955      --  investigated further ???
956
957      Conv := Relocate_Node (First_Actual (N));
958      Ftyp := Etype (First_Formal (Func));
959
960      if Is_Scalar_Type (Ftyp) then
961         Conv := Convert_To (Ftyp, Conv);
962         Set_Parent (Conv, N);
963         Analyze_And_Resolve (Conv);
964      end if;
965
966      --  The instantiation of Unchecked_Conversion creates a wrapper package,
967      --  and the target type is declared as a subtype of the actual. Recover
968      --  the actual, which is the subtype indic. in the subtype declaration
969      --  for the target type. This is semantically correct, and avoids
970      --  anomalies with access subtypes. For entities, leave type as is.
971
972      --  We do the analysis here, because we do not want the compiler
973      --  to try to optimize or otherwise reorganize the unchecked
974      --  conversion node.
975
976      Ttyp := Etype (E);
977
978      if Is_Entity_Name (Conv) then
979         null;
980
981      elsif Nkind (Parent (Ttyp)) = N_Subtype_Declaration then
982         Ttyp := Entity (Subtype_Indication (Parent (Etype (E))));
983
984      elsif Is_Itype (Ttyp) then
985         Ttyp :=
986           Entity (Subtype_Indication (Associated_Node_For_Itype (Ttyp)));
987      else
988         raise Program_Error;
989      end if;
990
991      Rewrite (N, Unchecked_Convert_To (Ttyp, Conv));
992      Set_Etype (N, Ttyp);
993      Set_Analyzed (N);
994
995      if Nkind (N) = N_Unchecked_Type_Conversion then
996         Expand_N_Unchecked_Type_Conversion (N);
997      end if;
998   end Expand_Unc_Conversion;
999
1000   -----------------------------
1001   -- Expand_Unc_Deallocation --
1002   -----------------------------
1003
1004   procedure Expand_Unc_Deallocation (N : Node_Id) is
1005      Arg       : constant Node_Id    := First_Actual (N);
1006      Loc       : constant Source_Ptr := Sloc (N);
1007      Typ       : constant Entity_Id  := Etype (Arg);
1008      Desig_Typ : constant Entity_Id  := Designated_Type (Typ);
1009      Needs_Fin : constant Boolean    := Needs_Finalization (Desig_Typ);
1010      Root_Typ  : constant Entity_Id  := Underlying_Type (Root_Type (Typ));
1011      Pool      : constant Entity_Id  := Associated_Storage_Pool (Root_Typ);
1012      Stmts     : constant List_Id    := New_List;
1013
1014      Arg_Known_Non_Null : constant Boolean := Known_Non_Null (N);
1015      --  This captures whether we know the argument to be non-null so that
1016      --  we can avoid the test. The reason that we need to capture this is
1017      --  that we analyze some generated statements before properly attaching
1018      --  them to the tree, and that can disturb current value settings.
1019
1020      Exceptions_OK : constant Boolean :=
1021                        not Restriction_Active (No_Exception_Propagation);
1022
1023      Abrt_Blk    : Node_Id := Empty;
1024      Abrt_Blk_Id : Entity_Id;
1025      Abrt_HSS    : Node_Id;
1026      AUD         : Entity_Id;
1027      Fin_Blk     : Node_Id;
1028      Fin_Call    : Node_Id;
1029      Fin_Data    : Finalization_Exception_Data;
1030      Free_Arg    : Node_Id;
1031      Free_Nod    : Node_Id;
1032      Gen_Code    : Node_Id;
1033      Obj_Ref     : Node_Id;
1034
1035   begin
1036      --  Nothing to do if we know the argument is null
1037
1038      if Known_Null (N) then
1039         return;
1040      end if;
1041
1042      --  Processing for pointer to controlled types. Generate:
1043
1044      --    Abrt   : constant Boolean := ...;
1045      --    Ex     : Exception_Occurrence;
1046      --    Raised : Boolean := False;
1047
1048      --    begin
1049      --       Abort_Defer;
1050
1051      --       begin
1052      --          [Deep_]Finalize (Obj_Ref);
1053
1054      --       exception
1055      --          when others =>
1056      --             if not Raised then
1057      --                Raised := True;
1058      --                Save_Occurrence (Ex, Get_Current_Excep.all.all);
1059      --       end;
1060      --    at end
1061      --       Abort_Undefer_Direct;
1062      --    end;
1063
1064      --  Depending on whether exception propagation is enabled and/or aborts
1065      --  are allowed, the generated code may lack block statements.
1066
1067      if Needs_Fin then
1068         Obj_Ref :=
1069           Make_Explicit_Dereference (Loc,
1070             Prefix => Duplicate_Subexpr_No_Checks (Arg));
1071
1072         --  If the designated type is tagged, the finalization call must
1073         --  dispatch because the designated type may not be the actual type
1074         --  of the object. If the type is synchronized, the deallocation
1075         --  applies to the corresponding record type.
1076
1077         if Is_Tagged_Type (Desig_Typ) then
1078            if Is_Concurrent_Type (Desig_Typ) then
1079               Obj_Ref :=
1080                 Unchecked_Convert_To
1081                   (Class_Wide_Type (Corresponding_Record_Type (Desig_Typ)),
1082                      Obj_Ref);
1083
1084            elsif not Is_Class_Wide_Type (Desig_Typ) then
1085               Obj_Ref :=
1086                 Unchecked_Convert_To (Class_Wide_Type (Desig_Typ), Obj_Ref);
1087            end if;
1088
1089         --  Otherwise the designated type is untagged. Set the type of the
1090         --  dereference explicitly to force a conversion when needed given
1091         --  that [Deep_]Finalize may be inherited from a parent type.
1092
1093         else
1094            Set_Etype (Obj_Ref, Desig_Typ);
1095         end if;
1096
1097         --  Generate:
1098         --    [Deep_]Finalize (Obj_Ref);
1099
1100         Fin_Call := Make_Final_Call (Obj_Ref => Obj_Ref, Typ => Desig_Typ);
1101
1102         --  Generate:
1103         --    Abrt   : constant Boolean := ...;
1104         --    Ex     : Exception_Occurrence;
1105         --    Raised : Boolean := False;
1106
1107         --    begin
1108         --       <Fin_Call>
1109
1110         --    exception
1111         --       when others =>
1112         --          if not Raised then
1113         --             Raised := True;
1114         --             Save_Occurrence (Ex, Get_Current_Excep.all.all);
1115         --    end;
1116
1117         if Exceptions_OK then
1118            Build_Object_Declarations (Fin_Data, Stmts, Loc);
1119
1120            Fin_Blk :=
1121              Make_Block_Statement (Loc,
1122                Handled_Statement_Sequence =>
1123                  Make_Handled_Sequence_Of_Statements (Loc,
1124                    Statements         => New_List (Fin_Call),
1125                    Exception_Handlers => New_List (
1126                      Build_Exception_Handler (Fin_Data))));
1127
1128         --  Otherwise exception propagation is not allowed
1129
1130         else
1131            Fin_Blk := Fin_Call;
1132         end if;
1133
1134         --  The finalization action must be protected by an abort defer and
1135         --  undefer pair when aborts are allowed. Generate:
1136
1137         --    begin
1138         --       Abort_Defer;
1139         --       <Fin_Blk>
1140         --    at end
1141         --       Abort_Undefer_Direct;
1142         --    end;
1143
1144         if Abort_Allowed then
1145            AUD := RTE (RE_Abort_Undefer_Direct);
1146
1147            Abrt_HSS :=
1148              Make_Handled_Sequence_Of_Statements (Loc,
1149                Statements  => New_List (
1150                  Build_Runtime_Call (Loc, RE_Abort_Defer),
1151                  Fin_Blk),
1152                At_End_Proc => New_Occurrence_Of (AUD, Loc));
1153
1154            Abrt_Blk :=
1155              Make_Block_Statement (Loc,
1156                Handled_Statement_Sequence => Abrt_HSS);
1157
1158            Add_Block_Identifier  (Abrt_Blk, Abrt_Blk_Id);
1159            Expand_At_End_Handler (Abrt_HSS, Abrt_Blk_Id);
1160
1161            --  Present the Abort_Undefer_Direct function to the backend so
1162            --  that it can inline the call to the function.
1163
1164            Add_Inlined_Body (AUD, N);
1165
1166         --  Otherwise aborts are not allowed
1167
1168         else
1169            Abrt_Blk := Fin_Blk;
1170         end if;
1171
1172         Append_To (Stmts, Abrt_Blk);
1173      end if;
1174
1175      --  For a task type, call Free_Task before freeing the ATCB. We used to
1176      --  detect the case of Abort followed by a Free here, because the Free
1177      --  wouldn't actually free if it happens before the aborted task actually
1178      --  terminates. The warning was removed, because Free now works properly
1179      --  (the task will be freed once it terminates).
1180
1181      if Is_Task_Type (Desig_Typ) then
1182         Append_To (Stmts,
1183           Cleanup_Task (N, Duplicate_Subexpr_No_Checks (Arg)));
1184
1185      --  For composite types that contain tasks, recurse over the structure
1186      --  to build the selectors for the task subcomponents.
1187
1188      elsif Has_Task (Desig_Typ) then
1189         if Is_Array_Type (Desig_Typ) then
1190            Append_List_To (Stmts, Cleanup_Array (N, Arg, Desig_Typ));
1191
1192         elsif Is_Record_Type (Desig_Typ) then
1193            Append_List_To (Stmts, Cleanup_Record (N, Arg, Desig_Typ));
1194         end if;
1195      end if;
1196
1197      --  Same for simple protected types. Eventually call Finalize_Protection
1198      --  before freeing the PO for each protected component.
1199
1200      if Is_Simple_Protected_Type (Desig_Typ) then
1201         Append_To (Stmts,
1202           Cleanup_Protected_Object (N, Duplicate_Subexpr_No_Checks (Arg)));
1203
1204      elsif Has_Simple_Protected_Object (Desig_Typ) then
1205         if Is_Array_Type (Desig_Typ) then
1206            Append_List_To (Stmts, Cleanup_Array (N, Arg, Desig_Typ));
1207
1208         elsif Is_Record_Type (Desig_Typ) then
1209            Append_List_To (Stmts, Cleanup_Record (N, Arg, Desig_Typ));
1210         end if;
1211      end if;
1212
1213      --  Normal processing for non-controlled types. The argument to free is
1214      --  a renaming rather than a constant to ensure that the original context
1215      --  is always set to null after the deallocation takes place.
1216
1217      Free_Arg := Duplicate_Subexpr_No_Checks (Arg, Renaming_Req => True);
1218      Free_Nod := Make_Free_Statement (Loc, Empty);
1219      Append_To (Stmts, Free_Nod);
1220      Set_Storage_Pool (Free_Nod, Pool);
1221
1222      --  Attach to tree before analysis of generated subtypes below
1223
1224      Set_Parent (Stmts, Parent (N));
1225
1226      --  Deal with storage pool
1227
1228      if Present (Pool) then
1229
1230         --  Freeing the secondary stack is meaningless
1231
1232         if Is_RTE (Pool, RE_SS_Pool) then
1233            null;
1234
1235         --  If the pool object is of a simple storage pool type, then attempt
1236         --  to locate the type's Deallocate procedure, if any, and set the
1237         --  free operation's procedure to call. If the type doesn't have a
1238         --  Deallocate (which is allowed), then the actual will simply be set
1239         --  to null.
1240
1241         elsif Present
1242                 (Get_Rep_Pragma (Etype (Pool), Name_Simple_Storage_Pool_Type))
1243         then
1244            declare
1245               Pool_Typ : constant Entity_Id := Base_Type (Etype (Pool));
1246               Dealloc  : Entity_Id;
1247
1248            begin
1249               Dealloc := Get_Name_Entity_Id (Name_Deallocate);
1250               while Present (Dealloc) loop
1251                  if Scope (Dealloc) = Scope (Pool_Typ)
1252                    and then Present (First_Formal (Dealloc))
1253                    and then Etype (First_Formal (Dealloc)) = Pool_Typ
1254                  then
1255                     Set_Procedure_To_Call (Free_Nod, Dealloc);
1256                     exit;
1257                  else
1258                     Dealloc := Homonym (Dealloc);
1259                  end if;
1260               end loop;
1261            end;
1262
1263         --  Case of a class-wide pool type: make a dispatching call to
1264         --  Deallocate through the class-wide Deallocate_Any.
1265
1266         elsif Is_Class_Wide_Type (Etype (Pool)) then
1267            Set_Procedure_To_Call (Free_Nod, RTE (RE_Deallocate_Any));
1268
1269         --  Case of a specific pool type: make a statically bound call
1270
1271         else
1272            Set_Procedure_To_Call
1273              (Free_Nod, Find_Prim_Op (Etype (Pool), Name_Deallocate));
1274         end if;
1275      end if;
1276
1277      if Present (Procedure_To_Call (Free_Nod)) then
1278
1279         --  For all cases of a Deallocate call, the back-end needs to be able
1280         --  to compute the size of the object being freed. This may require
1281         --  some adjustments for objects of dynamic size.
1282         --
1283         --  If the type is class wide, we generate an implicit type with the
1284         --  right dynamic size, so that the deallocate call gets the right
1285         --  size parameter computed by GIGI. Same for an access to
1286         --  unconstrained packed array.
1287
1288         if Is_Class_Wide_Type (Desig_Typ)
1289           or else
1290            (Is_Array_Type (Desig_Typ)
1291              and then not Is_Constrained (Desig_Typ)
1292              and then Is_Packed (Desig_Typ))
1293         then
1294            declare
1295               Deref    : constant Node_Id :=
1296                            Make_Explicit_Dereference (Loc,
1297                              Duplicate_Subexpr_No_Checks (Arg));
1298               D_Subtyp : Node_Id;
1299               D_Type   : Entity_Id;
1300
1301            begin
1302               --  Perform minor decoration as it is needed by the side effect
1303               --  removal mechanism.
1304
1305               Set_Etype  (Deref, Desig_Typ);
1306               Set_Parent (Deref, Free_Nod);
1307               D_Subtyp := Make_Subtype_From_Expr (Deref, Desig_Typ);
1308
1309               if Nkind (D_Subtyp) in N_Has_Entity then
1310                  D_Type := Entity (D_Subtyp);
1311
1312               else
1313                  D_Type := Make_Temporary (Loc, 'A');
1314                  Insert_Action (Deref,
1315                    Make_Subtype_Declaration (Loc,
1316                      Defining_Identifier => D_Type,
1317                      Subtype_Indication  => D_Subtyp));
1318               end if;
1319
1320               --  Force freezing at the point of the dereference. For the
1321               --  class wide case, this avoids having the subtype frozen
1322               --  before the equivalent type.
1323
1324               Freeze_Itype (D_Type, Deref);
1325
1326               Set_Actual_Designated_Subtype (Free_Nod, D_Type);
1327            end;
1328         end if;
1329      end if;
1330
1331      --  Ada 2005 (AI-251): In case of abstract interface type we must
1332      --  displace the pointer to reference the base of the object to
1333      --  deallocate its memory, unless we're targetting a VM, in which case
1334      --  no special processing is required.
1335
1336      --  Generate:
1337      --    free (Base_Address (Obj_Ptr))
1338
1339      if Is_Interface (Directly_Designated_Type (Typ))
1340        and then Tagged_Type_Expansion
1341      then
1342         Set_Expression (Free_Nod,
1343           Unchecked_Convert_To (Typ,
1344             Make_Function_Call (Loc,
1345               Name                   =>
1346                 New_Occurrence_Of (RTE (RE_Base_Address), Loc),
1347               Parameter_Associations => New_List (
1348                 Unchecked_Convert_To (RTE (RE_Address), Free_Arg)))));
1349
1350      --  Generate:
1351      --    free (Obj_Ptr)
1352
1353      else
1354         Set_Expression (Free_Nod, Free_Arg);
1355      end if;
1356
1357      --  Only remaining step is to set result to null, or generate a raise of
1358      --  Constraint_Error if the target object is "not null".
1359
1360      if Can_Never_Be_Null (Etype (Arg)) then
1361         Append_To (Stmts,
1362           Make_Raise_Constraint_Error (Loc,
1363             Reason => CE_Access_Check_Failed));
1364
1365      else
1366         declare
1367            Lhs : constant Node_Id := Duplicate_Subexpr_No_Checks (Arg);
1368         begin
1369            Set_Assignment_OK (Lhs);
1370            Append_To (Stmts,
1371              Make_Assignment_Statement (Loc,
1372                Name       => Lhs,
1373                Expression => Make_Null (Loc)));
1374         end;
1375      end if;
1376
1377      --  Generate a test of whether any earlier finalization raised an
1378      --  exception, and in that case raise Program_Error with the previous
1379      --  exception occurrence.
1380
1381      --  Generate:
1382      --    if Raised and then not Abrt then
1383      --       raise Program_Error;                  --  for restricted RTS
1384      --         <or>
1385      --       Raise_From_Controlled_Operation (E);  --  all other cases
1386      --    end if;
1387
1388      if Needs_Fin and then Exceptions_OK then
1389         Append_To (Stmts, Build_Raise_Statement (Fin_Data));
1390      end if;
1391
1392      --  If we know the argument is non-null, then make a block statement
1393      --  that contains the required statements, no need for a test.
1394
1395      if Arg_Known_Non_Null then
1396         Gen_Code :=
1397           Make_Block_Statement (Loc,
1398             Handled_Statement_Sequence =>
1399               Make_Handled_Sequence_Of_Statements (Loc,
1400             Statements => Stmts));
1401
1402      --  If the argument may be null, wrap the statements inside an IF that
1403      --  does an explicit test to exclude the null case.
1404
1405      else
1406         Gen_Code :=
1407           Make_Implicit_If_Statement (N,
1408             Condition       =>
1409               Make_Op_Ne (Loc,
1410                 Left_Opnd  => Duplicate_Subexpr (Arg),
1411                 Right_Opnd => Make_Null (Loc)),
1412             Then_Statements => Stmts);
1413      end if;
1414
1415      --  Rewrite the call
1416
1417      Rewrite (N, Gen_Code);
1418      Analyze (N);
1419   end Expand_Unc_Deallocation;
1420
1421   -----------------------
1422   -- Expand_To_Address --
1423   -----------------------
1424
1425   procedure Expand_To_Address (N : Node_Id) is
1426      Loc : constant Source_Ptr := Sloc (N);
1427      Arg : constant Node_Id := First_Actual (N);
1428      Obj : Node_Id;
1429
1430   begin
1431      Remove_Side_Effects (Arg);
1432
1433      Obj := Make_Explicit_Dereference (Loc, Relocate_Node (Arg));
1434
1435      Rewrite (N,
1436        Make_If_Expression (Loc,
1437          Expressions => New_List (
1438            Make_Op_Eq (Loc,
1439              Left_Opnd => New_Copy_Tree (Arg),
1440              Right_Opnd => Make_Null (Loc)),
1441            New_Occurrence_Of (RTE (RE_Null_Address), Loc),
1442            Make_Attribute_Reference (Loc,
1443              Prefix         => Obj,
1444              Attribute_Name => Name_Address))));
1445
1446      Analyze_And_Resolve (N, RTE (RE_Address));
1447   end Expand_To_Address;
1448
1449   -----------------------
1450   -- Expand_To_Pointer --
1451   -----------------------
1452
1453   procedure Expand_To_Pointer (N : Node_Id) is
1454      Arg : constant Node_Id := First_Actual (N);
1455
1456   begin
1457      Rewrite (N, Unchecked_Convert_To (Etype (N), Arg));
1458      Analyze (N);
1459   end Expand_To_Pointer;
1460
1461   -----------------------
1462   -- Write_Entity_Name --
1463   -----------------------
1464
1465   procedure Write_Entity_Name (E : Entity_Id) is
1466
1467      procedure Write_Entity_Name_Inner (E : Entity_Id);
1468      --  Inner recursive routine, keep outer routine non-recursive to ease
1469      --  debugging when we get strange results from this routine.
1470
1471      -----------------------------
1472      -- Write_Entity_Name_Inner --
1473      -----------------------------
1474
1475      procedure Write_Entity_Name_Inner (E : Entity_Id) is
1476      begin
1477         --  If entity has an internal name, skip by it, and print its scope.
1478         --  Note that Is_Internal_Name destroys Name_Buffer, hence the save
1479         --  and restore since we depend on its current contents. Note that
1480         --  we strip a final R from the name before the test, this is needed
1481         --  for some cases of instantiations.
1482
1483         declare
1484            Save_NB : constant String  := Name_Buffer (1 .. Name_Len);
1485            Save_NL : constant Natural := Name_Len;
1486            Iname   : Boolean;
1487
1488         begin
1489            Get_Name_String (Chars (E));
1490
1491            if Name_Buffer (Name_Len) = 'R' then
1492               Name_Len := Name_Len - 1;
1493            end if;
1494
1495            Iname := Is_Internal_Name;
1496
1497            Name_Buffer (1 .. Save_NL) := Save_NB;
1498            Name_Len := Save_NL;
1499
1500            if Iname then
1501               Write_Entity_Name_Inner (Scope (E));
1502               return;
1503            end if;
1504         end;
1505
1506         --  Just print entity name if its scope is at the outer level
1507
1508         if Scope (E) = Standard_Standard then
1509            null;
1510
1511         --  If scope comes from source, write scope and entity
1512
1513         elsif Comes_From_Source (Scope (E)) then
1514            Write_Entity_Name (Scope (E));
1515            Add_Char_To_Name_Buffer ('.');
1516
1517         --  If in wrapper package skip past it
1518
1519         elsif Is_Wrapper_Package (Scope (E)) then
1520            Write_Entity_Name (Scope (Scope (E)));
1521            Add_Char_To_Name_Buffer ('.');
1522
1523         --  Otherwise nothing to output (happens in unnamed block statements)
1524
1525         else
1526            null;
1527         end if;
1528
1529         --  Output the name
1530
1531         declare
1532            Save_NB : constant String  := Name_Buffer (1 .. Name_Len);
1533            Save_NL : constant Natural := Name_Len;
1534
1535         begin
1536            Get_Unqualified_Decoded_Name_String (Chars (E));
1537
1538            --  Remove trailing upper case letters from the name (useful for
1539            --  dealing with some cases of internal names generated in the case
1540            --  of references from within a generic.
1541
1542            while Name_Len > 1
1543              and then Name_Buffer (Name_Len) in 'A' .. 'Z'
1544            loop
1545               Name_Len := Name_Len  - 1;
1546            end loop;
1547
1548            --  Adjust casing appropriately (gets name from source if possible)
1549
1550            Adjust_Name_Case (Sloc (E));
1551
1552            --  Append to original entry value of Name_Buffer
1553
1554            Name_Buffer (Save_NL + 1 ..  Save_NL + Name_Len) :=
1555              Name_Buffer (1 .. Name_Len);
1556            Name_Buffer (1 .. Save_NL) := Save_NB;
1557            Name_Len := Save_NL + Name_Len;
1558         end;
1559      end Write_Entity_Name_Inner;
1560
1561   --  Start of processing for Write_Entity_Name
1562
1563   begin
1564      Write_Entity_Name_Inner (E);
1565   end Write_Entity_Name;
1566end Exp_Intr;
1567