OSDN Git Service

2010-09-09 Doug Rupp <rupp@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_attr.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ A T T R                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, 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.                                     --
17 --                                                                          --
18 -- You should have received a copy of the GNU General Public License along  --
19 -- with this program; see file COPYING3.  If not see                        --
20 -- <http://www.gnu.org/licenses/>.                                          --
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 Checks;   use Checks;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Exp_Atag; use Exp_Atag;
32 with Exp_Ch2;  use Exp_Ch2;
33 with Exp_Ch3;  use Exp_Ch3;
34 with Exp_Ch6;  use Exp_Ch6;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Dist; use Exp_Dist;
37 with Exp_Imgv; use Exp_Imgv;
38 with Exp_Pakd; use Exp_Pakd;
39 with Exp_Strm; use Exp_Strm;
40 with Exp_Tss;  use Exp_Tss;
41 with Exp_Util; use Exp_Util;
42 with Exp_VFpt; use Exp_VFpt;
43 with Fname;    use Fname;
44 with Freeze;   use Freeze;
45 with Gnatvsn;  use Gnatvsn;
46 with Itypes;   use Itypes;
47 with Lib;      use Lib;
48 with Namet;    use Namet;
49 with Nmake;    use Nmake;
50 with Nlists;   use Nlists;
51 with Opt;      use Opt;
52 with Restrict; use Restrict;
53 with Rident;   use Rident;
54 with Rtsfind;  use Rtsfind;
55 with Sem;      use Sem;
56 with Sem_Aux;  use Sem_Aux;
57 with Sem_Ch6;  use Sem_Ch6;
58 with Sem_Ch7;  use Sem_Ch7;
59 with Sem_Ch8;  use Sem_Ch8;
60 with Sem_Eval; use Sem_Eval;
61 with Sem_Res;  use Sem_Res;
62 with Sem_Util; use Sem_Util;
63 with Sinfo;    use Sinfo;
64 with Snames;   use Snames;
65 with Stand;    use Stand;
66 with Stringt;  use Stringt;
67 with Targparm; use Targparm;
68 with Tbuild;   use Tbuild;
69 with Ttypes;   use Ttypes;
70 with Uintp;    use Uintp;
71 with Uname;    use Uname;
72 with Validsw;  use Validsw;
73
74 package body Exp_Attr is
75
76    -----------------------
77    -- Local Subprograms --
78    -----------------------
79
80    procedure Compile_Stream_Body_In_Scope
81      (N     : Node_Id;
82       Decl  : Node_Id;
83       Arr   : Entity_Id;
84       Check : Boolean);
85    --  The body for a stream subprogram may be generated outside of the scope
86    --  of the type. If the type is fully private, it may depend on the full
87    --  view of other types (e.g. indices) that are currently private as well.
88    --  We install the declarations of the package in which the type is declared
89    --  before compiling the body in what is its proper environment. The Check
90    --  parameter indicates if checks are to be suppressed for the stream body.
91    --  We suppress checks for array/record reads, since the rule is that these
92    --  are like assignments, out of range values due to uninitialized storage,
93    --  or other invalid values do NOT cause a Constraint_Error to be raised.
94
95    procedure Expand_Access_To_Protected_Op
96      (N    : Node_Id;
97       Pref : Node_Id;
98       Typ  : Entity_Id);
99    --  An attribute reference to a protected subprogram is transformed into
100    --  a pair of pointers: one to the object, and one to the operations.
101    --  This expansion is performed for 'Access and for 'Unrestricted_Access.
102
103    procedure Expand_Fpt_Attribute
104      (N    : Node_Id;
105       Pkg  : RE_Id;
106       Nam  : Name_Id;
107       Args : List_Id);
108    --  This procedure expands a call to a floating-point attribute function.
109    --  N is the attribute reference node, and Args is a list of arguments to
110    --  be passed to the function call. Pkg identifies the package containing
111    --  the appropriate instantiation of System.Fat_Gen. Float arguments in Args
112    --  have already been converted to the floating-point type for which Pkg was
113    --  instantiated. The Nam argument is the relevant attribute processing
114    --  routine to be called. This is the same as the attribute name, except in
115    --  the Unaligned_Valid case.
116
117    procedure Expand_Fpt_Attribute_R (N : Node_Id);
118    --  This procedure expands a call to a floating-point attribute function
119    --  that takes a single floating-point argument. The function to be called
120    --  is always the same as the attribute name.
121
122    procedure Expand_Fpt_Attribute_RI (N : Node_Id);
123    --  This procedure expands a call to a floating-point attribute function
124    --  that takes one floating-point argument and one integer argument. The
125    --  function to be called is always the same as the attribute name.
126
127    procedure Expand_Fpt_Attribute_RR (N : Node_Id);
128    --  This procedure expands a call to a floating-point attribute function
129    --  that takes two floating-point arguments. The function to be called
130    --  is always the same as the attribute name.
131
132    procedure Expand_Pred_Succ (N : Node_Id);
133    --  Handles expansion of Pred or Succ attributes for case of non-real
134    --  operand with overflow checking required.
135
136    function Get_Index_Subtype (N : Node_Id) return Entity_Id;
137    --  Used for Last, Last, and Length, when the prefix is an array type.
138    --  Obtains the corresponding index subtype.
139
140    procedure Find_Fat_Info
141      (T        : Entity_Id;
142       Fat_Type : out Entity_Id;
143       Fat_Pkg  : out RE_Id);
144    --  Given a floating-point type T, identifies the package containing the
145    --  attributes for this type (returned in Fat_Pkg), and the corresponding
146    --  type for which this package was instantiated from Fat_Gen. Error if T
147    --  is not a floating-point type.
148
149    function Find_Stream_Subprogram
150      (Typ : Entity_Id;
151       Nam : TSS_Name_Type) return Entity_Id;
152    --  Returns the stream-oriented subprogram attribute for Typ. For tagged
153    --  types, the corresponding primitive operation is looked up, else the
154    --  appropriate TSS from the type itself, or from its closest ancestor
155    --  defining it, is returned. In both cases, inheritance of representation
156    --  aspects is thus taken into account.
157
158    function Get_Stream_Convert_Pragma (T : Entity_Id) return Node_Id;
159    --  Given a type, find a corresponding stream convert pragma that applies to
160    --  the implementation base type of this type (Typ). If found, return the
161    --  pragma node, otherwise return Empty if no pragma is found.
162
163    function Is_Constrained_Packed_Array (Typ : Entity_Id) return Boolean;
164    --  Utility for array attributes, returns true on packed constrained
165    --  arrays, and on access to same.
166
167    function Is_Inline_Floating_Point_Attribute (N : Node_Id) return Boolean;
168    --  Returns true iff the given node refers to an attribute call that
169    --  can be expanded directly by the back end and does not need front end
170    --  expansion. Typically used for rounding and truncation attributes that
171    --  appear directly inside a conversion to integer.
172
173    ----------------------------------
174    -- Compile_Stream_Body_In_Scope --
175    ----------------------------------
176
177    procedure Compile_Stream_Body_In_Scope
178      (N     : Node_Id;
179       Decl  : Node_Id;
180       Arr   : Entity_Id;
181       Check : Boolean)
182    is
183       Installed : Boolean := False;
184       Scop      : constant Entity_Id := Scope (Arr);
185       Curr      : constant Entity_Id := Current_Scope;
186
187    begin
188       if Is_Hidden (Arr)
189         and then not In_Open_Scopes (Scop)
190         and then Ekind (Scop) = E_Package
191       then
192          Push_Scope (Scop);
193          Install_Visible_Declarations (Scop);
194          Install_Private_Declarations (Scop);
195          Installed := True;
196
197          --  The entities in the package are now visible, but the generated
198          --  stream entity must appear in the current scope (usually an
199          --  enclosing stream function) so that itypes all have their proper
200          --  scopes.
201
202          Push_Scope (Curr);
203       end if;
204
205       if Check then
206          Insert_Action (N, Decl);
207       else
208          Insert_Action (N, Decl, Suppress => All_Checks);
209       end if;
210
211       if Installed then
212
213          --  Remove extra copy of current scope, and package itself
214
215          Pop_Scope;
216          End_Package_Scope (Scop);
217       end if;
218    end Compile_Stream_Body_In_Scope;
219
220    -----------------------------------
221    -- Expand_Access_To_Protected_Op --
222    -----------------------------------
223
224    procedure Expand_Access_To_Protected_Op
225      (N    : Node_Id;
226       Pref : Node_Id;
227       Typ  : Entity_Id)
228    is
229       --  The value of the attribute_reference is a record containing two
230       --  fields: an access to the protected object, and an access to the
231       --  subprogram itself. The prefix is a selected component.
232
233       Loc     : constant Source_Ptr := Sloc (N);
234       Agg     : Node_Id;
235       Btyp    : constant Entity_Id := Base_Type (Typ);
236       Sub     : Entity_Id;
237       Sub_Ref : Node_Id;
238       E_T     : constant Entity_Id := Equivalent_Type (Btyp);
239       Acc     : constant Entity_Id :=
240                   Etype (Next_Component (First_Component (E_T)));
241       Obj_Ref : Node_Id;
242       Curr    : Entity_Id;
243
244       function May_Be_External_Call return Boolean;
245       --  If the 'Access is to a local operation, but appears in a context
246       --  where it may lead to a call from outside the object, we must treat
247       --  this as an external call. Clearly we cannot tell without full
248       --  flow analysis, and a subsequent call that uses this 'Access may
249       --  lead to a bounded error (trying to seize locks twice, e.g.). For
250       --  now we treat 'Access as a potential external call if it is an actual
251       --  in a call to an outside subprogram.
252
253       --------------------------
254       -- May_Be_External_Call --
255       --------------------------
256
257       function May_Be_External_Call return Boolean is
258          Subp : Entity_Id;
259          Par  : Node_Id := Parent (N);
260
261       begin
262          --  Account for the case where the Access attribute is part of a
263          --  named parameter association.
264
265          if Nkind (Par) = N_Parameter_Association then
266             Par := Parent (Par);
267          end if;
268
269          if Nkind_In (Par, N_Procedure_Call_Statement, N_Function_Call)
270             and then Is_Entity_Name (Name (Par))
271          then
272             Subp := Entity (Name (Par));
273             return not In_Open_Scopes (Scope (Subp));
274          else
275             return False;
276          end if;
277       end May_Be_External_Call;
278
279    --  Start of processing for Expand_Access_To_Protected_Op
280
281    begin
282       --  Within the body of the protected type, the prefix designates a local
283       --  operation, and the object is the first parameter of the corresponding
284       --  protected body of the current enclosing operation.
285
286       if Is_Entity_Name (Pref) then
287          if May_Be_External_Call then
288             Sub :=
289               New_Occurrence_Of (External_Subprogram (Entity (Pref)), Loc);
290          else
291             Sub :=
292               New_Occurrence_Of
293                 (Protected_Body_Subprogram (Entity (Pref)), Loc);
294          end if;
295
296          --  Don't traverse the scopes when the attribute occurs within an init
297          --  proc, because we directly use the _init formal of the init proc in
298          --  that case.
299
300          Curr := Current_Scope;
301          if not Is_Init_Proc (Curr) then
302             pragma Assert (In_Open_Scopes (Scope (Entity (Pref))));
303
304             while Scope (Curr) /= Scope (Entity (Pref)) loop
305                Curr := Scope (Curr);
306             end loop;
307          end if;
308
309          --  In case of protected entries the first formal of its Protected_
310          --  Body_Subprogram is the address of the object.
311
312          if Ekind (Curr) = E_Entry then
313             Obj_Ref :=
314                New_Occurrence_Of
315                  (First_Formal
316                    (Protected_Body_Subprogram (Curr)), Loc);
317
318          --  If the current scope is an init proc, then use the address of the
319          --  _init formal as the object reference.
320
321          elsif Is_Init_Proc (Curr) then
322             Obj_Ref :=
323               Make_Attribute_Reference (Loc,
324                 Prefix         => New_Occurrence_Of (First_Formal (Curr), Loc),
325                 Attribute_Name => Name_Address);
326
327          --  In case of protected subprograms the first formal of its
328          --  Protected_Body_Subprogram is the object and we get its address.
329
330          else
331             Obj_Ref :=
332               Make_Attribute_Reference (Loc,
333                 Prefix =>
334                    New_Occurrence_Of
335                      (First_Formal
336                         (Protected_Body_Subprogram (Curr)), Loc),
337                 Attribute_Name => Name_Address);
338          end if;
339
340       --  Case where the prefix is not an entity name. Find the
341       --  version of the protected operation to be called from
342       --  outside the protected object.
343
344       else
345          Sub :=
346            New_Occurrence_Of
347              (External_Subprogram
348                (Entity (Selector_Name (Pref))), Loc);
349
350          Obj_Ref :=
351            Make_Attribute_Reference (Loc,
352              Prefix => Relocate_Node (Prefix (Pref)),
353                Attribute_Name => Name_Address);
354       end if;
355
356       Sub_Ref :=
357         Make_Attribute_Reference (Loc,
358           Prefix         => Sub,
359           Attribute_Name => Name_Access);
360
361       --  We set the type of the access reference to the already generated
362       --  access_to_subprogram type, and declare the reference analyzed, to
363       --  prevent further expansion when the enclosing aggregate is analyzed.
364
365       Set_Etype (Sub_Ref, Acc);
366       Set_Analyzed (Sub_Ref);
367
368       Agg :=
369         Make_Aggregate (Loc,
370           Expressions => New_List (Obj_Ref, Sub_Ref));
371
372       --  Sub_Ref has been marked as analyzed, but we still need to make sure
373       --  Sub is correctly frozen.
374
375       Freeze_Before (N, Entity (Sub));
376
377       Rewrite (N, Agg);
378       Analyze_And_Resolve (N, E_T);
379
380       --  For subsequent analysis, the node must retain its type. The backend
381       --  will replace it with the equivalent type where needed.
382
383       Set_Etype (N, Typ);
384    end Expand_Access_To_Protected_Op;
385
386    --------------------------
387    -- Expand_Fpt_Attribute --
388    --------------------------
389
390    procedure Expand_Fpt_Attribute
391      (N    : Node_Id;
392       Pkg  : RE_Id;
393       Nam  : Name_Id;
394       Args : List_Id)
395    is
396       Loc : constant Source_Ptr := Sloc (N);
397       Typ : constant Entity_Id  := Etype (N);
398       Fnm : Node_Id;
399
400    begin
401       --  The function name is the selected component Attr_xxx.yyy where
402       --  Attr_xxx is the package name, and yyy is the argument Nam.
403
404       --  Note: it would be more usual to have separate RE entries for each
405       --  of the entities in the Fat packages, but first they have identical
406       --  names (so we would have to have lots of renaming declarations to
407       --  meet the normal RE rule of separate names for all runtime entities),
408       --  and second there would be an awful lot of them!
409
410       Fnm :=
411         Make_Selected_Component (Loc,
412           Prefix        => New_Reference_To (RTE (Pkg), Loc),
413           Selector_Name => Make_Identifier (Loc, Nam));
414
415       --  The generated call is given the provided set of parameters, and then
416       --  wrapped in a conversion which converts the result to the target type
417       --  We use the base type as the target because a range check may be
418       --  required.
419
420       Rewrite (N,
421         Unchecked_Convert_To (Base_Type (Etype (N)),
422           Make_Function_Call (Loc,
423             Name                   => Fnm,
424             Parameter_Associations => Args)));
425
426       Analyze_And_Resolve (N, Typ);
427    end Expand_Fpt_Attribute;
428
429    ----------------------------
430    -- Expand_Fpt_Attribute_R --
431    ----------------------------
432
433    --  The single argument is converted to its root type to call the
434    --  appropriate runtime function, with the actual call being built
435    --  by Expand_Fpt_Attribute
436
437    procedure Expand_Fpt_Attribute_R (N : Node_Id) is
438       E1  : constant Node_Id    := First (Expressions (N));
439       Ftp : Entity_Id;
440       Pkg : RE_Id;
441    begin
442       Find_Fat_Info (Etype (E1), Ftp, Pkg);
443       Expand_Fpt_Attribute
444         (N, Pkg, Attribute_Name (N),
445          New_List (Unchecked_Convert_To (Ftp, Relocate_Node (E1))));
446    end Expand_Fpt_Attribute_R;
447
448    -----------------------------
449    -- Expand_Fpt_Attribute_RI --
450    -----------------------------
451
452    --  The first argument is converted to its root type and the second
453    --  argument is converted to standard long long integer to call the
454    --  appropriate runtime function, with the actual call being built
455    --  by Expand_Fpt_Attribute
456
457    procedure Expand_Fpt_Attribute_RI (N : Node_Id) is
458       E1  : constant Node_Id   := First (Expressions (N));
459       Ftp : Entity_Id;
460       Pkg : RE_Id;
461       E2  : constant Node_Id   := Next (E1);
462    begin
463       Find_Fat_Info (Etype (E1), Ftp, Pkg);
464       Expand_Fpt_Attribute
465         (N, Pkg, Attribute_Name (N),
466          New_List (
467            Unchecked_Convert_To (Ftp, Relocate_Node (E1)),
468            Unchecked_Convert_To (Standard_Integer, Relocate_Node (E2))));
469    end Expand_Fpt_Attribute_RI;
470
471    -----------------------------
472    -- Expand_Fpt_Attribute_RR --
473    -----------------------------
474
475    --  The two arguments are converted to their root types to call the
476    --  appropriate runtime function, with the actual call being built
477    --  by Expand_Fpt_Attribute
478
479    procedure Expand_Fpt_Attribute_RR (N : Node_Id) is
480       E1  : constant Node_Id   := First (Expressions (N));
481       Ftp : Entity_Id;
482       Pkg : RE_Id;
483       E2  : constant Node_Id   := Next (E1);
484    begin
485       Find_Fat_Info (Etype (E1), Ftp, Pkg);
486       Expand_Fpt_Attribute
487         (N, Pkg, Attribute_Name (N),
488          New_List (
489            Unchecked_Convert_To (Ftp, Relocate_Node (E1)),
490            Unchecked_Convert_To (Ftp, Relocate_Node (E2))));
491    end Expand_Fpt_Attribute_RR;
492
493    ----------------------------------
494    -- Expand_N_Attribute_Reference --
495    ----------------------------------
496
497    procedure Expand_N_Attribute_Reference (N : Node_Id) is
498       Loc   : constant Source_Ptr   := Sloc (N);
499       Typ   : constant Entity_Id    := Etype (N);
500       Btyp  : constant Entity_Id    := Base_Type (Typ);
501       Pref  : constant Node_Id      := Prefix (N);
502       Ptyp  : constant Entity_Id    := Etype (Pref);
503       Exprs : constant List_Id      := Expressions (N);
504       Id    : constant Attribute_Id := Get_Attribute_Id (Attribute_Name (N));
505
506       procedure Rewrite_Stream_Proc_Call (Pname : Entity_Id);
507       --  Rewrites a stream attribute for Read, Write or Output with the
508       --  procedure call. Pname is the entity for the procedure to call.
509
510       ------------------------------
511       -- Rewrite_Stream_Proc_Call --
512       ------------------------------
513
514       procedure Rewrite_Stream_Proc_Call (Pname : Entity_Id) is
515          Item       : constant Node_Id   := Next (First (Exprs));
516          Formal     : constant Entity_Id := Next_Formal (First_Formal (Pname));
517          Formal_Typ : constant Entity_Id := Etype (Formal);
518          Is_Written : constant Boolean   := (Ekind (Formal) /= E_In_Parameter);
519
520       begin
521          --  The expansion depends on Item, the second actual, which is
522          --  the object being streamed in or out.
523
524          --  If the item is a component of a packed array type, and
525          --  a conversion is needed on exit, we introduce a temporary to
526          --  hold the value, because otherwise the packed reference will
527          --  not be properly expanded.
528
529          if Nkind (Item) = N_Indexed_Component
530            and then Is_Packed (Base_Type (Etype (Prefix (Item))))
531            and then Base_Type (Etype (Item)) /= Base_Type (Formal_Typ)
532            and then Is_Written
533          then
534             declare
535                Temp : constant Entity_Id := Make_Temporary (Loc, 'V');
536                Decl : Node_Id;
537                Assn : Node_Id;
538
539             begin
540                Decl :=
541                  Make_Object_Declaration (Loc,
542                    Defining_Identifier => Temp,
543                    Object_Definition    =>
544                      New_Occurrence_Of (Formal_Typ, Loc));
545                Set_Etype (Temp, Formal_Typ);
546
547                Assn :=
548                  Make_Assignment_Statement (Loc,
549                    Name => New_Copy_Tree (Item),
550                    Expression =>
551                      Unchecked_Convert_To
552                        (Etype (Item), New_Occurrence_Of (Temp, Loc)));
553
554                Rewrite (Item, New_Occurrence_Of (Temp, Loc));
555                Insert_Actions (N,
556                  New_List (
557                    Decl,
558                    Make_Procedure_Call_Statement (Loc,
559                      Name => New_Occurrence_Of (Pname, Loc),
560                      Parameter_Associations => Exprs),
561                    Assn));
562
563                Rewrite (N, Make_Null_Statement (Loc));
564                return;
565             end;
566          end if;
567
568          --  For the class-wide dispatching cases, and for cases in which
569          --  the base type of the second argument matches the base type of
570          --  the corresponding formal parameter (that is to say the stream
571          --  operation is not inherited), we are all set, and can use the
572          --  argument unchanged.
573
574          --  For all other cases we do an unchecked conversion of the second
575          --  parameter to the type of the formal of the procedure we are
576          --  calling. This deals with the private type cases, and with going
577          --  to the root type as required in elementary type case.
578
579          if not Is_Class_Wide_Type (Entity (Pref))
580            and then not Is_Class_Wide_Type (Etype (Item))
581            and then Base_Type (Etype (Item)) /= Base_Type (Formal_Typ)
582          then
583             Rewrite (Item,
584               Unchecked_Convert_To (Formal_Typ, Relocate_Node (Item)));
585
586             --  For untagged derived types set Assignment_OK, to prevent
587             --  copies from being created when the unchecked conversion
588             --  is expanded (which would happen in Remove_Side_Effects
589             --  if Expand_N_Unchecked_Conversion were allowed to call
590             --  Force_Evaluation). The copy could violate Ada semantics
591             --  in cases such as an actual that is an out parameter.
592             --  Note that this approach is also used in exp_ch7 for calls
593             --  to controlled type operations to prevent problems with
594             --  actuals wrapped in unchecked conversions.
595
596             if Is_Untagged_Derivation (Etype (Expression (Item))) then
597                Set_Assignment_OK (Item);
598             end if;
599          end if;
600
601          --  The stream operation to call maybe a renaming created by
602          --  an attribute definition clause, and may not be frozen yet.
603          --  Ensure that it has the necessary extra formals.
604
605          if not Is_Frozen (Pname) then
606             Create_Extra_Formals (Pname);
607          end if;
608
609          --  And now rewrite the call
610
611          Rewrite (N,
612            Make_Procedure_Call_Statement (Loc,
613              Name => New_Occurrence_Of (Pname, Loc),
614              Parameter_Associations => Exprs));
615
616          Analyze (N);
617       end Rewrite_Stream_Proc_Call;
618
619    --  Start of processing for Expand_N_Attribute_Reference
620
621    begin
622       --  Do required validity checking, if enabled. Do not apply check to
623       --  output parameters of an Asm instruction, since the value of this
624       --  is not set till after the attribute has been elaborated, and do
625       --  not apply the check to the arguments of a 'Read or 'Input attribute
626       --  reference since the scalar argument is an OUT scalar.
627
628       if Validity_Checks_On and then Validity_Check_Operands
629         and then Id /= Attribute_Asm_Output
630         and then Id /= Attribute_Read
631         and then Id /= Attribute_Input
632       then
633          declare
634             Expr : Node_Id;
635          begin
636             Expr := First (Expressions (N));
637             while Present (Expr) loop
638                Ensure_Valid (Expr);
639                Next (Expr);
640             end loop;
641          end;
642       end if;
643
644       --  Ada 2005 (AI-318-02): If attribute prefix is a call to a build-in-
645       --  place function, then a temporary return object needs to be created
646       --  and access to it must be passed to the function. Currently we limit
647       --  such functions to those with inherently limited result subtypes, but
648       --  eventually we plan to expand the functions that are treated as
649       --  build-in-place to include other composite result types.
650
651       if Ada_Version >= Ada_05
652         and then Is_Build_In_Place_Function_Call (Pref)
653       then
654          Make_Build_In_Place_Call_In_Anonymous_Context (Pref);
655       end if;
656
657       --  If prefix is a protected type name, this is a reference to the
658       --  current instance of the type. For a component definition, nothing
659       --  to do (expansion will occur in the init proc). In other contexts,
660       --  rewrite into reference to current instance.
661
662       if Is_Protected_Self_Reference (Pref)
663            and then not
664              (Nkind_In (Parent (N), N_Index_Or_Discriminant_Constraint,
665                                     N_Discriminant_Association)
666                 and then Nkind (Parent (Parent (Parent (Parent (N))))) =
667                                                       N_Component_Definition)
668       then
669          Rewrite (Pref, Concurrent_Ref (Pref));
670          Analyze (Pref);
671       end if;
672
673       --  Remaining processing depends on specific attribute
674
675       case Id is
676
677       ------------
678       -- Access --
679       ------------
680
681       when Attribute_Access              |
682            Attribute_Unchecked_Access    |
683            Attribute_Unrestricted_Access =>
684
685          Access_Cases : declare
686             Ref_Object : constant Node_Id := Get_Referenced_Object (Pref);
687             Btyp_DDT   : Entity_Id;
688
689             function Enclosing_Object (N : Node_Id) return Node_Id;
690             --  If N denotes a compound name (selected component, indexed
691             --  component, or slice), returns the name of the outermost such
692             --  enclosing object. Otherwise returns N. If the object is a
693             --  renaming, then the renamed object is returned.
694
695             ----------------------
696             -- Enclosing_Object --
697             ----------------------
698
699             function Enclosing_Object (N : Node_Id) return Node_Id is
700                Obj_Name : Node_Id;
701
702             begin
703                Obj_Name := N;
704                while Nkind_In (Obj_Name, N_Selected_Component,
705                                          N_Indexed_Component,
706                                          N_Slice)
707                loop
708                   Obj_Name := Prefix (Obj_Name);
709                end loop;
710
711                return Get_Referenced_Object (Obj_Name);
712             end Enclosing_Object;
713
714             --  Local declarations
715
716             Enc_Object : constant Node_Id := Enclosing_Object (Ref_Object);
717
718          --  Start of processing for Access_Cases
719
720          begin
721             Btyp_DDT := Designated_Type (Btyp);
722
723             --  Handle designated types that come from the limited view
724
725             if Ekind (Btyp_DDT) = E_Incomplete_Type
726               and then From_With_Type (Btyp_DDT)
727               and then Present (Non_Limited_View (Btyp_DDT))
728             then
729                Btyp_DDT := Non_Limited_View (Btyp_DDT);
730
731             elsif Is_Class_Wide_Type (Btyp_DDT)
732                and then Ekind (Etype (Btyp_DDT)) = E_Incomplete_Type
733                and then From_With_Type (Etype (Btyp_DDT))
734                and then Present (Non_Limited_View (Etype (Btyp_DDT)))
735                and then Present (Class_Wide_Type
736                                   (Non_Limited_View (Etype (Btyp_DDT))))
737             then
738                Btyp_DDT :=
739                  Class_Wide_Type (Non_Limited_View (Etype (Btyp_DDT)));
740             end if;
741
742             --  In order to improve the text of error messages, the designated
743             --  type of access-to-subprogram itypes is set by the semantics as
744             --  the associated subprogram entity (see sem_attr). Now we replace
745             --  such node with the proper E_Subprogram_Type itype.
746
747             if Id = Attribute_Unrestricted_Access
748               and then Is_Subprogram (Directly_Designated_Type (Typ))
749             then
750                --  The following conditions ensure that this special management
751                --  is done only for "Address!(Prim'Unrestricted_Access)" nodes.
752                --  At this stage other cases in which the designated type is
753                --  still a subprogram (instead of an E_Subprogram_Type) are
754                --  wrong because the semantics must have overridden the type of
755                --  the node with the type imposed by the context.
756
757                if Nkind (Parent (N)) = N_Unchecked_Type_Conversion
758                  and then Etype (Parent (N)) = RTE (RE_Prim_Ptr)
759                then
760                   Set_Etype (N, RTE (RE_Prim_Ptr));
761
762                else
763                   declare
764                      Subp       : constant Entity_Id :=
765                                     Directly_Designated_Type (Typ);
766                      Etyp       : Entity_Id;
767                      Extra      : Entity_Id := Empty;
768                      New_Formal : Entity_Id;
769                      Old_Formal : Entity_Id := First_Formal (Subp);
770                      Subp_Typ   : Entity_Id;
771
772                   begin
773                      Subp_Typ := Create_Itype (E_Subprogram_Type, N);
774                      Set_Etype (Subp_Typ, Etype (Subp));
775                      Set_Returns_By_Ref (Subp_Typ, Returns_By_Ref (Subp));
776
777                      if Present (Old_Formal) then
778                         New_Formal := New_Copy (Old_Formal);
779                         Set_First_Entity (Subp_Typ, New_Formal);
780
781                         loop
782                            Set_Scope (New_Formal, Subp_Typ);
783                            Etyp := Etype (New_Formal);
784
785                            --  Handle itypes. There is no need to duplicate
786                            --  here the itypes associated with record types
787                            --  (i.e the implicit full view of private types).
788
789                            if Is_Itype (Etyp)
790                              and then Ekind (Base_Type (Etyp)) /= E_Record_Type
791                            then
792                               Extra := New_Copy (Etyp);
793                               Set_Parent (Extra, New_Formal);
794                               Set_Etype (New_Formal, Extra);
795                               Set_Scope (Extra, Subp_Typ);
796                            end if;
797
798                            Extra := New_Formal;
799                            Next_Formal (Old_Formal);
800                            exit when No (Old_Formal);
801
802                            Set_Next_Entity (New_Formal,
803                              New_Copy (Old_Formal));
804                            Next_Entity (New_Formal);
805                         end loop;
806
807                         Set_Next_Entity (New_Formal, Empty);
808                         Set_Last_Entity (Subp_Typ, Extra);
809                      end if;
810
811                      --  Now that the explicit formals have been duplicated,
812                      --  any extra formals needed by the subprogram must be
813                      --  created.
814
815                      if Present (Extra) then
816                         Set_Extra_Formal (Extra, Empty);
817                      end if;
818
819                      Create_Extra_Formals (Subp_Typ);
820                      Set_Directly_Designated_Type (Typ, Subp_Typ);
821                   end;
822                end if;
823             end if;
824
825             if Is_Access_Protected_Subprogram_Type (Btyp) then
826                Expand_Access_To_Protected_Op (N, Pref, Typ);
827
828             --  If prefix is a type name, this is a reference to the current
829             --  instance of the type, within its initialization procedure.
830
831             elsif Is_Entity_Name (Pref)
832               and then Is_Type (Entity (Pref))
833             then
834                declare
835                   Par    : Node_Id;
836                   Formal : Entity_Id;
837
838                begin
839                   --  If the current instance name denotes a task type, then
840                   --  the access attribute is rewritten to be the name of the
841                   --  "_task" parameter associated with the task type's task
842                   --  procedure. An unchecked conversion is applied to ensure
843                   --  a type match in cases of expander-generated calls (e.g.
844                   --  init procs).
845
846                   if Is_Task_Type (Entity (Pref)) then
847                      Formal :=
848                        First_Entity (Get_Task_Body_Procedure (Entity (Pref)));
849                      while Present (Formal) loop
850                         exit when Chars (Formal) = Name_uTask;
851                         Next_Entity (Formal);
852                      end loop;
853
854                      pragma Assert (Present (Formal));
855
856                      Rewrite (N,
857                        Unchecked_Convert_To (Typ,
858                          New_Occurrence_Of (Formal, Loc)));
859                      Set_Etype (N, Typ);
860
861                      --  The expression must appear in a default expression,
862                      --  (which in the initialization procedure is the
863                      --  right-hand side of an assignment), and not in a
864                      --  discriminant constraint.
865
866                   else
867                      Par := Parent (N);
868                      while Present (Par) loop
869                         exit when Nkind (Par) = N_Assignment_Statement;
870
871                         if Nkind (Par) = N_Component_Declaration then
872                            return;
873                         end if;
874
875                         Par := Parent (Par);
876                      end loop;
877
878                      if Present (Par) then
879                         Rewrite (N,
880                           Make_Attribute_Reference (Loc,
881                             Prefix => Make_Identifier (Loc, Name_uInit),
882                             Attribute_Name  => Attribute_Name (N)));
883
884                         Analyze_And_Resolve (N, Typ);
885                      end if;
886                   end if;
887                end;
888
889             --  If the prefix of an Access attribute is a dereference of an
890             --  access parameter (or a renaming of such a dereference, or a
891             --  subcomponent of such a dereference) and the context is a
892             --  general access type (including the type of an object or
893             --  component with an access_definition, but not the anonymous
894             --  type of an access parameter or access discriminant), then
895             --  apply an accessibility check to the access parameter. We used
896             --  to rewrite the access parameter as a type conversion, but that
897             --  could only be done if the immediate prefix of the Access
898             --  attribute was the dereference, and didn't handle cases where
899             --  the attribute is applied to a subcomponent of the dereference,
900             --  since there's generally no available, appropriate access type
901             --  to convert to in that case. The attribute is passed as the
902             --  point to insert the check, because the access parameter may
903             --  come from a renaming, possibly in a different scope, and the
904             --  check must be associated with the attribute itself.
905
906             elsif Id = Attribute_Access
907               and then Nkind (Enc_Object) = N_Explicit_Dereference
908               and then Is_Entity_Name (Prefix (Enc_Object))
909               and then (Ekind (Btyp) = E_General_Access_Type
910                          or else Is_Local_Anonymous_Access (Btyp))
911               and then Ekind (Entity (Prefix (Enc_Object))) in Formal_Kind
912               and then Ekind (Etype (Entity (Prefix (Enc_Object))))
913                          = E_Anonymous_Access_Type
914               and then Present (Extra_Accessibility
915                                 (Entity (Prefix (Enc_Object))))
916             then
917                Apply_Accessibility_Check (Prefix (Enc_Object), Typ, N);
918
919             --  Ada 2005 (AI-251): If the designated type is an interface we
920             --  add an implicit conversion to force the displacement of the
921             --  pointer to reference the secondary dispatch table.
922
923             elsif Is_Interface (Btyp_DDT)
924               and then (Comes_From_Source (N)
925                          or else Comes_From_Source (Ref_Object)
926                          or else (Nkind (Ref_Object) in N_Has_Chars
927                                    and then Chars (Ref_Object) = Name_uInit))
928             then
929                if Nkind (Ref_Object) /= N_Explicit_Dereference then
930
931                   --  No implicit conversion required if types match, or if
932                   --  the prefix is the class_wide_type of the interface. In
933                   --  either case passing an object of the interface type has
934                   --  already set the pointer correctly.
935
936                   if Btyp_DDT = Etype (Ref_Object)
937                     or else (Is_Class_Wide_Type (Etype (Ref_Object))
938                               and then
939                                Class_Wide_Type (Btyp_DDT) = Etype (Ref_Object))
940                   then
941                      null;
942
943                   else
944                      Rewrite (Prefix (N),
945                        Convert_To (Btyp_DDT,
946                          New_Copy_Tree (Prefix (N))));
947
948                      Analyze_And_Resolve (Prefix (N), Btyp_DDT);
949                   end if;
950
951                --  When the object is an explicit dereference, convert the
952                --  dereference's prefix.
953
954                else
955                   declare
956                      Obj_DDT : constant Entity_Id :=
957                                  Base_Type
958                                    (Directly_Designated_Type
959                                      (Etype (Prefix (Ref_Object))));
960                   begin
961                      --  No implicit conversion required if designated types
962                      --  match.
963
964                      if Obj_DDT /= Btyp_DDT
965                        and then not (Is_Class_Wide_Type (Obj_DDT)
966                                        and then Etype (Obj_DDT) = Btyp_DDT)
967                      then
968                         Rewrite (N,
969                           Convert_To (Typ,
970                             New_Copy_Tree (Prefix (Ref_Object))));
971                         Analyze_And_Resolve (N, Typ);
972                      end if;
973                   end;
974                end if;
975             end if;
976          end Access_Cases;
977
978       --------------
979       -- Adjacent --
980       --------------
981
982       --  Transforms 'Adjacent into a call to the floating-point attribute
983       --  function Adjacent in Fat_xxx (where xxx is the root type)
984
985       when Attribute_Adjacent =>
986          Expand_Fpt_Attribute_RR (N);
987
988       -------------
989       -- Address --
990       -------------
991
992       when Attribute_Address => Address : declare
993          Task_Proc : Entity_Id;
994
995       begin
996          --  If the prefix is a task or a task type, the useful address is that
997          --  of the procedure for the task body, i.e. the actual program unit.
998          --  We replace the original entity with that of the procedure.
999
1000          if Is_Entity_Name (Pref)
1001            and then Is_Task_Type (Entity (Pref))
1002          then
1003             Task_Proc := Next_Entity (Root_Type (Ptyp));
1004
1005             while Present (Task_Proc) loop
1006                exit when Ekind (Task_Proc) = E_Procedure
1007                  and then Etype (First_Formal (Task_Proc)) =
1008                                   Corresponding_Record_Type (Ptyp);
1009                Next_Entity (Task_Proc);
1010             end loop;
1011
1012             if Present (Task_Proc) then
1013                Set_Entity (Pref, Task_Proc);
1014                Set_Etype  (Pref, Etype (Task_Proc));
1015             end if;
1016
1017          --  Similarly, the address of a protected operation is the address
1018          --  of the corresponding protected body, regardless of the protected
1019          --  object from which it is selected.
1020
1021          elsif Nkind (Pref) = N_Selected_Component
1022            and then Is_Subprogram (Entity (Selector_Name (Pref)))
1023            and then Is_Protected_Type (Scope (Entity (Selector_Name (Pref))))
1024          then
1025             Rewrite (Pref,
1026               New_Occurrence_Of (
1027                 External_Subprogram (Entity (Selector_Name (Pref))), Loc));
1028
1029          elsif Nkind (Pref) = N_Explicit_Dereference
1030            and then Ekind (Ptyp) = E_Subprogram_Type
1031            and then Convention (Ptyp) = Convention_Protected
1032          then
1033             --  The prefix is be a dereference of an access_to_protected_
1034             --  subprogram. The desired address is the second component of
1035             --  the record that represents the access.
1036
1037             declare
1038                Addr : constant Entity_Id := Etype (N);
1039                Ptr  : constant Node_Id   := Prefix (Pref);
1040                T    : constant Entity_Id :=
1041                         Equivalent_Type (Base_Type (Etype (Ptr)));
1042
1043             begin
1044                Rewrite (N,
1045                  Unchecked_Convert_To (Addr,
1046                    Make_Selected_Component (Loc,
1047                      Prefix => Unchecked_Convert_To (T, Ptr),
1048                      Selector_Name => New_Occurrence_Of (
1049                        Next_Entity (First_Entity (T)), Loc))));
1050
1051                Analyze_And_Resolve (N, Addr);
1052             end;
1053
1054          --  Ada 2005 (AI-251): Class-wide interface objects are always
1055          --  "displaced" to reference the tag associated with the interface
1056          --  type. In order to obtain the real address of such objects we
1057          --  generate a call to a run-time subprogram that returns the base
1058          --  address of the object.
1059
1060          --  This processing is not needed in the VM case, where dispatching
1061          --  issues are taken care of by the virtual machine.
1062
1063          elsif Is_Class_Wide_Type (Ptyp)
1064            and then Is_Interface (Ptyp)
1065            and then Tagged_Type_Expansion
1066            and then not (Nkind (Pref) in N_Has_Entity
1067                           and then Is_Subprogram (Entity (Pref)))
1068          then
1069             Rewrite (N,
1070               Make_Function_Call (Loc,
1071                 Name => New_Reference_To (RTE (RE_Base_Address), Loc),
1072                 Parameter_Associations => New_List (
1073                   Relocate_Node (N))));
1074             Analyze (N);
1075             return;
1076          end if;
1077
1078          --  Deal with packed array reference, other cases are handled by
1079          --  the back end.
1080
1081          if Involves_Packed_Array_Reference (Pref) then
1082             Expand_Packed_Address_Reference (N);
1083          end if;
1084       end Address;
1085
1086       ---------------
1087       -- Alignment --
1088       ---------------
1089
1090       when Attribute_Alignment => Alignment : declare
1091          New_Node : Node_Id;
1092
1093       begin
1094          --  For class-wide types, X'Class'Alignment is transformed into a
1095          --  direct reference to the Alignment of the class type, so that the
1096          --  back end does not have to deal with the X'Class'Alignment
1097          --  reference.
1098
1099          if Is_Entity_Name (Pref)
1100            and then Is_Class_Wide_Type (Entity (Pref))
1101          then
1102             Rewrite (Prefix (N), New_Occurrence_Of (Entity (Pref), Loc));
1103             return;
1104
1105          --  For x'Alignment applied to an object of a class wide type,
1106          --  transform X'Alignment into a call to the predefined primitive
1107          --  operation _Alignment applied to X.
1108
1109          elsif Is_Class_Wide_Type (Ptyp) then
1110
1111             --  No need to do anything else compiling under restriction
1112             --  No_Dispatching_Calls. During the semantic analysis we
1113             --  already notified such violation.
1114
1115             if Restriction_Active (No_Dispatching_Calls) then
1116                return;
1117             end if;
1118
1119             New_Node :=
1120               Make_Function_Call (Loc,
1121                 Name => New_Reference_To
1122                   (Find_Prim_Op (Ptyp, Name_uAlignment), Loc),
1123                 Parameter_Associations => New_List (Pref));
1124
1125             if Typ /= Standard_Integer then
1126
1127                --  The context is a specific integer type with which the
1128                --  original attribute was compatible. The function has a
1129                --  specific type as well, so to preserve the compatibility
1130                --  we must convert explicitly.
1131
1132                New_Node := Convert_To (Typ, New_Node);
1133             end if;
1134
1135             Rewrite (N, New_Node);
1136             Analyze_And_Resolve (N, Typ);
1137             return;
1138
1139          --  For all other cases, we just have to deal with the case of
1140          --  the fact that the result can be universal.
1141
1142          else
1143             Apply_Universal_Integer_Attribute_Checks (N);
1144          end if;
1145       end Alignment;
1146
1147       ---------------
1148       -- AST_Entry --
1149       ---------------
1150
1151       when Attribute_AST_Entry => AST_Entry : declare
1152          Ttyp : Entity_Id;
1153          T_Id : Node_Id;
1154          Eent : Entity_Id;
1155
1156          Entry_Ref : Node_Id;
1157          --  The reference to the entry or entry family
1158
1159          Index : Node_Id;
1160          --  The index expression for an entry family reference, or
1161          --  the Empty if Entry_Ref references a simple entry.
1162
1163       begin
1164          if Nkind (Pref) = N_Indexed_Component then
1165             Entry_Ref := Prefix (Pref);
1166             Index := First (Expressions (Pref));
1167          else
1168             Entry_Ref := Pref;
1169             Index := Empty;
1170          end if;
1171
1172          --  Get expression for Task_Id and the entry entity
1173
1174          if Nkind (Entry_Ref) = N_Selected_Component then
1175             T_Id :=
1176               Make_Attribute_Reference (Loc,
1177                 Attribute_Name => Name_Identity,
1178                 Prefix         => Prefix (Entry_Ref));
1179
1180             Ttyp := Etype (Prefix (Entry_Ref));
1181             Eent := Entity (Selector_Name (Entry_Ref));
1182
1183          else
1184             T_Id :=
1185               Make_Function_Call (Loc,
1186                 Name => New_Occurrence_Of (RTE (RE_Current_Task), Loc));
1187
1188             Eent  := Entity (Entry_Ref);
1189
1190             --  We have to find the enclosing task to get the task type
1191             --  There must be one, since we already validated this earlier
1192
1193             Ttyp := Current_Scope;
1194             while not Is_Task_Type (Ttyp) loop
1195                Ttyp := Scope (Ttyp);
1196             end loop;
1197          end if;
1198
1199          --  Now rewrite the attribute with a call to Create_AST_Handler
1200
1201          Rewrite (N,
1202            Make_Function_Call (Loc,
1203              Name => New_Occurrence_Of (RTE (RE_Create_AST_Handler), Loc),
1204              Parameter_Associations => New_List (
1205                T_Id,
1206                Entry_Index_Expression (Loc, Eent, Index, Ttyp))));
1207
1208          Analyze_And_Resolve (N, RTE (RE_AST_Handler));
1209       end AST_Entry;
1210
1211       ---------
1212       -- Bit --
1213       ---------
1214
1215       --  We compute this if a packed array reference was present, otherwise we
1216       --  leave the computation up to the back end.
1217
1218       when Attribute_Bit =>
1219          if Involves_Packed_Array_Reference (Pref) then
1220             Expand_Packed_Bit_Reference (N);
1221          else
1222             Apply_Universal_Integer_Attribute_Checks (N);
1223          end if;
1224
1225       ------------------
1226       -- Bit_Position --
1227       ------------------
1228
1229       --  We compute this if a component clause was present, otherwise we leave
1230       --  the computation up to the back end, since we don't know what layout
1231       --  will be chosen.
1232
1233       --  Note that the attribute can apply to a naked record component
1234       --  in generated code (i.e. the prefix is an identifier that
1235       --  references the component or discriminant entity).
1236
1237       when Attribute_Bit_Position => Bit_Position : declare
1238          CE : Entity_Id;
1239
1240       begin
1241          if Nkind (Pref) = N_Identifier then
1242             CE := Entity (Pref);
1243          else
1244             CE := Entity (Selector_Name (Pref));
1245          end if;
1246
1247          if Known_Static_Component_Bit_Offset (CE) then
1248             Rewrite (N,
1249               Make_Integer_Literal (Loc,
1250                 Intval => Component_Bit_Offset (CE)));
1251             Analyze_And_Resolve (N, Typ);
1252
1253          else
1254             Apply_Universal_Integer_Attribute_Checks (N);
1255          end if;
1256       end Bit_Position;
1257
1258       ------------------
1259       -- Body_Version --
1260       ------------------
1261
1262       --  A reference to P'Body_Version or P'Version is expanded to
1263
1264       --     Vnn : Unsigned;
1265       --     pragma Import (C, Vnn, "uuuuT");
1266       --     ...
1267       --     Get_Version_String (Vnn)
1268
1269       --  where uuuu is the unit name (dots replaced by double underscore)
1270       --  and T is B for the cases of Body_Version, or Version applied to a
1271       --  subprogram acting as its own spec, and S for Version applied to a
1272       --  subprogram spec or package. This sequence of code references the
1273       --  the unsigned constant created in the main program by the binder.
1274
1275       --  A special exception occurs for Standard, where the string returned
1276       --  is a copy of the library string in gnatvsn.ads.
1277
1278       when Attribute_Body_Version | Attribute_Version => Version : declare
1279          E    : constant Entity_Id := Make_Temporary (Loc, 'V');
1280          Pent : Entity_Id;
1281          S    : String_Id;
1282
1283       begin
1284          --  If not library unit, get to containing library unit
1285
1286          Pent := Entity (Pref);
1287          while Pent /= Standard_Standard
1288            and then Scope (Pent) /= Standard_Standard
1289            and then not Is_Child_Unit (Pent)
1290          loop
1291             Pent := Scope (Pent);
1292          end loop;
1293
1294          --  Special case Standard and Standard.ASCII
1295
1296          if Pent = Standard_Standard or else Pent = Standard_ASCII then
1297             Rewrite (N,
1298               Make_String_Literal (Loc,
1299                 Strval => Verbose_Library_Version));
1300
1301          --  All other cases
1302
1303          else
1304             --  Build required string constant
1305
1306             Get_Name_String (Get_Unit_Name (Pent));
1307
1308             Start_String;
1309             for J in 1 .. Name_Len - 2 loop
1310                if Name_Buffer (J) = '.' then
1311                   Store_String_Chars ("__");
1312                else
1313                   Store_String_Char (Get_Char_Code (Name_Buffer (J)));
1314                end if;
1315             end loop;
1316
1317             --  Case of subprogram acting as its own spec, always use body
1318
1319             if Nkind (Declaration_Node (Pent)) in N_Subprogram_Specification
1320               and then Nkind (Parent (Declaration_Node (Pent))) =
1321                                                           N_Subprogram_Body
1322               and then Acts_As_Spec (Parent (Declaration_Node (Pent)))
1323             then
1324                Store_String_Chars ("B");
1325
1326             --  Case of no body present, always use spec
1327
1328             elsif not Unit_Requires_Body (Pent) then
1329                Store_String_Chars ("S");
1330
1331             --  Otherwise use B for Body_Version, S for spec
1332
1333             elsif Id = Attribute_Body_Version then
1334                Store_String_Chars ("B");
1335             else
1336                Store_String_Chars ("S");
1337             end if;
1338
1339             S := End_String;
1340             Lib.Version_Referenced (S);
1341
1342             --  Insert the object declaration
1343
1344             Insert_Actions (N, New_List (
1345               Make_Object_Declaration (Loc,
1346                 Defining_Identifier => E,
1347                 Object_Definition   =>
1348                   New_Occurrence_Of (RTE (RE_Unsigned), Loc))));
1349
1350             --  Set entity as imported with correct external name
1351
1352             Set_Is_Imported (E);
1353             Set_Interface_Name (E, Make_String_Literal (Loc, S));
1354
1355             --  Set entity as internal to ensure proper Sprint output of its
1356             --  implicit importation.
1357
1358             Set_Is_Internal (E);
1359
1360             --  And now rewrite original reference
1361
1362             Rewrite (N,
1363               Make_Function_Call (Loc,
1364                 Name => New_Reference_To (RTE (RE_Get_Version_String), Loc),
1365                 Parameter_Associations => New_List (
1366                   New_Occurrence_Of (E, Loc))));
1367          end if;
1368
1369          Analyze_And_Resolve (N, RTE (RE_Version_String));
1370       end Version;
1371
1372       -------------
1373       -- Ceiling --
1374       -------------
1375
1376       --  Transforms 'Ceiling into a call to the floating-point attribute
1377       --  function Ceiling in Fat_xxx (where xxx is the root type)
1378
1379       when Attribute_Ceiling =>
1380          Expand_Fpt_Attribute_R (N);
1381
1382       --------------
1383       -- Callable --
1384       --------------
1385
1386       --  Transforms 'Callable attribute into a call to the Callable function
1387
1388       when Attribute_Callable => Callable :
1389       begin
1390          --  We have an object of a task interface class-wide type as a prefix
1391          --  to Callable. Generate:
1392          --    callable (Task_Id (Pref._disp_get_task_id));
1393
1394          if Ada_Version >= Ada_05
1395            and then Ekind (Ptyp) = E_Class_Wide_Type
1396            and then Is_Interface (Ptyp)
1397            and then Is_Task_Interface (Ptyp)
1398          then
1399             Rewrite (N,
1400               Make_Function_Call (Loc,
1401                 Name =>
1402                   New_Reference_To (RTE (RE_Callable), Loc),
1403                 Parameter_Associations => New_List (
1404                   Make_Unchecked_Type_Conversion (Loc,
1405                     Subtype_Mark =>
1406                       New_Reference_To (RTE (RO_ST_Task_Id), Loc),
1407                     Expression =>
1408                       Make_Selected_Component (Loc,
1409                         Prefix =>
1410                           New_Copy_Tree (Pref),
1411                         Selector_Name =>
1412                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id))))));
1413
1414          else
1415             Rewrite (N,
1416               Build_Call_With_Task (Pref, RTE (RE_Callable)));
1417          end if;
1418
1419          Analyze_And_Resolve (N, Standard_Boolean);
1420       end Callable;
1421
1422       ------------
1423       -- Caller --
1424       ------------
1425
1426       --  Transforms 'Caller attribute into a call to either the
1427       --  Task_Entry_Caller or the Protected_Entry_Caller function.
1428
1429       when Attribute_Caller => Caller : declare
1430          Id_Kind    : constant Entity_Id := RTE (RO_AT_Task_Id);
1431          Ent        : constant Entity_Id := Entity (Pref);
1432          Conctype   : constant Entity_Id := Scope (Ent);
1433          Nest_Depth : Integer := 0;
1434          Name       : Node_Id;
1435          S          : Entity_Id;
1436
1437       begin
1438          --  Protected case
1439
1440          if Is_Protected_Type (Conctype) then
1441             case Corresponding_Runtime_Package (Conctype) is
1442                when System_Tasking_Protected_Objects_Entries =>
1443                   Name :=
1444                     New_Reference_To
1445                       (RTE (RE_Protected_Entry_Caller), Loc);
1446
1447                when System_Tasking_Protected_Objects_Single_Entry =>
1448                   Name :=
1449                     New_Reference_To
1450                       (RTE (RE_Protected_Single_Entry_Caller), Loc);
1451
1452                when others =>
1453                   raise Program_Error;
1454             end case;
1455
1456             Rewrite (N,
1457               Unchecked_Convert_To (Id_Kind,
1458                 Make_Function_Call (Loc,
1459                   Name => Name,
1460                   Parameter_Associations => New_List (
1461                     New_Reference_To
1462                       (Find_Protection_Object (Current_Scope), Loc)))));
1463
1464          --  Task case
1465
1466          else
1467             --  Determine the nesting depth of the E'Caller attribute, that
1468             --  is, how many accept statements are nested within the accept
1469             --  statement for E at the point of E'Caller. The runtime uses
1470             --  this depth to find the specified entry call.
1471
1472             for J in reverse 0 .. Scope_Stack.Last loop
1473                S := Scope_Stack.Table (J).Entity;
1474
1475                --  We should not reach the scope of the entry, as it should
1476                --  already have been checked in Sem_Attr that this attribute
1477                --  reference is within a matching accept statement.
1478
1479                pragma Assert (S /= Conctype);
1480
1481                if S = Ent then
1482                   exit;
1483
1484                elsif Is_Entry (S) then
1485                   Nest_Depth := Nest_Depth + 1;
1486                end if;
1487             end loop;
1488
1489             Rewrite (N,
1490               Unchecked_Convert_To (Id_Kind,
1491                 Make_Function_Call (Loc,
1492                   Name =>
1493                     New_Reference_To (RTE (RE_Task_Entry_Caller), Loc),
1494                   Parameter_Associations => New_List (
1495                     Make_Integer_Literal (Loc,
1496                       Intval => Int (Nest_Depth))))));
1497          end if;
1498
1499          Analyze_And_Resolve (N, Id_Kind);
1500       end Caller;
1501
1502       -------------
1503       -- Compose --
1504       -------------
1505
1506       --  Transforms 'Compose into a call to the floating-point attribute
1507       --  function Compose in Fat_xxx (where xxx is the root type)
1508
1509       --  Note: we strictly should have special code here to deal with the
1510       --  case of absurdly negative arguments (less than Integer'First)
1511       --  which will return a (signed) zero value, but it hardly seems
1512       --  worth the effort. Absurdly large positive arguments will raise
1513       --  constraint error which is fine.
1514
1515       when Attribute_Compose =>
1516          Expand_Fpt_Attribute_RI (N);
1517
1518       -----------------
1519       -- Constrained --
1520       -----------------
1521
1522       when Attribute_Constrained => Constrained : declare
1523          Formal_Ent : constant Entity_Id := Param_Entity (Pref);
1524
1525          function Is_Constrained_Aliased_View (Obj : Node_Id) return Boolean;
1526          --  Ada 2005 (AI-363): Returns True if the object name Obj denotes a
1527          --  view of an aliased object whose subtype is constrained.
1528
1529          ---------------------------------
1530          -- Is_Constrained_Aliased_View --
1531          ---------------------------------
1532
1533          function Is_Constrained_Aliased_View (Obj : Node_Id) return Boolean is
1534             E : Entity_Id;
1535
1536          begin
1537             if Is_Entity_Name (Obj) then
1538                E := Entity (Obj);
1539
1540                if Present (Renamed_Object (E)) then
1541                   return Is_Constrained_Aliased_View (Renamed_Object (E));
1542                else
1543                   return Is_Aliased (E) and then Is_Constrained (Etype (E));
1544                end if;
1545
1546             else
1547                return Is_Aliased_View (Obj)
1548                         and then
1549                       (Is_Constrained (Etype (Obj))
1550                          or else (Nkind (Obj) = N_Explicit_Dereference
1551                                     and then
1552                                       not Has_Constrained_Partial_View
1553                                             (Base_Type (Etype (Obj)))));
1554             end if;
1555          end Is_Constrained_Aliased_View;
1556
1557       --  Start of processing for Constrained
1558
1559       begin
1560          --  Reference to a parameter where the value is passed as an extra
1561          --  actual, corresponding to the extra formal referenced by the
1562          --  Extra_Constrained field of the corresponding formal. If this
1563          --  is an entry in-parameter, it is replaced by a constant renaming
1564          --  for which Extra_Constrained is never created.
1565
1566          if Present (Formal_Ent)
1567            and then Ekind (Formal_Ent) /= E_Constant
1568            and then Present (Extra_Constrained (Formal_Ent))
1569          then
1570             Rewrite (N,
1571               New_Occurrence_Of
1572                 (Extra_Constrained (Formal_Ent), Sloc (N)));
1573
1574          --  For variables with a Extra_Constrained field, we use the
1575          --  corresponding entity.
1576
1577          elsif Nkind (Pref) = N_Identifier
1578            and then Ekind (Entity (Pref)) = E_Variable
1579            and then Present (Extra_Constrained (Entity (Pref)))
1580          then
1581             Rewrite (N,
1582               New_Occurrence_Of
1583                 (Extra_Constrained (Entity (Pref)), Sloc (N)));
1584
1585          --  For all other entity names, we can tell at compile time
1586
1587          elsif Is_Entity_Name (Pref) then
1588             declare
1589                Ent : constant Entity_Id   := Entity (Pref);
1590                Res : Boolean;
1591
1592             begin
1593                --  (RM J.4) obsolescent cases
1594
1595                if Is_Type (Ent) then
1596
1597                   --  Private type
1598
1599                   if Is_Private_Type (Ent) then
1600                      Res := not Has_Discriminants (Ent)
1601                               or else Is_Constrained (Ent);
1602
1603                   --  It not a private type, must be a generic actual type
1604                   --  that corresponded to a private type. We know that this
1605                   --  correspondence holds, since otherwise the reference
1606                   --  within the generic template would have been illegal.
1607
1608                   else
1609                      if Is_Composite_Type (Underlying_Type (Ent)) then
1610                         Res := Is_Constrained (Ent);
1611                      else
1612                         Res := True;
1613                      end if;
1614                   end if;
1615
1616                --  If the prefix is not a variable or is aliased, then
1617                --  definitely true; if it's a formal parameter without an
1618                --  associated extra formal, then treat it as constrained.
1619
1620                --  Ada 2005 (AI-363): An aliased prefix must be known to be
1621                --  constrained in order to set the attribute to True.
1622
1623                elsif not Is_Variable (Pref)
1624                  or else Present (Formal_Ent)
1625                  or else (Ada_Version < Ada_05
1626                             and then Is_Aliased_View (Pref))
1627                  or else (Ada_Version >= Ada_05
1628                             and then Is_Constrained_Aliased_View (Pref))
1629                then
1630                   Res := True;
1631
1632                --  Variable case, look at type to see if it is constrained.
1633                --  Note that the one case where this is not accurate (the
1634                --  procedure formal case), has been handled above.
1635
1636                --  We use the Underlying_Type here (and below) in case the
1637                --  type is private without discriminants, but the full type
1638                --  has discriminants. This case is illegal, but we generate it
1639                --  internally for passing to the Extra_Constrained parameter.
1640
1641                else
1642                   Res := Is_Constrained (Underlying_Type (Etype (Ent)));
1643                end if;
1644
1645                Rewrite (N,
1646                  New_Reference_To (Boolean_Literals (Res), Loc));
1647             end;
1648
1649          --  Prefix is not an entity name. These are also cases where we can
1650          --  always tell at compile time by looking at the form and type of the
1651          --  prefix. If an explicit dereference of an object with constrained
1652          --  partial view, this is unconstrained (Ada 2005 AI-363).
1653
1654          else
1655             Rewrite (N,
1656               New_Reference_To (
1657                 Boolean_Literals (
1658                   not Is_Variable (Pref)
1659                     or else
1660                      (Nkind (Pref) = N_Explicit_Dereference
1661                         and then
1662                           not Has_Constrained_Partial_View (Base_Type (Ptyp)))
1663                     or else Is_Constrained (Underlying_Type (Ptyp))),
1664                 Loc));
1665          end if;
1666
1667          Analyze_And_Resolve (N, Standard_Boolean);
1668       end Constrained;
1669
1670       ---------------
1671       -- Copy_Sign --
1672       ---------------
1673
1674       --  Transforms 'Copy_Sign into a call to the floating-point attribute
1675       --  function Copy_Sign in Fat_xxx (where xxx is the root type)
1676
1677       when Attribute_Copy_Sign =>
1678          Expand_Fpt_Attribute_RR (N);
1679
1680       -----------
1681       -- Count --
1682       -----------
1683
1684       --  Transforms 'Count attribute into a call to the Count function
1685
1686       when Attribute_Count => Count : declare
1687          Call     : Node_Id;
1688          Conctyp  : Entity_Id;
1689          Entnam   : Node_Id;
1690          Entry_Id : Entity_Id;
1691          Index    : Node_Id;
1692          Name     : Node_Id;
1693
1694       begin
1695          --  If the prefix is a member of an entry family, retrieve both
1696          --  entry name and index. For a simple entry there is no index.
1697
1698          if Nkind (Pref) = N_Indexed_Component then
1699             Entnam := Prefix (Pref);
1700             Index := First (Expressions (Pref));
1701          else
1702             Entnam := Pref;
1703             Index := Empty;
1704          end if;
1705
1706          Entry_Id := Entity (Entnam);
1707
1708          --  Find the concurrent type in which this attribute is referenced
1709          --  (there had better be one).
1710
1711          Conctyp := Current_Scope;
1712          while not Is_Concurrent_Type (Conctyp) loop
1713             Conctyp := Scope (Conctyp);
1714          end loop;
1715
1716          --  Protected case
1717
1718          if Is_Protected_Type (Conctyp) then
1719             case Corresponding_Runtime_Package (Conctyp) is
1720                when System_Tasking_Protected_Objects_Entries =>
1721                   Name := New_Reference_To (RTE (RE_Protected_Count), Loc);
1722
1723                   Call :=
1724                     Make_Function_Call (Loc,
1725                       Name => Name,
1726                       Parameter_Associations => New_List (
1727                         New_Reference_To
1728                           (Find_Protection_Object (Current_Scope), Loc),
1729                         Entry_Index_Expression
1730                           (Loc, Entry_Id, Index, Scope (Entry_Id))));
1731
1732                when System_Tasking_Protected_Objects_Single_Entry =>
1733                   Name :=
1734                     New_Reference_To (RTE (RE_Protected_Count_Entry), Loc);
1735
1736                   Call :=
1737                     Make_Function_Call (Loc,
1738                       Name => Name,
1739                       Parameter_Associations => New_List (
1740                         New_Reference_To
1741                           (Find_Protection_Object (Current_Scope), Loc)));
1742
1743                when others =>
1744                   raise Program_Error;
1745             end case;
1746
1747          --  Task case
1748
1749          else
1750             Call :=
1751               Make_Function_Call (Loc,
1752                 Name => New_Reference_To (RTE (RE_Task_Count), Loc),
1753                 Parameter_Associations => New_List (
1754                   Entry_Index_Expression (Loc,
1755                     Entry_Id, Index, Scope (Entry_Id))));
1756          end if;
1757
1758          --  The call returns type Natural but the context is universal integer
1759          --  so any integer type is allowed. The attribute was already resolved
1760          --  so its Etype is the required result type. If the base type of the
1761          --  context type is other than Standard.Integer we put in a conversion
1762          --  to the required type. This can be a normal typed conversion since
1763          --  both input and output types of the conversion are integer types
1764
1765          if Base_Type (Typ) /= Base_Type (Standard_Integer) then
1766             Rewrite (N, Convert_To (Typ, Call));
1767          else
1768             Rewrite (N, Call);
1769          end if;
1770
1771          Analyze_And_Resolve (N, Typ);
1772       end Count;
1773
1774       ---------------
1775       -- Elab_Body --
1776       ---------------
1777
1778       --  This processing is shared by Elab_Spec
1779
1780       --  What we do is to insert the following declarations
1781
1782       --     procedure tnn;
1783       --     pragma Import (C, enn, "name___elabb/s");
1784
1785       --  and then the Elab_Body/Spec attribute is replaced by a reference
1786       --  to this defining identifier.
1787
1788       when Attribute_Elab_Body |
1789            Attribute_Elab_Spec =>
1790
1791          Elab_Body : declare
1792             Ent  : constant Entity_Id := Make_Temporary (Loc, 'E');
1793             Str  : String_Id;
1794             Lang : Node_Id;
1795
1796             procedure Make_Elab_String (Nod : Node_Id);
1797             --  Given Nod, an identifier, or a selected component, put the
1798             --  image into the current string literal, with double underline
1799             --  between components.
1800
1801             ----------------------
1802             -- Make_Elab_String --
1803             ----------------------
1804
1805             procedure Make_Elab_String (Nod : Node_Id) is
1806             begin
1807                if Nkind (Nod) = N_Selected_Component then
1808                   Make_Elab_String (Prefix (Nod));
1809
1810                   case VM_Target is
1811                      when JVM_Target =>
1812                         Store_String_Char ('$');
1813                      when CLI_Target =>
1814                         Store_String_Char ('.');
1815                      when No_VM =>
1816                         Store_String_Char ('_');
1817                         Store_String_Char ('_');
1818                   end case;
1819
1820                   Get_Name_String (Chars (Selector_Name (Nod)));
1821
1822                else
1823                   pragma Assert (Nkind (Nod) = N_Identifier);
1824                   Get_Name_String (Chars (Nod));
1825                end if;
1826
1827                Store_String_Chars (Name_Buffer (1 .. Name_Len));
1828             end Make_Elab_String;
1829
1830          --  Start of processing for Elab_Body/Elab_Spec
1831
1832          begin
1833             --  First we need to prepare the string literal for the name of
1834             --  the elaboration routine to be referenced.
1835
1836             Start_String;
1837             Make_Elab_String (Pref);
1838
1839             if VM_Target = No_VM then
1840                Store_String_Chars ("___elab");
1841                Lang := Make_Identifier (Loc, Name_C);
1842             else
1843                Store_String_Chars ("._elab");
1844                Lang := Make_Identifier (Loc, Name_Ada);
1845             end if;
1846
1847             if Id = Attribute_Elab_Body then
1848                Store_String_Char ('b');
1849             else
1850                Store_String_Char ('s');
1851             end if;
1852
1853             Str := End_String;
1854
1855             Insert_Actions (N, New_List (
1856               Make_Subprogram_Declaration (Loc,
1857                 Specification =>
1858                   Make_Procedure_Specification (Loc,
1859                     Defining_Unit_Name => Ent)),
1860
1861               Make_Pragma (Loc,
1862                 Chars => Name_Import,
1863                 Pragma_Argument_Associations => New_List (
1864                   Make_Pragma_Argument_Association (Loc,
1865                     Expression => Lang),
1866
1867                   Make_Pragma_Argument_Association (Loc,
1868                     Expression =>
1869                       Make_Identifier (Loc, Chars (Ent))),
1870
1871                   Make_Pragma_Argument_Association (Loc,
1872                     Expression =>
1873                       Make_String_Literal (Loc, Str))))));
1874
1875             Set_Entity (N, Ent);
1876             Rewrite (N, New_Occurrence_Of (Ent, Loc));
1877          end Elab_Body;
1878
1879       ----------------
1880       -- Elaborated --
1881       ----------------
1882
1883       --  Elaborated is always True for preelaborated units, predefined units,
1884       --  pure units and units which have Elaborate_Body pragmas. These units
1885       --  have no elaboration entity.
1886
1887       --  Note: The Elaborated attribute is never passed to the back end
1888
1889       when Attribute_Elaborated => Elaborated : declare
1890          Ent : constant Entity_Id := Entity (Pref);
1891
1892       begin
1893          if Present (Elaboration_Entity (Ent)) then
1894             Rewrite (N,
1895               New_Occurrence_Of (Elaboration_Entity (Ent), Loc));
1896          else
1897             Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
1898          end if;
1899       end Elaborated;
1900
1901       --------------
1902       -- Enum_Rep --
1903       --------------
1904
1905       when Attribute_Enum_Rep => Enum_Rep :
1906       begin
1907          --  X'Enum_Rep (Y) expands to
1908
1909          --    target-type (Y)
1910
1911          --  This is simply a direct conversion from the enumeration type to
1912          --  the target integer type, which is treated by the back end as a
1913          --  normal integer conversion, treating the enumeration type as an
1914          --  integer, which is exactly what we want! We set Conversion_OK to
1915          --  make sure that the analyzer does not complain about what otherwise
1916          --  might be an illegal conversion.
1917
1918          if Is_Non_Empty_List (Exprs) then
1919             Rewrite (N,
1920               OK_Convert_To (Typ, Relocate_Node (First (Exprs))));
1921
1922          --  X'Enum_Rep where X is an enumeration literal is replaced by
1923          --  the literal value.
1924
1925          elsif Ekind (Entity (Pref)) = E_Enumeration_Literal then
1926             Rewrite (N,
1927               Make_Integer_Literal (Loc, Enumeration_Rep (Entity (Pref))));
1928
1929          --  If this is a renaming of a literal, recover the representation
1930          --  of the original.
1931
1932          elsif Ekind (Entity (Pref)) = E_Constant
1933            and then Present (Renamed_Object (Entity (Pref)))
1934            and then
1935              Ekind (Entity (Renamed_Object (Entity (Pref))))
1936                = E_Enumeration_Literal
1937          then
1938             Rewrite (N,
1939               Make_Integer_Literal (Loc,
1940                 Enumeration_Rep (Entity (Renamed_Object (Entity (Pref))))));
1941
1942          --  X'Enum_Rep where X is an object does a direct unchecked conversion
1943          --  of the object value, as described for the type case above.
1944
1945          else
1946             Rewrite (N,
1947               OK_Convert_To (Typ, Relocate_Node (Pref)));
1948          end if;
1949
1950          Set_Etype (N, Typ);
1951          Analyze_And_Resolve (N, Typ);
1952       end Enum_Rep;
1953
1954       --------------
1955       -- Enum_Val --
1956       --------------
1957
1958       when Attribute_Enum_Val => Enum_Val : declare
1959          Expr : Node_Id;
1960          Btyp : constant Entity_Id  := Base_Type (Ptyp);
1961
1962       begin
1963          --  X'Enum_Val (Y) expands to
1964
1965          --    [constraint_error when _rep_to_pos (Y, False) = -1, msg]
1966          --    X!(Y);
1967
1968          Expr := Unchecked_Convert_To (Ptyp, First (Exprs));
1969
1970          Insert_Action (N,
1971            Make_Raise_Constraint_Error (Loc,
1972              Condition =>
1973                Make_Op_Eq (Loc,
1974                  Left_Opnd =>
1975                    Make_Function_Call (Loc,
1976                      Name =>
1977                        New_Reference_To (TSS (Btyp, TSS_Rep_To_Pos), Loc),
1978                      Parameter_Associations => New_List (
1979                        Relocate_Node (Duplicate_Subexpr (Expr)),
1980                          New_Occurrence_Of (Standard_False, Loc))),
1981
1982                  Right_Opnd => Make_Integer_Literal (Loc, -1)),
1983              Reason => CE_Range_Check_Failed));
1984
1985          Rewrite (N, Expr);
1986          Analyze_And_Resolve (N, Ptyp);
1987       end Enum_Val;
1988
1989       --------------
1990       -- Exponent --
1991       --------------
1992
1993       --  Transforms 'Exponent into a call to the floating-point attribute
1994       --  function Exponent in Fat_xxx (where xxx is the root type)
1995
1996       when Attribute_Exponent =>
1997          Expand_Fpt_Attribute_R (N);
1998
1999       ------------------
2000       -- External_Tag --
2001       ------------------
2002
2003       --  transforme X'External_Tag into Ada.Tags.External_Tag (X'tag)
2004
2005       when Attribute_External_Tag => External_Tag :
2006       begin
2007          Rewrite (N,
2008            Make_Function_Call (Loc,
2009              Name => New_Reference_To (RTE (RE_External_Tag), Loc),
2010              Parameter_Associations => New_List (
2011                Make_Attribute_Reference (Loc,
2012                  Attribute_Name => Name_Tag,
2013                  Prefix => Prefix (N)))));
2014
2015          Analyze_And_Resolve (N, Standard_String);
2016       end External_Tag;
2017
2018       -----------
2019       -- First --
2020       -----------
2021
2022       when Attribute_First =>
2023
2024          --  If the prefix type is a constrained packed array type which
2025          --  already has a Packed_Array_Type representation defined, then
2026          --  replace this attribute with a direct reference to 'First of the
2027          --  appropriate index subtype (since otherwise the back end will try
2028          --  to give us the value of 'First for this implementation type).
2029
2030          if Is_Constrained_Packed_Array (Ptyp) then
2031             Rewrite (N,
2032               Make_Attribute_Reference (Loc,
2033                 Attribute_Name => Name_First,
2034                 Prefix => New_Reference_To (Get_Index_Subtype (N), Loc)));
2035             Analyze_And_Resolve (N, Typ);
2036
2037          elsif Is_Access_Type (Ptyp) then
2038             Apply_Access_Check (N);
2039          end if;
2040
2041       ---------------
2042       -- First_Bit --
2043       ---------------
2044
2045       --  Compute this if component clause was present, otherwise we leave the
2046       --  computation to be completed in the back-end, since we don't know what
2047       --  layout will be chosen.
2048
2049       when Attribute_First_Bit => First_Bit : declare
2050          CE : constant Entity_Id := Entity (Selector_Name (Pref));
2051
2052       begin
2053          if Known_Static_Component_Bit_Offset (CE) then
2054             Rewrite (N,
2055               Make_Integer_Literal (Loc,
2056                 Component_Bit_Offset (CE) mod System_Storage_Unit));
2057
2058             Analyze_And_Resolve (N, Typ);
2059
2060          else
2061             Apply_Universal_Integer_Attribute_Checks (N);
2062          end if;
2063       end First_Bit;
2064
2065       -----------------
2066       -- Fixed_Value --
2067       -----------------
2068
2069       --  We transform:
2070
2071       --     fixtype'Fixed_Value (integer-value)
2072
2073       --  into
2074
2075       --     fixtype(integer-value)
2076
2077       --  We do all the required analysis of the conversion here, because we do
2078       --  not want this to go through the fixed-point conversion circuits. Note
2079       --  that the back end always treats fixed-point as equivalent to the
2080       --  corresponding integer type anyway.
2081
2082       when Attribute_Fixed_Value => Fixed_Value :
2083       begin
2084          Rewrite (N,
2085            Make_Type_Conversion (Loc,
2086              Subtype_Mark => New_Occurrence_Of (Entity (Pref), Loc),
2087              Expression   => Relocate_Node (First (Exprs))));
2088          Set_Etype (N, Entity (Pref));
2089          Set_Analyzed (N);
2090
2091       --  Note: it might appear that a properly analyzed unchecked conversion
2092       --  would be just fine here, but that's not the case, since the full
2093       --  range checks performed by the following call are critical!
2094
2095          Apply_Type_Conversion_Checks (N);
2096       end Fixed_Value;
2097
2098       -----------
2099       -- Floor --
2100       -----------
2101
2102       --  Transforms 'Floor into a call to the floating-point attribute
2103       --  function Floor in Fat_xxx (where xxx is the root type)
2104
2105       when Attribute_Floor =>
2106          Expand_Fpt_Attribute_R (N);
2107
2108       ----------
2109       -- Fore --
2110       ----------
2111
2112       --  For the fixed-point type Typ:
2113
2114       --    Typ'Fore
2115
2116       --  expands into
2117
2118       --    Result_Type (System.Fore (Universal_Real (Type'First)),
2119       --                              Universal_Real (Type'Last))
2120
2121       --  Note that we know that the type is a non-static subtype, or Fore
2122       --  would have itself been computed dynamically in Eval_Attribute.
2123
2124       when Attribute_Fore => Fore : begin
2125          Rewrite (N,
2126            Convert_To (Typ,
2127              Make_Function_Call (Loc,
2128                Name => New_Reference_To (RTE (RE_Fore), Loc),
2129
2130                Parameter_Associations => New_List (
2131                  Convert_To (Universal_Real,
2132                    Make_Attribute_Reference (Loc,
2133                      Prefix => New_Reference_To (Ptyp, Loc),
2134                      Attribute_Name => Name_First)),
2135
2136                  Convert_To (Universal_Real,
2137                    Make_Attribute_Reference (Loc,
2138                      Prefix => New_Reference_To (Ptyp, Loc),
2139                      Attribute_Name => Name_Last))))));
2140
2141          Analyze_And_Resolve (N, Typ);
2142       end Fore;
2143
2144       --------------
2145       -- Fraction --
2146       --------------
2147
2148       --  Transforms 'Fraction into a call to the floating-point attribute
2149       --  function Fraction in Fat_xxx (where xxx is the root type)
2150
2151       when Attribute_Fraction =>
2152          Expand_Fpt_Attribute_R (N);
2153
2154       --------------
2155       -- From_Any --
2156       --------------
2157
2158       when Attribute_From_Any => From_Any : declare
2159          P_Type : constant Entity_Id := Etype (Pref);
2160          Decls  : constant List_Id   := New_List;
2161       begin
2162          Rewrite (N,
2163            Build_From_Any_Call (P_Type,
2164              Relocate_Node (First (Exprs)),
2165              Decls));
2166          Insert_Actions (N, Decls);
2167          Analyze_And_Resolve (N, P_Type);
2168       end From_Any;
2169
2170       --------------
2171       -- Identity --
2172       --------------
2173
2174       --  For an exception returns a reference to the exception data:
2175       --      Exception_Id!(Prefix'Reference)
2176
2177       --  For a task it returns a reference to the _task_id component of
2178       --  corresponding record:
2179
2180       --    taskV!(Prefix)._Task_Id, converted to the type Task_Id defined
2181
2182       --  in Ada.Task_Identification
2183
2184       when Attribute_Identity => Identity : declare
2185          Id_Kind : Entity_Id;
2186
2187       begin
2188          if Ptyp = Standard_Exception_Type then
2189             Id_Kind := RTE (RE_Exception_Id);
2190
2191             if Present (Renamed_Object (Entity (Pref))) then
2192                Set_Entity (Pref, Renamed_Object (Entity (Pref)));
2193             end if;
2194
2195             Rewrite (N,
2196               Unchecked_Convert_To (Id_Kind, Make_Reference (Loc, Pref)));
2197          else
2198             Id_Kind := RTE (RO_AT_Task_Id);
2199
2200             --  If the prefix is a task interface, the Task_Id is obtained
2201             --  dynamically through a dispatching call, as for other task
2202             --  attributes applied to interfaces.
2203
2204             if Ada_Version >= Ada_05
2205               and then Ekind (Ptyp) = E_Class_Wide_Type
2206               and then Is_Interface (Ptyp)
2207               and then Is_Task_Interface (Ptyp)
2208             then
2209                Rewrite (N,
2210                  Unchecked_Convert_To (Id_Kind,
2211                    Make_Selected_Component (Loc,
2212                      Prefix =>
2213                        New_Copy_Tree (Pref),
2214                      Selector_Name =>
2215                        Make_Identifier (Loc, Name_uDisp_Get_Task_Id))));
2216
2217             else
2218                Rewrite (N,
2219                  Unchecked_Convert_To (Id_Kind, Concurrent_Ref (Pref)));
2220             end if;
2221          end if;
2222
2223          Analyze_And_Resolve (N, Id_Kind);
2224       end Identity;
2225
2226       -----------
2227       -- Image --
2228       -----------
2229
2230       --  Image attribute is handled in separate unit Exp_Imgv
2231
2232       when Attribute_Image =>
2233          Exp_Imgv.Expand_Image_Attribute (N);
2234
2235       ---------
2236       -- Img --
2237       ---------
2238
2239       --  X'Img is expanded to typ'Image (X), where typ is the type of X
2240
2241       when Attribute_Img => Img :
2242       begin
2243          Rewrite (N,
2244            Make_Attribute_Reference (Loc,
2245              Prefix => New_Reference_To (Ptyp, Loc),
2246              Attribute_Name => Name_Image,
2247              Expressions => New_List (Relocate_Node (Pref))));
2248
2249          Analyze_And_Resolve (N, Standard_String);
2250       end Img;
2251
2252       -----------
2253       -- Input --
2254       -----------
2255
2256       when Attribute_Input => Input : declare
2257          P_Type : constant Entity_Id := Entity (Pref);
2258          B_Type : constant Entity_Id := Base_Type (P_Type);
2259          U_Type : constant Entity_Id := Underlying_Type (P_Type);
2260          Strm   : constant Node_Id   := First (Exprs);
2261          Fname  : Entity_Id;
2262          Decl   : Node_Id;
2263          Call   : Node_Id;
2264          Prag   : Node_Id;
2265          Arg2   : Node_Id;
2266          Rfunc  : Node_Id;
2267
2268          Cntrl  : Node_Id := Empty;
2269          --  Value for controlling argument in call. Always Empty except in
2270          --  the dispatching (class-wide type) case, where it is a reference
2271          --  to the dummy object initialized to the right internal tag.
2272
2273          procedure Freeze_Stream_Subprogram (F : Entity_Id);
2274          --  The expansion of the attribute reference may generate a call to
2275          --  a user-defined stream subprogram that is frozen by the call. This
2276          --  can lead to access-before-elaboration problem if the reference
2277          --  appears in an object declaration and the subprogram body has not
2278          --  been seen. The freezing of the subprogram requires special code
2279          --  because it appears in an expanded context where expressions do
2280          --  not freeze their constituents.
2281
2282          ------------------------------
2283          -- Freeze_Stream_Subprogram --
2284          ------------------------------
2285
2286          procedure Freeze_Stream_Subprogram (F : Entity_Id) is
2287             Decl : constant Node_Id := Unit_Declaration_Node (F);
2288             Bod  : Node_Id;
2289
2290          begin
2291             --  If this is user-defined subprogram, the corresponding
2292             --  stream function appears as a renaming-as-body, and the
2293             --  user subprogram must be retrieved by tree traversal.
2294
2295             if Present (Decl)
2296               and then Nkind (Decl) = N_Subprogram_Declaration
2297               and then Present (Corresponding_Body (Decl))
2298             then
2299                Bod := Corresponding_Body (Decl);
2300
2301                if Nkind (Unit_Declaration_Node (Bod)) =
2302                  N_Subprogram_Renaming_Declaration
2303                then
2304                   Set_Is_Frozen (Entity (Name (Unit_Declaration_Node (Bod))));
2305                end if;
2306             end if;
2307          end Freeze_Stream_Subprogram;
2308
2309       --  Start of processing for Input
2310
2311       begin
2312          --  If no underlying type, we have an error that will be diagnosed
2313          --  elsewhere, so here we just completely ignore the expansion.
2314
2315          if No (U_Type) then
2316             return;
2317          end if;
2318
2319          --  If there is a TSS for Input, just call it
2320
2321          Fname := Find_Stream_Subprogram (P_Type, TSS_Stream_Input);
2322
2323          if Present (Fname) then
2324             null;
2325
2326          else
2327             --  If there is a Stream_Convert pragma, use it, we rewrite
2328
2329             --     sourcetyp'Input (stream)
2330
2331             --  as
2332
2333             --     sourcetyp (streamread (strmtyp'Input (stream)));
2334
2335             --  where streamread is the given Read function that converts an
2336             --  argument of type strmtyp to type sourcetyp or a type from which
2337             --  it is derived (extra conversion required for the derived case).
2338
2339             Prag := Get_Stream_Convert_Pragma (P_Type);
2340
2341             if Present (Prag) then
2342                Arg2  := Next (First (Pragma_Argument_Associations (Prag)));
2343                Rfunc := Entity (Expression (Arg2));
2344
2345                Rewrite (N,
2346                  Convert_To (B_Type,
2347                    Make_Function_Call (Loc,
2348                      Name => New_Occurrence_Of (Rfunc, Loc),
2349                      Parameter_Associations => New_List (
2350                        Make_Attribute_Reference (Loc,
2351                          Prefix =>
2352                            New_Occurrence_Of
2353                              (Etype (First_Formal (Rfunc)), Loc),
2354                          Attribute_Name => Name_Input,
2355                          Expressions => Exprs)))));
2356
2357                Analyze_And_Resolve (N, B_Type);
2358                return;
2359
2360             --  Elementary types
2361
2362             elsif Is_Elementary_Type (U_Type) then
2363
2364                --  A special case arises if we have a defined _Read routine,
2365                --  since in this case we are required to call this routine.
2366
2367                if Present (TSS (Base_Type (U_Type), TSS_Stream_Read)) then
2368                   Build_Record_Or_Elementary_Input_Function
2369                     (Loc, U_Type, Decl, Fname);
2370                   Insert_Action (N, Decl);
2371
2372                --  For normal cases, we call the I_xxx routine directly
2373
2374                else
2375                   Rewrite (N, Build_Elementary_Input_Call (N));
2376                   Analyze_And_Resolve (N, P_Type);
2377                   return;
2378                end if;
2379
2380             --  Array type case
2381
2382             elsif Is_Array_Type (U_Type) then
2383                Build_Array_Input_Function (Loc, U_Type, Decl, Fname);
2384                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
2385
2386             --  Dispatching case with class-wide type
2387
2388             elsif Is_Class_Wide_Type (P_Type) then
2389
2390                --  No need to do anything else compiling under restriction
2391                --  No_Dispatching_Calls. During the semantic analysis we
2392                --  already notified such violation.
2393
2394                if Restriction_Active (No_Dispatching_Calls) then
2395                   return;
2396                end if;
2397
2398                declare
2399                   Rtyp : constant Entity_Id := Root_Type (P_Type);
2400                   Dnn  : Entity_Id;
2401                   Decl : Node_Id;
2402                   Expr : Node_Id;
2403
2404                begin
2405                   --  Read the internal tag (RM 13.13.2(34)) and use it to
2406                   --  initialize a dummy tag object:
2407
2408                   --    Dnn : Ada.Tags.Tag :=
2409                   --            Descendant_Tag (String'Input (Strm), P_Type);
2410
2411                   --  This dummy object is used only to provide a controlling
2412                   --  argument for the eventual _Input call. Descendant_Tag is
2413                   --  called rather than Internal_Tag to ensure that we have a
2414                   --  tag for a type that is descended from the prefix type and
2415                   --  declared at the same accessibility level (the exception
2416                   --  Tag_Error will be raised otherwise). The level check is
2417                   --  required for Ada 2005 because tagged types can be
2418                   --  extended in nested scopes (AI-344).
2419
2420                   Expr :=
2421                     Make_Function_Call (Loc,
2422                       Name =>
2423                         New_Occurrence_Of (RTE (RE_Descendant_Tag), Loc),
2424                       Parameter_Associations => New_List (
2425                         Make_Attribute_Reference (Loc,
2426                           Prefix => New_Occurrence_Of (Standard_String, Loc),
2427                           Attribute_Name => Name_Input,
2428                           Expressions => New_List (
2429                             Relocate_Node (Duplicate_Subexpr (Strm)))),
2430                         Make_Attribute_Reference (Loc,
2431                           Prefix => New_Reference_To (P_Type, Loc),
2432                           Attribute_Name => Name_Tag)));
2433
2434                   Dnn := Make_Temporary (Loc, 'D', Expr);
2435
2436                   Decl :=
2437                     Make_Object_Declaration (Loc,
2438                       Defining_Identifier => Dnn,
2439                       Object_Definition   =>
2440                         New_Occurrence_Of (RTE (RE_Tag), Loc),
2441                       Expression          => Expr);
2442
2443                   Insert_Action (N, Decl);
2444
2445                   --  Now we need to get the entity for the call, and construct
2446                   --  a function call node, where we preset a reference to Dnn
2447                   --  as the controlling argument (doing an unchecked convert
2448                   --  to the class-wide tagged type to make it look like a real
2449                   --  tagged object).
2450
2451                   Fname := Find_Prim_Op (Rtyp, TSS_Stream_Input);
2452                   Cntrl :=
2453                     Unchecked_Convert_To (P_Type,
2454                       New_Occurrence_Of (Dnn, Loc));
2455                   Set_Etype (Cntrl, P_Type);
2456                   Set_Parent (Cntrl, N);
2457                end;
2458
2459             --  For tagged types, use the primitive Input function
2460
2461             elsif Is_Tagged_Type (U_Type) then
2462                Fname := Find_Prim_Op (U_Type, TSS_Stream_Input);
2463
2464             --  All other record type cases, including protected records. The
2465             --  latter only arise for expander generated code for handling
2466             --  shared passive partition access.
2467
2468             else
2469                pragma Assert
2470                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
2471
2472                --  Ada 2005 (AI-216): Program_Error is raised executing default
2473                --  implementation of the Input attribute of an unchecked union
2474                --  type if the type lacks default discriminant values.
2475
2476                if Is_Unchecked_Union (Base_Type (U_Type))
2477                  and then No (Discriminant_Constraint (U_Type))
2478                then
2479                   Insert_Action (N,
2480                     Make_Raise_Program_Error (Loc,
2481                       Reason => PE_Unchecked_Union_Restriction));
2482
2483                   return;
2484                end if;
2485
2486                Build_Record_Or_Elementary_Input_Function
2487                  (Loc, Base_Type (U_Type), Decl, Fname);
2488                Insert_Action (N, Decl);
2489
2490                if Nkind (Parent (N)) = N_Object_Declaration
2491                  and then Is_Record_Type (U_Type)
2492                then
2493                   --  The stream function may contain calls to user-defined
2494                   --  Read procedures for individual components.
2495
2496                   declare
2497                      Comp : Entity_Id;
2498                      Func : Entity_Id;
2499
2500                   begin
2501                      Comp := First_Component (U_Type);
2502                      while Present (Comp) loop
2503                         Func :=
2504                           Find_Stream_Subprogram
2505                             (Etype (Comp), TSS_Stream_Read);
2506
2507                         if Present (Func) then
2508                            Freeze_Stream_Subprogram (Func);
2509                         end if;
2510
2511                         Next_Component (Comp);
2512                      end loop;
2513                   end;
2514                end if;
2515             end if;
2516          end if;
2517
2518          --  If we fall through, Fname is the function to be called. The result
2519          --  is obtained by calling the appropriate function, then converting
2520          --  the result. The conversion does a subtype check.
2521
2522          Call :=
2523            Make_Function_Call (Loc,
2524              Name => New_Occurrence_Of (Fname, Loc),
2525              Parameter_Associations => New_List (
2526                 Relocate_Node (Strm)));
2527
2528          Set_Controlling_Argument (Call, Cntrl);
2529          Rewrite (N, Unchecked_Convert_To (P_Type, Call));
2530          Analyze_And_Resolve (N, P_Type);
2531
2532          if Nkind (Parent (N)) = N_Object_Declaration then
2533             Freeze_Stream_Subprogram (Fname);
2534          end if;
2535       end Input;
2536
2537       -------------------
2538       -- Integer_Value --
2539       -------------------
2540
2541       --  We transform
2542
2543       --    inttype'Fixed_Value (fixed-value)
2544
2545       --  into
2546
2547       --    inttype(integer-value))
2548
2549       --  we do all the required analysis of the conversion here, because we do
2550       --  not want this to go through the fixed-point conversion circuits. Note
2551       --  that the back end always treats fixed-point as equivalent to the
2552       --  corresponding integer type anyway.
2553
2554       when Attribute_Integer_Value => Integer_Value :
2555       begin
2556          Rewrite (N,
2557            Make_Type_Conversion (Loc,
2558              Subtype_Mark => New_Occurrence_Of (Entity (Pref), Loc),
2559              Expression   => Relocate_Node (First (Exprs))));
2560          Set_Etype (N, Entity (Pref));
2561          Set_Analyzed (N);
2562
2563       --  Note: it might appear that a properly analyzed unchecked conversion
2564       --  would be just fine here, but that's not the case, since the full
2565       --  range checks performed by the following call are critical!
2566
2567          Apply_Type_Conversion_Checks (N);
2568       end Integer_Value;
2569
2570       -------------------
2571       -- Invalid_Value --
2572       -------------------
2573
2574       when Attribute_Invalid_Value =>
2575          Rewrite (N, Get_Simple_Init_Val (Ptyp, N));
2576
2577       ----------
2578       -- Last --
2579       ----------
2580
2581       when Attribute_Last =>
2582
2583          --  If the prefix type is a constrained packed array type which
2584          --  already has a Packed_Array_Type representation defined, then
2585          --  replace this attribute with a direct reference to 'Last of the
2586          --  appropriate index subtype (since otherwise the back end will try
2587          --  to give us the value of 'Last for this implementation type).
2588
2589          if Is_Constrained_Packed_Array (Ptyp) then
2590             Rewrite (N,
2591               Make_Attribute_Reference (Loc,
2592                 Attribute_Name => Name_Last,
2593                 Prefix => New_Reference_To (Get_Index_Subtype (N), Loc)));
2594             Analyze_And_Resolve (N, Typ);
2595
2596          elsif Is_Access_Type (Ptyp) then
2597             Apply_Access_Check (N);
2598          end if;
2599
2600       --------------
2601       -- Last_Bit --
2602       --------------
2603
2604       --  We compute this if a component clause was present, otherwise we leave
2605       --  the computation up to the back end, since we don't know what layout
2606       --  will be chosen.
2607
2608       when Attribute_Last_Bit => Last_Bit : declare
2609          CE : constant Entity_Id := Entity (Selector_Name (Pref));
2610
2611       begin
2612          if Known_Static_Component_Bit_Offset (CE)
2613            and then Known_Static_Esize (CE)
2614          then
2615             Rewrite (N,
2616               Make_Integer_Literal (Loc,
2617                Intval => (Component_Bit_Offset (CE) mod System_Storage_Unit)
2618                                 + Esize (CE) - 1));
2619
2620             Analyze_And_Resolve (N, Typ);
2621
2622          else
2623             Apply_Universal_Integer_Attribute_Checks (N);
2624          end if;
2625       end Last_Bit;
2626
2627       ------------------
2628       -- Leading_Part --
2629       ------------------
2630
2631       --  Transforms 'Leading_Part into a call to the floating-point attribute
2632       --  function Leading_Part in Fat_xxx (where xxx is the root type)
2633
2634       --  Note: strictly, we should generate special case code to deal with
2635       --  absurdly large positive arguments (greater than Integer'Last), which
2636       --  result in returning the first argument unchanged, but it hardly seems
2637       --  worth the effort. We raise constraint error for absurdly negative
2638       --  arguments which is fine.
2639
2640       when Attribute_Leading_Part =>
2641          Expand_Fpt_Attribute_RI (N);
2642
2643       ------------
2644       -- Length --
2645       ------------
2646
2647       when Attribute_Length => declare
2648          Ityp : Entity_Id;
2649          Xnum : Uint;
2650
2651       begin
2652          --  Processing for packed array types
2653
2654          if Is_Array_Type (Ptyp) and then Is_Packed (Ptyp) then
2655             Ityp := Get_Index_Subtype (N);
2656
2657             --  If the index type, Ityp, is an enumeration type with holes,
2658             --  then we calculate X'Length explicitly using
2659
2660             --     Typ'Max
2661             --       (0, Ityp'Pos (X'Last  (N)) -
2662             --           Ityp'Pos (X'First (N)) + 1);
2663
2664             --  Since the bounds in the template are the representation values
2665             --  and the back end would get the wrong value.
2666
2667             if Is_Enumeration_Type (Ityp)
2668               and then Present (Enum_Pos_To_Rep (Base_Type (Ityp)))
2669             then
2670                if No (Exprs) then
2671                   Xnum := Uint_1;
2672                else
2673                   Xnum := Expr_Value (First (Expressions (N)));
2674                end if;
2675
2676                Rewrite (N,
2677                  Make_Attribute_Reference (Loc,
2678                    Prefix         => New_Occurrence_Of (Typ, Loc),
2679                    Attribute_Name => Name_Max,
2680                    Expressions    => New_List
2681                      (Make_Integer_Literal (Loc, 0),
2682
2683                       Make_Op_Add (Loc,
2684                         Left_Opnd =>
2685                           Make_Op_Subtract (Loc,
2686                             Left_Opnd =>
2687                               Make_Attribute_Reference (Loc,
2688                                 Prefix => New_Occurrence_Of (Ityp, Loc),
2689                                 Attribute_Name => Name_Pos,
2690
2691                                 Expressions => New_List (
2692                                   Make_Attribute_Reference (Loc,
2693                                     Prefix => Duplicate_Subexpr (Pref),
2694                                    Attribute_Name => Name_Last,
2695                                     Expressions => New_List (
2696                                       Make_Integer_Literal (Loc, Xnum))))),
2697
2698                             Right_Opnd =>
2699                               Make_Attribute_Reference (Loc,
2700                                 Prefix => New_Occurrence_Of (Ityp, Loc),
2701                                 Attribute_Name => Name_Pos,
2702
2703                                 Expressions => New_List (
2704                                   Make_Attribute_Reference (Loc,
2705                                     Prefix =>
2706                                       Duplicate_Subexpr_No_Checks (Pref),
2707                                    Attribute_Name => Name_First,
2708                                     Expressions => New_List (
2709                                       Make_Integer_Literal (Loc, Xnum)))))),
2710
2711                         Right_Opnd => Make_Integer_Literal (Loc, 1)))));
2712
2713                Analyze_And_Resolve (N, Typ, Suppress => All_Checks);
2714                return;
2715
2716             --  If the prefix type is a constrained packed array type which
2717             --  already has a Packed_Array_Type representation defined, then
2718             --  replace this attribute with a direct reference to 'Range_Length
2719             --  of the appropriate index subtype (since otherwise the back end
2720             --  will try to give us the value of 'Length for this
2721             --  implementation type).
2722
2723             elsif Is_Constrained (Ptyp) then
2724                Rewrite (N,
2725                  Make_Attribute_Reference (Loc,
2726                    Attribute_Name => Name_Range_Length,
2727                    Prefix => New_Reference_To (Ityp, Loc)));
2728                Analyze_And_Resolve (N, Typ);
2729             end if;
2730
2731          --  Access type case
2732
2733          elsif Is_Access_Type (Ptyp) then
2734             Apply_Access_Check (N);
2735
2736             --  If the designated type is a packed array type, then we convert
2737             --  the reference to:
2738
2739             --    typ'Max (0, 1 +
2740             --                xtyp'Pos (Pref'Last (Expr)) -
2741             --                xtyp'Pos (Pref'First (Expr)));
2742
2743             --  This is a bit complex, but it is the easiest thing to do that
2744             --  works in all cases including enum types with holes xtyp here
2745             --  is the appropriate index type.
2746
2747             declare
2748                Dtyp : constant Entity_Id := Designated_Type (Ptyp);
2749                Xtyp : Entity_Id;
2750
2751             begin
2752                if Is_Array_Type (Dtyp) and then Is_Packed (Dtyp) then
2753                   Xtyp := Get_Index_Subtype (N);
2754
2755                   Rewrite (N,
2756                     Make_Attribute_Reference (Loc,
2757                       Prefix         => New_Occurrence_Of (Typ, Loc),
2758                       Attribute_Name => Name_Max,
2759                       Expressions    => New_List (
2760                         Make_Integer_Literal (Loc, 0),
2761
2762                         Make_Op_Add (Loc,
2763                           Make_Integer_Literal (Loc, 1),
2764                           Make_Op_Subtract (Loc,
2765                             Left_Opnd =>
2766                               Make_Attribute_Reference (Loc,
2767                                 Prefix => New_Occurrence_Of (Xtyp, Loc),
2768                                 Attribute_Name => Name_Pos,
2769                                 Expressions    => New_List (
2770                                   Make_Attribute_Reference (Loc,
2771                                     Prefix => Duplicate_Subexpr (Pref),
2772                                     Attribute_Name => Name_Last,
2773                                     Expressions =>
2774                                       New_Copy_List (Exprs)))),
2775
2776                             Right_Opnd =>
2777                               Make_Attribute_Reference (Loc,
2778                                 Prefix => New_Occurrence_Of (Xtyp, Loc),
2779                                 Attribute_Name => Name_Pos,
2780                                 Expressions    => New_List (
2781                                   Make_Attribute_Reference (Loc,
2782                                     Prefix =>
2783                                       Duplicate_Subexpr_No_Checks (Pref),
2784                                     Attribute_Name => Name_First,
2785                                     Expressions =>
2786                                       New_Copy_List (Exprs)))))))));
2787
2788                   Analyze_And_Resolve (N, Typ);
2789                end if;
2790             end;
2791
2792          --  Otherwise leave it to the back end
2793
2794          else
2795             Apply_Universal_Integer_Attribute_Checks (N);
2796          end if;
2797       end;
2798
2799       -------------
2800       -- Machine --
2801       -------------
2802
2803       --  Transforms 'Machine into a call to the floating-point attribute
2804       --  function Machine in Fat_xxx (where xxx is the root type)
2805
2806       when Attribute_Machine =>
2807          Expand_Fpt_Attribute_R (N);
2808
2809       ----------------------
2810       -- Machine_Rounding --
2811       ----------------------
2812
2813       --  Transforms 'Machine_Rounding into a call to the floating-point
2814       --  attribute function Machine_Rounding in Fat_xxx (where xxx is the root
2815       --  type). Expansion is avoided for cases the back end can handle
2816       --  directly.
2817
2818       when Attribute_Machine_Rounding =>
2819          if not Is_Inline_Floating_Point_Attribute (N) then
2820             Expand_Fpt_Attribute_R (N);
2821          end if;
2822
2823       ------------------
2824       -- Machine_Size --
2825       ------------------
2826
2827       --  Machine_Size is equivalent to Object_Size, so transform it into
2828       --  Object_Size and that way the back end never sees Machine_Size.
2829
2830       when Attribute_Machine_Size =>
2831          Rewrite (N,
2832            Make_Attribute_Reference (Loc,
2833              Prefix => Prefix (N),
2834              Attribute_Name => Name_Object_Size));
2835
2836          Analyze_And_Resolve (N, Typ);
2837
2838       --------------
2839       -- Mantissa --
2840       --------------
2841
2842       --  The only case that can get this far is the dynamic case of the old
2843       --  Ada 83 Mantissa attribute for the fixed-point case. For this case,
2844       --  we expand:
2845
2846       --    typ'Mantissa
2847
2848       --  into
2849
2850       --    ityp (System.Mantissa.Mantissa_Value
2851       --           (Integer'Integer_Value (typ'First),
2852       --            Integer'Integer_Value (typ'Last)));
2853
2854       when Attribute_Mantissa => Mantissa : begin
2855          Rewrite (N,
2856            Convert_To (Typ,
2857              Make_Function_Call (Loc,
2858                Name => New_Occurrence_Of (RTE (RE_Mantissa_Value), Loc),
2859
2860                Parameter_Associations => New_List (
2861
2862                  Make_Attribute_Reference (Loc,
2863                    Prefix => New_Occurrence_Of (Standard_Integer, Loc),
2864                    Attribute_Name => Name_Integer_Value,
2865                    Expressions => New_List (
2866
2867                      Make_Attribute_Reference (Loc,
2868                        Prefix => New_Occurrence_Of (Ptyp, Loc),
2869                        Attribute_Name => Name_First))),
2870
2871                  Make_Attribute_Reference (Loc,
2872                    Prefix => New_Occurrence_Of (Standard_Integer, Loc),
2873                    Attribute_Name => Name_Integer_Value,
2874                    Expressions => New_List (
2875
2876                      Make_Attribute_Reference (Loc,
2877                        Prefix => New_Occurrence_Of (Ptyp, Loc),
2878                        Attribute_Name => Name_Last)))))));
2879
2880          Analyze_And_Resolve (N, Typ);
2881       end Mantissa;
2882
2883       --------------------
2884       -- Mechanism_Code --
2885       --------------------
2886
2887       when Attribute_Mechanism_Code =>
2888
2889          --  We must replace the prefix in the renamed case
2890
2891          if Is_Entity_Name (Pref)
2892            and then Present (Alias (Entity (Pref)))
2893          then
2894             Set_Renamed_Subprogram (Pref, Alias (Entity (Pref)));
2895          end if;
2896
2897       ---------
2898       -- Mod --
2899       ---------
2900
2901       when Attribute_Mod => Mod_Case : declare
2902          Arg  : constant Node_Id := Relocate_Node (First (Exprs));
2903          Hi   : constant Node_Id := Type_High_Bound (Etype (Arg));
2904          Modv : constant Uint    := Modulus (Btyp);
2905
2906       begin
2907
2908          --  This is not so simple. The issue is what type to use for the
2909          --  computation of the modular value.
2910
2911          --  The easy case is when the modulus value is within the bounds
2912          --  of the signed integer type of the argument. In this case we can
2913          --  just do the computation in that signed integer type, and then
2914          --  do an ordinary conversion to the target type.
2915
2916          if Modv <= Expr_Value (Hi) then
2917             Rewrite (N,
2918               Convert_To (Btyp,
2919                 Make_Op_Mod (Loc,
2920                   Left_Opnd  => Arg,
2921                   Right_Opnd => Make_Integer_Literal (Loc, Modv))));
2922
2923          --  Here we know that the modulus is larger than type'Last of the
2924          --  integer type. There are two cases to consider:
2925
2926          --    a) The integer value is non-negative. In this case, it is
2927          --    returned as the result (since it is less than the modulus).
2928
2929          --    b) The integer value is negative. In this case, we know that the
2930          --    result is modulus + value, where the value might be as small as
2931          --    -modulus. The trouble is what type do we use to do the subtract.
2932          --    No type will do, since modulus can be as big as 2**64, and no
2933          --    integer type accommodates this value. Let's do bit of algebra
2934
2935          --         modulus + value
2936          --      =  modulus - (-value)
2937          --      =  (modulus - 1) - (-value - 1)
2938
2939          --    Now modulus - 1 is certainly in range of the modular type.
2940          --    -value is in the range 1 .. modulus, so -value -1 is in the
2941          --    range 0 .. modulus-1 which is in range of the modular type.
2942          --    Furthermore, (-value - 1) can be expressed as -(value + 1)
2943          --    which we can compute using the integer base type.
2944
2945          --  Once this is done we analyze the conditional expression without
2946          --  range checks, because we know everything is in range, and we
2947          --  want to prevent spurious warnings on either branch.
2948
2949          else
2950             Rewrite (N,
2951               Make_Conditional_Expression (Loc,
2952                 Expressions => New_List (
2953                   Make_Op_Ge (Loc,
2954                     Left_Opnd  => Duplicate_Subexpr (Arg),
2955                     Right_Opnd => Make_Integer_Literal (Loc, 0)),
2956
2957                   Convert_To (Btyp,
2958                     Duplicate_Subexpr_No_Checks (Arg)),
2959
2960                   Make_Op_Subtract (Loc,
2961                     Left_Opnd =>
2962                       Make_Integer_Literal (Loc,
2963                         Intval => Modv - 1),
2964                     Right_Opnd =>
2965                       Convert_To (Btyp,
2966                         Make_Op_Minus (Loc,
2967                           Right_Opnd =>
2968                             Make_Op_Add (Loc,
2969                               Left_Opnd  => Duplicate_Subexpr_No_Checks (Arg),
2970                               Right_Opnd =>
2971                                 Make_Integer_Literal (Loc,
2972                                   Intval => 1))))))));
2973
2974          end if;
2975
2976          Analyze_And_Resolve (N, Btyp, Suppress => All_Checks);
2977       end Mod_Case;
2978
2979       -----------
2980       -- Model --
2981       -----------
2982
2983       --  Transforms 'Model into a call to the floating-point attribute
2984       --  function Model in Fat_xxx (where xxx is the root type)
2985
2986       when Attribute_Model =>
2987          Expand_Fpt_Attribute_R (N);
2988
2989       -----------------
2990       -- Object_Size --
2991       -----------------
2992
2993       --  The processing for Object_Size shares the processing for Size
2994
2995       ---------
2996       -- Old --
2997       ---------
2998
2999       when Attribute_Old => Old : declare
3000          Tnn     : constant Entity_Id := Make_Temporary (Loc, 'T', Pref);
3001          Subp    : Node_Id;
3002          Asn_Stm : Node_Id;
3003
3004       begin
3005          --  Find the nearest subprogram body, ignoring _Preconditions
3006
3007          Subp := N;
3008          loop
3009             Subp := Parent (Subp);
3010             exit when Nkind (Subp) = N_Subprogram_Body
3011               and then Chars (Defining_Entity (Subp)) /= Name_uPostconditions;
3012          end loop;
3013
3014          --  Insert the initialized object declaration at the start of the
3015          --  subprogram's declarations.
3016
3017          Asn_Stm :=
3018            Make_Object_Declaration (Loc,
3019              Defining_Identifier => Tnn,
3020              Constant_Present    => True,
3021              Object_Definition   => New_Occurrence_Of (Etype (N), Loc),
3022              Expression          => Pref);
3023
3024          --  Push the subprogram's scope, so that the object will be analyzed
3025          --  in that context (rather than the context of the Precondition
3026          --  subprogram) and will have its Scope set properly.
3027
3028          if Present (Corresponding_Spec (Subp)) then
3029             Push_Scope (Corresponding_Spec (Subp));
3030          else
3031             Push_Scope (Defining_Entity (Subp));
3032          end if;
3033
3034          if Is_Empty_List (Declarations (Subp)) then
3035             Set_Declarations (Subp, New_List (Asn_Stm));
3036             Analyze (Asn_Stm);
3037          else
3038             Insert_Action (First (Declarations (Subp)), Asn_Stm);
3039          end if;
3040
3041          Pop_Scope;
3042
3043          Rewrite (N, New_Occurrence_Of (Tnn, Loc));
3044       end Old;
3045
3046       ------------
3047       -- Output --
3048       ------------
3049
3050       when Attribute_Output => Output : declare
3051          P_Type : constant Entity_Id := Entity (Pref);
3052          U_Type : constant Entity_Id := Underlying_Type (P_Type);
3053          Pname  : Entity_Id;
3054          Decl   : Node_Id;
3055          Prag   : Node_Id;
3056          Arg3   : Node_Id;
3057          Wfunc  : Node_Id;
3058
3059       begin
3060          --  If no underlying type, we have an error that will be diagnosed
3061          --  elsewhere, so here we just completely ignore the expansion.
3062
3063          if No (U_Type) then
3064             return;
3065          end if;
3066
3067          --  If TSS for Output is present, just call it
3068
3069          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Output);
3070
3071          if Present (Pname) then
3072             null;
3073
3074          else
3075             --  If there is a Stream_Convert pragma, use it, we rewrite
3076
3077             --     sourcetyp'Output (stream, Item)
3078
3079             --  as
3080
3081             --     strmtyp'Output (Stream, strmwrite (acttyp (Item)));
3082
3083             --  where strmwrite is the given Write function that converts an
3084             --  argument of type sourcetyp or a type acctyp, from which it is
3085             --  derived to type strmtyp. The conversion to acttyp is required
3086             --  for the derived case.
3087
3088             Prag := Get_Stream_Convert_Pragma (P_Type);
3089
3090             if Present (Prag) then
3091                Arg3 :=
3092                  Next (Next (First (Pragma_Argument_Associations (Prag))));
3093                Wfunc := Entity (Expression (Arg3));
3094
3095                Rewrite (N,
3096                  Make_Attribute_Reference (Loc,
3097                    Prefix => New_Occurrence_Of (Etype (Wfunc), Loc),
3098                    Attribute_Name => Name_Output,
3099                    Expressions => New_List (
3100                    Relocate_Node (First (Exprs)),
3101                      Make_Function_Call (Loc,
3102                        Name => New_Occurrence_Of (Wfunc, Loc),
3103                        Parameter_Associations => New_List (
3104                          OK_Convert_To (Etype (First_Formal (Wfunc)),
3105                            Relocate_Node (Next (First (Exprs)))))))));
3106
3107                Analyze (N);
3108                return;
3109
3110             --  For elementary types, we call the W_xxx routine directly.
3111             --  Note that the effect of Write and Output is identical for
3112             --  the case of an elementary type, since there are no
3113             --  discriminants or bounds.
3114
3115             elsif Is_Elementary_Type (U_Type) then
3116
3117                --  A special case arises if we have a defined _Write routine,
3118                --  since in this case we are required to call this routine.
3119
3120                if Present (TSS (Base_Type (U_Type), TSS_Stream_Write)) then
3121                   Build_Record_Or_Elementary_Output_Procedure
3122                     (Loc, U_Type, Decl, Pname);
3123                   Insert_Action (N, Decl);
3124
3125                --  For normal cases, we call the W_xxx routine directly
3126
3127                else
3128                   Rewrite (N, Build_Elementary_Write_Call (N));
3129                   Analyze (N);
3130                   return;
3131                end if;
3132
3133             --  Array type case
3134
3135             elsif Is_Array_Type (U_Type) then
3136                Build_Array_Output_Procedure (Loc, U_Type, Decl, Pname);
3137                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
3138
3139             --  Class-wide case, first output external tag, then dispatch
3140             --  to the appropriate primitive Output function (RM 13.13.2(31)).
3141
3142             elsif Is_Class_Wide_Type (P_Type) then
3143
3144                --  No need to do anything else compiling under restriction
3145                --  No_Dispatching_Calls. During the semantic analysis we
3146                --  already notified such violation.
3147
3148                if Restriction_Active (No_Dispatching_Calls) then
3149                   return;
3150                end if;
3151
3152                Tag_Write : declare
3153                   Strm : constant Node_Id := First (Exprs);
3154                   Item : constant Node_Id := Next (Strm);
3155
3156                begin
3157                   --  Ada 2005 (AI-344): Check that the accessibility level
3158                   --  of the type of the output object is not deeper than
3159                   --  that of the attribute's prefix type.
3160
3161                   --  if Get_Access_Level (Item'Tag)
3162                   --       /= Get_Access_Level (P_Type'Tag)
3163                   --  then
3164                   --     raise Tag_Error;
3165                   --  end if;
3166
3167                   --  String'Output (Strm, External_Tag (Item'Tag));
3168
3169                   --  We cannot figure out a practical way to implement this
3170                   --  accessibility check on virtual machines, so we omit it.
3171
3172                   if Ada_Version >= Ada_05
3173                     and then Tagged_Type_Expansion
3174                   then
3175                      Insert_Action (N,
3176                        Make_Implicit_If_Statement (N,
3177                          Condition =>
3178                            Make_Op_Ne (Loc,
3179                              Left_Opnd  =>
3180                                Build_Get_Access_Level (Loc,
3181                                  Make_Attribute_Reference (Loc,
3182                                    Prefix         =>
3183                                      Relocate_Node (
3184                                        Duplicate_Subexpr (Item,
3185                                          Name_Req => True)),
3186                                    Attribute_Name => Name_Tag)),
3187
3188                              Right_Opnd =>
3189                                Make_Integer_Literal (Loc,
3190                                  Type_Access_Level (P_Type))),
3191
3192                          Then_Statements =>
3193                            New_List (Make_Raise_Statement (Loc,
3194                                        New_Occurrence_Of (
3195                                          RTE (RE_Tag_Error), Loc)))));
3196                   end if;
3197
3198                   Insert_Action (N,
3199                     Make_Attribute_Reference (Loc,
3200                       Prefix => New_Occurrence_Of (Standard_String, Loc),
3201                       Attribute_Name => Name_Output,
3202                       Expressions => New_List (
3203                         Relocate_Node (Duplicate_Subexpr (Strm)),
3204                         Make_Function_Call (Loc,
3205                           Name =>
3206                             New_Occurrence_Of (RTE (RE_External_Tag), Loc),
3207                           Parameter_Associations => New_List (
3208                            Make_Attribute_Reference (Loc,
3209                              Prefix =>
3210                                Relocate_Node
3211                                  (Duplicate_Subexpr (Item, Name_Req => True)),
3212                              Attribute_Name => Name_Tag))))));
3213                end Tag_Write;
3214
3215                Pname := Find_Prim_Op (U_Type, TSS_Stream_Output);
3216
3217             --  Tagged type case, use the primitive Output function
3218
3219             elsif Is_Tagged_Type (U_Type) then
3220                Pname := Find_Prim_Op (U_Type, TSS_Stream_Output);
3221
3222             --  All other record type cases, including protected records.
3223             --  The latter only arise for expander generated code for
3224             --  handling shared passive partition access.
3225
3226             else
3227                pragma Assert
3228                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
3229
3230                --  Ada 2005 (AI-216): Program_Error is raised when executing
3231                --  the default implementation of the Output attribute of an
3232                --  unchecked union type if the type lacks default discriminant
3233                --  values.
3234
3235                if Is_Unchecked_Union (Base_Type (U_Type))
3236                  and then No (Discriminant_Constraint (U_Type))
3237                then
3238                   Insert_Action (N,
3239                     Make_Raise_Program_Error (Loc,
3240                       Reason => PE_Unchecked_Union_Restriction));
3241
3242                   return;
3243                end if;
3244
3245                Build_Record_Or_Elementary_Output_Procedure
3246                  (Loc, Base_Type (U_Type), Decl, Pname);
3247                Insert_Action (N, Decl);
3248             end if;
3249          end if;
3250
3251          --  If we fall through, Pname is the name of the procedure to call
3252
3253          Rewrite_Stream_Proc_Call (Pname);
3254       end Output;
3255
3256       ---------
3257       -- Pos --
3258       ---------
3259
3260       --  For enumeration types with a standard representation, Pos is
3261       --  handled by the back end.
3262
3263       --  For enumeration types, with a non-standard representation we generate
3264       --  a call to the _Rep_To_Pos function created when the type was frozen.
3265       --  The call has the form
3266
3267       --    _rep_to_pos (expr, flag)
3268
3269       --  The parameter flag is True if range checks are enabled, causing
3270       --  Program_Error to be raised if the expression has an invalid
3271       --  representation, and False if range checks are suppressed.
3272
3273       --  For integer types, Pos is equivalent to a simple integer
3274       --  conversion and we rewrite it as such
3275
3276       when Attribute_Pos => Pos :
3277       declare
3278          Etyp : Entity_Id := Base_Type (Entity (Pref));
3279
3280       begin
3281          --  Deal with zero/non-zero boolean values
3282
3283          if Is_Boolean_Type (Etyp) then
3284             Adjust_Condition (First (Exprs));
3285             Etyp := Standard_Boolean;
3286             Set_Prefix (N, New_Occurrence_Of (Standard_Boolean, Loc));
3287          end if;
3288
3289          --  Case of enumeration type
3290
3291          if Is_Enumeration_Type (Etyp) then
3292
3293             --  Non-standard enumeration type (generate call)
3294
3295             if Present (Enum_Pos_To_Rep (Etyp)) then
3296                Append_To (Exprs, Rep_To_Pos_Flag (Etyp, Loc));
3297                Rewrite (N,
3298                  Convert_To (Typ,
3299                    Make_Function_Call (Loc,
3300                      Name =>
3301                        New_Reference_To (TSS (Etyp, TSS_Rep_To_Pos), Loc),
3302                      Parameter_Associations => Exprs)));
3303
3304                Analyze_And_Resolve (N, Typ);
3305
3306             --  Standard enumeration type (do universal integer check)
3307
3308             else
3309                Apply_Universal_Integer_Attribute_Checks (N);
3310             end if;
3311
3312          --  Deal with integer types (replace by conversion)
3313
3314          elsif Is_Integer_Type (Etyp) then
3315             Rewrite (N, Convert_To (Typ, First (Exprs)));
3316             Analyze_And_Resolve (N, Typ);
3317          end if;
3318
3319       end Pos;
3320
3321       --------------
3322       -- Position --
3323       --------------
3324
3325       --  We compute this if a component clause was present, otherwise we leave
3326       --  the computation up to the back end, since we don't know what layout
3327       --  will be chosen.
3328
3329       when Attribute_Position => Position :
3330       declare
3331          CE : constant Entity_Id := Entity (Selector_Name (Pref));
3332
3333       begin
3334          if Present (Component_Clause (CE)) then
3335             Rewrite (N,
3336               Make_Integer_Literal (Loc,
3337                 Intval => Component_Bit_Offset (CE) / System_Storage_Unit));
3338             Analyze_And_Resolve (N, Typ);
3339
3340          else
3341             Apply_Universal_Integer_Attribute_Checks (N);
3342          end if;
3343       end Position;
3344
3345       ----------
3346       -- Pred --
3347       ----------
3348
3349       --  1. Deal with enumeration types with holes
3350       --  2. For floating-point, generate call to attribute function
3351       --  3. For other cases, deal with constraint checking
3352
3353       when Attribute_Pred => Pred :
3354       declare
3355          Etyp : constant Entity_Id := Base_Type (Ptyp);
3356
3357       begin
3358
3359          --  For enumeration types with non-standard representations, we
3360          --  expand typ'Pred (x) into
3361
3362          --    Pos_To_Rep (Rep_To_Pos (x) - 1)
3363
3364          --    If the representation is contiguous, we compute instead
3365          --    Lit1 + Rep_to_Pos (x -1), to catch invalid representations.
3366          --    The conversion function Enum_Pos_To_Rep is defined on the
3367          --    base type, not the subtype, so we have to use the base type
3368          --    explicitly for this and other enumeration attributes.
3369
3370          if Is_Enumeration_Type (Ptyp)
3371            and then Present (Enum_Pos_To_Rep (Etyp))
3372          then
3373             if Has_Contiguous_Rep (Etyp) then
3374                Rewrite (N,
3375                   Unchecked_Convert_To (Ptyp,
3376                      Make_Op_Add (Loc,
3377                         Left_Opnd  =>
3378                          Make_Integer_Literal (Loc,
3379                            Enumeration_Rep (First_Literal (Ptyp))),
3380                         Right_Opnd =>
3381                           Make_Function_Call (Loc,
3382                             Name =>
3383                               New_Reference_To
3384                                (TSS (Etyp, TSS_Rep_To_Pos), Loc),
3385
3386                             Parameter_Associations =>
3387                               New_List (
3388                                 Unchecked_Convert_To (Ptyp,
3389                                   Make_Op_Subtract (Loc,
3390                                     Left_Opnd =>
3391                                      Unchecked_Convert_To (Standard_Integer,
3392                                        Relocate_Node (First (Exprs))),
3393                                     Right_Opnd =>
3394                                       Make_Integer_Literal (Loc, 1))),
3395                                 Rep_To_Pos_Flag (Ptyp, Loc))))));
3396
3397             else
3398                --  Add Boolean parameter True, to request program errror if
3399                --  we have a bad representation on our hands. If checks are
3400                --  suppressed, then add False instead
3401
3402                Append_To (Exprs, Rep_To_Pos_Flag (Ptyp, Loc));
3403                Rewrite (N,
3404                  Make_Indexed_Component (Loc,
3405                    Prefix =>
3406                      New_Reference_To
3407                        (Enum_Pos_To_Rep (Etyp), Loc),
3408                    Expressions => New_List (
3409                      Make_Op_Subtract (Loc,
3410                     Left_Opnd =>
3411                       Make_Function_Call (Loc,
3412                         Name =>
3413                           New_Reference_To
3414                             (TSS (Etyp, TSS_Rep_To_Pos), Loc),
3415                           Parameter_Associations => Exprs),
3416                     Right_Opnd => Make_Integer_Literal (Loc, 1)))));
3417             end if;
3418
3419             Analyze_And_Resolve (N, Typ);
3420
3421          --  For floating-point, we transform 'Pred into a call to the Pred
3422          --  floating-point attribute function in Fat_xxx (xxx is root type)
3423
3424          elsif Is_Floating_Point_Type (Ptyp) then
3425             Expand_Fpt_Attribute_R (N);
3426             Analyze_And_Resolve (N, Typ);
3427
3428          --  For modular types, nothing to do (no overflow, since wraps)
3429
3430          elsif Is_Modular_Integer_Type (Ptyp) then
3431             null;
3432
3433          --  For other types, if argument is marked as needing a range check or
3434          --  overflow checking is enabled, we must generate a check.
3435
3436          elsif not Overflow_Checks_Suppressed (Ptyp)
3437            or else Do_Range_Check (First (Exprs))
3438          then
3439             Set_Do_Range_Check (First (Exprs), False);
3440             Expand_Pred_Succ (N);
3441          end if;
3442       end Pred;
3443
3444       --------------
3445       -- Priority --
3446       --------------
3447
3448       --  Ada 2005 (AI-327): Dynamic ceiling priorities
3449
3450       --  We rewrite X'Priority as the following run-time call:
3451
3452       --     Get_Ceiling (X._Object)
3453
3454       --  Note that although X'Priority is notionally an object, it is quite
3455       --  deliberately not defined as an aliased object in the RM. This means
3456       --  that it works fine to rewrite it as a call, without having to worry
3457       --  about complications that would other arise from X'Priority'Access,
3458       --  which is illegal, because of the lack of aliasing.
3459
3460       when Attribute_Priority =>
3461          declare
3462             Call           : Node_Id;
3463             Conctyp        : Entity_Id;
3464             Object_Parm    : Node_Id;
3465             Subprg         : Entity_Id;
3466             RT_Subprg_Name : Node_Id;
3467
3468          begin
3469             --  Look for the enclosing concurrent type
3470
3471             Conctyp := Current_Scope;
3472             while not Is_Concurrent_Type (Conctyp) loop
3473                Conctyp := Scope (Conctyp);
3474             end loop;
3475
3476             pragma Assert (Is_Protected_Type (Conctyp));
3477
3478             --  Generate the actual of the call
3479
3480             Subprg := Current_Scope;
3481             while not Present (Protected_Body_Subprogram (Subprg)) loop
3482                Subprg := Scope (Subprg);
3483             end loop;
3484
3485             --  Use of 'Priority inside protected entries and barriers (in
3486             --  both cases the type of the first formal of their expanded
3487             --  subprogram is Address)
3488
3489             if Etype (First_Entity (Protected_Body_Subprogram (Subprg)))
3490               = RTE (RE_Address)
3491             then
3492                declare
3493                   New_Itype : Entity_Id;
3494
3495                begin
3496                   --  In the expansion of protected entries the type of the
3497                   --  first formal of the Protected_Body_Subprogram is an
3498                   --  Address. In order to reference the _object component
3499                   --  we generate:
3500
3501                   --    type T is access p__ptTV;
3502                   --    freeze T []
3503
3504                   New_Itype := Create_Itype (E_Access_Type, N);
3505                   Set_Etype (New_Itype, New_Itype);
3506                   Set_Directly_Designated_Type (New_Itype,
3507                     Corresponding_Record_Type (Conctyp));
3508                   Freeze_Itype (New_Itype, N);
3509
3510                   --  Generate:
3511                   --    T!(O)._object'unchecked_access
3512
3513                   Object_Parm :=
3514                     Make_Attribute_Reference (Loc,
3515                        Prefix =>
3516                          Make_Selected_Component (Loc,
3517                            Prefix =>
3518                              Unchecked_Convert_To (New_Itype,
3519                                New_Reference_To
3520                                  (First_Entity
3521                                    (Protected_Body_Subprogram (Subprg)),
3522                                   Loc)),
3523                            Selector_Name =>
3524                              Make_Identifier (Loc, Name_uObject)),
3525                        Attribute_Name => Name_Unchecked_Access);
3526                end;
3527
3528             --  Use of 'Priority inside a protected subprogram
3529
3530             else
3531                Object_Parm :=
3532                  Make_Attribute_Reference (Loc,
3533                     Prefix =>
3534                       Make_Selected_Component (Loc,
3535                         Prefix => New_Reference_To
3536                                     (First_Entity
3537                                       (Protected_Body_Subprogram (Subprg)),
3538                                        Loc),
3539                         Selector_Name =>
3540                           Make_Identifier (Loc, Name_uObject)),
3541                     Attribute_Name => Name_Unchecked_Access);
3542             end if;
3543
3544             --  Select the appropriate run-time subprogram
3545
3546             if Number_Entries (Conctyp) = 0 then
3547                RT_Subprg_Name :=
3548                  New_Reference_To (RTE (RE_Get_Ceiling), Loc);
3549             else
3550                RT_Subprg_Name :=
3551                  New_Reference_To (RTE (RO_PE_Get_Ceiling), Loc);
3552             end if;
3553
3554             Call :=
3555               Make_Function_Call (Loc,
3556                 Name => RT_Subprg_Name,
3557                 Parameter_Associations => New_List (Object_Parm));
3558
3559             Rewrite (N, Call);
3560
3561             --  Avoid the generation of extra checks on the pointer to the
3562             --  protected object.
3563
3564             Analyze_And_Resolve (N, Typ, Suppress => Access_Check);
3565          end;
3566
3567       ------------------
3568       -- Range_Length --
3569       ------------------
3570
3571       when Attribute_Range_Length => Range_Length : begin
3572
3573          --  The only special processing required is for the case where
3574          --  Range_Length is applied to an enumeration type with holes.
3575          --  In this case we transform
3576
3577          --     X'Range_Length
3578
3579          --  to
3580
3581          --     X'Pos (X'Last) - X'Pos (X'First) + 1
3582
3583          --  So that the result reflects the proper Pos values instead
3584          --  of the underlying representations.
3585
3586          if Is_Enumeration_Type (Ptyp)
3587            and then Has_Non_Standard_Rep (Ptyp)
3588          then
3589             Rewrite (N,
3590               Make_Op_Add (Loc,
3591                 Left_Opnd =>
3592                   Make_Op_Subtract (Loc,
3593                     Left_Opnd =>
3594                       Make_Attribute_Reference (Loc,
3595                         Attribute_Name => Name_Pos,
3596                         Prefix => New_Occurrence_Of (Ptyp, Loc),
3597                         Expressions => New_List (
3598                           Make_Attribute_Reference (Loc,
3599                             Attribute_Name => Name_Last,
3600                             Prefix => New_Occurrence_Of (Ptyp, Loc)))),
3601
3602                     Right_Opnd =>
3603                       Make_Attribute_Reference (Loc,
3604                         Attribute_Name => Name_Pos,
3605                         Prefix => New_Occurrence_Of (Ptyp, Loc),
3606                         Expressions => New_List (
3607                           Make_Attribute_Reference (Loc,
3608                             Attribute_Name => Name_First,
3609                             Prefix => New_Occurrence_Of (Ptyp, Loc))))),
3610
3611                 Right_Opnd => Make_Integer_Literal (Loc, 1)));
3612
3613             Analyze_And_Resolve (N, Typ);
3614
3615          --  For all other cases, the attribute is handled by the back end, but
3616          --  we need to deal with the case of the range check on a universal
3617          --  integer.
3618
3619          else
3620             Apply_Universal_Integer_Attribute_Checks (N);
3621          end if;
3622       end Range_Length;
3623
3624       ----------
3625       -- Read --
3626       ----------
3627
3628       when Attribute_Read => Read : declare
3629          P_Type : constant Entity_Id := Entity (Pref);
3630          B_Type : constant Entity_Id := Base_Type (P_Type);
3631          U_Type : constant Entity_Id := Underlying_Type (P_Type);
3632          Pname  : Entity_Id;
3633          Decl   : Node_Id;
3634          Prag   : Node_Id;
3635          Arg2   : Node_Id;
3636          Rfunc  : Node_Id;
3637          Lhs    : Node_Id;
3638          Rhs    : Node_Id;
3639
3640       begin
3641          --  If no underlying type, we have an error that will be diagnosed
3642          --  elsewhere, so here we just completely ignore the expansion.
3643
3644          if No (U_Type) then
3645             return;
3646          end if;
3647
3648          --  The simple case, if there is a TSS for Read, just call it
3649
3650          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Read);
3651
3652          if Present (Pname) then
3653             null;
3654
3655          else
3656             --  If there is a Stream_Convert pragma, use it, we rewrite
3657
3658             --     sourcetyp'Read (stream, Item)
3659
3660             --  as
3661
3662             --     Item := sourcetyp (strmread (strmtyp'Input (Stream)));
3663
3664             --  where strmread is the given Read function that converts an
3665             --  argument of type strmtyp to type sourcetyp or a type from which
3666             --  it is derived. The conversion to sourcetyp is required in the
3667             --  latter case.
3668
3669             --  A special case arises if Item is a type conversion in which
3670             --  case, we have to expand to:
3671
3672             --     Itemx := typex (strmread (strmtyp'Input (Stream)));
3673
3674             --  where Itemx is the expression of the type conversion (i.e.
3675             --  the actual object), and typex is the type of Itemx.
3676
3677             Prag := Get_Stream_Convert_Pragma (P_Type);
3678
3679             if Present (Prag) then
3680                Arg2  := Next (First (Pragma_Argument_Associations (Prag)));
3681                Rfunc := Entity (Expression (Arg2));
3682                Lhs := Relocate_Node (Next (First (Exprs)));
3683                Rhs :=
3684                  OK_Convert_To (B_Type,
3685                    Make_Function_Call (Loc,
3686                      Name => New_Occurrence_Of (Rfunc, Loc),
3687                      Parameter_Associations => New_List (
3688                        Make_Attribute_Reference (Loc,
3689                          Prefix =>
3690                            New_Occurrence_Of
3691                              (Etype (First_Formal (Rfunc)), Loc),
3692                          Attribute_Name => Name_Input,
3693                          Expressions => New_List (
3694                            Relocate_Node (First (Exprs)))))));
3695
3696                if Nkind (Lhs) = N_Type_Conversion then
3697                   Lhs := Expression (Lhs);
3698                   Rhs := Convert_To (Etype (Lhs), Rhs);
3699                end if;
3700
3701                Rewrite (N,
3702                  Make_Assignment_Statement (Loc,
3703                    Name       => Lhs,
3704                    Expression => Rhs));
3705                Set_Assignment_OK (Lhs);
3706                Analyze (N);
3707                return;
3708
3709             --  For elementary types, we call the I_xxx routine using the first
3710             --  parameter and then assign the result into the second parameter.
3711             --  We set Assignment_OK to deal with the conversion case.
3712
3713             elsif Is_Elementary_Type (U_Type) then
3714                declare
3715                   Lhs : Node_Id;
3716                   Rhs : Node_Id;
3717
3718                begin
3719                   Lhs := Relocate_Node (Next (First (Exprs)));
3720                   Rhs := Build_Elementary_Input_Call (N);
3721
3722                   if Nkind (Lhs) = N_Type_Conversion then
3723                      Lhs := Expression (Lhs);
3724                      Rhs := Convert_To (Etype (Lhs), Rhs);
3725                   end if;
3726
3727                   Set_Assignment_OK (Lhs);
3728
3729                   Rewrite (N,
3730                     Make_Assignment_Statement (Loc,
3731                       Name       => Lhs,
3732                       Expression => Rhs));
3733
3734                   Analyze (N);
3735                   return;
3736                end;
3737
3738             --  Array type case
3739
3740             elsif Is_Array_Type (U_Type) then
3741                Build_Array_Read_Procedure (N, U_Type, Decl, Pname);
3742                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
3743
3744             --  Tagged type case, use the primitive Read function. Note that
3745             --  this will dispatch in the class-wide case which is what we want
3746
3747             elsif Is_Tagged_Type (U_Type) then
3748                Pname := Find_Prim_Op (U_Type, TSS_Stream_Read);
3749
3750             --  All other record type cases, including protected records. The
3751             --  latter only arise for expander generated code for handling
3752             --  shared passive partition access.
3753
3754             else
3755                pragma Assert
3756                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
3757
3758                --  Ada 2005 (AI-216): Program_Error is raised when executing
3759                --  the default implementation of the Read attribute of an
3760                --  Unchecked_Union type.
3761
3762                if Is_Unchecked_Union (Base_Type (U_Type)) then
3763                   Insert_Action (N,
3764                     Make_Raise_Program_Error (Loc,
3765                       Reason => PE_Unchecked_Union_Restriction));
3766                end if;
3767
3768                if Has_Discriminants (U_Type)
3769                  and then Present
3770                    (Discriminant_Default_Value (First_Discriminant (U_Type)))
3771                then
3772                   Build_Mutable_Record_Read_Procedure
3773                     (Loc, Base_Type (U_Type), Decl, Pname);
3774                else
3775                   Build_Record_Read_Procedure
3776                     (Loc, Base_Type (U_Type), Decl, Pname);
3777                end if;
3778
3779                --  Suppress checks, uninitialized or otherwise invalid
3780                --  data does not cause constraint errors to be raised for
3781                --  a complete record read.
3782
3783                Insert_Action (N, Decl, All_Checks);
3784             end if;
3785          end if;
3786
3787          Rewrite_Stream_Proc_Call (Pname);
3788       end Read;
3789
3790       ---------------
3791       -- Remainder --
3792       ---------------
3793
3794       --  Transforms 'Remainder into a call to the floating-point attribute
3795       --  function Remainder in Fat_xxx (where xxx is the root type)
3796
3797       when Attribute_Remainder =>
3798          Expand_Fpt_Attribute_RR (N);
3799
3800       ------------
3801       -- Result --
3802       ------------
3803
3804       --  Transform 'Result into reference to _Result formal. At the point
3805       --  where a legal 'Result attribute is expanded, we know that we are in
3806       --  the context of a _Postcondition function with a _Result parameter.
3807
3808       when Attribute_Result =>
3809          Rewrite (N, Make_Identifier (Loc, Chars => Name_uResult));
3810          Analyze_And_Resolve (N, Typ);
3811
3812       -----------
3813       -- Round --
3814       -----------
3815
3816       --  The handling of the Round attribute is quite delicate. The processing
3817       --  in Sem_Attr introduced a conversion to universal real, reflecting the
3818       --  semantics of Round, but we do not want anything to do with universal
3819       --  real at runtime, since this corresponds to using floating-point
3820       --  arithmetic.
3821
3822       --  What we have now is that the Etype of the Round attribute correctly
3823       --  indicates the final result type. The operand of the Round is the
3824       --  conversion to universal real, described above, and the operand of
3825       --  this conversion is the actual operand of Round, which may be the
3826       --  special case of a fixed point multiplication or division (Etype =
3827       --  universal fixed)
3828
3829       --  The exapander will expand first the operand of the conversion, then
3830       --  the conversion, and finally the round attribute itself, since we
3831       --  always work inside out. But we cannot simply process naively in this
3832       --  order. In the semantic world where universal fixed and real really
3833       --  exist and have infinite precision, there is no problem, but in the
3834       --  implementation world, where universal real is a floating-point type,
3835       --  we would get the wrong result.
3836
3837       --  So the approach is as follows. First, when expanding a multiply or
3838       --  divide whose type is universal fixed, we do nothing at all, instead
3839       --  deferring the operation till later.
3840
3841       --  The actual processing is done in Expand_N_Type_Conversion which
3842       --  handles the special case of Round by looking at its parent to see if
3843       --  it is a Round attribute, and if it is, handling the conversion (or
3844       --  its fixed multiply/divide child) in an appropriate manner.
3845
3846       --  This means that by the time we get to expanding the Round attribute
3847       --  itself, the Round is nothing more than a type conversion (and will
3848       --  often be a null type conversion), so we just replace it with the
3849       --  appropriate conversion operation.
3850
3851       when Attribute_Round =>
3852          Rewrite (N,
3853            Convert_To (Etype (N), Relocate_Node (First (Exprs))));
3854          Analyze_And_Resolve (N);
3855
3856       --------------
3857       -- Rounding --
3858       --------------
3859
3860       --  Transforms 'Rounding into a call to the floating-point attribute
3861       --  function Rounding in Fat_xxx (where xxx is the root type)
3862
3863       when Attribute_Rounding =>
3864          Expand_Fpt_Attribute_R (N);
3865
3866       -------------
3867       -- Scaling --
3868       -------------
3869
3870       --  Transforms 'Scaling into a call to the floating-point attribute
3871       --  function Scaling in Fat_xxx (where xxx is the root type)
3872
3873       when Attribute_Scaling =>
3874          Expand_Fpt_Attribute_RI (N);
3875
3876       ----------
3877       -- Size --
3878       ----------
3879
3880       when Attribute_Size        |
3881            Attribute_Object_Size |
3882            Attribute_Value_Size  |
3883            Attribute_VADS_Size   => Size :
3884
3885       declare
3886          Siz      : Uint;
3887          New_Node : Node_Id;
3888
3889       begin
3890          --  Processing for VADS_Size case. Note that this processing removes
3891          --  all traces of VADS_Size from the tree, and completes all required
3892          --  processing for VADS_Size by translating the attribute reference
3893          --  to an appropriate Size or Object_Size reference.
3894
3895          if Id = Attribute_VADS_Size
3896            or else (Use_VADS_Size and then Id = Attribute_Size)
3897          then
3898             --  If the size is specified, then we simply use the specified
3899             --  size. This applies to both types and objects. The size of an
3900             --  object can be specified in the following ways:
3901
3902             --    An explicit size object is given for an object
3903             --    A component size is specified for an indexed component
3904             --    A component clause is specified for a selected component
3905             --    The object is a component of a packed composite object
3906
3907             --  If the size is specified, then VADS_Size of an object
3908
3909             if (Is_Entity_Name (Pref)
3910                  and then Present (Size_Clause (Entity (Pref))))
3911               or else
3912                 (Nkind (Pref) = N_Component_Clause
3913                   and then (Present (Component_Clause
3914                                      (Entity (Selector_Name (Pref))))
3915                              or else Is_Packed (Etype (Prefix (Pref)))))
3916               or else
3917                 (Nkind (Pref) = N_Indexed_Component
3918                   and then (Component_Size (Etype (Prefix (Pref))) /= 0
3919                              or else Is_Packed (Etype (Prefix (Pref)))))
3920             then
3921                Set_Attribute_Name (N, Name_Size);
3922
3923             --  Otherwise if we have an object rather than a type, then the
3924             --  VADS_Size attribute applies to the type of the object, rather
3925             --  than the object itself. This is one of the respects in which
3926             --  VADS_Size differs from Size.
3927
3928             else
3929                if (not Is_Entity_Name (Pref)
3930                     or else not Is_Type (Entity (Pref)))
3931                  and then (Is_Scalar_Type (Ptyp) or else Is_Constrained (Ptyp))
3932                then
3933                   Rewrite (Pref, New_Occurrence_Of (Ptyp, Loc));
3934                end if;
3935
3936                --  For a scalar type for which no size was explicitly given,
3937                --  VADS_Size means Object_Size. This is the other respect in
3938                --  which VADS_Size differs from Size.
3939
3940                if Is_Scalar_Type (Ptyp) and then No (Size_Clause (Ptyp)) then
3941                   Set_Attribute_Name (N, Name_Object_Size);
3942
3943                --  In all other cases, Size and VADS_Size are the sane
3944
3945                else
3946                   Set_Attribute_Name (N, Name_Size);
3947                end if;
3948             end if;
3949          end if;
3950
3951          --  For class-wide types, X'Class'Size is transformed into a direct
3952          --  reference to the Size of the class type, so that the back end does
3953          --  not have to deal with the X'Class'Size reference.
3954
3955          if Is_Entity_Name (Pref)
3956            and then Is_Class_Wide_Type (Entity (Pref))
3957          then
3958             Rewrite (Prefix (N), New_Occurrence_Of (Entity (Pref), Loc));
3959             return;
3960
3961          --  For X'Size applied to an object of a class-wide type, transform
3962          --  X'Size into a call to the primitive operation _Size applied to X.
3963
3964          elsif Is_Class_Wide_Type (Ptyp)
3965            or else (Id = Attribute_Size
3966                       and then Is_Tagged_Type (Ptyp)
3967                       and then Has_Unknown_Discriminants (Ptyp))
3968          then
3969             --  No need to do anything else compiling under restriction
3970             --  No_Dispatching_Calls. During the semantic analysis we
3971             --  already notified such violation.
3972
3973             if Restriction_Active (No_Dispatching_Calls) then
3974                return;
3975             end if;
3976
3977             New_Node :=
3978               Make_Function_Call (Loc,
3979                 Name => New_Reference_To
3980                   (Find_Prim_Op (Ptyp, Name_uSize), Loc),
3981                 Parameter_Associations => New_List (Pref));
3982
3983             if Typ /= Standard_Long_Long_Integer then
3984
3985                --  The context is a specific integer type with which the
3986                --  original attribute was compatible. The function has a
3987                --  specific type as well, so to preserve the compatibility
3988                --  we must convert explicitly.
3989
3990                New_Node := Convert_To (Typ, New_Node);
3991             end if;
3992
3993             Rewrite (N, New_Node);
3994             Analyze_And_Resolve (N, Typ);
3995             return;
3996
3997          --  Case of known RM_Size of a type
3998
3999          elsif (Id = Attribute_Size or else Id = Attribute_Value_Size)
4000            and then Is_Entity_Name (Pref)
4001            and then Is_Type (Entity (Pref))
4002            and then Known_Static_RM_Size (Entity (Pref))
4003          then
4004             Siz := RM_Size (Entity (Pref));
4005
4006          --  Case of known Esize of a type
4007
4008          elsif Id = Attribute_Object_Size
4009            and then Is_Entity_Name (Pref)
4010            and then Is_Type (Entity (Pref))
4011            and then Known_Static_Esize (Entity (Pref))
4012          then
4013             Siz := Esize (Entity (Pref));
4014
4015          --  Case of known size of object
4016
4017          elsif Id = Attribute_Size
4018            and then Is_Entity_Name (Pref)
4019            and then Is_Object (Entity (Pref))
4020            and then Known_Esize (Entity (Pref))
4021            and then Known_Static_Esize (Entity (Pref))
4022          then
4023             Siz := Esize (Entity (Pref));
4024
4025          --  For an array component, we can do Size in the front end
4026          --  if the component_size of the array is set.
4027
4028          elsif Nkind (Pref) = N_Indexed_Component then
4029             Siz := Component_Size (Etype (Prefix (Pref)));
4030
4031          --  For a record component, we can do Size in the front end if there
4032          --  is a component clause, or if the record is packed and the
4033          --  component's size is known at compile time.
4034
4035          elsif Nkind (Pref) = N_Selected_Component then
4036             declare
4037                Rec  : constant Entity_Id := Etype (Prefix (Pref));
4038                Comp : constant Entity_Id := Entity (Selector_Name (Pref));
4039
4040             begin
4041                if Present (Component_Clause (Comp)) then
4042                   Siz := Esize (Comp);
4043
4044                elsif Is_Packed (Rec) then
4045                   Siz := RM_Size (Ptyp);
4046
4047                else
4048                   Apply_Universal_Integer_Attribute_Checks (N);
4049                   return;
4050                end if;
4051             end;
4052
4053          --  All other cases are handled by the back end
4054
4055          else
4056             Apply_Universal_Integer_Attribute_Checks (N);
4057
4058             --  If Size is applied to a formal parameter that is of a packed
4059             --  array subtype, then apply Size to the actual subtype.
4060
4061             if Is_Entity_Name (Pref)
4062               and then Is_Formal (Entity (Pref))
4063               and then Is_Array_Type (Ptyp)
4064               and then Is_Packed (Ptyp)
4065             then
4066                Rewrite (N,
4067                  Make_Attribute_Reference (Loc,
4068                    Prefix =>
4069                      New_Occurrence_Of (Get_Actual_Subtype (Pref), Loc),
4070                    Attribute_Name => Name_Size));
4071                Analyze_And_Resolve (N, Typ);
4072             end if;
4073
4074             --  If Size applies to a dereference of an access to unconstrained
4075             --  packed array, the back end needs to see its unconstrained
4076             --  nominal type, but also a hint to the actual constrained type.
4077
4078             if Nkind (Pref) = N_Explicit_Dereference
4079               and then Is_Array_Type (Ptyp)
4080               and then not Is_Constrained (Ptyp)
4081               and then Is_Packed (Ptyp)
4082             then
4083                Set_Actual_Designated_Subtype (Pref,
4084                  Get_Actual_Subtype (Pref));
4085             end if;
4086
4087             return;
4088          end if;
4089
4090          --  Common processing for record and array component case
4091
4092          if Siz /= No_Uint and then Siz /= 0 then
4093             declare
4094                CS : constant Boolean := Comes_From_Source (N);
4095
4096             begin
4097                Rewrite (N, Make_Integer_Literal (Loc, Siz));
4098
4099                --  This integer literal is not a static expression. We do not
4100                --  call Analyze_And_Resolve here, because this would activate
4101                --  the circuit for deciding that a static value was out of
4102                --  range, and we don't want that.
4103
4104                --  So just manually set the type, mark the expression as non-
4105                --  static, and then ensure that the result is checked properly
4106                --  if the attribute comes from source (if it was internally
4107                --  generated, we never need a constraint check).
4108
4109                Set_Etype (N, Typ);
4110                Set_Is_Static_Expression (N, False);
4111
4112                if CS then
4113                   Apply_Constraint_Check (N, Typ);
4114                end if;
4115             end;
4116          end if;
4117       end Size;
4118
4119       ------------------
4120       -- Storage_Pool --
4121       ------------------
4122
4123       when Attribute_Storage_Pool =>
4124          Rewrite (N,
4125            Make_Type_Conversion (Loc,
4126              Subtype_Mark => New_Reference_To (Etype (N), Loc),
4127              Expression   => New_Reference_To (Entity (N), Loc)));
4128          Analyze_And_Resolve (N, Typ);
4129
4130       ------------------
4131       -- Storage_Size --
4132       ------------------
4133
4134       when Attribute_Storage_Size => Storage_Size : begin
4135
4136          --  Access type case, always go to the root type
4137
4138          --  The case of access types results in a value of zero for the case
4139          --  where no storage size attribute clause has been given. If a
4140          --  storage size has been given, then the attribute is converted
4141          --  to a reference to the variable used to hold this value.
4142
4143          if Is_Access_Type (Ptyp) then
4144             if Present (Storage_Size_Variable (Root_Type (Ptyp))) then
4145                Rewrite (N,
4146                  Make_Attribute_Reference (Loc,
4147                    Prefix => New_Reference_To (Typ, Loc),
4148                    Attribute_Name => Name_Max,
4149                    Expressions => New_List (
4150                      Make_Integer_Literal (Loc, 0),
4151                      Convert_To (Typ,
4152                        New_Reference_To
4153                          (Storage_Size_Variable (Root_Type (Ptyp)), Loc)))));
4154
4155             elsif Present (Associated_Storage_Pool (Root_Type (Ptyp))) then
4156                Rewrite (N,
4157                  OK_Convert_To (Typ,
4158                    Make_Function_Call (Loc,
4159                      Name =>
4160                        New_Reference_To
4161                          (Find_Prim_Op
4162                            (Etype (Associated_Storage_Pool (Root_Type (Ptyp))),
4163                             Attribute_Name (N)),
4164                           Loc),
4165
4166                      Parameter_Associations => New_List (
4167                        New_Reference_To
4168                          (Associated_Storage_Pool (Root_Type (Ptyp)), Loc)))));
4169
4170             else
4171                Rewrite (N, Make_Integer_Literal (Loc, 0));
4172             end if;
4173
4174             Analyze_And_Resolve (N, Typ);
4175
4176          --  For tasks, we retrieve the size directly from the TCB. The
4177          --  size may depend on a discriminant of the type, and therefore
4178          --  can be a per-object expression, so type-level information is
4179          --  not sufficient in general. There are four cases to consider:
4180
4181          --  a) If the attribute appears within a task body, the designated
4182          --    TCB is obtained by a call to Self.
4183
4184          --  b) If the prefix of the attribute is the name of a task object,
4185          --  the designated TCB is the one stored in the corresponding record.
4186
4187          --  c) If the prefix is a task type, the size is obtained from the
4188          --  size variable created for each task type
4189
4190          --  d) If no storage_size was specified for the type , there is no
4191          --  size variable, and the value is a system-specific default.
4192
4193          else
4194             if In_Open_Scopes (Ptyp) then
4195
4196                --  Storage_Size (Self)
4197
4198                Rewrite (N,
4199                  Convert_To (Typ,
4200                    Make_Function_Call (Loc,
4201                      Name =>
4202                        New_Occurrence_Of (RTE (RE_Storage_Size), Loc),
4203                      Parameter_Associations =>
4204                        New_List (
4205                          Make_Function_Call (Loc,
4206                            Name =>
4207                              New_Reference_To (RTE (RE_Self), Loc))))));
4208
4209             elsif not Is_Entity_Name (Pref)
4210               or else not Is_Type (Entity (Pref))
4211             then
4212                --  Storage_Size (Rec (Obj).Size)
4213
4214                Rewrite (N,
4215                  Convert_To (Typ,
4216                    Make_Function_Call (Loc,
4217                      Name =>
4218                        New_Occurrence_Of (RTE (RE_Storage_Size), Loc),
4219                        Parameter_Associations =>
4220                           New_List (
4221                             Make_Selected_Component (Loc,
4222                               Prefix =>
4223                                 Unchecked_Convert_To (
4224                                   Corresponding_Record_Type (Ptyp),
4225                                     New_Copy_Tree (Pref)),
4226                               Selector_Name =>
4227                                  Make_Identifier (Loc, Name_uTask_Id))))));
4228
4229             elsif Present (Storage_Size_Variable (Ptyp)) then
4230
4231                --  Static storage size pragma given for type: retrieve value
4232                --  from its allocated storage variable.
4233
4234                Rewrite (N,
4235                  Convert_To (Typ,
4236                    Make_Function_Call (Loc,
4237                      Name => New_Occurrence_Of (
4238                        RTE (RE_Adjust_Storage_Size), Loc),
4239                      Parameter_Associations =>
4240                        New_List (
4241                          New_Reference_To (
4242                            Storage_Size_Variable (Ptyp), Loc)))));
4243             else
4244                --  Get system default
4245
4246                Rewrite (N,
4247                  Convert_To (Typ,
4248                    Make_Function_Call (Loc,
4249                      Name =>
4250                        New_Occurrence_Of (
4251                         RTE (RE_Default_Stack_Size), Loc))));
4252             end if;
4253
4254             Analyze_And_Resolve (N, Typ);
4255          end if;
4256       end Storage_Size;
4257
4258       -----------------
4259       -- Stream_Size --
4260       -----------------
4261
4262       when Attribute_Stream_Size => Stream_Size : declare
4263          Size : Int;
4264
4265       begin
4266          --  If we have a Stream_Size clause for this type use it, otherwise
4267          --  the Stream_Size if the size of the type.
4268
4269          if Has_Stream_Size_Clause (Ptyp) then
4270             Size :=
4271               UI_To_Int
4272                 (Static_Integer (Expression (Stream_Size_Clause (Ptyp))));
4273          else
4274             Size := UI_To_Int (Esize (Ptyp));
4275          end if;
4276
4277          Rewrite (N, Make_Integer_Literal (Loc, Intval => Size));
4278          Analyze_And_Resolve (N, Typ);
4279       end Stream_Size;
4280
4281       ----------
4282       -- Succ --
4283       ----------
4284
4285       --  1. Deal with enumeration types with holes
4286       --  2. For floating-point, generate call to attribute function
4287       --  3. For other cases, deal with constraint checking
4288
4289       when Attribute_Succ => Succ : declare
4290          Etyp : constant Entity_Id := Base_Type (Ptyp);
4291
4292       begin
4293
4294          --  For enumeration types with non-standard representations, we
4295          --  expand typ'Succ (x) into
4296
4297          --    Pos_To_Rep (Rep_To_Pos (x) + 1)
4298
4299          --    If the representation is contiguous, we compute instead
4300          --    Lit1 + Rep_to_Pos (x+1), to catch invalid representations.
4301
4302          if Is_Enumeration_Type (Ptyp)
4303            and then Present (Enum_Pos_To_Rep (Etyp))
4304          then
4305             if Has_Contiguous_Rep (Etyp) then
4306                Rewrite (N,
4307                   Unchecked_Convert_To (Ptyp,
4308                      Make_Op_Add (Loc,
4309                         Left_Opnd  =>
4310                          Make_Integer_Literal (Loc,
4311                            Enumeration_Rep (First_Literal (Ptyp))),
4312                         Right_Opnd =>
4313                           Make_Function_Call (Loc,
4314                             Name =>
4315                               New_Reference_To
4316                                (TSS (Etyp, TSS_Rep_To_Pos), Loc),
4317
4318                             Parameter_Associations =>
4319                               New_List (
4320                                 Unchecked_Convert_To (Ptyp,
4321                                   Make_Op_Add (Loc,
4322                                   Left_Opnd =>
4323                                     Unchecked_Convert_To (Standard_Integer,
4324                                       Relocate_Node (First (Exprs))),
4325                                   Right_Opnd =>
4326                                     Make_Integer_Literal (Loc, 1))),
4327                                 Rep_To_Pos_Flag (Ptyp, Loc))))));
4328             else
4329                --  Add Boolean parameter True, to request program errror if
4330                --  we have a bad representation on our hands. Add False if
4331                --  checks are suppressed.
4332
4333                Append_To (Exprs, Rep_To_Pos_Flag (Ptyp, Loc));
4334                Rewrite (N,
4335                  Make_Indexed_Component (Loc,
4336                    Prefix =>
4337                      New_Reference_To
4338                        (Enum_Pos_To_Rep (Etyp), Loc),
4339                    Expressions => New_List (
4340                      Make_Op_Add (Loc,
4341                        Left_Opnd =>
4342                          Make_Function_Call (Loc,
4343                            Name =>
4344                              New_Reference_To
4345                                (TSS (Etyp, TSS_Rep_To_Pos), Loc),
4346                            Parameter_Associations => Exprs),
4347                        Right_Opnd => Make_Integer_Literal (Loc, 1)))));
4348             end if;
4349
4350             Analyze_And_Resolve (N, Typ);
4351
4352          --  For floating-point, we transform 'Succ into a call to the Succ
4353          --  floating-point attribute function in Fat_xxx (xxx is root type)
4354
4355          elsif Is_Floating_Point_Type (Ptyp) then
4356             Expand_Fpt_Attribute_R (N);
4357             Analyze_And_Resolve (N, Typ);
4358
4359          --  For modular types, nothing to do (no overflow, since wraps)
4360
4361          elsif Is_Modular_Integer_Type (Ptyp) then
4362             null;
4363
4364          --  For other types, if argument is marked as needing a range check or
4365          --  overflow checking is enabled, we must generate a check.
4366
4367          elsif not Overflow_Checks_Suppressed (Ptyp)
4368            or else Do_Range_Check (First (Exprs))
4369          then
4370             Set_Do_Range_Check (First (Exprs), False);
4371             Expand_Pred_Succ (N);
4372          end if;
4373       end Succ;
4374
4375       ---------
4376       -- Tag --
4377       ---------
4378
4379       --  Transforms X'Tag into a direct reference to the tag of X
4380
4381       when Attribute_Tag => Tag : declare
4382          Ttyp           : Entity_Id;
4383          Prefix_Is_Type : Boolean;
4384
4385       begin
4386          if Is_Entity_Name (Pref) and then Is_Type (Entity (Pref)) then
4387             Ttyp := Entity (Pref);
4388             Prefix_Is_Type := True;
4389          else
4390             Ttyp := Ptyp;
4391             Prefix_Is_Type := False;
4392          end if;
4393
4394          if Is_Class_Wide_Type (Ttyp) then
4395             Ttyp := Root_Type (Ttyp);
4396          end if;
4397
4398          Ttyp := Underlying_Type (Ttyp);
4399
4400          --  Ada 2005: The type may be a synchronized tagged type, in which
4401          --  case the tag information is stored in the corresponding record.
4402
4403          if Is_Concurrent_Type (Ttyp) then
4404             Ttyp := Corresponding_Record_Type (Ttyp);
4405          end if;
4406
4407          if Prefix_Is_Type then
4408
4409             --  For VMs we leave the type attribute unexpanded because
4410             --  there's not a dispatching table to reference.
4411
4412             if Tagged_Type_Expansion then
4413                Rewrite (N,
4414                  Unchecked_Convert_To (RTE (RE_Tag),
4415                    New_Reference_To
4416                      (Node (First_Elmt (Access_Disp_Table (Ttyp))), Loc)));
4417                Analyze_And_Resolve (N, RTE (RE_Tag));
4418             end if;
4419
4420          --  Ada 2005 (AI-251): The use of 'Tag in the sources always
4421          --  references the primary tag of the actual object. If 'Tag is
4422          --  applied to class-wide interface objects we generate code that
4423          --  displaces "this" to reference the base of the object.
4424
4425          elsif Comes_From_Source (N)
4426             and then Is_Class_Wide_Type (Etype (Prefix (N)))
4427             and then Is_Interface (Etype (Prefix (N)))
4428          then
4429             --  Generate:
4430             --    (To_Tag_Ptr (Prefix'Address)).all
4431
4432             --  Note that Prefix'Address is recursively expanded into a call
4433             --  to Base_Address (Obj.Tag)
4434
4435             --  Not needed for VM targets, since all handled by the VM
4436
4437             if Tagged_Type_Expansion then
4438                Rewrite (N,
4439                  Make_Explicit_Dereference (Loc,
4440                    Unchecked_Convert_To (RTE (RE_Tag_Ptr),
4441                      Make_Attribute_Reference (Loc,
4442                        Prefix => Relocate_Node (Pref),
4443                        Attribute_Name => Name_Address))));
4444                Analyze_And_Resolve (N, RTE (RE_Tag));
4445             end if;
4446
4447          else
4448             Rewrite (N,
4449               Make_Selected_Component (Loc,
4450                 Prefix => Relocate_Node (Pref),
4451                 Selector_Name =>
4452                   New_Reference_To (First_Tag_Component (Ttyp), Loc)));
4453             Analyze_And_Resolve (N, RTE (RE_Tag));
4454          end if;
4455       end Tag;
4456
4457       ----------------
4458       -- Terminated --
4459       ----------------
4460
4461       --  Transforms 'Terminated attribute into a call to Terminated function
4462
4463       when Attribute_Terminated => Terminated :
4464       begin
4465          --  The prefix of Terminated is of a task interface class-wide type.
4466          --  Generate:
4467          --    terminated (Task_Id (Pref._disp_get_task_id));
4468
4469          if Ada_Version >= Ada_05
4470            and then Ekind (Ptyp) = E_Class_Wide_Type
4471            and then Is_Interface (Ptyp)
4472            and then Is_Task_Interface (Ptyp)
4473          then
4474             Rewrite (N,
4475               Make_Function_Call (Loc,
4476                 Name =>
4477                   New_Reference_To (RTE (RE_Terminated), Loc),
4478                 Parameter_Associations => New_List (
4479                   Make_Unchecked_Type_Conversion (Loc,
4480                     Subtype_Mark =>
4481                       New_Reference_To (RTE (RO_ST_Task_Id), Loc),
4482                     Expression =>
4483                       Make_Selected_Component (Loc,
4484                         Prefix =>
4485                           New_Copy_Tree (Pref),
4486                         Selector_Name =>
4487                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id))))));
4488
4489          elsif Restricted_Profile then
4490             Rewrite (N,
4491               Build_Call_With_Task (Pref, RTE (RE_Restricted_Terminated)));
4492
4493          else
4494             Rewrite (N,
4495               Build_Call_With_Task (Pref, RTE (RE_Terminated)));
4496          end if;
4497
4498          Analyze_And_Resolve (N, Standard_Boolean);
4499       end Terminated;
4500
4501       ----------------
4502       -- To_Address --
4503       ----------------
4504
4505       --  Transforms System'To_Address (X) into unchecked conversion
4506       --  from (integral) type of X to type address.
4507
4508       when Attribute_To_Address =>
4509          Rewrite (N,
4510            Unchecked_Convert_To (RTE (RE_Address),
4511              Relocate_Node (First (Exprs))));
4512          Analyze_And_Resolve (N, RTE (RE_Address));
4513
4514       ------------
4515       -- To_Any --
4516       ------------
4517
4518       when Attribute_To_Any => To_Any : declare
4519          P_Type : constant Entity_Id := Etype (Pref);
4520          Decls  : constant List_Id   := New_List;
4521       begin
4522          Rewrite (N,
4523            Build_To_Any_Call
4524              (Convert_To (P_Type,
4525               Relocate_Node (First (Exprs))), Decls));
4526          Insert_Actions (N, Decls);
4527          Analyze_And_Resolve (N, RTE (RE_Any));
4528       end To_Any;
4529
4530       ----------------
4531       -- Truncation --
4532       ----------------
4533
4534       --  Transforms 'Truncation into a call to the floating-point attribute
4535       --  function Truncation in Fat_xxx (where xxx is the root type).
4536       --  Expansion is avoided for cases the back end can handle directly.
4537
4538       when Attribute_Truncation =>
4539          if not Is_Inline_Floating_Point_Attribute (N) then
4540             Expand_Fpt_Attribute_R (N);
4541          end if;
4542
4543       --------------
4544       -- TypeCode --
4545       --------------
4546
4547       when Attribute_TypeCode => TypeCode : declare
4548          P_Type : constant Entity_Id := Etype (Pref);
4549          Decls  : constant List_Id   := New_List;
4550       begin
4551          Rewrite (N, Build_TypeCode_Call (Loc, P_Type, Decls));
4552          Insert_Actions (N, Decls);
4553          Analyze_And_Resolve (N, RTE (RE_TypeCode));
4554       end TypeCode;
4555
4556       -----------------------
4557       -- Unbiased_Rounding --
4558       -----------------------
4559
4560       --  Transforms 'Unbiased_Rounding into a call to the floating-point
4561       --  attribute function Unbiased_Rounding in Fat_xxx (where xxx is the
4562       --  root type). Expansion is avoided for cases the back end can handle
4563       --  directly.
4564
4565       when Attribute_Unbiased_Rounding =>
4566          if not Is_Inline_Floating_Point_Attribute (N) then
4567             Expand_Fpt_Attribute_R (N);
4568          end if;
4569
4570       -----------------
4571       -- UET_Address --
4572       -----------------
4573
4574       when Attribute_UET_Address => UET_Address : declare
4575          Ent : constant Entity_Id := Make_Temporary (Loc, 'T');
4576
4577       begin
4578          Insert_Action (N,
4579            Make_Object_Declaration (Loc,
4580              Defining_Identifier => Ent,
4581              Aliased_Present     => True,
4582              Object_Definition   =>
4583                New_Occurrence_Of (RTE (RE_Address), Loc)));
4584
4585          --  Construct name __gnat_xxx__SDP, where xxx is the unit name
4586          --  in normal external form.
4587
4588          Get_External_Unit_Name_String (Get_Unit_Name (Pref));
4589          Name_Buffer (1 + 7 .. Name_Len + 7) := Name_Buffer (1 .. Name_Len);
4590          Name_Len := Name_Len + 7;
4591          Name_Buffer (1 .. 7) := "__gnat_";
4592          Name_Buffer (Name_Len + 1 .. Name_Len + 5) := "__SDP";
4593          Name_Len := Name_Len + 5;
4594
4595          Set_Is_Imported (Ent);
4596          Set_Interface_Name (Ent,
4597            Make_String_Literal (Loc,
4598              Strval => String_From_Name_Buffer));
4599
4600          --  Set entity as internal to ensure proper Sprint output of its
4601          --  implicit importation.
4602
4603          Set_Is_Internal (Ent);
4604
4605          Rewrite (N,
4606            Make_Attribute_Reference (Loc,
4607              Prefix => New_Occurrence_Of (Ent, Loc),
4608              Attribute_Name => Name_Address));
4609
4610          Analyze_And_Resolve (N, Typ);
4611       end UET_Address;
4612
4613       ---------------
4614       -- VADS_Size --
4615       ---------------
4616
4617       --  The processing for VADS_Size is shared with Size
4618
4619       ---------
4620       -- Val --
4621       ---------
4622
4623       --  For enumeration types with a standard representation, and for all
4624       --  other types, Val is handled by the back end. For enumeration types
4625       --  with a non-standard representation we use the _Pos_To_Rep array that
4626       --  was created when the type was frozen.
4627
4628       when Attribute_Val => Val : declare
4629          Etyp : constant Entity_Id := Base_Type (Entity (Pref));
4630
4631       begin
4632          if Is_Enumeration_Type (Etyp)
4633            and then Present (Enum_Pos_To_Rep (Etyp))
4634          then
4635             if Has_Contiguous_Rep (Etyp) then
4636                declare
4637                   Rep_Node : constant Node_Id :=
4638                     Unchecked_Convert_To (Etyp,
4639                        Make_Op_Add (Loc,
4640                          Left_Opnd =>
4641                             Make_Integer_Literal (Loc,
4642                               Enumeration_Rep (First_Literal (Etyp))),
4643                          Right_Opnd =>
4644                           (Convert_To (Standard_Integer,
4645                              Relocate_Node (First (Exprs))))));
4646
4647                begin
4648                   Rewrite (N,
4649                      Unchecked_Convert_To (Etyp,
4650                          Make_Op_Add (Loc,
4651                            Left_Opnd =>
4652                              Make_Integer_Literal (Loc,
4653                                Enumeration_Rep (First_Literal (Etyp))),
4654                            Right_Opnd =>
4655                              Make_Function_Call (Loc,
4656                                Name =>
4657                                  New_Reference_To
4658                                    (TSS (Etyp, TSS_Rep_To_Pos), Loc),
4659                                Parameter_Associations => New_List (
4660                                  Rep_Node,
4661                                  Rep_To_Pos_Flag (Etyp, Loc))))));
4662                end;
4663
4664             else
4665                Rewrite (N,
4666                  Make_Indexed_Component (Loc,
4667                    Prefix => New_Reference_To (Enum_Pos_To_Rep (Etyp), Loc),
4668                    Expressions => New_List (
4669                      Convert_To (Standard_Integer,
4670                        Relocate_Node (First (Exprs))))));
4671             end if;
4672
4673             Analyze_And_Resolve (N, Typ);
4674
4675          --  If the argument is marked as requiring a range check then generate
4676          --  it here.
4677
4678          elsif Do_Range_Check (First (Exprs)) then
4679             Set_Do_Range_Check (First (Exprs), False);
4680             Generate_Range_Check (First (Exprs), Etyp, CE_Range_Check_Failed);
4681          end if;
4682       end Val;
4683
4684       -----------
4685       -- Valid --
4686       -----------
4687
4688       --  The code for valid is dependent on the particular types involved.
4689       --  See separate sections below for the generated code in each case.
4690
4691       when Attribute_Valid => Valid : declare
4692          Btyp : Entity_Id := Base_Type (Ptyp);
4693          Tst  : Node_Id;
4694
4695          Save_Validity_Checks_On : constant Boolean := Validity_Checks_On;
4696          --  Save the validity checking mode. We always turn off validity
4697          --  checking during process of 'Valid since this is one place
4698          --  where we do not want the implicit validity checks to intefere
4699          --  with the explicit validity check that the programmer is doing.
4700
4701          function Make_Range_Test return Node_Id;
4702          --  Build the code for a range test of the form
4703          --    Btyp!(Pref) >= Btyp!(Ptyp'First)
4704          --      and then
4705          --    Btyp!(Pref) <= Btyp!(Ptyp'Last)
4706
4707          ---------------------
4708          -- Make_Range_Test --
4709          ---------------------
4710
4711          function Make_Range_Test return Node_Id is
4712             Temp : constant Node_Id := Duplicate_Subexpr (Pref);
4713
4714          begin
4715             --  The value whose validity is being checked has been captured in
4716             --  an object declaration. We certainly don't want this object to
4717             --  appear valid because the declaration initializes it!
4718
4719             if Is_Entity_Name (Temp) then
4720                Set_Is_Known_Valid (Entity (Temp), False);
4721             end if;
4722
4723             return
4724               Make_And_Then (Loc,
4725                 Left_Opnd =>
4726                   Make_Op_Ge (Loc,
4727                     Left_Opnd =>
4728                       Unchecked_Convert_To (Btyp, Temp),
4729
4730                     Right_Opnd =>
4731                       Unchecked_Convert_To (Btyp,
4732                         Make_Attribute_Reference (Loc,
4733                           Prefix => New_Occurrence_Of (Ptyp, Loc),
4734                           Attribute_Name => Name_First))),
4735
4736                 Right_Opnd =>
4737                   Make_Op_Le (Loc,
4738                     Left_Opnd =>
4739                       Unchecked_Convert_To (Btyp, Temp),
4740
4741                     Right_Opnd =>
4742                       Unchecked_Convert_To (Btyp,
4743                         Make_Attribute_Reference (Loc,
4744                           Prefix => New_Occurrence_Of (Ptyp, Loc),
4745                           Attribute_Name => Name_Last))));
4746          end Make_Range_Test;
4747
4748       --  Start of processing for Attribute_Valid
4749
4750       begin
4751          --  Do not expand sourced code 'Valid reference in CodePeer mode,
4752          --  will be handled by the back-end directly.
4753
4754          if CodePeer_Mode and then Comes_From_Source (N) then
4755             return;
4756          end if;
4757
4758          --  Turn off validity checks. We do not want any implicit validity
4759          --  checks to intefere with the explicit check from the attribute
4760
4761          Validity_Checks_On := False;
4762
4763          --  Floating-point case. This case is handled by the Valid attribute
4764          --  code in the floating-point attribute run-time library.
4765
4766          if Is_Floating_Point_Type (Ptyp) then
4767             declare
4768                Pkg : RE_Id;
4769                Ftp : Entity_Id;
4770
4771             begin
4772                --  For vax fpt types, call appropriate routine in special vax
4773                --  floating point unit. We do not have to worry about loads in
4774                --  this case, since these types have no signalling NaN's.
4775
4776                if Vax_Float (Btyp) then
4777                   Expand_Vax_Valid (N);
4778
4779                --  The AAMP back end handles Valid for floating-point types
4780
4781                elsif Is_AAMP_Float (Btyp) then
4782                   Analyze_And_Resolve (Pref, Ptyp);
4783                   Set_Etype (N, Standard_Boolean);
4784                   Set_Analyzed (N);
4785
4786                --  Non VAX float case
4787
4788                else
4789                   Find_Fat_Info (Ptyp, Ftp, Pkg);
4790
4791                   --  If the floating-point object might be unaligned, we need
4792                   --  to call the special routine Unaligned_Valid, which makes
4793                   --  the needed copy, being careful not to load the value into
4794                   --  any floating-point register. The argument in this case is
4795                   --  obj'Address (see Unaligned_Valid routine in Fat_Gen).
4796
4797                   if Is_Possibly_Unaligned_Object (Pref) then
4798                      Expand_Fpt_Attribute
4799                        (N, Pkg, Name_Unaligned_Valid,
4800                         New_List (
4801                           Make_Attribute_Reference (Loc,
4802                             Prefix => Relocate_Node (Pref),
4803                             Attribute_Name => Name_Address)));
4804
4805                   --  In the normal case where we are sure the object is
4806                   --  aligned, we generate a call to Valid, and the argument in
4807                   --  this case is obj'Unrestricted_Access (after converting
4808                   --  obj to the right floating-point type).
4809
4810                   else
4811                      Expand_Fpt_Attribute
4812                        (N, Pkg, Name_Valid,
4813                         New_List (
4814                           Make_Attribute_Reference (Loc,
4815                             Prefix => Unchecked_Convert_To (Ftp, Pref),
4816                             Attribute_Name => Name_Unrestricted_Access)));
4817                   end if;
4818                end if;
4819
4820                --  One more task, we still need a range check. Required
4821                --  only if we have a constraint, since the Valid routine
4822                --  catches infinities properly (infinities are never valid).
4823
4824                --  The way we do the range check is simply to create the
4825                --  expression: Valid (N) and then Base_Type(Pref) in Typ.
4826
4827                if not Subtypes_Statically_Match (Ptyp, Btyp) then
4828                   Rewrite (N,
4829                     Make_And_Then (Loc,
4830                       Left_Opnd  => Relocate_Node (N),
4831                       Right_Opnd =>
4832                         Make_In (Loc,
4833                           Left_Opnd => Convert_To (Btyp, Pref),
4834                           Right_Opnd => New_Occurrence_Of (Ptyp, Loc))));
4835                end if;
4836             end;
4837
4838          --  Enumeration type with holes
4839
4840          --  For enumeration types with holes, the Pos value constructed by
4841          --  the Enum_Rep_To_Pos function built in Exp_Ch3 called with a
4842          --  second argument of False returns minus one for an invalid value,
4843          --  and the non-negative pos value for a valid value, so the
4844          --  expansion of X'Valid is simply:
4845
4846          --     type(X)'Pos (X) >= 0
4847
4848          --  We can't quite generate it that way because of the requirement
4849          --  for the non-standard second argument of False in the resulting
4850          --  rep_to_pos call, so we have to explicitly create:
4851
4852          --     _rep_to_pos (X, False) >= 0
4853
4854          --  If we have an enumeration subtype, we also check that the
4855          --  value is in range:
4856
4857          --    _rep_to_pos (X, False) >= 0
4858          --      and then
4859          --       (X >= type(X)'First and then type(X)'Last <= X)
4860
4861          elsif Is_Enumeration_Type (Ptyp)
4862            and then Present (Enum_Pos_To_Rep (Base_Type (Ptyp)))
4863          then
4864             Tst :=
4865               Make_Op_Ge (Loc,
4866                 Left_Opnd =>
4867                   Make_Function_Call (Loc,
4868                     Name =>
4869                       New_Reference_To
4870                         (TSS (Base_Type (Ptyp), TSS_Rep_To_Pos), Loc),
4871                     Parameter_Associations => New_List (
4872                       Pref,
4873                       New_Occurrence_Of (Standard_False, Loc))),
4874                 Right_Opnd => Make_Integer_Literal (Loc, 0));
4875
4876             if Ptyp /= Btyp
4877               and then
4878                 (Type_Low_Bound (Ptyp) /= Type_Low_Bound (Btyp)
4879                   or else
4880                  Type_High_Bound (Ptyp) /= Type_High_Bound (Btyp))
4881             then
4882                --  The call to Make_Range_Test will create declarations
4883                --  that need a proper insertion point, but Pref is now
4884                --  attached to a node with no ancestor. Attach to tree
4885                --  even if it is to be rewritten below.
4886
4887                Set_Parent (Tst, Parent (N));
4888
4889                Tst :=
4890                  Make_And_Then (Loc,
4891                    Left_Opnd  => Make_Range_Test,
4892                    Right_Opnd => Tst);
4893             end if;
4894
4895             Rewrite (N, Tst);
4896
4897          --  Fortran convention booleans
4898
4899          --  For the very special case of Fortran convention booleans, the
4900          --  value is always valid, since it is an integer with the semantics
4901          --  that non-zero is true, and any value is permissible.
4902
4903          elsif Is_Boolean_Type (Ptyp)
4904            and then Convention (Ptyp) = Convention_Fortran
4905          then
4906             Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
4907
4908          --  For biased representations, we will be doing an unchecked
4909          --  conversion without unbiasing the result. That means that the range
4910          --  test has to take this into account, and the proper form of the
4911          --  test is:
4912
4913          --    Btyp!(Pref) < Btyp!(Ptyp'Range_Length)
4914
4915          elsif Has_Biased_Representation (Ptyp) then
4916             Btyp := RTE (RE_Unsigned_32);
4917             Rewrite (N,
4918               Make_Op_Lt (Loc,
4919                 Left_Opnd =>
4920                   Unchecked_Convert_To (Btyp, Duplicate_Subexpr (Pref)),
4921                 Right_Opnd =>
4922                   Unchecked_Convert_To (Btyp,
4923                     Make_Attribute_Reference (Loc,
4924                       Prefix => New_Occurrence_Of (Ptyp, Loc),
4925                       Attribute_Name => Name_Range_Length))));
4926
4927          --  For all other scalar types, what we want logically is a
4928          --  range test:
4929
4930          --     X in type(X)'First .. type(X)'Last
4931
4932          --  But that's precisely what won't work because of possible
4933          --  unwanted optimization (and indeed the basic motivation for
4934          --  the Valid attribute is exactly that this test does not work!)
4935          --  What will work is:
4936
4937          --     Btyp!(X) >= Btyp!(type(X)'First)
4938          --       and then
4939          --     Btyp!(X) <= Btyp!(type(X)'Last)
4940
4941          --  where Btyp is an integer type large enough to cover the full
4942          --  range of possible stored values (i.e. it is chosen on the basis
4943          --  of the size of the type, not the range of the values). We write
4944          --  this as two tests, rather than a range check, so that static
4945          --  evaluation will easily remove either or both of the checks if
4946          --  they can be -statically determined to be true (this happens
4947          --  when the type of X is static and the range extends to the full
4948          --  range of stored values).
4949
4950          --  Unsigned types. Note: it is safe to consider only whether the
4951          --  subtype is unsigned, since we will in that case be doing all
4952          --  unsigned comparisons based on the subtype range. Since we use the
4953          --  actual subtype object size, this is appropriate.
4954
4955          --  For example, if we have
4956
4957          --    subtype x is integer range 1 .. 200;
4958          --    for x'Object_Size use 8;
4959
4960          --  Now the base type is signed, but objects of this type are bits
4961          --  unsigned, and doing an unsigned test of the range 1 to 200 is
4962          --  correct, even though a value greater than 127 looks signed to a
4963          --  signed comparison.
4964
4965          elsif Is_Unsigned_Type (Ptyp) then
4966             if Esize (Ptyp) <= 32 then
4967                Btyp := RTE (RE_Unsigned_32);
4968             else
4969                Btyp := RTE (RE_Unsigned_64);
4970             end if;
4971
4972             Rewrite (N, Make_Range_Test);
4973
4974          --  Signed types
4975
4976          else
4977             if Esize (Ptyp) <= Esize (Standard_Integer) then
4978                Btyp := Standard_Integer;
4979             else
4980                Btyp := Universal_Integer;
4981             end if;
4982
4983             Rewrite (N, Make_Range_Test);
4984          end if;
4985
4986          Analyze_And_Resolve (N, Standard_Boolean);
4987          Validity_Checks_On := Save_Validity_Checks_On;
4988       end Valid;
4989
4990       -----------
4991       -- Value --
4992       -----------
4993
4994       --  Value attribute is handled in separate unti Exp_Imgv
4995
4996       when Attribute_Value =>
4997          Exp_Imgv.Expand_Value_Attribute (N);
4998
4999       -----------------
5000       -- Value_Size --
5001       -----------------
5002
5003       --  The processing for Value_Size shares the processing for Size
5004
5005       -------------
5006       -- Version --
5007       -------------
5008
5009       --  The processing for Version shares the processing for Body_Version
5010
5011       ----------------
5012       -- Wide_Image --
5013       ----------------
5014
5015       --  Wide_Image attribute is handled in separate unit Exp_Imgv
5016
5017       when Attribute_Wide_Image =>
5018          Exp_Imgv.Expand_Wide_Image_Attribute (N);
5019
5020       ---------------------
5021       -- Wide_Wide_Image --
5022       ---------------------
5023
5024       --  Wide_Wide_Image attribute is handled in separate unit Exp_Imgv
5025
5026       when Attribute_Wide_Wide_Image =>
5027          Exp_Imgv.Expand_Wide_Wide_Image_Attribute (N);
5028
5029       ----------------
5030       -- Wide_Value --
5031       ----------------
5032
5033       --  We expand typ'Wide_Value (X) into
5034
5035       --    typ'Value
5036       --      (Wide_String_To_String (X, Wide_Character_Encoding_Method))
5037
5038       --  Wide_String_To_String is a runtime function that converts its wide
5039       --  string argument to String, converting any non-translatable characters
5040       --  into appropriate escape sequences. This preserves the required
5041       --  semantics of Wide_Value in all cases, and results in a very simple
5042       --  implementation approach.
5043
5044       --  Note: for this approach to be fully standard compliant for the cases
5045       --  where typ is Wide_Character and Wide_Wide_Character, the encoding
5046       --  method must cover the entire character range (e.g. UTF-8). But that
5047       --  is a reasonable requirement when dealing with encoded character
5048       --  sequences. Presumably if one of the restrictive encoding mechanisms
5049       --  is in use such as Shift-JIS, then characters that cannot be
5050       --  represented using this encoding will not appear in any case.
5051
5052       when Attribute_Wide_Value => Wide_Value :
5053       begin
5054          Rewrite (N,
5055            Make_Attribute_Reference (Loc,
5056              Prefix         => Pref,
5057              Attribute_Name => Name_Value,
5058
5059              Expressions    => New_List (
5060                Make_Function_Call (Loc,
5061                  Name =>
5062                    New_Reference_To (RTE (RE_Wide_String_To_String), Loc),
5063
5064                  Parameter_Associations => New_List (
5065                    Relocate_Node (First (Exprs)),
5066                    Make_Integer_Literal (Loc,
5067                      Intval => Int (Wide_Character_Encoding_Method)))))));
5068
5069          Analyze_And_Resolve (N, Typ);
5070       end Wide_Value;
5071
5072       ---------------------
5073       -- Wide_Wide_Value --
5074       ---------------------
5075
5076       --  We expand typ'Wide_Value_Value (X) into
5077
5078       --    typ'Value
5079       --      (Wide_Wide_String_To_String (X, Wide_Character_Encoding_Method))
5080
5081       --  Wide_Wide_String_To_String is a runtime function that converts its
5082       --  wide string argument to String, converting any non-translatable
5083       --  characters into appropriate escape sequences. This preserves the
5084       --  required semantics of Wide_Wide_Value in all cases, and results in a
5085       --  very simple implementation approach.
5086
5087       --  It's not quite right where typ = Wide_Wide_Character, because the
5088       --  encoding method may not cover the whole character type ???
5089
5090       when Attribute_Wide_Wide_Value => Wide_Wide_Value :
5091       begin
5092          Rewrite (N,
5093            Make_Attribute_Reference (Loc,
5094              Prefix         => Pref,
5095              Attribute_Name => Name_Value,
5096
5097              Expressions    => New_List (
5098                Make_Function_Call (Loc,
5099                  Name =>
5100                    New_Reference_To (RTE (RE_Wide_Wide_String_To_String), Loc),
5101
5102                  Parameter_Associations => New_List (
5103                    Relocate_Node (First (Exprs)),
5104                    Make_Integer_Literal (Loc,
5105                      Intval => Int (Wide_Character_Encoding_Method)))))));
5106
5107          Analyze_And_Resolve (N, Typ);
5108       end Wide_Wide_Value;
5109
5110       ---------------------
5111       -- Wide_Wide_Width --
5112       ---------------------
5113
5114       --  Wide_Wide_Width attribute is handled in separate unit Exp_Imgv
5115
5116       when Attribute_Wide_Wide_Width =>
5117          Exp_Imgv.Expand_Width_Attribute (N, Wide_Wide);
5118
5119       ----------------
5120       -- Wide_Width --
5121       ----------------
5122
5123       --  Wide_Width attribute is handled in separate unit Exp_Imgv
5124
5125       when Attribute_Wide_Width =>
5126          Exp_Imgv.Expand_Width_Attribute (N, Wide);
5127
5128       -----------
5129       -- Width --
5130       -----------
5131
5132       --  Width attribute is handled in separate unit Exp_Imgv
5133
5134       when Attribute_Width =>
5135          Exp_Imgv.Expand_Width_Attribute (N, Normal);
5136
5137       -----------
5138       -- Write --
5139       -----------
5140
5141       when Attribute_Write => Write : declare
5142          P_Type : constant Entity_Id := Entity (Pref);
5143          U_Type : constant Entity_Id := Underlying_Type (P_Type);
5144          Pname  : Entity_Id;
5145          Decl   : Node_Id;
5146          Prag   : Node_Id;
5147          Arg3   : Node_Id;
5148          Wfunc  : Node_Id;
5149
5150       begin
5151          --  If no underlying type, we have an error that will be diagnosed
5152          --  elsewhere, so here we just completely ignore the expansion.
5153
5154          if No (U_Type) then
5155             return;
5156          end if;
5157
5158          --  The simple case, if there is a TSS for Write, just call it
5159
5160          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Write);
5161
5162          if Present (Pname) then
5163             null;
5164
5165          else
5166             --  If there is a Stream_Convert pragma, use it, we rewrite
5167
5168             --     sourcetyp'Output (stream, Item)
5169
5170             --  as
5171
5172             --     strmtyp'Output (Stream, strmwrite (acttyp (Item)));
5173
5174             --  where strmwrite is the given Write function that converts an
5175             --  argument of type sourcetyp or a type acctyp, from which it is
5176             --  derived to type strmtyp. The conversion to acttyp is required
5177             --  for the derived case.
5178
5179             Prag := Get_Stream_Convert_Pragma (P_Type);
5180
5181             if Present (Prag) then
5182                Arg3 :=
5183                  Next (Next (First (Pragma_Argument_Associations (Prag))));
5184                Wfunc := Entity (Expression (Arg3));
5185
5186                Rewrite (N,
5187                  Make_Attribute_Reference (Loc,
5188                    Prefix => New_Occurrence_Of (Etype (Wfunc), Loc),
5189                    Attribute_Name => Name_Output,
5190                    Expressions => New_List (
5191                      Relocate_Node (First (Exprs)),
5192                      Make_Function_Call (Loc,
5193                        Name => New_Occurrence_Of (Wfunc, Loc),
5194                        Parameter_Associations => New_List (
5195                          OK_Convert_To (Etype (First_Formal (Wfunc)),
5196                            Relocate_Node (Next (First (Exprs)))))))));
5197
5198                Analyze (N);
5199                return;
5200
5201             --  For elementary types, we call the W_xxx routine directly
5202
5203             elsif Is_Elementary_Type (U_Type) then
5204                Rewrite (N, Build_Elementary_Write_Call (N));
5205                Analyze (N);
5206                return;
5207
5208             --  Array type case
5209
5210             elsif Is_Array_Type (U_Type) then
5211                Build_Array_Write_Procedure (N, U_Type, Decl, Pname);
5212                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
5213
5214             --  Tagged type case, use the primitive Write function. Note that
5215             --  this will dispatch in the class-wide case which is what we want
5216
5217             elsif Is_Tagged_Type (U_Type) then
5218                Pname := Find_Prim_Op (U_Type, TSS_Stream_Write);
5219
5220             --  All other record type cases, including protected records.
5221             --  The latter only arise for expander generated code for
5222             --  handling shared passive partition access.
5223
5224             else
5225                pragma Assert
5226                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
5227
5228                --  Ada 2005 (AI-216): Program_Error is raised when executing
5229                --  the default implementation of the Write attribute of an
5230                --  Unchecked_Union type. However, if the 'Write reference is
5231                --  within the generated Output stream procedure, Write outputs
5232                --  the components, and the default values of the discriminant
5233                --  are streamed by the Output procedure itself.
5234
5235                if Is_Unchecked_Union (Base_Type (U_Type))
5236                  and not Is_TSS (Current_Scope, TSS_Stream_Output)
5237                then
5238                   Insert_Action (N,
5239                     Make_Raise_Program_Error (Loc,
5240                       Reason => PE_Unchecked_Union_Restriction));
5241                end if;
5242
5243                if Has_Discriminants (U_Type)
5244                  and then Present
5245                    (Discriminant_Default_Value (First_Discriminant (U_Type)))
5246                then
5247                   Build_Mutable_Record_Write_Procedure
5248                     (Loc, Base_Type (U_Type), Decl, Pname);
5249                else
5250                   Build_Record_Write_Procedure
5251                     (Loc, Base_Type (U_Type), Decl, Pname);
5252                end if;
5253
5254                Insert_Action (N, Decl);
5255             end if;
5256          end if;
5257
5258          --  If we fall through, Pname is the procedure to be called
5259
5260          Rewrite_Stream_Proc_Call (Pname);
5261       end Write;
5262
5263       --  Component_Size is handled by the back end, unless the component size
5264       --  is known at compile time, which is always true in the packed array
5265       --  case. It is important that the packed array case is handled in the
5266       --  front end (see Eval_Attribute) since the back end would otherwise get
5267       --  confused by the equivalent packed array type.
5268
5269       when Attribute_Component_Size =>
5270          null;
5271
5272       --  The following attributes are handled by the back end (except that
5273       --  static cases have already been evaluated during semantic processing,
5274       --  but in any case the back end should not count on this). The one bit
5275       --  of special processing required is that these attributes typically
5276       --  generate conditionals in the code, so we need to check the relevant
5277       --  restriction.
5278
5279       when Attribute_Max                          |
5280            Attribute_Min                          =>
5281          Check_Restriction (No_Implicit_Conditionals, N);
5282
5283       --  The following attributes are handled by the back end (except that
5284       --  static cases have already been evaluated during semantic processing,
5285       --  but in any case the back end should not count on this).
5286
5287       --  The back end also handles the non-class-wide cases of Size
5288
5289       when Attribute_Bit_Order                    |
5290            Attribute_Code_Address                 |
5291            Attribute_Definite                     |
5292            Attribute_Null_Parameter               |
5293            Attribute_Passed_By_Reference          |
5294            Attribute_Pool_Address                 =>
5295          null;
5296
5297       --  The following attributes are also handled by the back end, but return
5298       --  a universal integer result, so may need a conversion for checking
5299       --  that the result is in range.
5300
5301       when Attribute_Aft                          |
5302            Attribute_Max_Size_In_Storage_Elements
5303       =>
5304          Apply_Universal_Integer_Attribute_Checks (N);
5305
5306       --  The following attributes should not appear at this stage, since they
5307       --  have already been handled by the analyzer (and properly rewritten
5308       --  with corresponding values or entities to represent the right values)
5309
5310       when Attribute_Abort_Signal                 |
5311            Attribute_Address_Size                 |
5312            Attribute_Base                         |
5313            Attribute_Class                        |
5314            Attribute_Compiler_Version             |
5315            Attribute_Default_Bit_Order            |
5316            Attribute_Delta                        |
5317            Attribute_Denorm                       |
5318            Attribute_Digits                       |
5319            Attribute_Emax                         |
5320            Attribute_Enabled                      |
5321            Attribute_Epsilon                      |
5322            Attribute_Fast_Math                    |
5323            Attribute_Has_Access_Values            |
5324            Attribute_Has_Discriminants            |
5325            Attribute_Has_Tagged_Values            |
5326            Attribute_Large                        |
5327            Attribute_Machine_Emax                 |
5328            Attribute_Machine_Emin                 |
5329            Attribute_Machine_Mantissa             |
5330            Attribute_Machine_Overflows            |
5331            Attribute_Machine_Radix                |
5332            Attribute_Machine_Rounds               |
5333            Attribute_Maximum_Alignment            |
5334            Attribute_Model_Emin                   |
5335            Attribute_Model_Epsilon                |
5336            Attribute_Model_Mantissa               |
5337            Attribute_Model_Small                  |
5338            Attribute_Modulus                      |
5339            Attribute_Partition_ID                 |
5340            Attribute_Range                        |
5341            Attribute_Safe_Emax                    |
5342            Attribute_Safe_First                   |
5343            Attribute_Safe_Large                   |
5344            Attribute_Safe_Last                    |
5345            Attribute_Safe_Small                   |
5346            Attribute_Scale                        |
5347            Attribute_Signed_Zeros                 |
5348            Attribute_Small                        |
5349            Attribute_Storage_Unit                 |
5350            Attribute_Stub_Type                    |
5351            Attribute_Target_Name                  |
5352            Attribute_Type_Class                   |
5353            Attribute_Unconstrained_Array          |
5354            Attribute_Universal_Literal_String     |
5355            Attribute_Wchar_T_Size                 |
5356            Attribute_Word_Size                    =>
5357
5358          raise Program_Error;
5359
5360       --  The Asm_Input and Asm_Output attributes are not expanded at this
5361       --  stage, but will be eliminated in the expansion of the Asm call, see
5362       --  Exp_Intr for details. So the back end will never see these either.
5363
5364       when Attribute_Asm_Input                    |
5365            Attribute_Asm_Output                   =>
5366
5367          null;
5368
5369       end case;
5370
5371    exception
5372       when RE_Not_Available =>
5373          return;
5374    end Expand_N_Attribute_Reference;
5375
5376    ----------------------
5377    -- Expand_Pred_Succ --
5378    ----------------------
5379
5380    --  For typ'Pred (exp), we generate the check
5381
5382    --    [constraint_error when exp = typ'Base'First]
5383
5384    --  Similarly, for typ'Succ (exp), we generate the check
5385
5386    --    [constraint_error when exp = typ'Base'Last]
5387
5388    --  These checks are not generated for modular types, since the proper
5389    --  semantics for Succ and Pred on modular types is to wrap, not raise CE.
5390
5391    procedure Expand_Pred_Succ (N : Node_Id) is
5392       Loc  : constant Source_Ptr := Sloc (N);
5393       Cnam : Name_Id;
5394
5395    begin
5396       if Attribute_Name (N) = Name_Pred then
5397          Cnam := Name_First;
5398       else
5399          Cnam := Name_Last;
5400       end if;
5401
5402       Insert_Action (N,
5403         Make_Raise_Constraint_Error (Loc,
5404           Condition =>
5405             Make_Op_Eq (Loc,
5406               Left_Opnd =>
5407                 Duplicate_Subexpr_Move_Checks (First (Expressions (N))),
5408               Right_Opnd =>
5409                 Make_Attribute_Reference (Loc,
5410                   Prefix =>
5411                     New_Reference_To (Base_Type (Etype (Prefix (N))), Loc),
5412                   Attribute_Name => Cnam)),
5413           Reason => CE_Overflow_Check_Failed));
5414    end Expand_Pred_Succ;
5415
5416    -------------------
5417    -- Find_Fat_Info --
5418    -------------------
5419
5420    procedure Find_Fat_Info
5421      (T        : Entity_Id;
5422       Fat_Type : out Entity_Id;
5423       Fat_Pkg  : out RE_Id)
5424    is
5425       Btyp : constant Entity_Id := Base_Type (T);
5426       Rtyp : constant Entity_Id := Root_Type (T);
5427       Digs : constant Nat       := UI_To_Int (Digits_Value (Btyp));
5428
5429    begin
5430       --  If the base type is VAX float, then get appropriate VAX float type
5431
5432       if Vax_Float (Btyp) then
5433          case Digs is
5434             when 6 =>
5435                Fat_Type := RTE (RE_Fat_VAX_F);
5436                Fat_Pkg  := RE_Attr_VAX_F_Float;
5437
5438             when 9 =>
5439                Fat_Type := RTE (RE_Fat_VAX_D);
5440                Fat_Pkg  := RE_Attr_VAX_D_Float;
5441
5442             when 15 =>
5443                Fat_Type := RTE (RE_Fat_VAX_G);
5444                Fat_Pkg  := RE_Attr_VAX_G_Float;
5445
5446             when others =>
5447                raise Program_Error;
5448          end case;
5449
5450       --  If root type is VAX float, this is the case where the library has
5451       --  been recompiled in VAX float mode, and we have an IEEE float type.
5452       --  This is when we use the special IEEE Fat packages.
5453
5454       elsif Vax_Float (Rtyp) then
5455          case Digs is
5456             when 6 =>
5457                Fat_Type := RTE (RE_Fat_IEEE_Short);
5458                Fat_Pkg  := RE_Attr_IEEE_Short;
5459
5460             when 15 =>
5461                Fat_Type := RTE (RE_Fat_IEEE_Long);
5462                Fat_Pkg  := RE_Attr_IEEE_Long;
5463
5464             when others =>
5465                raise Program_Error;
5466          end case;
5467
5468       --  If neither the base type nor the root type is VAX_Float then VAX
5469       --  float is out of the picture, and we can just use the root type.
5470
5471       else
5472          Fat_Type := Rtyp;
5473
5474          if Fat_Type = Standard_Short_Float then
5475             Fat_Pkg := RE_Attr_Short_Float;
5476
5477          elsif Fat_Type = Standard_Float then
5478             Fat_Pkg := RE_Attr_Float;
5479
5480          elsif Fat_Type = Standard_Long_Float then
5481             Fat_Pkg := RE_Attr_Long_Float;
5482
5483          elsif Fat_Type = Standard_Long_Long_Float then
5484             Fat_Pkg := RE_Attr_Long_Long_Float;
5485
5486          --  Universal real (which is its own root type) is treated as being
5487          --  equivalent to Standard.Long_Long_Float, since it is defined to
5488          --  have the same precision as the longest Float type.
5489
5490          elsif Fat_Type = Universal_Real then
5491             Fat_Type := Standard_Long_Long_Float;
5492             Fat_Pkg := RE_Attr_Long_Long_Float;
5493
5494          else
5495             raise Program_Error;
5496          end if;
5497       end if;
5498    end Find_Fat_Info;
5499
5500    ----------------------------
5501    -- Find_Stream_Subprogram --
5502    ----------------------------
5503
5504    function Find_Stream_Subprogram
5505      (Typ : Entity_Id;
5506       Nam : TSS_Name_Type) return Entity_Id
5507    is
5508       Base_Typ : constant Entity_Id := Base_Type (Typ);
5509       Ent      : constant Entity_Id := TSS (Typ, Nam);
5510
5511    begin
5512       if Present (Ent) then
5513          return Ent;
5514       end if;
5515
5516       --  Stream attributes for strings are expanded into library calls. The
5517       --  following checks are disabled when the run-time is not available or
5518       --  when compiling predefined types due to bootstrap issues. As a result,
5519       --  the compiler will generate in-place stream routines for string types
5520       --  that appear in GNAT's library, but will generate calls via rtsfind
5521       --  to library routines for user code.
5522       --  ??? For now, disable this code for JVM, since this generates a
5523       --  VerifyError exception at run-time on e.g. c330001.
5524       --  This is disabled for AAMP, to avoid making dependences on files not
5525       --  supported in the AAMP library (such as s-fileio.adb).
5526
5527       if VM_Target /= JVM_Target
5528         and then not AAMP_On_Target
5529         and then
5530           not Is_Predefined_File_Name (Unit_File_Name (Current_Sem_Unit))
5531       then
5532          --  String as defined in package Ada
5533
5534          if Base_Typ = Standard_String then
5535             if Restriction_Active (No_Stream_Optimizations) then
5536                if Nam = TSS_Stream_Input then
5537                   return RTE (RE_String_Input);
5538
5539                elsif Nam = TSS_Stream_Output then
5540                   return RTE (RE_String_Output);
5541
5542                elsif Nam = TSS_Stream_Read then
5543                   return RTE (RE_String_Read);
5544
5545                else pragma Assert (Nam = TSS_Stream_Write);
5546                   return RTE (RE_String_Write);
5547                end if;
5548
5549             else
5550                if Nam = TSS_Stream_Input then
5551                   return RTE (RE_String_Input_Blk_IO);
5552
5553                elsif Nam = TSS_Stream_Output then
5554                   return RTE (RE_String_Output_Blk_IO);
5555
5556                elsif Nam = TSS_Stream_Read then
5557                   return RTE (RE_String_Read_Blk_IO);
5558
5559                else pragma Assert (Nam = TSS_Stream_Write);
5560                   return RTE (RE_String_Write_Blk_IO);
5561                end if;
5562             end if;
5563
5564          --  Wide_String as defined in package Ada
5565
5566          elsif Base_Typ = Standard_Wide_String then
5567             if Restriction_Active (No_Stream_Optimizations) then
5568                if Nam = TSS_Stream_Input then
5569                   return RTE (RE_Wide_String_Input);
5570
5571                elsif Nam = TSS_Stream_Output then
5572                   return RTE (RE_Wide_String_Output);
5573
5574                elsif Nam = TSS_Stream_Read then
5575                   return RTE (RE_Wide_String_Read);
5576
5577                else pragma Assert (Nam = TSS_Stream_Write);
5578                   return RTE (RE_Wide_String_Write);
5579                end if;
5580
5581             else
5582                if Nam = TSS_Stream_Input then
5583                   return RTE (RE_Wide_String_Input_Blk_IO);
5584
5585                elsif Nam = TSS_Stream_Output then
5586                   return RTE (RE_Wide_String_Output_Blk_IO);
5587
5588                elsif Nam = TSS_Stream_Read then
5589                   return RTE (RE_Wide_String_Read_Blk_IO);
5590
5591                else pragma Assert (Nam = TSS_Stream_Write);
5592                   return RTE (RE_Wide_String_Write_Blk_IO);
5593                end if;
5594             end if;
5595
5596          --  Wide_Wide_String as defined in package Ada
5597
5598          elsif Base_Typ = Standard_Wide_Wide_String then
5599             if Restriction_Active (No_Stream_Optimizations) then
5600                if Nam = TSS_Stream_Input then
5601                   return RTE (RE_Wide_Wide_String_Input);
5602
5603                elsif Nam = TSS_Stream_Output then
5604                   return RTE (RE_Wide_Wide_String_Output);
5605
5606                elsif Nam = TSS_Stream_Read then
5607                   return RTE (RE_Wide_Wide_String_Read);
5608
5609                else pragma Assert (Nam = TSS_Stream_Write);
5610                   return RTE (RE_Wide_Wide_String_Write);
5611                end if;
5612
5613             else
5614                if Nam = TSS_Stream_Input then
5615                   return RTE (RE_Wide_Wide_String_Input_Blk_IO);
5616
5617                elsif Nam = TSS_Stream_Output then
5618                   return RTE (RE_Wide_Wide_String_Output_Blk_IO);
5619
5620                elsif Nam = TSS_Stream_Read then
5621                   return RTE (RE_Wide_Wide_String_Read_Blk_IO);
5622
5623                else pragma Assert (Nam = TSS_Stream_Write);
5624                   return RTE (RE_Wide_Wide_String_Write_Blk_IO);
5625                end if;
5626             end if;
5627          end if;
5628       end if;
5629
5630       if Is_Tagged_Type (Typ)
5631         and then Is_Derived_Type (Typ)
5632       then
5633          return Find_Prim_Op (Typ, Nam);
5634       else
5635          return Find_Inherited_TSS (Typ, Nam);
5636       end if;
5637    end Find_Stream_Subprogram;
5638
5639    -----------------------
5640    -- Get_Index_Subtype --
5641    -----------------------
5642
5643    function Get_Index_Subtype (N : Node_Id) return Node_Id is
5644       P_Type : Entity_Id := Etype (Prefix (N));
5645       Indx   : Node_Id;
5646       J      : Int;
5647
5648    begin
5649       if Is_Access_Type (P_Type) then
5650          P_Type := Designated_Type (P_Type);
5651       end if;
5652
5653       if No (Expressions (N)) then
5654          J := 1;
5655       else
5656          J := UI_To_Int (Expr_Value (First (Expressions (N))));
5657       end if;
5658
5659       Indx := First_Index (P_Type);
5660       while J > 1 loop
5661          Next_Index (Indx);
5662          J := J - 1;
5663       end loop;
5664
5665       return Etype (Indx);
5666    end Get_Index_Subtype;
5667
5668    -------------------------------
5669    -- Get_Stream_Convert_Pragma --
5670    -------------------------------
5671
5672    function Get_Stream_Convert_Pragma (T : Entity_Id) return Node_Id is
5673       Typ : Entity_Id;
5674       N   : Node_Id;
5675
5676    begin
5677       --  Note: we cannot use Get_Rep_Pragma here because of the peculiarity
5678       --  that a stream convert pragma for a tagged type is not inherited from
5679       --  its parent. Probably what is wrong here is that it is basically
5680       --  incorrect to consider a stream convert pragma to be a representation
5681       --  pragma at all ???
5682
5683       N := First_Rep_Item (Implementation_Base_Type (T));
5684       while Present (N) loop
5685          if Nkind (N) = N_Pragma
5686            and then Pragma_Name (N) = Name_Stream_Convert
5687          then
5688             --  For tagged types this pragma is not inherited, so we
5689             --  must verify that it is defined for the given type and
5690             --  not an ancestor.
5691
5692             Typ :=
5693               Entity (Expression (First (Pragma_Argument_Associations (N))));
5694
5695             if not Is_Tagged_Type (T)
5696               or else T = Typ
5697               or else (Is_Private_Type (Typ) and then T = Full_View (Typ))
5698             then
5699                return N;
5700             end if;
5701          end if;
5702
5703          Next_Rep_Item (N);
5704       end loop;
5705
5706       return Empty;
5707    end Get_Stream_Convert_Pragma;
5708
5709    ---------------------------------
5710    -- Is_Constrained_Packed_Array --
5711    ---------------------------------
5712
5713    function Is_Constrained_Packed_Array (Typ : Entity_Id) return Boolean is
5714       Arr : Entity_Id := Typ;
5715
5716    begin
5717       if Is_Access_Type (Arr) then
5718          Arr := Designated_Type (Arr);
5719       end if;
5720
5721       return Is_Array_Type (Arr)
5722         and then Is_Constrained (Arr)
5723         and then Present (Packed_Array_Type (Arr));
5724    end Is_Constrained_Packed_Array;
5725
5726    ----------------------------------------
5727    -- Is_Inline_Floating_Point_Attribute --
5728    ----------------------------------------
5729
5730    function Is_Inline_Floating_Point_Attribute (N : Node_Id) return Boolean is
5731       Id : constant Attribute_Id := Get_Attribute_Id (Attribute_Name (N));
5732
5733    begin
5734       if Nkind (Parent (N)) /= N_Type_Conversion
5735         or else not Is_Integer_Type (Etype (Parent (N)))
5736       then
5737          return False;
5738       end if;
5739
5740       --  Should also support 'Machine_Rounding and 'Unbiased_Rounding, but
5741       --  required back end support has not been implemented yet ???
5742
5743       return Id = Attribute_Truncation;
5744    end Is_Inline_Floating_Point_Attribute;
5745
5746 end Exp_Attr;