OSDN Git Service

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