snames.ads-tmpl (Renamed): New name for the pragma argument.
[platform/upstream/gcc.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-2016, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Aspects;  use Aspects;
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 Fname;    use Fname;
43 with Freeze;   use Freeze;
44 with Gnatvsn;  use Gnatvsn;
45 with Itypes;   use Itypes;
46 with Lib;      use Lib;
47 with Namet;    use Namet;
48 with Nmake;    use Nmake;
49 with Nlists;   use Nlists;
50 with Opt;      use Opt;
51 with Restrict; use Restrict;
52 with Rident;   use Rident;
53 with Rtsfind;  use Rtsfind;
54 with Sem;      use Sem;
55 with Sem_Aux;  use Sem_Aux;
56 with Sem_Ch6;  use Sem_Ch6;
57 with Sem_Ch7;  use Sem_Ch7;
58 with Sem_Ch8;  use Sem_Ch8;
59 with Sem_Eval; use Sem_Eval;
60 with Sem_Res;  use Sem_Res;
61 with Sem_Util; use Sem_Util;
62 with Sinfo;    use Sinfo;
63 with Snames;   use Snames;
64 with Stand;    use Stand;
65 with Stringt;  use Stringt;
66 with Targparm; use Targparm;
67 with Tbuild;   use Tbuild;
68 with Ttypes;   use Ttypes;
69 with Uintp;    use Uintp;
70 with Uname;    use Uname;
71 with Validsw;  use Validsw;
72
73 package body Exp_Attr is
74
75    -----------------------
76    -- Local Subprograms --
77    -----------------------
78
79    function Build_Array_VS_Func
80      (A_Type : Entity_Id;
81       Nod    : Node_Id) return Entity_Id;
82    --  Build function to test Valid_Scalars for array type A_Type. Nod is the
83    --  Valid_Scalars attribute node, used to insert the function body, and the
84    --  value returned is the entity of the constructed function body. We do not
85    --  bother to generate a separate spec for this subprogram.
86
87    function Build_Record_VS_Func
88      (R_Type : Entity_Id;
89       Nod    : Node_Id) return Entity_Id;
90    --  Build function to test Valid_Scalars for record type A_Type. Nod is the
91    --  Valid_Scalars attribute node, used to insert the function body, and the
92    --  value returned is the entity of the constructed function body. We do not
93    --  bother to generate a separate spec for this subprogram.
94
95    procedure Compile_Stream_Body_In_Scope
96      (N     : Node_Id;
97       Decl  : Node_Id;
98       Arr   : Entity_Id;
99       Check : Boolean);
100    --  The body for a stream subprogram may be generated outside of the scope
101    --  of the type. If the type is fully private, it may depend on the full
102    --  view of other types (e.g. indexes) that are currently private as well.
103    --  We install the declarations of the package in which the type is declared
104    --  before compiling the body in what is its proper environment. The Check
105    --  parameter indicates if checks are to be suppressed for the stream body.
106    --  We suppress checks for array/record reads, since the rule is that these
107    --  are like assignments, out of range values due to uninitialized storage,
108    --  or other invalid values do NOT cause a Constraint_Error to be raised.
109    --  If we are within an instance body all visibility has been established
110    --  already and there is no need to install the package.
111
112    --  This mechanism is now extended to the component types of the array type,
113    --  when the component type is not in scope and is private, to handle
114    --  properly the case when the full view has defaulted discriminants.
115
116    --  This special processing is ultimately caused by the fact that the
117    --  compiler lacks a well-defined phase when full views are visible
118    --  everywhere. Having such a separate pass would remove much of the
119    --  special-case code that shuffles partial and full views in the middle
120    --  of semantic analysis and expansion.
121
122    procedure Expand_Access_To_Protected_Op
123      (N    : Node_Id;
124       Pref : Node_Id;
125       Typ  : Entity_Id);
126    --  An attribute reference to a protected subprogram is transformed into
127    --  a pair of pointers: one to the object, and one to the operations.
128    --  This expansion is performed for 'Access and for 'Unrestricted_Access.
129
130    procedure Expand_Fpt_Attribute
131      (N    : Node_Id;
132       Pkg  : RE_Id;
133       Nam  : Name_Id;
134       Args : List_Id);
135    --  This procedure expands a call to a floating-point attribute function.
136    --  N is the attribute reference node, and Args is a list of arguments to
137    --  be passed to the function call. Pkg identifies the package containing
138    --  the appropriate instantiation of System.Fat_Gen. Float arguments in Args
139    --  have already been converted to the floating-point type for which Pkg was
140    --  instantiated. The Nam argument is the relevant attribute processing
141    --  routine to be called. This is the same as the attribute name, except in
142    --  the Unaligned_Valid case.
143
144    procedure Expand_Fpt_Attribute_R (N : Node_Id);
145    --  This procedure expands a call to a floating-point attribute function
146    --  that takes a single floating-point argument. The function to be called
147    --  is always the same as the attribute name.
148
149    procedure Expand_Fpt_Attribute_RI (N : Node_Id);
150    --  This procedure expands a call to a floating-point attribute function
151    --  that takes one floating-point argument and one integer argument. The
152    --  function to be called is always the same as the attribute name.
153
154    procedure Expand_Fpt_Attribute_RR (N : Node_Id);
155    --  This procedure expands a call to a floating-point attribute function
156    --  that takes two floating-point arguments. The function to be called
157    --  is always the same as the attribute name.
158
159    procedure Expand_Loop_Entry_Attribute (N : Node_Id);
160    --  Handle the expansion of attribute 'Loop_Entry. As a result, the related
161    --  loop may be converted into a conditional block. See body for details.
162
163    procedure Expand_Min_Max_Attribute (N : Node_Id);
164    --  Handle the expansion of attributes 'Max and 'Min, including expanding
165    --  then out if we are in Modify_Tree_For_C mode.
166
167    procedure Expand_Pred_Succ_Attribute (N : Node_Id);
168    --  Handles expansion of Pred or Succ attributes for case of non-real
169    --  operand with overflow checking required.
170
171    procedure Expand_Update_Attribute (N : Node_Id);
172    --  Handle the expansion of attribute Update
173
174    function Get_Index_Subtype (N : Node_Id) return Entity_Id;
175    --  Used for Last, Last, and Length, when the prefix is an array type.
176    --  Obtains the corresponding index subtype.
177
178    procedure Find_Fat_Info
179      (T        : Entity_Id;
180       Fat_Type : out Entity_Id;
181       Fat_Pkg  : out RE_Id);
182    --  Given a floating-point type T, identifies the package containing the
183    --  attributes for this type (returned in Fat_Pkg), and the corresponding
184    --  type for which this package was instantiated from Fat_Gen. Error if T
185    --  is not a floating-point type.
186
187    function Find_Stream_Subprogram
188      (Typ : Entity_Id;
189       Nam : TSS_Name_Type) return Entity_Id;
190    --  Returns the stream-oriented subprogram attribute for Typ. For tagged
191    --  types, the corresponding primitive operation is looked up, else the
192    --  appropriate TSS from the type itself, or from its closest ancestor
193    --  defining it, is returned. In both cases, inheritance of representation
194    --  aspects is thus taken into account.
195
196    function Full_Base (T : Entity_Id) return Entity_Id;
197    --  The stream functions need to examine the underlying representation of
198    --  composite types. In some cases T may be non-private but its base type
199    --  is, in which case the function returns the corresponding full view.
200
201    function Get_Stream_Convert_Pragma (T : Entity_Id) return Node_Id;
202    --  Given a type, find a corresponding stream convert pragma that applies to
203    --  the implementation base type of this type (Typ). If found, return the
204    --  pragma node, otherwise return Empty if no pragma is found.
205
206    function Is_Constrained_Packed_Array (Typ : Entity_Id) return Boolean;
207    --  Utility for array attributes, returns true on packed constrained
208    --  arrays, and on access to same.
209
210    function Is_Inline_Floating_Point_Attribute (N : Node_Id) return Boolean;
211    --  Returns true iff the given node refers to an attribute call that
212    --  can be expanded directly by the back end and does not need front end
213    --  expansion. Typically used for rounding and truncation attributes that
214    --  appear directly inside a conversion to integer.
215
216    -------------------------
217    -- Build_Array_VS_Func --
218    -------------------------
219
220    function Build_Array_VS_Func
221      (A_Type : Entity_Id;
222       Nod    : Node_Id) return Entity_Id
223    is
224       Loc        : constant Source_Ptr := Sloc (Nod);
225       Func_Id    : constant Entity_Id  := Make_Temporary (Loc, 'V');
226       Comp_Type  : constant Entity_Id  := Component_Type (A_Type);
227       Body_Stmts : List_Id;
228       Index_List : List_Id;
229       Formals    : List_Id;
230
231       function Test_Component return List_Id;
232       --  Create one statement to test validity of one component designated by
233       --  a full set of indexes. Returns statement list containing test.
234
235       function Test_One_Dimension (N : Int) return List_Id;
236       --  Create loop to test one dimension of the array. The single statement
237       --  in the loop body tests the inner dimensions if any, or else the
238       --  single component. Note that this procedure is called recursively,
239       --  with N being the dimension to be initialized. A call with N greater
240       --  than the number of dimensions simply generates the component test,
241       --  terminating the recursion. Returns statement list containing tests.
242
243       --------------------
244       -- Test_Component --
245       --------------------
246
247       function Test_Component return List_Id is
248          Comp : Node_Id;
249          Anam : Name_Id;
250
251       begin
252          Comp :=
253            Make_Indexed_Component (Loc,
254              Prefix      => Make_Identifier (Loc, Name_uA),
255              Expressions => Index_List);
256
257          if Is_Scalar_Type (Comp_Type) then
258             Anam := Name_Valid;
259          else
260             Anam := Name_Valid_Scalars;
261          end if;
262
263          return New_List (
264            Make_If_Statement (Loc,
265              Condition =>
266                Make_Op_Not (Loc,
267                  Right_Opnd =>
268                    Make_Attribute_Reference (Loc,
269                      Attribute_Name => Anam,
270                      Prefix         => Comp)),
271              Then_Statements => New_List (
272                Make_Simple_Return_Statement (Loc,
273                  Expression => New_Occurrence_Of (Standard_False, Loc)))));
274       end Test_Component;
275
276       ------------------------
277       -- Test_One_Dimension --
278       ------------------------
279
280       function Test_One_Dimension (N : Int) return List_Id is
281          Index : Entity_Id;
282
283       begin
284          --  If all dimensions dealt with, we simply test the component
285
286          if N > Number_Dimensions (A_Type) then
287             return Test_Component;
288
289          --  Here we generate the required loop
290
291          else
292             Index :=
293               Make_Defining_Identifier (Loc, New_External_Name ('J', N));
294
295             Append (New_Occurrence_Of (Index, Loc), Index_List);
296
297             return New_List (
298               Make_Implicit_Loop_Statement (Nod,
299                 Identifier => Empty,
300                 Iteration_Scheme =>
301                   Make_Iteration_Scheme (Loc,
302                     Loop_Parameter_Specification =>
303                       Make_Loop_Parameter_Specification (Loc,
304                         Defining_Identifier => Index,
305                         Discrete_Subtype_Definition =>
306                           Make_Attribute_Reference (Loc,
307                             Prefix => Make_Identifier (Loc, Name_uA),
308                             Attribute_Name  => Name_Range,
309                             Expressions     => New_List (
310                               Make_Integer_Literal (Loc, N))))),
311                 Statements =>  Test_One_Dimension (N + 1)),
312               Make_Simple_Return_Statement (Loc,
313                 Expression => New_Occurrence_Of (Standard_True, Loc)));
314          end if;
315       end Test_One_Dimension;
316
317    --  Start of processing for Build_Array_VS_Func
318
319    begin
320       Index_List := New_List;
321       Body_Stmts := Test_One_Dimension (1);
322
323       --  Parameter is always (A : A_Typ)
324
325       Formals := New_List (
326         Make_Parameter_Specification (Loc,
327           Defining_Identifier => Make_Defining_Identifier (Loc, Name_uA),
328           In_Present          => True,
329           Out_Present         => False,
330           Parameter_Type      => New_Occurrence_Of (A_Type, Loc)));
331
332       --  Build body
333
334       Set_Ekind       (Func_Id, E_Function);
335       Set_Is_Internal (Func_Id);
336
337       Insert_Action (Nod,
338         Make_Subprogram_Body (Loc,
339           Specification              =>
340             Make_Function_Specification (Loc,
341               Defining_Unit_Name       => Func_Id,
342               Parameter_Specifications => Formals,
343                 Result_Definition        =>
344                   New_Occurrence_Of (Standard_Boolean, Loc)),
345           Declarations               => New_List,
346           Handled_Statement_Sequence =>
347             Make_Handled_Sequence_Of_Statements (Loc,
348               Statements => Body_Stmts)));
349
350       if not Debug_Generated_Code then
351          Set_Debug_Info_Off (Func_Id);
352       end if;
353
354       Set_Is_Pure (Func_Id);
355       return Func_Id;
356    end Build_Array_VS_Func;
357
358    --------------------------
359    -- Build_Record_VS_Func --
360    --------------------------
361
362    --  Generates:
363
364    --    function _Valid_Scalars (X : T) return Boolean is
365    --    begin
366    --       --  Check discriminants
367
368    --       if not X.D1'Valid_Scalars or else
369    --          not X.D2'Valid_Scalars or else
370    --         ...
371    --       then
372    --          return False;
373    --       end if;
374
375    --       --  Check components
376
377    --       if not X.C1'Valid_Scalars or else
378    --          not X.C2'Valid_Scalars or else
379    --          ...
380    --       then
381    --          return False;
382    --       end if;
383
384    --       --  Check variant part
385
386    --       case X.D1 is
387    --          when V1 =>
388    --             if not X.C2'Valid_Scalars or else
389    --                not X.C3'Valid_Scalars or else
390    --               ...
391    --             then
392    --                return False;
393    --             end if;
394    --          ...
395    --          when Vn =>
396    --             if not X.Cn'Valid_Scalars or else
397    --               ...
398    --             then
399    --                return False;
400    --             end if;
401    --       end case;
402
403    --       return True;
404    --    end _Valid_Scalars;
405
406    function Build_Record_VS_Func
407      (R_Type : Entity_Id;
408       Nod    : Node_Id) return Entity_Id
409    is
410       Loc     : constant Source_Ptr := Sloc (R_Type);
411       Func_Id : constant Entity_Id  := Make_Temporary (Loc, 'V');
412       X       : constant Entity_Id  := Make_Defining_Identifier (Loc, Name_X);
413
414       function Make_VS_Case
415         (E      : Entity_Id;
416          CL     : Node_Id;
417          Discrs : Elist_Id := New_Elmt_List) return List_Id;
418       --  Building block for variant valid scalars. Given a Component_List node
419       --  CL, it generates an 'if' followed by a 'case' statement that compares
420       --  all components of local temporaries named X and Y (that are declared
421       --  as formals at some upper level). E provides the Sloc to be used for
422       --  the generated code.
423
424       function Make_VS_If
425         (E : Entity_Id;
426          L : List_Id) return Node_Id;
427       --  Building block for variant validate scalars. Given the list, L, of
428       --  components (or discriminants) L, it generates a return statement that
429       --  compares all components of local temporaries named X and Y (that are
430       --  declared as formals at some upper level). E provides the Sloc to be
431       --  used for the generated code.
432
433       ------------------
434       -- Make_VS_Case --
435       ------------------
436
437       --  <Make_VS_If on shared components>
438
439       --  case X.D1 is
440       --     when V1 => <Make_VS_Case> on subcomponents
441       --     ...
442       --     when Vn => <Make_VS_Case> on subcomponents
443       --  end case;
444
445       function Make_VS_Case
446         (E      : Entity_Id;
447          CL     : Node_Id;
448          Discrs : Elist_Id := New_Elmt_List) return List_Id
449       is
450          Loc      : constant Source_Ptr := Sloc (E);
451          Result   : constant List_Id    := New_List;
452          Variant  : Node_Id;
453          Alt_List : List_Id;
454
455       begin
456          Append_To (Result, Make_VS_If (E, Component_Items (CL)));
457
458          if No (Variant_Part (CL)) then
459             return Result;
460          end if;
461
462          Variant := First_Non_Pragma (Variants (Variant_Part (CL)));
463
464          if No (Variant) then
465             return Result;
466          end if;
467
468          Alt_List := New_List;
469          while Present (Variant) loop
470             Append_To (Alt_List,
471               Make_Case_Statement_Alternative (Loc,
472                 Discrete_Choices => New_Copy_List (Discrete_Choices (Variant)),
473                 Statements       =>
474                   Make_VS_Case (E, Component_List (Variant), Discrs)));
475             Next_Non_Pragma (Variant);
476          end loop;
477
478          Append_To (Result,
479            Make_Case_Statement (Loc,
480              Expression   =>
481                Make_Selected_Component (Loc,
482                  Prefix        => Make_Identifier (Loc, Name_X),
483                  Selector_Name => New_Copy (Name (Variant_Part (CL)))),
484              Alternatives => Alt_List));
485
486          return Result;
487       end Make_VS_Case;
488
489       ----------------
490       -- Make_VS_If --
491       ----------------
492
493       --  Generates:
494
495       --    if
496       --      not X.C1'Valid_Scalars
497       --        or else
498       --      not X.C2'Valid_Scalars
499       --        ...
500       --    then
501       --       return False;
502       --    end if;
503
504       --  or a null statement if the list L is empty
505
506       function Make_VS_If
507         (E : Entity_Id;
508          L : List_Id) return Node_Id
509       is
510          Loc        : constant Source_Ptr := Sloc (E);
511          C          : Node_Id;
512          Def_Id     : Entity_Id;
513          Field_Name : Name_Id;
514          Cond       : Node_Id;
515
516       begin
517          if No (L) then
518             return Make_Null_Statement (Loc);
519
520          else
521             Cond := Empty;
522
523             C := First_Non_Pragma (L);
524             while Present (C) loop
525                Def_Id := Defining_Identifier (C);
526                Field_Name := Chars (Def_Id);
527
528                --  The tags need not be checked since they will always be valid
529
530                --  Note also that in the following, we use Make_Identifier for
531                --  the component names. Use of New_Occurrence_Of to identify
532                --  the components would be incorrect because wrong entities for
533                --  discriminants could be picked up in the private type case.
534
535                --  Don't bother with abstract parent in interface case
536
537                if Field_Name = Name_uParent
538                  and then Is_Interface (Etype (Def_Id))
539                then
540                   null;
541
542                --  Don't bother with tag, always valid, and not scalar anyway
543
544                elsif Field_Name = Name_uTag then
545                   null;
546
547                --  Don't bother with component with no scalar components
548
549                elsif not Scalar_Part_Present (Etype (Def_Id)) then
550                   null;
551
552                --  Normal case, generate Valid_Scalars attribute reference
553
554                else
555                   Evolve_Or_Else (Cond,
556                     Make_Op_Not (Loc,
557                       Right_Opnd =>
558                         Make_Attribute_Reference (Loc,
559                           Prefix =>
560                             Make_Selected_Component (Loc,
561                               Prefix        =>
562                                 Make_Identifier (Loc, Name_X),
563                               Selector_Name =>
564                                 Make_Identifier (Loc, Field_Name)),
565                           Attribute_Name => Name_Valid_Scalars)));
566                end if;
567
568                Next_Non_Pragma (C);
569             end loop;
570
571             if No (Cond) then
572                return Make_Null_Statement (Loc);
573
574             else
575                return
576                  Make_Implicit_If_Statement (E,
577                    Condition       => Cond,
578                    Then_Statements => New_List (
579                      Make_Simple_Return_Statement (Loc,
580                        Expression =>
581                          New_Occurrence_Of (Standard_False, Loc))));
582             end if;
583          end if;
584       end Make_VS_If;
585
586       --  Local variables
587
588       Def    : constant Node_Id := Parent (R_Type);
589       Comps  : constant Node_Id := Component_List (Type_Definition (Def));
590       Stmts  : constant List_Id := New_List;
591       Pspecs : constant List_Id := New_List;
592
593    --  Start of processing for Build_Record_VS_Func
594
595    begin
596       Append_To (Pspecs,
597         Make_Parameter_Specification (Loc,
598           Defining_Identifier => X,
599           Parameter_Type      => New_Occurrence_Of (R_Type, Loc)));
600
601       Append_To (Stmts,
602         Make_VS_If (R_Type, Discriminant_Specifications (Def)));
603       Append_List_To (Stmts, Make_VS_Case (R_Type, Comps));
604
605       Append_To (Stmts,
606         Make_Simple_Return_Statement (Loc,
607           Expression => New_Occurrence_Of (Standard_True, Loc)));
608
609       Insert_Action (Nod,
610         Make_Subprogram_Body (Loc,
611           Specification =>
612             Make_Function_Specification (Loc,
613               Defining_Unit_Name       => Func_Id,
614               Parameter_Specifications => Pspecs,
615               Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
616           Declarations               => New_List,
617           Handled_Statement_Sequence =>
618             Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts)),
619         Suppress => Discriminant_Check);
620
621       if not Debug_Generated_Code then
622          Set_Debug_Info_Off (Func_Id);
623       end if;
624
625       Set_Is_Pure (Func_Id);
626       return Func_Id;
627    end Build_Record_VS_Func;
628
629    ----------------------------------
630    -- Compile_Stream_Body_In_Scope --
631    ----------------------------------
632
633    procedure Compile_Stream_Body_In_Scope
634      (N     : Node_Id;
635       Decl  : Node_Id;
636       Arr   : Entity_Id;
637       Check : Boolean)
638    is
639       C_Type  : constant Entity_Id := Base_Type (Component_Type (Arr));
640       Curr    : constant Entity_Id := Current_Scope;
641       Install : Boolean := False;
642       Scop    : Entity_Id := Scope (Arr);
643
644    begin
645       if Is_Hidden (Arr)
646         and then not In_Open_Scopes (Scop)
647         and then Ekind (Scop) = E_Package
648       then
649          Install := True;
650
651       else
652          --  The component type may be private, in which case we install its
653          --  full view to compile the subprogram.
654
655          --  The component type may be private, in which case we install its
656          --  full view to compile the subprogram. We do not do this if the
657          --  type has a Stream_Convert pragma, which indicates that there are
658          --  special stream-processing operations for that type (for example
659          --  Unbounded_String and its wide varieties).
660
661          Scop := Scope (C_Type);
662
663          if Is_Private_Type (C_Type)
664            and then Present (Full_View (C_Type))
665            and then not In_Open_Scopes (Scop)
666            and then Ekind (Scop) = E_Package
667            and then No (Get_Stream_Convert_Pragma (C_Type))
668          then
669             Install := True;
670          end if;
671       end if;
672
673       --  If we are within an instance body, then all visibility has been
674       --  established already and there is no need to install the package.
675
676       if Install and then not In_Instance_Body then
677          Push_Scope (Scop);
678          Install_Visible_Declarations (Scop);
679          Install_Private_Declarations (Scop);
680
681          --  The entities in the package are now visible, but the generated
682          --  stream entity must appear in the current scope (usually an
683          --  enclosing stream function) so that itypes all have their proper
684          --  scopes.
685
686          Push_Scope (Curr);
687       else
688          Install := False;
689       end if;
690
691       if Check then
692          Insert_Action (N, Decl);
693       else
694          Insert_Action (N, Decl, Suppress => All_Checks);
695       end if;
696
697       if Install then
698
699          --  Remove extra copy of current scope, and package itself
700
701          Pop_Scope;
702          End_Package_Scope (Scop);
703       end if;
704    end Compile_Stream_Body_In_Scope;
705
706    -----------------------------------
707    -- Expand_Access_To_Protected_Op --
708    -----------------------------------
709
710    procedure Expand_Access_To_Protected_Op
711      (N    : Node_Id;
712       Pref : Node_Id;
713       Typ  : Entity_Id)
714    is
715       --  The value of the attribute_reference is a record containing two
716       --  fields: an access to the protected object, and an access to the
717       --  subprogram itself. The prefix is a selected component.
718
719       Loc     : constant Source_Ptr := Sloc (N);
720       Agg     : Node_Id;
721       Btyp    : constant Entity_Id := Base_Type (Typ);
722       Sub     : Entity_Id;
723       Sub_Ref : Node_Id;
724       E_T     : constant Entity_Id := Equivalent_Type (Btyp);
725       Acc     : constant Entity_Id :=
726                   Etype (Next_Component (First_Component (E_T)));
727       Obj_Ref : Node_Id;
728       Curr    : Entity_Id;
729
730    --  Start of processing for Expand_Access_To_Protected_Op
731
732    begin
733       --  Within the body of the protected type, the prefix designates a local
734       --  operation, and the object is the first parameter of the corresponding
735       --  protected body of the current enclosing operation.
736
737       if Is_Entity_Name (Pref) then
738          --  All indirect calls are external calls, so must do locking and
739          --  barrier reevaluation, even if the 'Access occurs within the
740          --  protected body. Hence the call to External_Subprogram, as opposed
741          --  to Protected_Body_Subprogram, below. See RM-9.5(5). This means
742          --  that indirect calls from within the same protected body will
743          --  deadlock, as allowed by RM-9.5.1(8,15,17).
744
745          Sub := New_Occurrence_Of (External_Subprogram (Entity (Pref)), Loc);
746
747          --  Don't traverse the scopes when the attribute occurs within an init
748          --  proc, because we directly use the _init formal of the init proc in
749          --  that case.
750
751          Curr := Current_Scope;
752          if not Is_Init_Proc (Curr) then
753             pragma Assert (In_Open_Scopes (Scope (Entity (Pref))));
754
755             while Scope (Curr) /= Scope (Entity (Pref)) loop
756                Curr := Scope (Curr);
757             end loop;
758          end if;
759
760          --  In case of protected entries the first formal of its Protected_
761          --  Body_Subprogram is the address of the object.
762
763          if Ekind (Curr) = E_Entry then
764             Obj_Ref :=
765                New_Occurrence_Of
766                  (First_Formal
767                    (Protected_Body_Subprogram (Curr)), Loc);
768
769          --  If the current scope is an init proc, then use the address of the
770          --  _init formal as the object reference.
771
772          elsif Is_Init_Proc (Curr) then
773             Obj_Ref :=
774               Make_Attribute_Reference (Loc,
775                 Prefix         => New_Occurrence_Of (First_Formal (Curr), Loc),
776                 Attribute_Name => Name_Address);
777
778          --  In case of protected subprograms the first formal of its
779          --  Protected_Body_Subprogram is the object and we get its address.
780
781          else
782             Obj_Ref :=
783               Make_Attribute_Reference (Loc,
784                 Prefix =>
785                    New_Occurrence_Of
786                      (First_Formal
787                         (Protected_Body_Subprogram (Curr)), Loc),
788                 Attribute_Name => Name_Address);
789          end if;
790
791       --  Case where the prefix is not an entity name. Find the
792       --  version of the protected operation to be called from
793       --  outside the protected object.
794
795       else
796          Sub :=
797            New_Occurrence_Of
798              (External_Subprogram
799                (Entity (Selector_Name (Pref))), Loc);
800
801          Obj_Ref :=
802            Make_Attribute_Reference (Loc,
803              Prefix => Relocate_Node (Prefix (Pref)),
804                Attribute_Name => Name_Address);
805       end if;
806
807       Sub_Ref :=
808         Make_Attribute_Reference (Loc,
809           Prefix         => Sub,
810           Attribute_Name => Name_Access);
811
812       --  We set the type of the access reference to the already generated
813       --  access_to_subprogram type, and declare the reference analyzed, to
814       --  prevent further expansion when the enclosing aggregate is analyzed.
815
816       Set_Etype (Sub_Ref, Acc);
817       Set_Analyzed (Sub_Ref);
818
819       Agg :=
820         Make_Aggregate (Loc,
821           Expressions => New_List (Obj_Ref, Sub_Ref));
822
823       --  Sub_Ref has been marked as analyzed, but we still need to make sure
824       --  Sub is correctly frozen.
825
826       Freeze_Before (N, Entity (Sub));
827
828       Rewrite (N, Agg);
829       Analyze_And_Resolve (N, E_T);
830
831       --  For subsequent analysis, the node must retain its type. The backend
832       --  will replace it with the equivalent type where needed.
833
834       Set_Etype (N, Typ);
835    end Expand_Access_To_Protected_Op;
836
837    --------------------------
838    -- Expand_Fpt_Attribute --
839    --------------------------
840
841    procedure Expand_Fpt_Attribute
842      (N    : Node_Id;
843       Pkg  : RE_Id;
844       Nam  : Name_Id;
845       Args : List_Id)
846    is
847       Loc : constant Source_Ptr := Sloc (N);
848       Typ : constant Entity_Id  := Etype (N);
849       Fnm : Node_Id;
850
851    begin
852       --  The function name is the selected component Attr_xxx.yyy where
853       --  Attr_xxx is the package name, and yyy is the argument Nam.
854
855       --  Note: it would be more usual to have separate RE entries for each
856       --  of the entities in the Fat packages, but first they have identical
857       --  names (so we would have to have lots of renaming declarations to
858       --  meet the normal RE rule of separate names for all runtime entities),
859       --  and second there would be an awful lot of them.
860
861       Fnm :=
862         Make_Selected_Component (Loc,
863           Prefix        => New_Occurrence_Of (RTE (Pkg), Loc),
864           Selector_Name => Make_Identifier (Loc, Nam));
865
866       --  The generated call is given the provided set of parameters, and then
867       --  wrapped in a conversion which converts the result to the target type
868       --  We use the base type as the target because a range check may be
869       --  required.
870
871       Rewrite (N,
872         Unchecked_Convert_To (Base_Type (Etype (N)),
873           Make_Function_Call (Loc,
874             Name                   => Fnm,
875             Parameter_Associations => Args)));
876
877       Analyze_And_Resolve (N, Typ);
878    end Expand_Fpt_Attribute;
879
880    ----------------------------
881    -- Expand_Fpt_Attribute_R --
882    ----------------------------
883
884    --  The single argument is converted to its root type to call the
885    --  appropriate runtime function, with the actual call being built
886    --  by Expand_Fpt_Attribute
887
888    procedure Expand_Fpt_Attribute_R (N : Node_Id) is
889       E1  : constant Node_Id    := First (Expressions (N));
890       Ftp : Entity_Id;
891       Pkg : RE_Id;
892    begin
893       Find_Fat_Info (Etype (E1), Ftp, Pkg);
894       Expand_Fpt_Attribute
895         (N, Pkg, Attribute_Name (N),
896          New_List (Unchecked_Convert_To (Ftp, Relocate_Node (E1))));
897    end Expand_Fpt_Attribute_R;
898
899    -----------------------------
900    -- Expand_Fpt_Attribute_RI --
901    -----------------------------
902
903    --  The first argument is converted to its root type and the second
904    --  argument is converted to standard long long integer to call the
905    --  appropriate runtime function, with the actual call being built
906    --  by Expand_Fpt_Attribute
907
908    procedure Expand_Fpt_Attribute_RI (N : Node_Id) is
909       E1  : constant Node_Id   := First (Expressions (N));
910       Ftp : Entity_Id;
911       Pkg : RE_Id;
912       E2  : constant Node_Id   := Next (E1);
913    begin
914       Find_Fat_Info (Etype (E1), Ftp, Pkg);
915       Expand_Fpt_Attribute
916         (N, Pkg, Attribute_Name (N),
917          New_List (
918            Unchecked_Convert_To (Ftp, Relocate_Node (E1)),
919            Unchecked_Convert_To (Standard_Integer, Relocate_Node (E2))));
920    end Expand_Fpt_Attribute_RI;
921
922    -----------------------------
923    -- Expand_Fpt_Attribute_RR --
924    -----------------------------
925
926    --  The two arguments are converted to their root types to call the
927    --  appropriate runtime function, with the actual call being built
928    --  by Expand_Fpt_Attribute
929
930    procedure Expand_Fpt_Attribute_RR (N : Node_Id) is
931       E1  : constant Node_Id := First (Expressions (N));
932       E2  : constant Node_Id := Next (E1);
933       Ftp : Entity_Id;
934       Pkg : RE_Id;
935
936    begin
937       Find_Fat_Info (Etype (E1), Ftp, Pkg);
938       Expand_Fpt_Attribute
939         (N, Pkg, Attribute_Name (N),
940          New_List (
941            Unchecked_Convert_To (Ftp, Relocate_Node (E1)),
942            Unchecked_Convert_To (Ftp, Relocate_Node (E2))));
943    end Expand_Fpt_Attribute_RR;
944
945    ---------------------------------
946    -- Expand_Loop_Entry_Attribute --
947    ---------------------------------
948
949    procedure Expand_Loop_Entry_Attribute (N : Node_Id) is
950       procedure Build_Conditional_Block
951         (Loc       : Source_Ptr;
952          Cond      : Node_Id;
953          Loop_Stmt : Node_Id;
954          If_Stmt   : out Node_Id;
955          Blk_Stmt  : out Node_Id);
956       --  Create a block Blk_Stmt with an empty declarative list and a single
957       --  loop Loop_Stmt. The block is encased in an if statement If_Stmt with
958       --  condition Cond. If_Stmt is Empty when there is no condition provided.
959
960       function Is_Array_Iteration (N : Node_Id) return Boolean;
961       --  Determine whether loop statement N denotes an Ada 2012 iteration over
962       --  an array object.
963
964       -----------------------------
965       -- Build_Conditional_Block --
966       -----------------------------
967
968       procedure Build_Conditional_Block
969         (Loc       : Source_Ptr;
970          Cond      : Node_Id;
971          Loop_Stmt : Node_Id;
972          If_Stmt   : out Node_Id;
973          Blk_Stmt  : out Node_Id)
974       is
975       begin
976          --  Do not reanalyze the original loop statement because it is simply
977          --  being relocated.
978
979          Set_Analyzed (Loop_Stmt);
980
981          Blk_Stmt :=
982            Make_Block_Statement (Loc,
983              Declarations               => New_List,
984              Handled_Statement_Sequence =>
985                Make_Handled_Sequence_Of_Statements (Loc,
986                  Statements => New_List (Loop_Stmt)));
987
988          if Present (Cond) then
989             If_Stmt :=
990               Make_If_Statement (Loc,
991                 Condition       => Cond,
992                 Then_Statements => New_List (Blk_Stmt));
993          else
994             If_Stmt := Empty;
995          end if;
996       end Build_Conditional_Block;
997
998       ------------------------
999       -- Is_Array_Iteration --
1000       ------------------------
1001
1002       function Is_Array_Iteration (N : Node_Id) return Boolean is
1003          Stmt : constant Node_Id := Original_Node (N);
1004          Iter : Node_Id;
1005
1006       begin
1007          if Nkind (Stmt) = N_Loop_Statement
1008            and then Present (Iteration_Scheme (Stmt))
1009            and then Present (Iterator_Specification (Iteration_Scheme (Stmt)))
1010          then
1011             Iter := Iterator_Specification (Iteration_Scheme (Stmt));
1012
1013             return
1014               Of_Present (Iter) and then Is_Array_Type (Etype (Name (Iter)));
1015          end if;
1016
1017          return False;
1018       end Is_Array_Iteration;
1019
1020       --  Local variables
1021
1022       Exprs     : constant List_Id   := Expressions (N);
1023       Pref      : constant Node_Id   := Prefix (N);
1024       Typ       : constant Entity_Id := Etype (Pref);
1025       Blk       : Node_Id;
1026       CW_Decl   : Node_Id;
1027       CW_Temp   : Entity_Id;
1028       CW_Typ    : Entity_Id;
1029       Decls     : List_Id;
1030       Installed : Boolean;
1031       Loc       : Source_Ptr;
1032       Loop_Id   : Entity_Id;
1033       Loop_Stmt : Node_Id;
1034       Result    : Node_Id;
1035       Scheme    : Node_Id;
1036       Temp_Decl : Node_Id;
1037       Temp_Id   : Entity_Id;
1038
1039    --  Start of processing for Expand_Loop_Entry_Attribute
1040
1041    begin
1042       --  Step 1: Find the related loop
1043
1044       --  The loop label variant of attribute 'Loop_Entry already has all the
1045       --  information in its expression.
1046
1047       if Present (Exprs) then
1048          Loop_Id   := Entity (First (Exprs));
1049          Loop_Stmt := Label_Construct (Parent (Loop_Id));
1050
1051       --  Climb the parent chain to find the nearest enclosing loop. Skip all
1052       --  internally generated loops for quantified expressions and for
1053       --  element iterators over multidimensional arrays: pragma applies to
1054       --  source loop.
1055
1056       else
1057          Loop_Stmt := N;
1058          while Present (Loop_Stmt) loop
1059             if Nkind (Loop_Stmt) = N_Loop_Statement
1060               and then Comes_From_Source (Loop_Stmt)
1061             then
1062                exit;
1063             end if;
1064
1065             Loop_Stmt := Parent (Loop_Stmt);
1066          end loop;
1067
1068          Loop_Id := Entity (Identifier (Loop_Stmt));
1069       end if;
1070
1071       Loc := Sloc (Loop_Stmt);
1072
1073       --  Step 2: Transform the loop
1074
1075       --  The loop has already been transformed during the expansion of a prior
1076       --  'Loop_Entry attribute. Retrieve the declarative list of the block.
1077
1078       if Has_Loop_Entry_Attributes (Loop_Id) then
1079
1080          --  When the related loop name appears as the argument of attribute
1081          --  Loop_Entry, the corresponding label construct is the generated
1082          --  block statement. This is because the expander reuses the label.
1083
1084          if Nkind (Loop_Stmt) = N_Block_Statement then
1085             Decls := Declarations (Loop_Stmt);
1086
1087          --  In all other cases, the loop must appear in the handled sequence
1088          --  of statements of the generated block.
1089
1090          else
1091             pragma Assert
1092               (Nkind (Parent (Loop_Stmt)) = N_Handled_Sequence_Of_Statements
1093                 and then
1094                   Nkind (Parent (Parent (Loop_Stmt))) = N_Block_Statement);
1095
1096             Decls := Declarations (Parent (Parent (Loop_Stmt)));
1097          end if;
1098
1099          Result := Empty;
1100
1101       --  Transform the loop into a conditional block
1102
1103       else
1104          Set_Has_Loop_Entry_Attributes (Loop_Id);
1105          Scheme := Iteration_Scheme (Loop_Stmt);
1106
1107          --  Infinite loops are transformed into:
1108
1109          --    declare
1110          --       Temp1 : constant <type of Pref1> := <Pref1>;
1111          --       . . .
1112          --       TempN : constant <type of PrefN> := <PrefN>;
1113          --    begin
1114          --       loop
1115          --          <original source statements with attribute rewrites>
1116          --       end loop;
1117          --    end;
1118
1119          if No (Scheme) then
1120             Build_Conditional_Block (Loc,
1121               Cond      => Empty,
1122               Loop_Stmt => Relocate_Node (Loop_Stmt),
1123               If_Stmt   => Result,
1124               Blk_Stmt  => Blk);
1125
1126             Result := Blk;
1127
1128          --  While loops are transformed into:
1129
1130          --    function Fnn return Boolean is
1131          --    begin
1132          --       <condition actions>
1133          --       return <condition>;
1134          --    end Fnn;
1135
1136          --    if Fnn then
1137          --       declare
1138          --          Temp1 : constant <type of Pref1> := <Pref1>;
1139          --          . . .
1140          --          TempN : constant <type of PrefN> := <PrefN>;
1141          --       begin
1142          --          loop
1143          --             <original source statements with attribute rewrites>
1144          --             exit when not Fnn;
1145          --          end loop;
1146          --       end;
1147          --    end if;
1148
1149          --  Note that loops over iterators and containers are already
1150          --  converted into while loops.
1151
1152          elsif Present (Condition (Scheme)) then
1153             declare
1154                Func_Decl : Node_Id;
1155                Func_Id   : Entity_Id;
1156                Stmts     : List_Id;
1157
1158             begin
1159                --  Wrap the condition of the while loop in a Boolean function.
1160                --  This avoids the duplication of the same code which may lead
1161                --  to gigi issues with respect to multiple declaration of the
1162                --  same entity in the presence of side effects or checks. Note
1163                --  that the condition actions must also be relocated to the
1164                --  wrapping function.
1165
1166                --  Generate:
1167                --    <condition actions>
1168                --    return <condition>;
1169
1170                if Present (Condition_Actions (Scheme)) then
1171                   Stmts := Condition_Actions (Scheme);
1172                else
1173                   Stmts := New_List;
1174                end if;
1175
1176                Append_To (Stmts,
1177                  Make_Simple_Return_Statement (Loc,
1178                    Expression => Relocate_Node (Condition (Scheme))));
1179
1180                --  Generate:
1181                --    function Fnn return Boolean is
1182                --    begin
1183                --       <Stmts>
1184                --    end Fnn;
1185
1186                Func_Id   := Make_Temporary (Loc, 'F');
1187                Func_Decl :=
1188                  Make_Subprogram_Body (Loc,
1189                    Specification              =>
1190                      Make_Function_Specification (Loc,
1191                        Defining_Unit_Name => Func_Id,
1192                        Result_Definition  =>
1193                          New_Occurrence_Of (Standard_Boolean, Loc)),
1194                    Declarations               => Empty_List,
1195                    Handled_Statement_Sequence =>
1196                      Make_Handled_Sequence_Of_Statements (Loc,
1197                        Statements => Stmts));
1198
1199                --  The function is inserted before the related loop. Make sure
1200                --  to analyze it in the context of the loop's enclosing scope.
1201
1202                Push_Scope (Scope (Loop_Id));
1203                Insert_Action (Loop_Stmt, Func_Decl);
1204                Pop_Scope;
1205
1206                --  Transform the original while loop into an infinite loop
1207                --  where the last statement checks the negated condition. This
1208                --  placement ensures that the condition will not be evaluated
1209                --  twice on the first iteration.
1210
1211                Set_Iteration_Scheme (Loop_Stmt, Empty);
1212                Scheme := Empty;
1213
1214                --  Generate:
1215                --    exit when not Fnn;
1216
1217                Append_To (Statements (Loop_Stmt),
1218                  Make_Exit_Statement (Loc,
1219                    Condition =>
1220                      Make_Op_Not (Loc,
1221                        Right_Opnd =>
1222                          Make_Function_Call (Loc,
1223                            Name => New_Occurrence_Of (Func_Id, Loc)))));
1224
1225                Build_Conditional_Block (Loc,
1226                  Cond      =>
1227                    Make_Function_Call (Loc,
1228                      Name => New_Occurrence_Of (Func_Id, Loc)),
1229                  Loop_Stmt => Relocate_Node (Loop_Stmt),
1230                  If_Stmt   => Result,
1231                  Blk_Stmt  => Blk);
1232             end;
1233
1234          --  Ada 2012 iteration over an array is transformed into:
1235
1236          --    if <Array_Nam>'Length (1) > 0
1237          --      and then <Array_Nam>'Length (N) > 0
1238          --    then
1239          --       declare
1240          --          Temp1 : constant <type of Pref1> := <Pref1>;
1241          --          . . .
1242          --          TempN : constant <type of PrefN> := <PrefN>;
1243          --       begin
1244          --          for X in ... loop  --  multiple loops depending on dims
1245          --             <original source statements with attribute rewrites>
1246          --          end loop;
1247          --       end;
1248          --    end if;
1249
1250          elsif Is_Array_Iteration (Loop_Stmt) then
1251             declare
1252                Array_Nam : constant Entity_Id :=
1253                              Entity (Name (Iterator_Specification
1254                               (Iteration_Scheme (Original_Node (Loop_Stmt)))));
1255                Num_Dims  : constant Pos :=
1256                              Number_Dimensions (Etype (Array_Nam));
1257                Cond      : Node_Id := Empty;
1258                Check     : Node_Id;
1259
1260             begin
1261                --  Generate a check which determines whether all dimensions of
1262                --  the array are non-null.
1263
1264                for Dim in 1 .. Num_Dims loop
1265                   Check :=
1266                     Make_Op_Gt (Loc,
1267                       Left_Opnd  =>
1268                         Make_Attribute_Reference (Loc,
1269                           Prefix         => New_Occurrence_Of (Array_Nam, Loc),
1270                           Attribute_Name => Name_Length,
1271                           Expressions    => New_List (
1272                             Make_Integer_Literal (Loc, Dim))),
1273                       Right_Opnd =>
1274                         Make_Integer_Literal (Loc, 0));
1275
1276                   if No (Cond) then
1277                      Cond := Check;
1278                   else
1279                      Cond :=
1280                        Make_And_Then (Loc,
1281                          Left_Opnd  => Cond,
1282                          Right_Opnd => Check);
1283                   end if;
1284                end loop;
1285
1286                Build_Conditional_Block (Loc,
1287                  Cond      => Cond,
1288                  Loop_Stmt => Relocate_Node (Loop_Stmt),
1289                  If_Stmt   => Result,
1290                  Blk_Stmt  => Blk);
1291             end;
1292
1293          --  For loops are transformed into:
1294
1295          --    if <Low> <= <High> then
1296          --       declare
1297          --          Temp1 : constant <type of Pref1> := <Pref1>;
1298          --          . . .
1299          --          TempN : constant <type of PrefN> := <PrefN>;
1300          --       begin
1301          --          for <Def_Id> in <Low> .. <High> loop
1302          --             <original source statements with attribute rewrites>
1303          --          end loop;
1304          --       end;
1305          --    end if;
1306
1307          elsif Present (Loop_Parameter_Specification (Scheme)) then
1308             declare
1309                Loop_Spec : constant Node_Id :=
1310                              Loop_Parameter_Specification (Scheme);
1311                Cond      : Node_Id;
1312                Subt_Def  : Node_Id;
1313
1314             begin
1315                Subt_Def := Discrete_Subtype_Definition (Loop_Spec);
1316
1317                --  When the loop iterates over a subtype indication with a
1318                --  range, use the low and high bounds of the subtype itself.
1319
1320                if Nkind (Subt_Def) = N_Subtype_Indication then
1321                   Subt_Def := Scalar_Range (Etype (Subt_Def));
1322                end if;
1323
1324                pragma Assert (Nkind (Subt_Def) = N_Range);
1325
1326                --  Generate
1327                --    Low <= High
1328
1329                Cond :=
1330                  Make_Op_Le (Loc,
1331                    Left_Opnd  => New_Copy_Tree (Low_Bound (Subt_Def)),
1332                    Right_Opnd => New_Copy_Tree (High_Bound (Subt_Def)));
1333
1334                Build_Conditional_Block (Loc,
1335                  Cond      => Cond,
1336                  Loop_Stmt => Relocate_Node (Loop_Stmt),
1337                  If_Stmt   => Result,
1338                  Blk_Stmt  => Blk);
1339             end;
1340          end if;
1341
1342          Decls := Declarations (Blk);
1343       end if;
1344
1345       --  Step 3: Create a constant to capture the value of the prefix at the
1346       --  entry point into the loop.
1347
1348       Temp_Id := Make_Temporary (Loc, 'P');
1349
1350       --  Preserve the tag of the prefix by offering a specific view of the
1351       --  class-wide version of the prefix.
1352
1353       if Is_Tagged_Type (Typ) then
1354
1355          --  Generate:
1356          --    CW_Temp : constant Typ'Class := Typ'Class (Pref);
1357
1358          CW_Temp := Make_Temporary (Loc, 'T');
1359          CW_Typ  := Class_Wide_Type (Typ);
1360
1361          CW_Decl :=
1362            Make_Object_Declaration (Loc,
1363              Defining_Identifier => CW_Temp,
1364              Constant_Present    => True,
1365              Object_Definition   => New_Occurrence_Of (CW_Typ, Loc),
1366              Expression          =>
1367                Convert_To (CW_Typ, Relocate_Node (Pref)));
1368          Append_To (Decls, CW_Decl);
1369
1370          --  Generate:
1371          --    Temp : Typ renames Typ (CW_Temp);
1372
1373          Temp_Decl :=
1374            Make_Object_Renaming_Declaration (Loc,
1375              Defining_Identifier => Temp_Id,
1376              Subtype_Mark        => New_Occurrence_Of (Typ, Loc),
1377              Name                =>
1378                Convert_To (Typ, New_Occurrence_Of (CW_Temp, Loc)));
1379          Append_To (Decls, Temp_Decl);
1380
1381       --  Non-tagged case
1382
1383       else
1384          CW_Decl := Empty;
1385
1386          --  Generate:
1387          --    Temp : constant Typ := Pref;
1388
1389          Temp_Decl :=
1390            Make_Object_Declaration (Loc,
1391              Defining_Identifier => Temp_Id,
1392              Constant_Present    => True,
1393              Object_Definition   => New_Occurrence_Of (Typ, Loc),
1394              Expression          => Relocate_Node (Pref));
1395          Append_To (Decls, Temp_Decl);
1396       end if;
1397
1398       --  Step 4: Analyze all bits
1399
1400       Installed := Current_Scope = Scope (Loop_Id);
1401
1402       --  Depending on the pracement of attribute 'Loop_Entry relative to the
1403       --  associated loop, ensure the proper visibility for analysis.
1404
1405       if not Installed then
1406          Push_Scope (Scope (Loop_Id));
1407       end if;
1408
1409       --  The analysis of the conditional block takes care of the constant
1410       --  declaration.
1411
1412       if Present (Result) then
1413          Rewrite (Loop_Stmt, Result);
1414          Analyze (Loop_Stmt);
1415
1416       --  The conditional block was analyzed when a previous 'Loop_Entry was
1417       --  expanded. There is no point in reanalyzing the block, simply analyze
1418       --  the declaration of the constant.
1419
1420       else
1421          if Present (CW_Decl) then
1422             Analyze (CW_Decl);
1423          end if;
1424
1425          Analyze (Temp_Decl);
1426       end if;
1427
1428       Rewrite (N, New_Occurrence_Of (Temp_Id, Loc));
1429       Analyze (N);
1430
1431       if not Installed then
1432          Pop_Scope;
1433       end if;
1434    end Expand_Loop_Entry_Attribute;
1435
1436    ------------------------------
1437    -- Expand_Min_Max_Attribute --
1438    ------------------------------
1439
1440    procedure Expand_Min_Max_Attribute (N : Node_Id) is
1441    begin
1442       --  Min and Max are handled by the back end (except that static cases
1443       --  have already been evaluated during semantic processing, although the
1444       --  back end should not count on this). The one bit of special processing
1445       --  required in the normal case is that these two attributes typically
1446       --  generate conditionals in the code, so check the relevant restriction.
1447
1448       Check_Restriction (No_Implicit_Conditionals, N);
1449
1450       --  In Modify_Tree_For_C mode, we rewrite as an if expression
1451
1452       if Modify_Tree_For_C then
1453          declare
1454             Loc   : constant Source_Ptr := Sloc (N);
1455             Typ   : constant Entity_Id  := Etype (N);
1456             Expr  : constant Node_Id    := First (Expressions (N));
1457             Left  : constant Node_Id    := Relocate_Node (Expr);
1458             Right : constant Node_Id    := Relocate_Node (Next (Expr));
1459
1460             function Make_Compare (Left, Right : Node_Id) return Node_Id;
1461             --  Returns Left >= Right for Max, Left <= Right for Min
1462
1463             ------------------
1464             -- Make_Compare --
1465             ------------------
1466
1467             function Make_Compare (Left, Right : Node_Id) return Node_Id is
1468             begin
1469                if Attribute_Name (N) = Name_Max then
1470                   return
1471                     Make_Op_Ge (Loc,
1472                       Left_Opnd  => Left,
1473                       Right_Opnd => Right);
1474                else
1475                   return
1476                     Make_Op_Le (Loc,
1477                       Left_Opnd  => Left,
1478                       Right_Opnd => Right);
1479                end if;
1480             end Make_Compare;
1481
1482          --  Start of processing for Min_Max
1483
1484          begin
1485             --  If both Left and Right are side effect free, then we can just
1486             --  use Duplicate_Expr to duplicate the references and return
1487
1488             --    (if Left >=|<= Right then Left else Right)
1489
1490             if Side_Effect_Free (Left) and then Side_Effect_Free (Right) then
1491                Rewrite (N,
1492                  Make_If_Expression (Loc,
1493                    Expressions => New_List (
1494                      Make_Compare (Left, Right),
1495                      Duplicate_Subexpr_No_Checks (Left),
1496                      Duplicate_Subexpr_No_Checks (Right))));
1497
1498             --  Otherwise we generate declarations to capture the values.
1499
1500             --  The translation is
1501
1502             --    do
1503             --      T1 : constant typ := Left;
1504             --      T2 : constant typ := Right;
1505             --    in
1506             --      (if T1 >=|<= T2 then T1 else T2)
1507             --    end;
1508
1509             else
1510                declare
1511                   T1 : constant Entity_Id := Make_Temporary (Loc, 'T', Left);
1512                   T2 : constant Entity_Id := Make_Temporary (Loc, 'T', Right);
1513
1514                begin
1515                   Rewrite (N,
1516                     Make_Expression_With_Actions (Loc,
1517                       Actions    => New_List (
1518                         Make_Object_Declaration (Loc,
1519                           Defining_Identifier => T1,
1520                           Constant_Present    => True,
1521                           Object_Definition   =>
1522                             New_Occurrence_Of (Etype (Left), Loc),
1523                           Expression          => Relocate_Node (Left)),
1524
1525                         Make_Object_Declaration (Loc,
1526                           Defining_Identifier => T2,
1527                           Constant_Present    => True,
1528                           Object_Definition   =>
1529                             New_Occurrence_Of (Etype (Right), Loc),
1530                           Expression          => Relocate_Node (Right))),
1531
1532                       Expression =>
1533                         Make_If_Expression (Loc,
1534                           Expressions => New_List (
1535                             Make_Compare
1536                               (New_Occurrence_Of (T1, Loc),
1537                                New_Occurrence_Of (T2, Loc)),
1538                                New_Occurrence_Of (T1, Loc),
1539                                New_Occurrence_Of (T2, Loc)))));
1540                end;
1541             end if;
1542
1543             Analyze_And_Resolve (N, Typ);
1544          end;
1545       end if;
1546    end Expand_Min_Max_Attribute;
1547
1548    ----------------------------------
1549    -- Expand_N_Attribute_Reference --
1550    ----------------------------------
1551
1552    procedure Expand_N_Attribute_Reference (N : Node_Id) is
1553       Loc   : constant Source_Ptr   := Sloc (N);
1554       Typ   : constant Entity_Id    := Etype (N);
1555       Btyp  : constant Entity_Id    := Base_Type (Typ);
1556       Pref  : constant Node_Id      := Prefix (N);
1557       Ptyp  : constant Entity_Id    := Etype (Pref);
1558       Exprs : constant List_Id      := Expressions (N);
1559       Id    : constant Attribute_Id := Get_Attribute_Id (Attribute_Name (N));
1560
1561       procedure Rewrite_Stream_Proc_Call (Pname : Entity_Id);
1562       --  Rewrites a stream attribute for Read, Write or Output with the
1563       --  procedure call. Pname is the entity for the procedure to call.
1564
1565       ------------------------------
1566       -- Rewrite_Stream_Proc_Call --
1567       ------------------------------
1568
1569       procedure Rewrite_Stream_Proc_Call (Pname : Entity_Id) is
1570          Item       : constant Node_Id   := Next (First (Exprs));
1571          Item_Typ   : constant Entity_Id := Etype (Item);
1572          Formal     : constant Entity_Id := Next_Formal (First_Formal (Pname));
1573          Formal_Typ : constant Entity_Id := Etype (Formal);
1574          Is_Written : constant Boolean   := Ekind (Formal) /= E_In_Parameter;
1575
1576       begin
1577          --  The expansion depends on Item, the second actual, which is
1578          --  the object being streamed in or out.
1579
1580          --  If the item is a component of a packed array type, and
1581          --  a conversion is needed on exit, we introduce a temporary to
1582          --  hold the value, because otherwise the packed reference will
1583          --  not be properly expanded.
1584
1585          if Nkind (Item) = N_Indexed_Component
1586            and then Is_Packed (Base_Type (Etype (Prefix (Item))))
1587            and then Base_Type (Item_Typ) /= Base_Type (Formal_Typ)
1588            and then Is_Written
1589          then
1590             declare
1591                Temp : constant Entity_Id := Make_Temporary (Loc, 'V');
1592                Decl : Node_Id;
1593                Assn : Node_Id;
1594
1595             begin
1596                Decl :=
1597                  Make_Object_Declaration (Loc,
1598                    Defining_Identifier => Temp,
1599                    Object_Definition   => New_Occurrence_Of (Formal_Typ, Loc));
1600                Set_Etype (Temp, Formal_Typ);
1601
1602                Assn :=
1603                  Make_Assignment_Statement (Loc,
1604                    Name       => New_Copy_Tree (Item),
1605                    Expression =>
1606                      Unchecked_Convert_To
1607                        (Item_Typ, New_Occurrence_Of (Temp, Loc)));
1608
1609                Rewrite (Item, New_Occurrence_Of (Temp, Loc));
1610                Insert_Actions (N,
1611                  New_List (
1612                    Decl,
1613                    Make_Procedure_Call_Statement (Loc,
1614                      Name                   => New_Occurrence_Of (Pname, Loc),
1615                      Parameter_Associations => Exprs),
1616                    Assn));
1617
1618                Rewrite (N, Make_Null_Statement (Loc));
1619                return;
1620             end;
1621          end if;
1622
1623          --  For the class-wide dispatching cases, and for cases in which
1624          --  the base type of the second argument matches the base type of
1625          --  the corresponding formal parameter (that is to say the stream
1626          --  operation is not inherited), we are all set, and can use the
1627          --  argument unchanged.
1628
1629          if not Is_Class_Wide_Type (Entity (Pref))
1630            and then not Is_Class_Wide_Type (Etype (Item))
1631            and then Base_Type (Item_Typ) /= Base_Type (Formal_Typ)
1632          then
1633             --  Perform a view conversion when either the argument or the
1634             --  formal parameter are of a private type.
1635
1636             if Is_Private_Type (Formal_Typ)
1637               or else Is_Private_Type (Item_Typ)
1638             then
1639                Rewrite (Item,
1640                  Unchecked_Convert_To (Formal_Typ, Relocate_Node (Item)));
1641
1642             --  Otherwise perform a regular type conversion to ensure that all
1643             --  relevant checks are installed.
1644
1645             else
1646                Rewrite (Item, Convert_To (Formal_Typ, Relocate_Node (Item)));
1647             end if;
1648
1649             --  For untagged derived types set Assignment_OK, to prevent
1650             --  copies from being created when the unchecked conversion
1651             --  is expanded (which would happen in Remove_Side_Effects
1652             --  if Expand_N_Unchecked_Conversion were allowed to call
1653             --  Force_Evaluation). The copy could violate Ada semantics in
1654             --  cases such as an actual that is an out parameter. Note that
1655             --  this approach is also used in exp_ch7 for calls to controlled
1656             --  type operations to prevent problems with actuals wrapped in
1657             --  unchecked conversions.
1658
1659             if Is_Untagged_Derivation (Etype (Expression (Item))) then
1660                Set_Assignment_OK (Item);
1661             end if;
1662          end if;
1663
1664          --  The stream operation to call may be a renaming created by an
1665          --  attribute definition clause, and may not be frozen yet. Ensure
1666          --  that it has the necessary extra formals.
1667
1668          if not Is_Frozen (Pname) then
1669             Create_Extra_Formals (Pname);
1670          end if;
1671
1672          --  And now rewrite the call
1673
1674          Rewrite (N,
1675            Make_Procedure_Call_Statement (Loc,
1676              Name                   => New_Occurrence_Of (Pname, Loc),
1677              Parameter_Associations => Exprs));
1678
1679          Analyze (N);
1680       end Rewrite_Stream_Proc_Call;
1681
1682    --  Start of processing for Expand_N_Attribute_Reference
1683
1684    begin
1685       --  Do required validity checking, if enabled. Do not apply check to
1686       --  output parameters of an Asm instruction, since the value of this
1687       --  is not set till after the attribute has been elaborated, and do
1688       --  not apply the check to the arguments of a 'Read or 'Input attribute
1689       --  reference since the scalar argument is an OUT scalar.
1690
1691       if Validity_Checks_On and then Validity_Check_Operands
1692         and then Id /= Attribute_Asm_Output
1693         and then Id /= Attribute_Read
1694         and then Id /= Attribute_Input
1695       then
1696          declare
1697             Expr : Node_Id;
1698          begin
1699             Expr := First (Expressions (N));
1700             while Present (Expr) loop
1701                Ensure_Valid (Expr);
1702                Next (Expr);
1703             end loop;
1704          end;
1705       end if;
1706
1707       --  Ada 2005 (AI-318-02): If attribute prefix is a call to a build-in-
1708       --  place function, then a temporary return object needs to be created
1709       --  and access to it must be passed to the function. Currently we limit
1710       --  such functions to those with inherently limited result subtypes, but
1711       --  eventually we plan to expand the functions that are treated as
1712       --  build-in-place to include other composite result types.
1713
1714       if Ada_Version >= Ada_2005
1715         and then Is_Build_In_Place_Function_Call (Pref)
1716       then
1717          Make_Build_In_Place_Call_In_Anonymous_Context (Pref);
1718       end if;
1719
1720       --  If prefix is a protected type name, this is a reference to the
1721       --  current instance of the type. For a component definition, nothing
1722       --  to do (expansion will occur in the init proc). In other contexts,
1723       --  rewrite into reference to current instance.
1724
1725       if Is_Protected_Self_Reference (Pref)
1726         and then not
1727           (Nkind_In (Parent (N), N_Index_Or_Discriminant_Constraint,
1728                                  N_Discriminant_Association)
1729             and then Nkind (Parent (Parent (Parent (Parent (N))))) =
1730                                                       N_Component_Definition)
1731
1732          --  No action needed for these attributes since the current instance
1733          --  will be rewritten to be the name of the _object parameter
1734          --  associated with the enclosing protected subprogram (see below).
1735
1736         and then Id /= Attribute_Access
1737         and then Id /= Attribute_Unchecked_Access
1738         and then Id /= Attribute_Unrestricted_Access
1739       then
1740          Rewrite (Pref, Concurrent_Ref (Pref));
1741          Analyze (Pref);
1742       end if;
1743
1744       --  Remaining processing depends on specific attribute
1745
1746       --  Note: individual sections of the following case statement are
1747       --  allowed to assume there is no code after the case statement, and
1748       --  are legitimately allowed to execute return statements if they have
1749       --  nothing more to do.
1750
1751       case Id is
1752
1753       --  Attributes related to Ada 2012 iterators
1754
1755       when Attribute_Constant_Indexing    |
1756            Attribute_Default_Iterator     |
1757            Attribute_Implicit_Dereference |
1758            Attribute_Iterable             |
1759            Attribute_Iterator_Element     |
1760            Attribute_Variable_Indexing    =>
1761          null;
1762
1763       --  Internal attributes used to deal with Ada 2012 delayed aspects. These
1764       --  were already rejected by the parser. Thus they shouldn't appear here.
1765
1766       when Internal_Attribute_Id =>
1767          raise Program_Error;
1768
1769       ------------
1770       -- Access --
1771       ------------
1772
1773       when Attribute_Access              |
1774            Attribute_Unchecked_Access    |
1775            Attribute_Unrestricted_Access =>
1776
1777          Access_Cases : declare
1778             Ref_Object : constant Node_Id := Get_Referenced_Object (Pref);
1779             Btyp_DDT   : Entity_Id;
1780
1781             function Enclosing_Object (N : Node_Id) return Node_Id;
1782             --  If N denotes a compound name (selected component, indexed
1783             --  component, or slice), returns the name of the outermost such
1784             --  enclosing object. Otherwise returns N. If the object is a
1785             --  renaming, then the renamed object is returned.
1786
1787             ----------------------
1788             -- Enclosing_Object --
1789             ----------------------
1790
1791             function Enclosing_Object (N : Node_Id) return Node_Id is
1792                Obj_Name : Node_Id;
1793
1794             begin
1795                Obj_Name := N;
1796                while Nkind_In (Obj_Name, N_Selected_Component,
1797                                          N_Indexed_Component,
1798                                          N_Slice)
1799                loop
1800                   Obj_Name := Prefix (Obj_Name);
1801                end loop;
1802
1803                return Get_Referenced_Object (Obj_Name);
1804             end Enclosing_Object;
1805
1806             --  Local declarations
1807
1808             Enc_Object : constant Node_Id := Enclosing_Object (Ref_Object);
1809
1810          --  Start of processing for Access_Cases
1811
1812          begin
1813             Btyp_DDT := Designated_Type (Btyp);
1814
1815             --  Handle designated types that come from the limited view
1816
1817             if From_Limited_With (Btyp_DDT)
1818               and then Has_Non_Limited_View (Btyp_DDT)
1819             then
1820                Btyp_DDT := Non_Limited_View (Btyp_DDT);
1821             end if;
1822
1823             --  In order to improve the text of error messages, the designated
1824             --  type of access-to-subprogram itypes is set by the semantics as
1825             --  the associated subprogram entity (see sem_attr). Now we replace
1826             --  such node with the proper E_Subprogram_Type itype.
1827
1828             if Id = Attribute_Unrestricted_Access
1829               and then Is_Subprogram (Directly_Designated_Type (Typ))
1830             then
1831                --  The following conditions ensure that this special management
1832                --  is done only for "Address!(Prim'Unrestricted_Access)" nodes.
1833                --  At this stage other cases in which the designated type is
1834                --  still a subprogram (instead of an E_Subprogram_Type) are
1835                --  wrong because the semantics must have overridden the type of
1836                --  the node with the type imposed by the context.
1837
1838                if Nkind (Parent (N)) = N_Unchecked_Type_Conversion
1839                  and then Etype (Parent (N)) = RTE (RE_Prim_Ptr)
1840                then
1841                   Set_Etype (N, RTE (RE_Prim_Ptr));
1842
1843                else
1844                   declare
1845                      Subp       : constant Entity_Id :=
1846                                     Directly_Designated_Type (Typ);
1847                      Etyp       : Entity_Id;
1848                      Extra      : Entity_Id := Empty;
1849                      New_Formal : Entity_Id;
1850                      Old_Formal : Entity_Id := First_Formal (Subp);
1851                      Subp_Typ   : Entity_Id;
1852
1853                   begin
1854                      Subp_Typ := Create_Itype (E_Subprogram_Type, N);
1855                      Set_Etype (Subp_Typ, Etype (Subp));
1856                      Set_Returns_By_Ref (Subp_Typ, Returns_By_Ref (Subp));
1857
1858                      if Present (Old_Formal) then
1859                         New_Formal := New_Copy (Old_Formal);
1860                         Set_First_Entity (Subp_Typ, New_Formal);
1861
1862                         loop
1863                            Set_Scope (New_Formal, Subp_Typ);
1864                            Etyp := Etype (New_Formal);
1865
1866                            --  Handle itypes. There is no need to duplicate
1867                            --  here the itypes associated with record types
1868                            --  (i.e the implicit full view of private types).
1869
1870                            if Is_Itype (Etyp)
1871                              and then Ekind (Base_Type (Etyp)) /= E_Record_Type
1872                            then
1873                               Extra := New_Copy (Etyp);
1874                               Set_Parent (Extra, New_Formal);
1875                               Set_Etype (New_Formal, Extra);
1876                               Set_Scope (Extra, Subp_Typ);
1877                            end if;
1878
1879                            Extra := New_Formal;
1880                            Next_Formal (Old_Formal);
1881                            exit when No (Old_Formal);
1882
1883                            Set_Next_Entity (New_Formal,
1884                              New_Copy (Old_Formal));
1885                            Next_Entity (New_Formal);
1886                         end loop;
1887
1888                         Set_Next_Entity (New_Formal, Empty);
1889                         Set_Last_Entity (Subp_Typ, Extra);
1890                      end if;
1891
1892                      --  Now that the explicit formals have been duplicated,
1893                      --  any extra formals needed by the subprogram must be
1894                      --  created.
1895
1896                      if Present (Extra) then
1897                         Set_Extra_Formal (Extra, Empty);
1898                      end if;
1899
1900                      Create_Extra_Formals (Subp_Typ);
1901                      Set_Directly_Designated_Type (Typ, Subp_Typ);
1902                   end;
1903                end if;
1904             end if;
1905
1906             if Is_Access_Protected_Subprogram_Type (Btyp) then
1907                Expand_Access_To_Protected_Op (N, Pref, Typ);
1908
1909             --  If prefix is a type name, this is a reference to the current
1910             --  instance of the type, within its initialization procedure.
1911
1912             elsif Is_Entity_Name (Pref)
1913               and then Is_Type (Entity (Pref))
1914             then
1915                declare
1916                   Par    : Node_Id;
1917                   Formal : Entity_Id;
1918
1919                begin
1920                   --  If the current instance name denotes a task type, then
1921                   --  the access attribute is rewritten to be the name of the
1922                   --  "_task" parameter associated with the task type's task
1923                   --  procedure. An unchecked conversion is applied to ensure
1924                   --  a type match in cases of expander-generated calls (e.g.
1925                   --  init procs).
1926
1927                   if Is_Task_Type (Entity (Pref)) then
1928                      Formal :=
1929                        First_Entity (Get_Task_Body_Procedure (Entity (Pref)));
1930                      while Present (Formal) loop
1931                         exit when Chars (Formal) = Name_uTask;
1932                         Next_Entity (Formal);
1933                      end loop;
1934
1935                      pragma Assert (Present (Formal));
1936
1937                      Rewrite (N,
1938                        Unchecked_Convert_To (Typ,
1939                          New_Occurrence_Of (Formal, Loc)));
1940                      Set_Etype (N, Typ);
1941
1942                   elsif Is_Protected_Type (Entity (Pref)) then
1943
1944                      --  No action needed for current instance located in a
1945                      --  component definition (expansion will occur in the
1946                      --  init proc)
1947
1948                      if Is_Protected_Type (Current_Scope) then
1949                         null;
1950
1951                      --  If the current instance reference is located in a
1952                      --  protected subprogram or entry then rewrite the access
1953                      --  attribute to be the name of the "_object" parameter.
1954                      --  An unchecked conversion is applied to ensure a type
1955                      --  match in cases of expander-generated calls (e.g. init
1956                      --  procs).
1957
1958                      --  The code may be nested in a block, so find enclosing
1959                      --  scope that is a protected operation.
1960
1961                      else
1962                         declare
1963                            Subp : Entity_Id;
1964
1965                         begin
1966                            Subp := Current_Scope;
1967                            while Ekind_In (Subp, E_Loop, E_Block) loop
1968                               Subp := Scope (Subp);
1969                            end loop;
1970
1971                            Formal :=
1972                              First_Entity
1973                                (Protected_Body_Subprogram (Subp));
1974
1975                            --  For a protected subprogram the _Object parameter
1976                            --  is the protected record, so we create an access
1977                            --  to it. The _Object parameter of an entry is an
1978                            --  address.
1979
1980                            if Ekind (Subp) = E_Entry then
1981                               Rewrite (N,
1982                                 Unchecked_Convert_To (Typ,
1983                                   New_Occurrence_Of (Formal, Loc)));
1984                               Set_Etype (N, Typ);
1985
1986                            else
1987                               Rewrite (N,
1988                                 Unchecked_Convert_To (Typ,
1989                                   Make_Attribute_Reference (Loc,
1990                                     Attribute_Name => Name_Unrestricted_Access,
1991                                     Prefix         =>
1992                                       New_Occurrence_Of (Formal, Loc))));
1993                               Analyze_And_Resolve (N);
1994                            end if;
1995                         end;
1996                      end if;
1997
1998                   --  The expression must appear in a default expression,
1999                   --  (which in the initialization procedure is the right-hand
2000                   --  side of an assignment), and not in a discriminant
2001                   --  constraint.
2002
2003                   else
2004                      Par := Parent (N);
2005                      while Present (Par) loop
2006                         exit when Nkind (Par) = N_Assignment_Statement;
2007
2008                         if Nkind (Par) = N_Component_Declaration then
2009                            return;
2010                         end if;
2011
2012                         Par := Parent (Par);
2013                      end loop;
2014
2015                      if Present (Par) then
2016                         Rewrite (N,
2017                           Make_Attribute_Reference (Loc,
2018                             Prefix => Make_Identifier (Loc, Name_uInit),
2019                             Attribute_Name  => Attribute_Name (N)));
2020
2021                         Analyze_And_Resolve (N, Typ);
2022                      end if;
2023                   end if;
2024                end;
2025
2026             --  If the prefix of an Access attribute is a dereference of an
2027             --  access parameter (or a renaming of such a dereference, or a
2028             --  subcomponent of such a dereference) and the context is a
2029             --  general access type (including the type of an object or
2030             --  component with an access_definition, but not the anonymous
2031             --  type of an access parameter or access discriminant), then
2032             --  apply an accessibility check to the access parameter. We used
2033             --  to rewrite the access parameter as a type conversion, but that
2034             --  could only be done if the immediate prefix of the Access
2035             --  attribute was the dereference, and didn't handle cases where
2036             --  the attribute is applied to a subcomponent of the dereference,
2037             --  since there's generally no available, appropriate access type
2038             --  to convert to in that case. The attribute is passed as the
2039             --  point to insert the check, because the access parameter may
2040             --  come from a renaming, possibly in a different scope, and the
2041             --  check must be associated with the attribute itself.
2042
2043             elsif Id = Attribute_Access
2044               and then Nkind (Enc_Object) = N_Explicit_Dereference
2045               and then Is_Entity_Name (Prefix (Enc_Object))
2046               and then (Ekind (Btyp) = E_General_Access_Type
2047                          or else Is_Local_Anonymous_Access (Btyp))
2048               and then Ekind (Entity (Prefix (Enc_Object))) in Formal_Kind
2049               and then Ekind (Etype (Entity (Prefix (Enc_Object))))
2050                          = E_Anonymous_Access_Type
2051               and then Present (Extra_Accessibility
2052                                 (Entity (Prefix (Enc_Object))))
2053             then
2054                Apply_Accessibility_Check (Prefix (Enc_Object), Typ, N);
2055
2056             --  Ada 2005 (AI-251): If the designated type is an interface we
2057             --  add an implicit conversion to force the displacement of the
2058             --  pointer to reference the secondary dispatch table.
2059
2060             elsif Is_Interface (Btyp_DDT)
2061               and then (Comes_From_Source (N)
2062                          or else Comes_From_Source (Ref_Object)
2063                          or else (Nkind (Ref_Object) in N_Has_Chars
2064                                    and then Chars (Ref_Object) = Name_uInit))
2065             then
2066                if Nkind (Ref_Object) /= N_Explicit_Dereference then
2067
2068                   --  No implicit conversion required if types match, or if
2069                   --  the prefix is the class_wide_type of the interface. In
2070                   --  either case passing an object of the interface type has
2071                   --  already set the pointer correctly.
2072
2073                   if Btyp_DDT = Etype (Ref_Object)
2074                     or else (Is_Class_Wide_Type (Etype (Ref_Object))
2075                               and then
2076                                Class_Wide_Type (Btyp_DDT) = Etype (Ref_Object))
2077                   then
2078                      null;
2079
2080                   else
2081                      Rewrite (Prefix (N),
2082                        Convert_To (Btyp_DDT,
2083                          New_Copy_Tree (Prefix (N))));
2084
2085                      Analyze_And_Resolve (Prefix (N), Btyp_DDT);
2086                   end if;
2087
2088                --  When the object is an explicit dereference, convert the
2089                --  dereference's prefix.
2090
2091                else
2092                   declare
2093                      Obj_DDT : constant Entity_Id :=
2094                                  Base_Type
2095                                    (Directly_Designated_Type
2096                                      (Etype (Prefix (Ref_Object))));
2097                   begin
2098                      --  No implicit conversion required if designated types
2099                      --  match, or if we have an unrestricted access.
2100
2101                      if Obj_DDT /= Btyp_DDT
2102                        and then Id /= Attribute_Unrestricted_Access
2103                        and then not (Is_Class_Wide_Type (Obj_DDT)
2104                                       and then Etype (Obj_DDT) = Btyp_DDT)
2105                      then
2106                         Rewrite (N,
2107                           Convert_To (Typ,
2108                             New_Copy_Tree (Prefix (Ref_Object))));
2109                         Analyze_And_Resolve (N, Typ);
2110                      end if;
2111                   end;
2112                end if;
2113             end if;
2114          end Access_Cases;
2115
2116       --------------
2117       -- Adjacent --
2118       --------------
2119
2120       --  Transforms 'Adjacent into a call to the floating-point attribute
2121       --  function Adjacent in Fat_xxx (where xxx is the root type)
2122
2123       when Attribute_Adjacent =>
2124          Expand_Fpt_Attribute_RR (N);
2125
2126       -------------
2127       -- Address --
2128       -------------
2129
2130       when Attribute_Address => Address : declare
2131          Task_Proc : Entity_Id;
2132
2133       begin
2134          --  If the prefix is a task or a task type, the useful address is that
2135          --  of the procedure for the task body, i.e. the actual program unit.
2136          --  We replace the original entity with that of the procedure.
2137
2138          if Is_Entity_Name (Pref)
2139            and then Is_Task_Type (Entity (Pref))
2140          then
2141             Task_Proc := Next_Entity (Root_Type (Ptyp));
2142
2143             while Present (Task_Proc) loop
2144                exit when Ekind (Task_Proc) = E_Procedure
2145                  and then Etype (First_Formal (Task_Proc)) =
2146                                   Corresponding_Record_Type (Ptyp);
2147                Next_Entity (Task_Proc);
2148             end loop;
2149
2150             if Present (Task_Proc) then
2151                Set_Entity (Pref, Task_Proc);
2152                Set_Etype  (Pref, Etype (Task_Proc));
2153             end if;
2154
2155          --  Similarly, the address of a protected operation is the address
2156          --  of the corresponding protected body, regardless of the protected
2157          --  object from which it is selected.
2158
2159          elsif Nkind (Pref) = N_Selected_Component
2160            and then Is_Subprogram (Entity (Selector_Name (Pref)))
2161            and then Is_Protected_Type (Scope (Entity (Selector_Name (Pref))))
2162          then
2163             Rewrite (Pref,
2164               New_Occurrence_Of (
2165                 External_Subprogram (Entity (Selector_Name (Pref))), Loc));
2166
2167          elsif Nkind (Pref) = N_Explicit_Dereference
2168            and then Ekind (Ptyp) = E_Subprogram_Type
2169            and then Convention (Ptyp) = Convention_Protected
2170          then
2171             --  The prefix is be a dereference of an access_to_protected_
2172             --  subprogram. The desired address is the second component of
2173             --  the record that represents the access.
2174
2175             declare
2176                Addr : constant Entity_Id := Etype (N);
2177                Ptr  : constant Node_Id   := Prefix (Pref);
2178                T    : constant Entity_Id :=
2179                         Equivalent_Type (Base_Type (Etype (Ptr)));
2180
2181             begin
2182                Rewrite (N,
2183                  Unchecked_Convert_To (Addr,
2184                    Make_Selected_Component (Loc,
2185                      Prefix => Unchecked_Convert_To (T, Ptr),
2186                      Selector_Name => New_Occurrence_Of (
2187                        Next_Entity (First_Entity (T)), Loc))));
2188
2189                Analyze_And_Resolve (N, Addr);
2190             end;
2191
2192          --  Ada 2005 (AI-251): Class-wide interface objects are always
2193          --  "displaced" to reference the tag associated with the interface
2194          --  type. In order to obtain the real address of such objects we
2195          --  generate a call to a run-time subprogram that returns the base
2196          --  address of the object.
2197
2198          --  This processing is not needed in the VM case, where dispatching
2199          --  issues are taken care of by the virtual machine.
2200
2201          elsif Is_Class_Wide_Type (Ptyp)
2202            and then Is_Interface (Ptyp)
2203            and then Tagged_Type_Expansion
2204            and then not (Nkind (Pref) in N_Has_Entity
2205                           and then Is_Subprogram (Entity (Pref)))
2206          then
2207             Rewrite (N,
2208               Make_Function_Call (Loc,
2209                 Name => New_Occurrence_Of (RTE (RE_Base_Address), Loc),
2210                 Parameter_Associations => New_List (
2211                   Relocate_Node (N))));
2212             Analyze (N);
2213             return;
2214          end if;
2215
2216          --  Deal with packed array reference, other cases are handled by
2217          --  the back end.
2218
2219          if Involves_Packed_Array_Reference (Pref) then
2220             Expand_Packed_Address_Reference (N);
2221          end if;
2222       end Address;
2223
2224       ---------------
2225       -- Alignment --
2226       ---------------
2227
2228       when Attribute_Alignment => Alignment : declare
2229          New_Node : Node_Id;
2230
2231       begin
2232          --  For class-wide types, X'Class'Alignment is transformed into a
2233          --  direct reference to the Alignment of the class type, so that the
2234          --  back end does not have to deal with the X'Class'Alignment
2235          --  reference.
2236
2237          if Is_Entity_Name (Pref)
2238            and then Is_Class_Wide_Type (Entity (Pref))
2239          then
2240             Rewrite (Prefix (N), New_Occurrence_Of (Entity (Pref), Loc));
2241             return;
2242
2243          --  For x'Alignment applied to an object of a class wide type,
2244          --  transform X'Alignment into a call to the predefined primitive
2245          --  operation _Alignment applied to X.
2246
2247          elsif Is_Class_Wide_Type (Ptyp) then
2248             New_Node :=
2249               Make_Attribute_Reference (Loc,
2250                 Prefix         => Pref,
2251                 Attribute_Name => Name_Tag);
2252
2253             New_Node := Build_Get_Alignment (Loc, New_Node);
2254
2255             --  Case where the context is a specific integer type with which
2256             --  the original attribute was compatible. The function has a
2257             --  specific type as well, so to preserve the compatibility we
2258             --  must convert explicitly.
2259
2260             if Typ /= Standard_Integer then
2261                New_Node := Convert_To (Typ, New_Node);
2262             end if;
2263
2264             Rewrite (N, New_Node);
2265             Analyze_And_Resolve (N, Typ);
2266             return;
2267
2268          --  For all other cases, we just have to deal with the case of
2269          --  the fact that the result can be universal.
2270
2271          else
2272             Apply_Universal_Integer_Attribute_Checks (N);
2273          end if;
2274       end Alignment;
2275
2276       ---------
2277       -- Bit --
2278       ---------
2279
2280       --  We compute this if a packed array reference was present, otherwise we
2281       --  leave the computation up to the back end.
2282
2283       when Attribute_Bit =>
2284          if Involves_Packed_Array_Reference (Pref) then
2285             Expand_Packed_Bit_Reference (N);
2286          else
2287             Apply_Universal_Integer_Attribute_Checks (N);
2288          end if;
2289
2290       ------------------
2291       -- Bit_Position --
2292       ------------------
2293
2294       --  We compute this if a component clause was present, otherwise we leave
2295       --  the computation up to the back end, since we don't know what layout
2296       --  will be chosen.
2297
2298       --  Note that the attribute can apply to a naked record component
2299       --  in generated code (i.e. the prefix is an identifier that
2300       --  references the component or discriminant entity).
2301
2302       when Attribute_Bit_Position => Bit_Position : declare
2303          CE : Entity_Id;
2304
2305       begin
2306          if Nkind (Pref) = N_Identifier then
2307             CE := Entity (Pref);
2308          else
2309             CE := Entity (Selector_Name (Pref));
2310          end if;
2311
2312          if Known_Static_Component_Bit_Offset (CE) then
2313             Rewrite (N,
2314               Make_Integer_Literal (Loc,
2315                 Intval => Component_Bit_Offset (CE)));
2316             Analyze_And_Resolve (N, Typ);
2317
2318          else
2319             Apply_Universal_Integer_Attribute_Checks (N);
2320          end if;
2321       end Bit_Position;
2322
2323       ------------------
2324       -- Body_Version --
2325       ------------------
2326
2327       --  A reference to P'Body_Version or P'Version is expanded to
2328
2329       --     Vnn : Unsigned;
2330       --     pragma Import (C, Vnn, "uuuuT");
2331       --     ...
2332       --     Get_Version_String (Vnn)
2333
2334       --  where uuuu is the unit name (dots replaced by double underscore)
2335       --  and T is B for the cases of Body_Version, or Version applied to a
2336       --  subprogram acting as its own spec, and S for Version applied to a
2337       --  subprogram spec or package. This sequence of code references the
2338       --  unsigned constant created in the main program by the binder.
2339
2340       --  A special exception occurs for Standard, where the string returned
2341       --  is a copy of the library string in gnatvsn.ads.
2342
2343       when Attribute_Body_Version | Attribute_Version => Version : declare
2344          E    : constant Entity_Id := Make_Temporary (Loc, 'V');
2345          Pent : Entity_Id;
2346          S    : String_Id;
2347
2348       begin
2349          --  If not library unit, get to containing library unit
2350
2351          Pent := Entity (Pref);
2352          while Pent /= Standard_Standard
2353            and then Scope (Pent) /= Standard_Standard
2354            and then not Is_Child_Unit (Pent)
2355          loop
2356             Pent := Scope (Pent);
2357          end loop;
2358
2359          --  Special case Standard and Standard.ASCII
2360
2361          if Pent = Standard_Standard or else Pent = Standard_ASCII then
2362             Rewrite (N,
2363               Make_String_Literal (Loc,
2364                 Strval => Verbose_Library_Version));
2365
2366          --  All other cases
2367
2368          else
2369             --  Build required string constant
2370
2371             Get_Name_String (Get_Unit_Name (Pent));
2372
2373             Start_String;
2374             for J in 1 .. Name_Len - 2 loop
2375                if Name_Buffer (J) = '.' then
2376                   Store_String_Chars ("__");
2377                else
2378                   Store_String_Char (Get_Char_Code (Name_Buffer (J)));
2379                end if;
2380             end loop;
2381
2382             --  Case of subprogram acting as its own spec, always use body
2383
2384             if Nkind (Declaration_Node (Pent)) in N_Subprogram_Specification
2385               and then Nkind (Parent (Declaration_Node (Pent))) =
2386                                                           N_Subprogram_Body
2387               and then Acts_As_Spec (Parent (Declaration_Node (Pent)))
2388             then
2389                Store_String_Chars ("B");
2390
2391             --  Case of no body present, always use spec
2392
2393             elsif not Unit_Requires_Body (Pent) then
2394                Store_String_Chars ("S");
2395
2396             --  Otherwise use B for Body_Version, S for spec
2397
2398             elsif Id = Attribute_Body_Version then
2399                Store_String_Chars ("B");
2400             else
2401                Store_String_Chars ("S");
2402             end if;
2403
2404             S := End_String;
2405             Lib.Version_Referenced (S);
2406
2407             --  Insert the object declaration
2408
2409             Insert_Actions (N, New_List (
2410               Make_Object_Declaration (Loc,
2411                 Defining_Identifier => E,
2412                 Object_Definition   =>
2413                   New_Occurrence_Of (RTE (RE_Unsigned), Loc))));
2414
2415             --  Set entity as imported with correct external name
2416
2417             Set_Is_Imported (E);
2418             Set_Interface_Name (E, Make_String_Literal (Loc, S));
2419
2420             --  Set entity as internal to ensure proper Sprint output of its
2421             --  implicit importation.
2422
2423             Set_Is_Internal (E);
2424
2425             --  And now rewrite original reference
2426
2427             Rewrite (N,
2428               Make_Function_Call (Loc,
2429                 Name => New_Occurrence_Of (RTE (RE_Get_Version_String), Loc),
2430                 Parameter_Associations => New_List (
2431                   New_Occurrence_Of (E, Loc))));
2432          end if;
2433
2434          Analyze_And_Resolve (N, RTE (RE_Version_String));
2435       end Version;
2436
2437       -------------
2438       -- Ceiling --
2439       -------------
2440
2441       --  Transforms 'Ceiling into a call to the floating-point attribute
2442       --  function Ceiling in Fat_xxx (where xxx is the root type)
2443
2444       when Attribute_Ceiling =>
2445          Expand_Fpt_Attribute_R (N);
2446
2447       --------------
2448       -- Callable --
2449       --------------
2450
2451       --  Transforms 'Callable attribute into a call to the Callable function
2452
2453       when Attribute_Callable => Callable :
2454       begin
2455          --  We have an object of a task interface class-wide type as a prefix
2456          --  to Callable. Generate:
2457          --    callable (Task_Id (Pref._disp_get_task_id));
2458
2459          if Ada_Version >= Ada_2005
2460            and then Ekind (Ptyp) = E_Class_Wide_Type
2461            and then Is_Interface (Ptyp)
2462            and then Is_Task_Interface (Ptyp)
2463          then
2464             Rewrite (N,
2465               Make_Function_Call (Loc,
2466                 Name =>
2467                   New_Occurrence_Of (RTE (RE_Callable), Loc),
2468                 Parameter_Associations => New_List (
2469                   Make_Unchecked_Type_Conversion (Loc,
2470                     Subtype_Mark =>
2471                       New_Occurrence_Of (RTE (RO_ST_Task_Id), Loc),
2472                     Expression =>
2473                       Make_Selected_Component (Loc,
2474                         Prefix =>
2475                           New_Copy_Tree (Pref),
2476                         Selector_Name =>
2477                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id))))));
2478
2479          else
2480             Rewrite (N,
2481               Build_Call_With_Task (Pref, RTE (RE_Callable)));
2482          end if;
2483
2484          Analyze_And_Resolve (N, Standard_Boolean);
2485       end Callable;
2486
2487       ------------
2488       -- Caller --
2489       ------------
2490
2491       --  Transforms 'Caller attribute into a call to either the
2492       --  Task_Entry_Caller or the Protected_Entry_Caller function.
2493
2494       when Attribute_Caller => Caller : declare
2495          Id_Kind    : constant Entity_Id := RTE (RO_AT_Task_Id);
2496          Ent        : constant Entity_Id := Entity (Pref);
2497          Conctype   : constant Entity_Id := Scope (Ent);
2498          Nest_Depth : Integer := 0;
2499          Name       : Node_Id;
2500          S          : Entity_Id;
2501
2502       begin
2503          --  Protected case
2504
2505          if Is_Protected_Type (Conctype) then
2506             case Corresponding_Runtime_Package (Conctype) is
2507                when System_Tasking_Protected_Objects_Entries =>
2508                   Name :=
2509                     New_Occurrence_Of
2510                       (RTE (RE_Protected_Entry_Caller), Loc);
2511
2512                when System_Tasking_Protected_Objects_Single_Entry =>
2513                   Name :=
2514                     New_Occurrence_Of
2515                       (RTE (RE_Protected_Single_Entry_Caller), Loc);
2516
2517                when others =>
2518                   raise Program_Error;
2519             end case;
2520
2521             Rewrite (N,
2522               Unchecked_Convert_To (Id_Kind,
2523                 Make_Function_Call (Loc,
2524                   Name => Name,
2525                   Parameter_Associations => New_List (
2526                     New_Occurrence_Of
2527                       (Find_Protection_Object (Current_Scope), Loc)))));
2528
2529          --  Task case
2530
2531          else
2532             --  Determine the nesting depth of the E'Caller attribute, that
2533             --  is, how many accept statements are nested within the accept
2534             --  statement for E at the point of E'Caller. The runtime uses
2535             --  this depth to find the specified entry call.
2536
2537             for J in reverse 0 .. Scope_Stack.Last loop
2538                S := Scope_Stack.Table (J).Entity;
2539
2540                --  We should not reach the scope of the entry, as it should
2541                --  already have been checked in Sem_Attr that this attribute
2542                --  reference is within a matching accept statement.
2543
2544                pragma Assert (S /= Conctype);
2545
2546                if S = Ent then
2547                   exit;
2548
2549                elsif Is_Entry (S) then
2550                   Nest_Depth := Nest_Depth + 1;
2551                end if;
2552             end loop;
2553
2554             Rewrite (N,
2555               Unchecked_Convert_To (Id_Kind,
2556                 Make_Function_Call (Loc,
2557                   Name =>
2558                     New_Occurrence_Of (RTE (RE_Task_Entry_Caller), Loc),
2559                   Parameter_Associations => New_List (
2560                     Make_Integer_Literal (Loc,
2561                       Intval => Int (Nest_Depth))))));
2562          end if;
2563
2564          Analyze_And_Resolve (N, Id_Kind);
2565       end Caller;
2566
2567       -------------
2568       -- Compose --
2569       -------------
2570
2571       --  Transforms 'Compose into a call to the floating-point attribute
2572       --  function Compose in Fat_xxx (where xxx is the root type)
2573
2574       --  Note: we strictly should have special code here to deal with the
2575       --  case of absurdly negative arguments (less than Integer'First)
2576       --  which will return a (signed) zero value, but it hardly seems
2577       --  worth the effort. Absurdly large positive arguments will raise
2578       --  constraint error which is fine.
2579
2580       when Attribute_Compose =>
2581          Expand_Fpt_Attribute_RI (N);
2582
2583       -----------------
2584       -- Constrained --
2585       -----------------
2586
2587       when Attribute_Constrained => Constrained : declare
2588          Formal_Ent : constant Entity_Id := Param_Entity (Pref);
2589
2590          function Is_Constrained_Aliased_View (Obj : Node_Id) return Boolean;
2591          --  Ada 2005 (AI-363): Returns True if the object name Obj denotes a
2592          --  view of an aliased object whose subtype is constrained.
2593
2594          ---------------------------------
2595          -- Is_Constrained_Aliased_View --
2596          ---------------------------------
2597
2598          function Is_Constrained_Aliased_View (Obj : Node_Id) return Boolean is
2599             E : Entity_Id;
2600
2601          begin
2602             if Is_Entity_Name (Obj) then
2603                E := Entity (Obj);
2604
2605                if Present (Renamed_Object (E)) then
2606                   return Is_Constrained_Aliased_View (Renamed_Object (E));
2607                else
2608                   return Is_Aliased (E) and then Is_Constrained (Etype (E));
2609                end if;
2610
2611             else
2612                return Is_Aliased_View (Obj)
2613                         and then
2614                       (Is_Constrained (Etype (Obj))
2615                          or else
2616                            (Nkind (Obj) = N_Explicit_Dereference
2617                               and then
2618                                 not Object_Type_Has_Constrained_Partial_View
2619                                       (Typ  => Base_Type (Etype (Obj)),
2620                                        Scop => Current_Scope)));
2621             end if;
2622          end Is_Constrained_Aliased_View;
2623
2624       --  Start of processing for Constrained
2625
2626       begin
2627          --  Reference to a parameter where the value is passed as an extra
2628          --  actual, corresponding to the extra formal referenced by the
2629          --  Extra_Constrained field of the corresponding formal. If this
2630          --  is an entry in-parameter, it is replaced by a constant renaming
2631          --  for which Extra_Constrained is never created.
2632
2633          if Present (Formal_Ent)
2634            and then Ekind (Formal_Ent) /= E_Constant
2635            and then Present (Extra_Constrained (Formal_Ent))
2636          then
2637             Rewrite (N,
2638               New_Occurrence_Of
2639                 (Extra_Constrained (Formal_Ent), Sloc (N)));
2640
2641          --  For variables with a Extra_Constrained field, we use the
2642          --  corresponding entity.
2643
2644          elsif Nkind (Pref) = N_Identifier
2645            and then Ekind (Entity (Pref)) = E_Variable
2646            and then Present (Extra_Constrained (Entity (Pref)))
2647          then
2648             Rewrite (N,
2649               New_Occurrence_Of
2650                 (Extra_Constrained (Entity (Pref)), Sloc (N)));
2651
2652          --  For all other entity names, we can tell at compile time
2653
2654          elsif Is_Entity_Name (Pref) then
2655             declare
2656                Ent : constant Entity_Id   := Entity (Pref);
2657                Res : Boolean;
2658
2659             begin
2660                --  (RM J.4) obsolescent cases
2661
2662                if Is_Type (Ent) then
2663
2664                   --  Private type
2665
2666                   if Is_Private_Type (Ent) then
2667                      Res := not Has_Discriminants (Ent)
2668                               or else Is_Constrained (Ent);
2669
2670                   --  It not a private type, must be a generic actual type
2671                   --  that corresponded to a private type. We know that this
2672                   --  correspondence holds, since otherwise the reference
2673                   --  within the generic template would have been illegal.
2674
2675                   else
2676                      if Is_Composite_Type (Underlying_Type (Ent)) then
2677                         Res := Is_Constrained (Ent);
2678                      else
2679                         Res := True;
2680                      end if;
2681                   end if;
2682
2683                --  If the prefix is not a variable or is aliased, then
2684                --  definitely true; if it's a formal parameter without an
2685                --  associated extra formal, then treat it as constrained.
2686
2687                --  Ada 2005 (AI-363): An aliased prefix must be known to be
2688                --  constrained in order to set the attribute to True.
2689
2690                elsif not Is_Variable (Pref)
2691                  or else Present (Formal_Ent)
2692                  or else (Ada_Version < Ada_2005
2693                             and then Is_Aliased_View (Pref))
2694                  or else (Ada_Version >= Ada_2005
2695                             and then Is_Constrained_Aliased_View (Pref))
2696                then
2697                   Res := True;
2698
2699                --  Variable case, look at type to see if it is constrained.
2700                --  Note that the one case where this is not accurate (the
2701                --  procedure formal case), has been handled above.
2702
2703                --  We use the Underlying_Type here (and below) in case the
2704                --  type is private without discriminants, but the full type
2705                --  has discriminants. This case is illegal, but we generate it
2706                --  internally for passing to the Extra_Constrained parameter.
2707
2708                else
2709                   --  In Ada 2012, test for case of a limited tagged type, in
2710                   --  which case the attribute is always required to return
2711                   --  True. The underlying type is tested, to make sure we also
2712                   --  return True for cases where there is an unconstrained
2713                   --  object with an untagged limited partial view which has
2714                   --  defaulted discriminants (such objects always produce a
2715                   --  False in earlier versions of Ada). (Ada 2012: AI05-0214)
2716
2717                   Res := Is_Constrained (Underlying_Type (Etype (Ent)))
2718                            or else
2719                              (Ada_Version >= Ada_2012
2720                                and then Is_Tagged_Type (Underlying_Type (Ptyp))
2721                                and then Is_Limited_Type (Ptyp));
2722                end if;
2723
2724                Rewrite (N, New_Occurrence_Of (Boolean_Literals (Res), Loc));
2725             end;
2726
2727          --  Prefix is not an entity name. These are also cases where we can
2728          --  always tell at compile time by looking at the form and type of the
2729          --  prefix. If an explicit dereference of an object with constrained
2730          --  partial view, this is unconstrained (Ada 2005: AI95-0363). If the
2731          --  underlying type is a limited tagged type, then Constrained is
2732          --  required to always return True (Ada 2012: AI05-0214).
2733
2734          else
2735             Rewrite (N,
2736               New_Occurrence_Of (
2737                 Boolean_Literals (
2738                   not Is_Variable (Pref)
2739                     or else
2740                      (Nkind (Pref) = N_Explicit_Dereference
2741                        and then
2742                          not Object_Type_Has_Constrained_Partial_View
2743                                (Typ  => Base_Type (Ptyp),
2744                                 Scop => Current_Scope))
2745                     or else Is_Constrained (Underlying_Type (Ptyp))
2746                     or else (Ada_Version >= Ada_2012
2747                               and then Is_Tagged_Type (Underlying_Type (Ptyp))
2748                               and then Is_Limited_Type (Ptyp))),
2749                 Loc));
2750          end if;
2751
2752          Analyze_And_Resolve (N, Standard_Boolean);
2753       end Constrained;
2754
2755       ---------------
2756       -- Copy_Sign --
2757       ---------------
2758
2759       --  Transforms 'Copy_Sign into a call to the floating-point attribute
2760       --  function Copy_Sign in Fat_xxx (where xxx is the root type)
2761
2762       when Attribute_Copy_Sign =>
2763          Expand_Fpt_Attribute_RR (N);
2764
2765       -----------
2766       -- Count --
2767       -----------
2768
2769       --  Transforms 'Count attribute into a call to the Count function
2770
2771       when Attribute_Count => Count : declare
2772          Call     : Node_Id;
2773          Conctyp  : Entity_Id;
2774          Entnam   : Node_Id;
2775          Entry_Id : Entity_Id;
2776          Index    : Node_Id;
2777          Name     : Node_Id;
2778
2779       begin
2780          --  If the prefix is a member of an entry family, retrieve both
2781          --  entry name and index. For a simple entry there is no index.
2782
2783          if Nkind (Pref) = N_Indexed_Component then
2784             Entnam := Prefix (Pref);
2785             Index := First (Expressions (Pref));
2786          else
2787             Entnam := Pref;
2788             Index := Empty;
2789          end if;
2790
2791          Entry_Id := Entity (Entnam);
2792
2793          --  Find the concurrent type in which this attribute is referenced
2794          --  (there had better be one).
2795
2796          Conctyp := Current_Scope;
2797          while not Is_Concurrent_Type (Conctyp) loop
2798             Conctyp := Scope (Conctyp);
2799          end loop;
2800
2801          --  Protected case
2802
2803          if Is_Protected_Type (Conctyp) then
2804             case Corresponding_Runtime_Package (Conctyp) is
2805                when System_Tasking_Protected_Objects_Entries =>
2806                   Name := New_Occurrence_Of (RTE (RE_Protected_Count), Loc);
2807
2808                   Call :=
2809                     Make_Function_Call (Loc,
2810                       Name => Name,
2811                       Parameter_Associations => New_List (
2812                         New_Occurrence_Of
2813                           (Find_Protection_Object (Current_Scope), Loc),
2814                         Entry_Index_Expression
2815                           (Loc, Entry_Id, Index, Scope (Entry_Id))));
2816
2817                when System_Tasking_Protected_Objects_Single_Entry =>
2818                   Name :=
2819                     New_Occurrence_Of (RTE (RE_Protected_Count_Entry), Loc);
2820
2821                   Call :=
2822                     Make_Function_Call (Loc,
2823                       Name => Name,
2824                       Parameter_Associations => New_List (
2825                         New_Occurrence_Of
2826                           (Find_Protection_Object (Current_Scope), Loc)));
2827
2828                when others =>
2829                   raise Program_Error;
2830             end case;
2831
2832          --  Task case
2833
2834          else
2835             Call :=
2836               Make_Function_Call (Loc,
2837                 Name => New_Occurrence_Of (RTE (RE_Task_Count), Loc),
2838                 Parameter_Associations => New_List (
2839                   Entry_Index_Expression (Loc,
2840                     Entry_Id, Index, Scope (Entry_Id))));
2841          end if;
2842
2843          --  The call returns type Natural but the context is universal integer
2844          --  so any integer type is allowed. The attribute was already resolved
2845          --  so its Etype is the required result type. If the base type of the
2846          --  context type is other than Standard.Integer we put in a conversion
2847          --  to the required type. This can be a normal typed conversion since
2848          --  both input and output types of the conversion are integer types
2849
2850          if Base_Type (Typ) /= Base_Type (Standard_Integer) then
2851             Rewrite (N, Convert_To (Typ, Call));
2852          else
2853             Rewrite (N, Call);
2854          end if;
2855
2856          Analyze_And_Resolve (N, Typ);
2857       end Count;
2858
2859       ---------------------
2860       -- Descriptor_Size --
2861       ---------------------
2862
2863       when Attribute_Descriptor_Size =>
2864
2865          --  Attribute Descriptor_Size is handled by the back end when applied
2866          --  to an unconstrained array type.
2867
2868          if Is_Array_Type (Ptyp)
2869            and then not Is_Constrained (Ptyp)
2870          then
2871             Apply_Universal_Integer_Attribute_Checks (N);
2872
2873          --  For any other type, the descriptor size is 0 because there is no
2874          --  actual descriptor, but the result is not formally static.
2875
2876          else
2877             Rewrite (N, Make_Integer_Literal (Loc, 0));
2878             Analyze (N);
2879             Set_Is_Static_Expression (N, False);
2880          end if;
2881
2882       ---------------
2883       -- Elab_Body --
2884       ---------------
2885
2886       --  This processing is shared by Elab_Spec
2887
2888       --  What we do is to insert the following declarations
2889
2890       --     procedure tnn;
2891       --     pragma Import (C, enn, "name___elabb/s");
2892
2893       --  and then the Elab_Body/Spec attribute is replaced by a reference
2894       --  to this defining identifier.
2895
2896       when Attribute_Elab_Body      |
2897            Attribute_Elab_Spec      =>
2898
2899          --  Leave attribute unexpanded in CodePeer mode: the gnat2scil
2900          --  back-end knows how to handle these attributes directly.
2901
2902          if CodePeer_Mode then
2903             return;
2904          end if;
2905
2906          Elab_Body : declare
2907             Ent  : constant Entity_Id := Make_Temporary (Loc, 'E');
2908             Str  : String_Id;
2909             Lang : Node_Id;
2910
2911             procedure Make_Elab_String (Nod : Node_Id);
2912             --  Given Nod, an identifier, or a selected component, put the
2913             --  image into the current string literal, with double underline
2914             --  between components.
2915
2916             ----------------------
2917             -- Make_Elab_String --
2918             ----------------------
2919
2920             procedure Make_Elab_String (Nod : Node_Id) is
2921             begin
2922                if Nkind (Nod) = N_Selected_Component then
2923                   Make_Elab_String (Prefix (Nod));
2924                   Store_String_Char ('_');
2925                   Store_String_Char ('_');
2926                   Get_Name_String (Chars (Selector_Name (Nod)));
2927
2928                else
2929                   pragma Assert (Nkind (Nod) = N_Identifier);
2930                   Get_Name_String (Chars (Nod));
2931                end if;
2932
2933                Store_String_Chars (Name_Buffer (1 .. Name_Len));
2934             end Make_Elab_String;
2935
2936          --  Start of processing for Elab_Body/Elab_Spec
2937
2938          begin
2939             --  First we need to prepare the string literal for the name of
2940             --  the elaboration routine to be referenced.
2941
2942             Start_String;
2943             Make_Elab_String (Pref);
2944             Store_String_Chars ("___elab");
2945             Lang := Make_Identifier (Loc, Name_C);
2946
2947             if Id = Attribute_Elab_Body then
2948                Store_String_Char ('b');
2949             else
2950                Store_String_Char ('s');
2951             end if;
2952
2953             Str := End_String;
2954
2955             Insert_Actions (N, New_List (
2956               Make_Subprogram_Declaration (Loc,
2957                 Specification =>
2958                   Make_Procedure_Specification (Loc,
2959                     Defining_Unit_Name => Ent)),
2960
2961               Make_Pragma (Loc,
2962                 Chars                        => Name_Import,
2963                 Pragma_Argument_Associations => New_List (
2964                   Make_Pragma_Argument_Association (Loc, Expression => Lang),
2965
2966                   Make_Pragma_Argument_Association (Loc,
2967                     Expression => Make_Identifier (Loc, Chars (Ent))),
2968
2969                   Make_Pragma_Argument_Association (Loc,
2970                     Expression => Make_String_Literal (Loc, Str))))));
2971
2972             Set_Entity (N, Ent);
2973             Rewrite (N, New_Occurrence_Of (Ent, Loc));
2974          end Elab_Body;
2975
2976       --------------------
2977       -- Elab_Subp_Body --
2978       --------------------
2979
2980       --  Always ignored. In CodePeer mode, gnat2scil knows how to handle
2981       --  this attribute directly, and if we are not in CodePeer mode it is
2982       --  entirely ignored ???
2983
2984       when Attribute_Elab_Subp_Body =>
2985          return;
2986
2987       ----------------
2988       -- Elaborated --
2989       ----------------
2990
2991       --  Elaborated is always True for preelaborated units, predefined units,
2992       --  pure units and units which have Elaborate_Body pragmas. These units
2993       --  have no elaboration entity.
2994
2995       --  Note: The Elaborated attribute is never passed to the back end
2996
2997       when Attribute_Elaborated => Elaborated : declare
2998          Ent : constant Entity_Id := Entity (Pref);
2999
3000       begin
3001          if Present (Elaboration_Entity (Ent)) then
3002             Rewrite (N,
3003               Make_Op_Ne (Loc,
3004                 Left_Opnd =>
3005                   New_Occurrence_Of (Elaboration_Entity (Ent), Loc),
3006                 Right_Opnd =>
3007                   Make_Integer_Literal (Loc, Uint_0)));
3008             Analyze_And_Resolve (N, Typ);
3009          else
3010             Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
3011          end if;
3012       end Elaborated;
3013
3014       --------------
3015       -- Enum_Rep --
3016       --------------
3017
3018       when Attribute_Enum_Rep => Enum_Rep : declare
3019          Expr : Node_Id;
3020
3021       begin
3022          --  Get the expression, which is X for Enum_Type'Enum_Rep (X) or
3023          --  X'Enum_Rep.
3024
3025          if Is_Non_Empty_List (Exprs) then
3026             Expr := First (Exprs);
3027          else
3028             Expr := Pref;
3029          end if;
3030
3031          --  If the expression is an enumeration literal, it is replaced by the
3032          --  literal value.
3033
3034          if Nkind (Expr) in N_Has_Entity
3035            and then Ekind (Entity (Expr)) = E_Enumeration_Literal
3036          then
3037             Rewrite (N,
3038               Make_Integer_Literal (Loc, Enumeration_Rep (Entity (Expr))));
3039
3040          --  If this is a renaming of a literal, recover the representation
3041          --  of the original. If it renames an expression there is nothing to
3042          --  fold.
3043
3044          elsif Nkind (Expr) in N_Has_Entity
3045            and then Ekind (Entity (Expr)) = E_Constant
3046            and then Present (Renamed_Object (Entity (Expr)))
3047            and then Is_Entity_Name (Renamed_Object (Entity (Expr)))
3048            and then Ekind (Entity (Renamed_Object (Entity (Expr)))) =
3049                       E_Enumeration_Literal
3050          then
3051             Rewrite (N,
3052               Make_Integer_Literal (Loc,
3053                 Enumeration_Rep (Entity (Renamed_Object (Entity (Expr))))));
3054
3055          --  If not constant-folded above, Enum_Type'Enum_Rep (X) or
3056          --  X'Enum_Rep expands to
3057
3058          --    target-type (X)
3059
3060          --  This is simply a direct conversion from the enumeration type to
3061          --  the target integer type, which is treated by the back end as a
3062          --  normal integer conversion, treating the enumeration type as an
3063          --  integer, which is exactly what we want. We set Conversion_OK to
3064          --  make sure that the analyzer does not complain about what otherwise
3065          --  might be an illegal conversion.
3066
3067          else
3068             Rewrite (N, OK_Convert_To (Typ, Relocate_Node (Expr)));
3069          end if;
3070
3071          Set_Etype (N, Typ);
3072          Analyze_And_Resolve (N, Typ);
3073       end Enum_Rep;
3074
3075       --------------
3076       -- Enum_Val --
3077       --------------
3078
3079       when Attribute_Enum_Val => Enum_Val : declare
3080          Expr : Node_Id;
3081          Btyp : constant Entity_Id  := Base_Type (Ptyp);
3082
3083       begin
3084          --  X'Enum_Val (Y) expands to
3085
3086          --    [constraint_error when _rep_to_pos (Y, False) = -1, msg]
3087          --    X!(Y);
3088
3089          Expr := Unchecked_Convert_To (Ptyp, First (Exprs));
3090
3091          Insert_Action (N,
3092            Make_Raise_Constraint_Error (Loc,
3093              Condition =>
3094                Make_Op_Eq (Loc,
3095                  Left_Opnd =>
3096                    Make_Function_Call (Loc,
3097                      Name =>
3098                        New_Occurrence_Of (TSS (Btyp, TSS_Rep_To_Pos), Loc),
3099                      Parameter_Associations => New_List (
3100                        Relocate_Node (Duplicate_Subexpr (Expr)),
3101                          New_Occurrence_Of (Standard_False, Loc))),
3102
3103                  Right_Opnd => Make_Integer_Literal (Loc, -1)),
3104              Reason => CE_Range_Check_Failed));
3105
3106          Rewrite (N, Expr);
3107          Analyze_And_Resolve (N, Ptyp);
3108       end Enum_Val;
3109
3110       --------------
3111       -- Exponent --
3112       --------------
3113
3114       --  Transforms 'Exponent into a call to the floating-point attribute
3115       --  function Exponent in Fat_xxx (where xxx is the root type)
3116
3117       when Attribute_Exponent =>
3118          Expand_Fpt_Attribute_R (N);
3119
3120       ------------------
3121       -- External_Tag --
3122       ------------------
3123
3124       --  transforme X'External_Tag into Ada.Tags.External_Tag (X'tag)
3125
3126       when Attribute_External_Tag => External_Tag :
3127       begin
3128          Rewrite (N,
3129            Make_Function_Call (Loc,
3130              Name => New_Occurrence_Of (RTE (RE_External_Tag), Loc),
3131              Parameter_Associations => New_List (
3132                Make_Attribute_Reference (Loc,
3133                  Attribute_Name => Name_Tag,
3134                  Prefix => Prefix (N)))));
3135
3136          Analyze_And_Resolve (N, Standard_String);
3137       end External_Tag;
3138
3139       -----------------------
3140       -- Finalization_Size --
3141       -----------------------
3142
3143       when Attribute_Finalization_Size => Finalization_Size : declare
3144          function Calculate_Header_Size return Node_Id;
3145          --  Generate a runtime call to calculate the size of the hidden header
3146          --  along with any added padding which would precede a heap-allocated
3147          --  object of the prefix type.
3148
3149          ---------------------------
3150          -- Calculate_Header_Size --
3151          ---------------------------
3152
3153          function Calculate_Header_Size return Node_Id is
3154          begin
3155             --  Generate:
3156             --    Universal_Integer
3157             --      (Header_Size_With_Padding (Pref'Alignment))
3158
3159             return
3160               Convert_To (Universal_Integer,
3161                 Make_Function_Call (Loc,
3162                   Name                   =>
3163                     New_Occurrence_Of (RTE (RE_Header_Size_With_Padding), Loc),
3164
3165                   Parameter_Associations => New_List (
3166                     Make_Attribute_Reference (Loc,
3167                       Prefix         => New_Copy_Tree (Pref),
3168                       Attribute_Name => Name_Alignment))));
3169          end Calculate_Header_Size;
3170
3171          --  Local variables
3172
3173          Size : Entity_Id;
3174
3175       --  Start of Finalization_Size
3176
3177       begin
3178          --  An object of a class-wide type first requires a runtime check to
3179          --  determine whether it is actually controlled or not. Depending on
3180          --  the outcome of this check, the Finalization_Size of the object
3181          --  may be zero or some positive value.
3182          --
3183          --  In this scenario, Pref'Finalization_Size is expanded into
3184          --
3185          --    Size : Integer := 0;
3186          --
3187          --    if Needs_Finalization (Pref'Tag) then
3188          --       Size :=
3189          --         Universal_Integer
3190          --           (Header_Size_With_Padding (Pref'Alignment));
3191          --    end if;
3192          --
3193          --  and the attribute reference is replaced with a reference to Size.
3194
3195          if Is_Class_Wide_Type (Ptyp) then
3196             Size := Make_Temporary (Loc, 'S');
3197
3198             Insert_Actions (N, New_List (
3199
3200               --  Generate:
3201               --    Size : Integer := 0;
3202
3203               Make_Object_Declaration (Loc,
3204                 Defining_Identifier => Size,
3205                 Object_Definition   =>
3206                   New_Occurrence_Of (Standard_Integer, Loc),
3207                 Expression          => Make_Integer_Literal (Loc, 0)),
3208
3209               --  Generate:
3210               --    if Needs_Finalization (Pref'Tag) then
3211               --       Size :=
3212               --         Universal_Integer
3213               --           (Header_Size_With_Padding (Pref'Alignment));
3214               --    end if;
3215
3216               Make_If_Statement (Loc,
3217                 Condition              =>
3218                   Make_Function_Call (Loc,
3219                     Name                   =>
3220                       New_Occurrence_Of (RTE (RE_Needs_Finalization), Loc),
3221
3222                     Parameter_Associations => New_List (
3223                       Make_Attribute_Reference (Loc,
3224                         Prefix         => New_Copy_Tree (Pref),
3225                         Attribute_Name => Name_Tag))),
3226
3227                 Then_Statements        => New_List (
3228                    Make_Assignment_Statement (Loc,
3229                      Name       => New_Occurrence_Of (Size, Loc),
3230                      Expression => Calculate_Header_Size)))));
3231
3232             Rewrite (N, New_Occurrence_Of (Size, Loc));
3233
3234          --  The prefix is known to be controlled at compile time. Calculate
3235          --  Finalization_Size by calling function Header_Size_With_Padding.
3236
3237          elsif Needs_Finalization (Ptyp) then
3238             Rewrite (N, Calculate_Header_Size);
3239
3240          --  The prefix is not an object with controlled parts, so its
3241          --  Finalization_Size is zero.
3242
3243          else
3244             Rewrite (N, Make_Integer_Literal (Loc, 0));
3245          end if;
3246
3247          Analyze (N);
3248       end Finalization_Size;
3249
3250       -----------
3251       -- First --
3252       -----------
3253
3254       when Attribute_First =>
3255
3256          --  If the prefix type is a constrained packed array type which
3257          --  already has a Packed_Array_Impl_Type representation defined, then
3258          --  replace this attribute with a direct reference to 'First of the
3259          --  appropriate index subtype (since otherwise the back end will try
3260          --  to give us the value of 'First for this implementation type).
3261
3262          if Is_Constrained_Packed_Array (Ptyp) then
3263             Rewrite (N,
3264               Make_Attribute_Reference (Loc,
3265                 Attribute_Name => Name_First,
3266                 Prefix         =>
3267                   New_Occurrence_Of (Get_Index_Subtype (N), Loc)));
3268             Analyze_And_Resolve (N, Typ);
3269
3270          --  For access type, apply access check as needed
3271
3272          elsif Is_Access_Type (Ptyp) then
3273             Apply_Access_Check (N);
3274
3275          --  For scalar type, if low bound is a reference to an entity, just
3276          --  replace with a direct reference. Note that we can only have a
3277          --  reference to a constant entity at this stage, anything else would
3278          --  have already been rewritten.
3279
3280          elsif Is_Scalar_Type (Ptyp) then
3281             declare
3282                Lo : constant Node_Id := Type_Low_Bound (Ptyp);
3283             begin
3284                if Is_Entity_Name (Lo) then
3285                   Rewrite (N, New_Occurrence_Of (Entity (Lo), Loc));
3286                end if;
3287             end;
3288          end if;
3289
3290       ---------------
3291       -- First_Bit --
3292       ---------------
3293
3294       --  Compute this if component clause was present, otherwise we leave the
3295       --  computation to be completed in the back-end, since we don't know what
3296       --  layout will be chosen.
3297
3298       when Attribute_First_Bit => First_Bit_Attr : declare
3299          CE : constant Entity_Id := Entity (Selector_Name (Pref));
3300
3301       begin
3302          --  In Ada 2005 (or later) if we have the non-default bit order, then
3303          --  we return the original value as given in the component clause
3304          --  (RM 2005 13.5.2(3/2)).
3305
3306          if Present (Component_Clause (CE))
3307            and then Ada_Version >= Ada_2005
3308            and then Reverse_Bit_Order (Scope (CE))
3309          then
3310             Rewrite (N,
3311               Make_Integer_Literal (Loc,
3312                 Intval => Expr_Value (First_Bit (Component_Clause (CE)))));
3313             Analyze_And_Resolve (N, Typ);
3314
3315          --  Otherwise (Ada 83/95 or Ada 2005 or later with default bit order),
3316          --  rewrite with normalized value if we know it statically.
3317
3318          elsif Known_Static_Component_Bit_Offset (CE) then
3319             Rewrite (N,
3320               Make_Integer_Literal (Loc,
3321                 Component_Bit_Offset (CE) mod System_Storage_Unit));
3322             Analyze_And_Resolve (N, Typ);
3323
3324          --  Otherwise left to back end, just do universal integer checks
3325
3326          else
3327             Apply_Universal_Integer_Attribute_Checks (N);
3328          end if;
3329       end First_Bit_Attr;
3330
3331       -----------------
3332       -- Fixed_Value --
3333       -----------------
3334
3335       --  We transform:
3336
3337       --     fixtype'Fixed_Value (integer-value)
3338
3339       --  into
3340
3341       --     fixtype(integer-value)
3342
3343       --  We do all the required analysis of the conversion here, because we do
3344       --  not want this to go through the fixed-point conversion circuits. Note
3345       --  that the back end always treats fixed-point as equivalent to the
3346       --  corresponding integer type anyway.
3347
3348       when Attribute_Fixed_Value => Fixed_Value :
3349       begin
3350          Rewrite (N,
3351            Make_Type_Conversion (Loc,
3352              Subtype_Mark => New_Occurrence_Of (Entity (Pref), Loc),
3353              Expression   => Relocate_Node (First (Exprs))));
3354          Set_Etype (N, Entity (Pref));
3355          Set_Analyzed (N);
3356
3357       --  Note: it might appear that a properly analyzed unchecked conversion
3358       --  would be just fine here, but that's not the case, since the full
3359       --  range checks performed by the following call are critical.
3360
3361          Apply_Type_Conversion_Checks (N);
3362       end Fixed_Value;
3363
3364       -----------
3365       -- Floor --
3366       -----------
3367
3368       --  Transforms 'Floor into a call to the floating-point attribute
3369       --  function Floor in Fat_xxx (where xxx is the root type)
3370
3371       when Attribute_Floor =>
3372          Expand_Fpt_Attribute_R (N);
3373
3374       ----------
3375       -- Fore --
3376       ----------
3377
3378       --  For the fixed-point type Typ:
3379
3380       --    Typ'Fore
3381
3382       --  expands into
3383
3384       --    Result_Type (System.Fore (Universal_Real (Type'First)),
3385       --                              Universal_Real (Type'Last))
3386
3387       --  Note that we know that the type is a non-static subtype, or Fore
3388       --  would have itself been computed dynamically in Eval_Attribute.
3389
3390       when Attribute_Fore => Fore : begin
3391          Rewrite (N,
3392            Convert_To (Typ,
3393              Make_Function_Call (Loc,
3394                Name => New_Occurrence_Of (RTE (RE_Fore), Loc),
3395
3396                Parameter_Associations => New_List (
3397                  Convert_To (Universal_Real,
3398                    Make_Attribute_Reference (Loc,
3399                      Prefix => New_Occurrence_Of (Ptyp, Loc),
3400                      Attribute_Name => Name_First)),
3401
3402                  Convert_To (Universal_Real,
3403                    Make_Attribute_Reference (Loc,
3404                      Prefix => New_Occurrence_Of (Ptyp, Loc),
3405                      Attribute_Name => Name_Last))))));
3406
3407          Analyze_And_Resolve (N, Typ);
3408       end Fore;
3409
3410       --------------
3411       -- Fraction --
3412       --------------
3413
3414       --  Transforms 'Fraction into a call to the floating-point attribute
3415       --  function Fraction in Fat_xxx (where xxx is the root type)
3416
3417       when Attribute_Fraction =>
3418          Expand_Fpt_Attribute_R (N);
3419
3420       --------------
3421       -- From_Any --
3422       --------------
3423
3424       when Attribute_From_Any => From_Any : declare
3425          P_Type : constant Entity_Id := Etype (Pref);
3426          Decls  : constant List_Id   := New_List;
3427       begin
3428          Rewrite (N,
3429            Build_From_Any_Call (P_Type,
3430              Relocate_Node (First (Exprs)),
3431              Decls));
3432          Insert_Actions (N, Decls);
3433          Analyze_And_Resolve (N, P_Type);
3434       end From_Any;
3435
3436       ----------------------
3437       -- Has_Same_Storage --
3438       ----------------------
3439
3440       when Attribute_Has_Same_Storage => Has_Same_Storage : declare
3441             Loc : constant Source_Ptr := Sloc (N);
3442
3443             X   : constant Node_Id := Prefix (N);
3444             Y   : constant Node_Id := First (Expressions (N));
3445             --  The arguments
3446
3447             X_Addr, Y_Addr : Node_Id;
3448             --  Rhe expressions for their addresses
3449
3450             X_Size, Y_Size : Node_Id;
3451             --  Rhe expressions for their sizes
3452
3453       begin
3454          --  The attribute is expanded as:
3455
3456          --    (X'address = Y'address)
3457          --      and then (X'Size = Y'Size)
3458
3459          --  If both arguments have the same Etype the second conjunct can be
3460          --  omitted.
3461
3462          X_Addr :=
3463            Make_Attribute_Reference (Loc,
3464                                      Attribute_Name => Name_Address,
3465                                      Prefix         => New_Copy_Tree (X));
3466
3467          Y_Addr :=
3468            Make_Attribute_Reference (Loc,
3469                                      Attribute_Name => Name_Address,
3470                                      Prefix         => New_Copy_Tree (Y));
3471
3472          X_Size :=
3473            Make_Attribute_Reference (Loc,
3474                                      Attribute_Name => Name_Size,
3475                                      Prefix         => New_Copy_Tree (X));
3476
3477          Y_Size :=
3478            Make_Attribute_Reference (Loc,
3479                                      Attribute_Name => Name_Size,
3480                                      Prefix         => New_Copy_Tree (Y));
3481
3482          if Etype (X) = Etype (Y) then
3483             Rewrite (N,
3484                      (Make_Op_Eq (Loc,
3485                       Left_Opnd  => X_Addr,
3486                       Right_Opnd => Y_Addr)));
3487          else
3488             Rewrite (N,
3489                      Make_Op_And (Loc,
3490                        Left_Opnd  =>
3491                          Make_Op_Eq (Loc,
3492                            Left_Opnd  => X_Addr,
3493                            Right_Opnd => Y_Addr),
3494                        Right_Opnd =>
3495                          Make_Op_Eq (Loc,
3496                            Left_Opnd  => X_Size,
3497                            Right_Opnd => Y_Size)));
3498          end if;
3499
3500          Analyze_And_Resolve (N, Standard_Boolean);
3501       end Has_Same_Storage;
3502
3503       --------------
3504       -- Identity --
3505       --------------
3506
3507       --  For an exception returns a reference to the exception data:
3508       --      Exception_Id!(Prefix'Reference)
3509
3510       --  For a task it returns a reference to the _task_id component of
3511       --  corresponding record:
3512
3513       --    taskV!(Prefix)._Task_Id, converted to the type Task_Id defined
3514
3515       --  in Ada.Task_Identification
3516
3517       when Attribute_Identity => Identity : declare
3518          Id_Kind : Entity_Id;
3519
3520       begin
3521          if Ptyp = Standard_Exception_Type then
3522             Id_Kind := RTE (RE_Exception_Id);
3523
3524             if Present (Renamed_Object (Entity (Pref))) then
3525                Set_Entity (Pref, Renamed_Object (Entity (Pref)));
3526             end if;
3527
3528             Rewrite (N,
3529               Unchecked_Convert_To (Id_Kind, Make_Reference (Loc, Pref)));
3530          else
3531             Id_Kind := RTE (RO_AT_Task_Id);
3532
3533             --  If the prefix is a task interface, the Task_Id is obtained
3534             --  dynamically through a dispatching call, as for other task
3535             --  attributes applied to interfaces.
3536
3537             if Ada_Version >= Ada_2005
3538               and then Ekind (Ptyp) = E_Class_Wide_Type
3539               and then Is_Interface (Ptyp)
3540               and then Is_Task_Interface (Ptyp)
3541             then
3542                Rewrite (N,
3543                  Unchecked_Convert_To (Id_Kind,
3544                    Make_Selected_Component (Loc,
3545                      Prefix =>
3546                        New_Copy_Tree (Pref),
3547                      Selector_Name =>
3548                        Make_Identifier (Loc, Name_uDisp_Get_Task_Id))));
3549
3550             else
3551                Rewrite (N,
3552                  Unchecked_Convert_To (Id_Kind, Concurrent_Ref (Pref)));
3553             end if;
3554          end if;
3555
3556          Analyze_And_Resolve (N, Id_Kind);
3557       end Identity;
3558
3559       -----------
3560       -- Image --
3561       -----------
3562
3563       --  Image attribute is handled in separate unit Exp_Imgv
3564
3565       when Attribute_Image =>
3566          Exp_Imgv.Expand_Image_Attribute (N);
3567
3568       ---------
3569       -- Img --
3570       ---------
3571
3572       --  X'Img is expanded to typ'Image (X), where typ is the type of X
3573
3574       when Attribute_Img => Img :
3575       begin
3576          Rewrite (N,
3577            Make_Attribute_Reference (Loc,
3578              Prefix         => New_Occurrence_Of (Ptyp, Loc),
3579              Attribute_Name => Name_Image,
3580              Expressions    => New_List (Relocate_Node (Pref))));
3581
3582          Analyze_And_Resolve (N, Standard_String);
3583       end Img;
3584
3585       -----------
3586       -- Input --
3587       -----------
3588
3589       when Attribute_Input => Input : declare
3590          P_Type : constant Entity_Id := Entity (Pref);
3591          B_Type : constant Entity_Id := Base_Type (P_Type);
3592          U_Type : constant Entity_Id := Underlying_Type (P_Type);
3593          Strm   : constant Node_Id   := First (Exprs);
3594          Fname  : Entity_Id;
3595          Decl   : Node_Id;
3596          Call   : Node_Id;
3597          Prag   : Node_Id;
3598          Arg2   : Node_Id;
3599          Rfunc  : Node_Id;
3600
3601          Cntrl  : Node_Id := Empty;
3602          --  Value for controlling argument in call. Always Empty except in
3603          --  the dispatching (class-wide type) case, where it is a reference
3604          --  to the dummy object initialized to the right internal tag.
3605
3606          procedure Freeze_Stream_Subprogram (F : Entity_Id);
3607          --  The expansion of the attribute reference may generate a call to
3608          --  a user-defined stream subprogram that is frozen by the call. This
3609          --  can lead to access-before-elaboration problem if the reference
3610          --  appears in an object declaration and the subprogram body has not
3611          --  been seen. The freezing of the subprogram requires special code
3612          --  because it appears in an expanded context where expressions do
3613          --  not freeze their constituents.
3614
3615          ------------------------------
3616          -- Freeze_Stream_Subprogram --
3617          ------------------------------
3618
3619          procedure Freeze_Stream_Subprogram (F : Entity_Id) is
3620             Decl : constant Node_Id := Unit_Declaration_Node (F);
3621             Bod  : Node_Id;
3622
3623          begin
3624             --  If this is user-defined subprogram, the corresponding
3625             --  stream function appears as a renaming-as-body, and the
3626             --  user subprogram must be retrieved by tree traversal.
3627
3628             if Present (Decl)
3629               and then Nkind (Decl) = N_Subprogram_Declaration
3630               and then Present (Corresponding_Body (Decl))
3631             then
3632                Bod := Corresponding_Body (Decl);
3633
3634                if Nkind (Unit_Declaration_Node (Bod)) =
3635                  N_Subprogram_Renaming_Declaration
3636                then
3637                   Set_Is_Frozen (Entity (Name (Unit_Declaration_Node (Bod))));
3638                end if;
3639             end if;
3640          end Freeze_Stream_Subprogram;
3641
3642       --  Start of processing for Input
3643
3644       begin
3645          --  If no underlying type, we have an error that will be diagnosed
3646          --  elsewhere, so here we just completely ignore the expansion.
3647
3648          if No (U_Type) then
3649             return;
3650          end if;
3651
3652          --  Stream operations can appear in user code even if the restriction
3653          --  No_Streams is active (for example, when instantiating a predefined
3654          --  container). In that case rewrite the attribute as a Raise to
3655          --  prevent any run-time use.
3656
3657          if Restriction_Active (No_Streams) then
3658             Rewrite (N,
3659               Make_Raise_Program_Error (Sloc (N),
3660                 Reason => PE_Stream_Operation_Not_Allowed));
3661             Set_Etype (N, B_Type);
3662             return;
3663          end if;
3664
3665          --  If there is a TSS for Input, just call it
3666
3667          Fname := Find_Stream_Subprogram (P_Type, TSS_Stream_Input);
3668
3669          if Present (Fname) then
3670             null;
3671
3672          else
3673             --  If there is a Stream_Convert pragma, use it, we rewrite
3674
3675             --     sourcetyp'Input (stream)
3676
3677             --  as
3678
3679             --     sourcetyp (streamread (strmtyp'Input (stream)));
3680
3681             --  where streamread 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 (extra conversion required for the derived case).
3684
3685             Prag := Get_Stream_Convert_Pragma (P_Type);
3686
3687             if Present (Prag) then
3688                Arg2  := Next (First (Pragma_Argument_Associations (Prag)));
3689                Rfunc := Entity (Expression (Arg2));
3690
3691                Rewrite (N,
3692                  Convert_To (B_Type,
3693                    Make_Function_Call (Loc,
3694                      Name => New_Occurrence_Of (Rfunc, Loc),
3695                      Parameter_Associations => New_List (
3696                        Make_Attribute_Reference (Loc,
3697                          Prefix =>
3698                            New_Occurrence_Of
3699                              (Etype (First_Formal (Rfunc)), Loc),
3700                          Attribute_Name => Name_Input,
3701                          Expressions => Exprs)))));
3702
3703                Analyze_And_Resolve (N, B_Type);
3704                return;
3705
3706             --  Elementary types
3707
3708             elsif Is_Elementary_Type (U_Type) then
3709
3710                --  A special case arises if we have a defined _Read routine,
3711                --  since in this case we are required to call this routine.
3712
3713                if Present (TSS (Base_Type (U_Type), TSS_Stream_Read)) then
3714                   Build_Record_Or_Elementary_Input_Function
3715                     (Loc, U_Type, Decl, Fname);
3716                   Insert_Action (N, Decl);
3717
3718                --  For normal cases, we call the I_xxx routine directly
3719
3720                else
3721                   Rewrite (N, Build_Elementary_Input_Call (N));
3722                   Analyze_And_Resolve (N, P_Type);
3723                   return;
3724                end if;
3725
3726             --  Array type case
3727
3728             elsif Is_Array_Type (U_Type) then
3729                Build_Array_Input_Function (Loc, U_Type, Decl, Fname);
3730                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
3731
3732             --  Dispatching case with class-wide type
3733
3734             elsif Is_Class_Wide_Type (P_Type) then
3735
3736                --  No need to do anything else compiling under restriction
3737                --  No_Dispatching_Calls. During the semantic analysis we
3738                --  already notified such violation.
3739
3740                if Restriction_Active (No_Dispatching_Calls) then
3741                   return;
3742                end if;
3743
3744                declare
3745                   Rtyp : constant Entity_Id := Root_Type (P_Type);
3746                   Expr : Node_Id;
3747
3748                begin
3749                   --  Read the internal tag (RM 13.13.2(34)) and use it to
3750                   --  initialize a dummy tag value:
3751
3752                   --     Descendant_Tag (String'Input (Strm), P_Type);
3753
3754                   --  This value is used only to provide a controlling
3755                   --  argument for the eventual _Input call. Descendant_Tag is
3756                   --  called rather than Internal_Tag to ensure that we have a
3757                   --  tag for a type that is descended from the prefix type and
3758                   --  declared at the same accessibility level (the exception
3759                   --  Tag_Error will be raised otherwise). The level check is
3760                   --  required for Ada 2005 because tagged types can be
3761                   --  extended in nested scopes (AI-344).
3762
3763                   --  Note: we used to generate an explicit declaration of a
3764                   --  constant Ada.Tags.Tag object, and use an occurrence of
3765                   --  this constant in Cntrl, but this caused a secondary stack
3766                   --  leak.
3767
3768                   Expr :=
3769                     Make_Function_Call (Loc,
3770                       Name                   =>
3771                         New_Occurrence_Of (RTE (RE_Descendant_Tag), Loc),
3772                       Parameter_Associations => New_List (
3773                         Make_Attribute_Reference (Loc,
3774                           Prefix         =>
3775                             New_Occurrence_Of (Standard_String, Loc),
3776                           Attribute_Name => Name_Input,
3777                           Expressions    => New_List (
3778                             Relocate_Node (Duplicate_Subexpr (Strm)))),
3779                         Make_Attribute_Reference (Loc,
3780                           Prefix         => New_Occurrence_Of (P_Type, Loc),
3781                           Attribute_Name => Name_Tag)));
3782                   Set_Etype (Expr, RTE (RE_Tag));
3783
3784                   --  Now we need to get the entity for the call, and construct
3785                   --  a function call node, where we preset a reference to Dnn
3786                   --  as the controlling argument (doing an unchecked convert
3787                   --  to the class-wide tagged type to make it look like a real
3788                   --  tagged object).
3789
3790                   Fname := Find_Prim_Op (Rtyp, TSS_Stream_Input);
3791                   Cntrl := Unchecked_Convert_To (P_Type, Expr);
3792                   Set_Etype (Cntrl, P_Type);
3793                   Set_Parent (Cntrl, N);
3794                end;
3795
3796             --  For tagged types, use the primitive Input function
3797
3798             elsif Is_Tagged_Type (U_Type) then
3799                Fname := Find_Prim_Op (U_Type, TSS_Stream_Input);
3800
3801             --  All other record type cases, including protected records. The
3802             --  latter only arise for expander generated code for handling
3803             --  shared passive partition access.
3804
3805             else
3806                pragma Assert
3807                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
3808
3809                --  Ada 2005 (AI-216): Program_Error is raised executing default
3810                --  implementation of the Input attribute of an unchecked union
3811                --  type if the type lacks default discriminant values.
3812
3813                if Is_Unchecked_Union (Base_Type (U_Type))
3814                  and then No (Discriminant_Constraint (U_Type))
3815                then
3816                   Insert_Action (N,
3817                     Make_Raise_Program_Error (Loc,
3818                       Reason => PE_Unchecked_Union_Restriction));
3819
3820                   return;
3821                end if;
3822
3823                --  Build the type's Input function, passing the subtype rather
3824                --  than its base type, because checks are needed in the case of
3825                --  constrained discriminants (see Ada 2012 AI05-0192).
3826
3827                Build_Record_Or_Elementary_Input_Function
3828                  (Loc, U_Type, Decl, Fname);
3829                Insert_Action (N, Decl);
3830
3831                if Nkind (Parent (N)) = N_Object_Declaration
3832                  and then Is_Record_Type (U_Type)
3833                then
3834                   --  The stream function may contain calls to user-defined
3835                   --  Read procedures for individual components.
3836
3837                   declare
3838                      Comp : Entity_Id;
3839                      Func : Entity_Id;
3840
3841                   begin
3842                      Comp := First_Component (U_Type);
3843                      while Present (Comp) loop
3844                         Func :=
3845                           Find_Stream_Subprogram
3846                             (Etype (Comp), TSS_Stream_Read);
3847
3848                         if Present (Func) then
3849                            Freeze_Stream_Subprogram (Func);
3850                         end if;
3851
3852                         Next_Component (Comp);
3853                      end loop;
3854                   end;
3855                end if;
3856             end if;
3857          end if;
3858
3859          --  If we fall through, Fname is the function to be called. The result
3860          --  is obtained by calling the appropriate function, then converting
3861          --  the result. The conversion does a subtype check.
3862
3863          Call :=
3864            Make_Function_Call (Loc,
3865              Name => New_Occurrence_Of (Fname, Loc),
3866              Parameter_Associations => New_List (
3867                 Relocate_Node (Strm)));
3868
3869          Set_Controlling_Argument (Call, Cntrl);
3870          Rewrite (N, Unchecked_Convert_To (P_Type, Call));
3871          Analyze_And_Resolve (N, P_Type);
3872
3873          if Nkind (Parent (N)) = N_Object_Declaration then
3874             Freeze_Stream_Subprogram (Fname);
3875          end if;
3876       end Input;
3877
3878       -------------------
3879       -- Integer_Value --
3880       -------------------
3881
3882       --  We transform
3883
3884       --    inttype'Fixed_Value (fixed-value)
3885
3886       --  into
3887
3888       --    inttype(integer-value))
3889
3890       --  we do all the required analysis of the conversion here, because we do
3891       --  not want this to go through the fixed-point conversion circuits. Note
3892       --  that the back end always treats fixed-point as equivalent to the
3893       --  corresponding integer type anyway.
3894
3895       when Attribute_Integer_Value => Integer_Value :
3896       begin
3897          Rewrite (N,
3898            Make_Type_Conversion (Loc,
3899              Subtype_Mark => New_Occurrence_Of (Entity (Pref), Loc),
3900              Expression   => Relocate_Node (First (Exprs))));
3901          Set_Etype (N, Entity (Pref));
3902          Set_Analyzed (N);
3903
3904       --  Note: it might appear that a properly analyzed unchecked conversion
3905       --  would be just fine here, but that's not the case, since the full
3906       --  range checks performed by the following call are critical.
3907
3908          Apply_Type_Conversion_Checks (N);
3909       end Integer_Value;
3910
3911       -------------------
3912       -- Invalid_Value --
3913       -------------------
3914
3915       when Attribute_Invalid_Value =>
3916          Rewrite (N, Get_Simple_Init_Val (Ptyp, N));
3917
3918       ----------
3919       -- Last --
3920       ----------
3921
3922       when Attribute_Last =>
3923
3924          --  If the prefix type is a constrained packed array type which
3925          --  already has a Packed_Array_Impl_Type representation defined, then
3926          --  replace this attribute with a direct reference to 'Last of the
3927          --  appropriate index subtype (since otherwise the back end will try
3928          --  to give us the value of 'Last for this implementation type).
3929
3930          if Is_Constrained_Packed_Array (Ptyp) then
3931             Rewrite (N,
3932               Make_Attribute_Reference (Loc,
3933                 Attribute_Name => Name_Last,
3934                 Prefix => New_Occurrence_Of (Get_Index_Subtype (N), Loc)));
3935             Analyze_And_Resolve (N, Typ);
3936
3937          --  For access type, apply access check as needed
3938
3939          elsif Is_Access_Type (Ptyp) then
3940             Apply_Access_Check (N);
3941
3942          --  For scalar type, if low bound is a reference to an entity, just
3943          --  replace with a direct reference. Note that we can only have a
3944          --  reference to a constant entity at this stage, anything else would
3945          --  have already been rewritten.
3946
3947          elsif Is_Scalar_Type (Ptyp) then
3948             declare
3949                Hi : constant Node_Id := Type_High_Bound (Ptyp);
3950             begin
3951                if Is_Entity_Name (Hi) then
3952                   Rewrite (N, New_Occurrence_Of (Entity (Hi), Loc));
3953                end if;
3954             end;
3955          end if;
3956
3957       --------------
3958       -- Last_Bit --
3959       --------------
3960
3961       --  We compute this if a component clause was present, otherwise we leave
3962       --  the computation up to the back end, since we don't know what layout
3963       --  will be chosen.
3964
3965       when Attribute_Last_Bit => Last_Bit_Attr : declare
3966          CE : constant Entity_Id := Entity (Selector_Name (Pref));
3967
3968       begin
3969          --  In Ada 2005 (or later) if we have the non-default bit order, then
3970          --  we return the original value as given in the component clause
3971          --  (RM 2005 13.5.2(3/2)).
3972
3973          if Present (Component_Clause (CE))
3974            and then Ada_Version >= Ada_2005
3975            and then Reverse_Bit_Order (Scope (CE))
3976          then
3977             Rewrite (N,
3978               Make_Integer_Literal (Loc,
3979                 Intval => Expr_Value (Last_Bit (Component_Clause (CE)))));
3980             Analyze_And_Resolve (N, Typ);
3981
3982          --  Otherwise (Ada 83/95 or Ada 2005 or later with default bit order),
3983          --  rewrite with normalized value if we know it statically.
3984
3985          elsif Known_Static_Component_Bit_Offset (CE)
3986            and then Known_Static_Esize (CE)
3987          then
3988             Rewrite (N,
3989               Make_Integer_Literal (Loc,
3990                Intval => (Component_Bit_Offset (CE) mod System_Storage_Unit)
3991                                 + Esize (CE) - 1));
3992             Analyze_And_Resolve (N, Typ);
3993
3994          --  Otherwise leave to back end, just apply universal integer checks
3995
3996          else
3997             Apply_Universal_Integer_Attribute_Checks (N);
3998          end if;
3999       end Last_Bit_Attr;
4000
4001       ------------------
4002       -- Leading_Part --
4003       ------------------
4004
4005       --  Transforms 'Leading_Part into a call to the floating-point attribute
4006       --  function Leading_Part in Fat_xxx (where xxx is the root type)
4007
4008       --  Note: strictly, we should generate special case code to deal with
4009       --  absurdly large positive arguments (greater than Integer'Last), which
4010       --  result in returning the first argument unchanged, but it hardly seems
4011       --  worth the effort. We raise constraint error for absurdly negative
4012       --  arguments which is fine.
4013
4014       when Attribute_Leading_Part =>
4015          Expand_Fpt_Attribute_RI (N);
4016
4017       ------------
4018       -- Length --
4019       ------------
4020
4021       when Attribute_Length => Length : declare
4022          Ityp : Entity_Id;
4023          Xnum : Uint;
4024
4025       begin
4026          --  Processing for packed array types
4027
4028          if Is_Array_Type (Ptyp) and then Is_Packed (Ptyp) then
4029             Ityp := Get_Index_Subtype (N);
4030
4031             --  If the index type, Ityp, is an enumeration type with holes,
4032             --  then we calculate X'Length explicitly using
4033
4034             --     Typ'Max
4035             --       (0, Ityp'Pos (X'Last  (N)) -
4036             --           Ityp'Pos (X'First (N)) + 1);
4037
4038             --  Since the bounds in the template are the representation values
4039             --  and the back end would get the wrong value.
4040
4041             if Is_Enumeration_Type (Ityp)
4042               and then Present (Enum_Pos_To_Rep (Base_Type (Ityp)))
4043             then
4044                if No (Exprs) then
4045                   Xnum := Uint_1;
4046                else
4047                   Xnum := Expr_Value (First (Expressions (N)));
4048                end if;
4049
4050                Rewrite (N,
4051                  Make_Attribute_Reference (Loc,
4052                    Prefix         => New_Occurrence_Of (Typ, Loc),
4053                    Attribute_Name => Name_Max,
4054                    Expressions    => New_List
4055                      (Make_Integer_Literal (Loc, 0),
4056
4057                       Make_Op_Add (Loc,
4058                         Left_Opnd =>
4059                           Make_Op_Subtract (Loc,
4060                             Left_Opnd =>
4061                               Make_Attribute_Reference (Loc,
4062                                 Prefix => New_Occurrence_Of (Ityp, Loc),
4063                                 Attribute_Name => Name_Pos,
4064
4065                                 Expressions => New_List (
4066                                   Make_Attribute_Reference (Loc,
4067                                     Prefix => Duplicate_Subexpr (Pref),
4068                                    Attribute_Name => Name_Last,
4069                                     Expressions => New_List (
4070                                       Make_Integer_Literal (Loc, Xnum))))),
4071
4072                             Right_Opnd =>
4073                               Make_Attribute_Reference (Loc,
4074                                 Prefix => New_Occurrence_Of (Ityp, Loc),
4075                                 Attribute_Name => Name_Pos,
4076
4077                                 Expressions => New_List (
4078                                   Make_Attribute_Reference (Loc,
4079                                     Prefix =>
4080                                       Duplicate_Subexpr_No_Checks (Pref),
4081                                    Attribute_Name => Name_First,
4082                                     Expressions => New_List (
4083                                       Make_Integer_Literal (Loc, Xnum)))))),
4084
4085                         Right_Opnd => Make_Integer_Literal (Loc, 1)))));
4086
4087                Analyze_And_Resolve (N, Typ, Suppress => All_Checks);
4088                return;
4089
4090             --  If the prefix type is a constrained packed array type which
4091             --  already has a Packed_Array_Impl_Type representation defined,
4092             --  then replace this attribute with a reference to 'Range_Length
4093             --  of the appropriate index subtype (since otherwise the
4094             --  back end will try to give us the value of 'Length for
4095             --  this implementation type).s
4096
4097             elsif Is_Constrained (Ptyp) then
4098                Rewrite (N,
4099                  Make_Attribute_Reference (Loc,
4100                    Attribute_Name => Name_Range_Length,
4101                    Prefix => New_Occurrence_Of (Ityp, Loc)));
4102                Analyze_And_Resolve (N, Typ);
4103             end if;
4104
4105          --  Access type case
4106
4107          elsif Is_Access_Type (Ptyp) then
4108             Apply_Access_Check (N);
4109
4110             --  If the designated type is a packed array type, then we convert
4111             --  the reference to:
4112
4113             --    typ'Max (0, 1 +
4114             --                xtyp'Pos (Pref'Last (Expr)) -
4115             --                xtyp'Pos (Pref'First (Expr)));
4116
4117             --  This is a bit complex, but it is the easiest thing to do that
4118             --  works in all cases including enum types with holes xtyp here
4119             --  is the appropriate index type.
4120
4121             declare
4122                Dtyp : constant Entity_Id := Designated_Type (Ptyp);
4123                Xtyp : Entity_Id;
4124
4125             begin
4126                if Is_Array_Type (Dtyp) and then Is_Packed (Dtyp) then
4127                   Xtyp := Get_Index_Subtype (N);
4128
4129                   Rewrite (N,
4130                     Make_Attribute_Reference (Loc,
4131                       Prefix         => New_Occurrence_Of (Typ, Loc),
4132                       Attribute_Name => Name_Max,
4133                       Expressions    => New_List (
4134                         Make_Integer_Literal (Loc, 0),
4135
4136                         Make_Op_Add (Loc,
4137                           Make_Integer_Literal (Loc, 1),
4138                           Make_Op_Subtract (Loc,
4139                             Left_Opnd =>
4140                               Make_Attribute_Reference (Loc,
4141                                 Prefix => New_Occurrence_Of (Xtyp, Loc),
4142                                 Attribute_Name => Name_Pos,
4143                                 Expressions    => New_List (
4144                                   Make_Attribute_Reference (Loc,
4145                                     Prefix => Duplicate_Subexpr (Pref),
4146                                     Attribute_Name => Name_Last,
4147                                     Expressions =>
4148                                       New_Copy_List (Exprs)))),
4149
4150                             Right_Opnd =>
4151                               Make_Attribute_Reference (Loc,
4152                                 Prefix => New_Occurrence_Of (Xtyp, Loc),
4153                                 Attribute_Name => Name_Pos,
4154                                 Expressions    => New_List (
4155                                   Make_Attribute_Reference (Loc,
4156                                     Prefix =>
4157                                       Duplicate_Subexpr_No_Checks (Pref),
4158                                     Attribute_Name => Name_First,
4159                                     Expressions =>
4160                                       New_Copy_List (Exprs)))))))));
4161
4162                   Analyze_And_Resolve (N, Typ);
4163                end if;
4164             end;
4165
4166          --  Otherwise leave it to the back end
4167
4168          else
4169             Apply_Universal_Integer_Attribute_Checks (N);
4170          end if;
4171       end Length;
4172
4173       --  Attribute Loop_Entry is replaced with a reference to a constant value
4174       --  which captures the prefix at the entry point of the related loop. The
4175       --  loop itself may be transformed into a conditional block.
4176
4177       when Attribute_Loop_Entry =>
4178          Expand_Loop_Entry_Attribute (N);
4179
4180       -------------
4181       -- Machine --
4182       -------------
4183
4184       --  Transforms 'Machine into a call to the floating-point attribute
4185       --  function Machine in Fat_xxx (where xxx is the root type).
4186       --  Expansion is avoided for cases the back end can handle directly.
4187
4188       when Attribute_Machine =>
4189          if not Is_Inline_Floating_Point_Attribute (N) then
4190             Expand_Fpt_Attribute_R (N);
4191          end if;
4192
4193       ----------------------
4194       -- Machine_Rounding --
4195       ----------------------
4196
4197       --  Transforms 'Machine_Rounding into a call to the floating-point
4198       --  attribute function Machine_Rounding in Fat_xxx (where xxx is the root
4199       --  type). Expansion is avoided for cases the back end can handle
4200       --  directly.
4201
4202       when Attribute_Machine_Rounding =>
4203          if not Is_Inline_Floating_Point_Attribute (N) then
4204             Expand_Fpt_Attribute_R (N);
4205          end if;
4206
4207       ------------------
4208       -- Machine_Size --
4209       ------------------
4210
4211       --  Machine_Size is equivalent to Object_Size, so transform it into
4212       --  Object_Size and that way the back end never sees Machine_Size.
4213
4214       when Attribute_Machine_Size =>
4215          Rewrite (N,
4216            Make_Attribute_Reference (Loc,
4217              Prefix => Prefix (N),
4218              Attribute_Name => Name_Object_Size));
4219
4220          Analyze_And_Resolve (N, Typ);
4221
4222       --------------
4223       -- Mantissa --
4224       --------------
4225
4226       --  The only case that can get this far is the dynamic case of the old
4227       --  Ada 83 Mantissa attribute for the fixed-point case. For this case,
4228       --  we expand:
4229
4230       --    typ'Mantissa
4231
4232       --  into
4233
4234       --    ityp (System.Mantissa.Mantissa_Value
4235       --           (Integer'Integer_Value (typ'First),
4236       --            Integer'Integer_Value (typ'Last)));
4237
4238       when Attribute_Mantissa => Mantissa : begin
4239          Rewrite (N,
4240            Convert_To (Typ,
4241              Make_Function_Call (Loc,
4242                Name => New_Occurrence_Of (RTE (RE_Mantissa_Value), Loc),
4243
4244                Parameter_Associations => New_List (
4245
4246                  Make_Attribute_Reference (Loc,
4247                    Prefix => New_Occurrence_Of (Standard_Integer, Loc),
4248                    Attribute_Name => Name_Integer_Value,
4249                    Expressions => New_List (
4250
4251                      Make_Attribute_Reference (Loc,
4252                        Prefix => New_Occurrence_Of (Ptyp, Loc),
4253                        Attribute_Name => Name_First))),
4254
4255                  Make_Attribute_Reference (Loc,
4256                    Prefix => New_Occurrence_Of (Standard_Integer, Loc),
4257                    Attribute_Name => Name_Integer_Value,
4258                    Expressions => New_List (
4259
4260                      Make_Attribute_Reference (Loc,
4261                        Prefix => New_Occurrence_Of (Ptyp, Loc),
4262                        Attribute_Name => Name_Last)))))));
4263
4264          Analyze_And_Resolve (N, Typ);
4265       end Mantissa;
4266
4267       ---------
4268       -- Max --
4269       ---------
4270
4271       when Attribute_Max =>
4272          Expand_Min_Max_Attribute (N);
4273
4274       ----------------------------------
4275       -- Max_Size_In_Storage_Elements --
4276       ----------------------------------
4277
4278       when Attribute_Max_Size_In_Storage_Elements => declare
4279          Typ  : constant Entity_Id := Etype (N);
4280          Attr : Node_Id;
4281
4282          Conversion_Added : Boolean := False;
4283          --  A flag which tracks whether the original attribute has been
4284          --  wrapped inside a type conversion.
4285
4286       begin
4287          --  If the prefix is X'Class, we transform it into a direct reference
4288          --  to the class-wide type, because the back end must not see a 'Class
4289          --  reference. See also 'Size.
4290
4291          if Is_Entity_Name (Pref)
4292            and then Is_Class_Wide_Type (Entity (Pref))
4293          then
4294             Rewrite (Prefix (N), New_Occurrence_Of (Entity (Pref), Loc));
4295             return;
4296          end if;
4297
4298          Apply_Universal_Integer_Attribute_Checks (N);
4299
4300          --  The universal integer check may sometimes add a type conversion,
4301          --  retrieve the original attribute reference from the expression.
4302
4303          Attr := N;
4304
4305          if Nkind (Attr) = N_Type_Conversion then
4306             Attr := Expression (Attr);
4307             Conversion_Added := True;
4308          end if;
4309
4310          pragma Assert (Nkind (Attr) = N_Attribute_Reference);
4311
4312          --  Heap-allocated controlled objects contain two extra pointers which
4313          --  are not part of the actual type. Transform the attribute reference
4314          --  into a runtime expression to add the size of the hidden header.
4315
4316          if Needs_Finalization (Ptyp)
4317            and then not Header_Size_Added (Attr)
4318          then
4319             Set_Header_Size_Added (Attr);
4320
4321             --  Generate:
4322             --    P'Max_Size_In_Storage_Elements +
4323             --      Universal_Integer
4324             --        (Header_Size_With_Padding (Ptyp'Alignment))
4325
4326             Rewrite (Attr,
4327               Make_Op_Add (Loc,
4328                 Left_Opnd  => Relocate_Node (Attr),
4329                 Right_Opnd =>
4330                   Convert_To (Universal_Integer,
4331                     Make_Function_Call (Loc,
4332                       Name                   =>
4333                         New_Occurrence_Of
4334                           (RTE (RE_Header_Size_With_Padding), Loc),
4335
4336                       Parameter_Associations => New_List (
4337                         Make_Attribute_Reference (Loc,
4338                           Prefix         =>
4339                             New_Occurrence_Of (Ptyp, Loc),
4340                           Attribute_Name => Name_Alignment))))));
4341
4342             --  Add a conversion to the target type
4343
4344             if not Conversion_Added then
4345                Rewrite (Attr,
4346                  Make_Type_Conversion (Loc,
4347                    Subtype_Mark => New_Occurrence_Of (Typ, Loc),
4348                    Expression   => Relocate_Node (Attr)));
4349             end if;
4350
4351             Analyze (Attr);
4352             return;
4353          end if;
4354       end;
4355
4356       --------------------
4357       -- Mechanism_Code --
4358       --------------------
4359
4360       when Attribute_Mechanism_Code =>
4361
4362          --  We must replace the prefix i the renamed case
4363
4364          if Is_Entity_Name (Pref)
4365            and then Present (Alias (Entity (Pref)))
4366          then
4367             Set_Renamed_Subprogram (Pref, Alias (Entity (Pref)));
4368          end if;
4369
4370       ---------
4371       -- Min --
4372       ---------
4373
4374       when Attribute_Min =>
4375          Expand_Min_Max_Attribute (N);
4376
4377       ---------
4378       -- Mod --
4379       ---------
4380
4381       when Attribute_Mod => Mod_Case : declare
4382          Arg  : constant Node_Id := Relocate_Node (First (Exprs));
4383          Hi   : constant Node_Id := Type_High_Bound (Etype (Arg));
4384          Modv : constant Uint    := Modulus (Btyp);
4385
4386       begin
4387
4388          --  This is not so simple. The issue is what type to use for the
4389          --  computation of the modular value.
4390
4391          --  The easy case is when the modulus value is within the bounds
4392          --  of the signed integer type of the argument. In this case we can
4393          --  just do the computation in that signed integer type, and then
4394          --  do an ordinary conversion to the target type.
4395
4396          if Modv <= Expr_Value (Hi) then
4397             Rewrite (N,
4398               Convert_To (Btyp,
4399                 Make_Op_Mod (Loc,
4400                   Left_Opnd  => Arg,
4401                   Right_Opnd => Make_Integer_Literal (Loc, Modv))));
4402
4403          --  Here we know that the modulus is larger than type'Last of the
4404          --  integer type. There are two cases to consider:
4405
4406          --    a) The integer value is non-negative. In this case, it is
4407          --    returned as the result (since it is less than the modulus).
4408
4409          --    b) The integer value is negative. In this case, we know that the
4410          --    result is modulus + value, where the value might be as small as
4411          --    -modulus. The trouble is what type do we use to do the subtract.
4412          --    No type will do, since modulus can be as big as 2**64, and no
4413          --    integer type accommodates this value. Let's do bit of algebra
4414
4415          --         modulus + value
4416          --      =  modulus - (-value)
4417          --      =  (modulus - 1) - (-value - 1)
4418
4419          --    Now modulus - 1 is certainly in range of the modular type.
4420          --    -value is in the range 1 .. modulus, so -value -1 is in the
4421          --    range 0 .. modulus-1 which is in range of the modular type.
4422          --    Furthermore, (-value - 1) can be expressed as -(value + 1)
4423          --    which we can compute using the integer base type.
4424
4425          --  Once this is done we analyze the if expression without range
4426          --  checks, because we know everything is in range, and we want
4427          --  to prevent spurious warnings on either branch.
4428
4429          else
4430             Rewrite (N,
4431               Make_If_Expression (Loc,
4432                 Expressions => New_List (
4433                   Make_Op_Ge (Loc,
4434                     Left_Opnd  => Duplicate_Subexpr (Arg),
4435                     Right_Opnd => Make_Integer_Literal (Loc, 0)),
4436
4437                   Convert_To (Btyp,
4438                     Duplicate_Subexpr_No_Checks (Arg)),
4439
4440                   Make_Op_Subtract (Loc,
4441                     Left_Opnd =>
4442                       Make_Integer_Literal (Loc,
4443                         Intval => Modv - 1),
4444                     Right_Opnd =>
4445                       Convert_To (Btyp,
4446                         Make_Op_Minus (Loc,
4447                           Right_Opnd =>
4448                             Make_Op_Add (Loc,
4449                               Left_Opnd  => Duplicate_Subexpr_No_Checks (Arg),
4450                               Right_Opnd =>
4451                                 Make_Integer_Literal (Loc,
4452                                   Intval => 1))))))));
4453
4454          end if;
4455
4456          Analyze_And_Resolve (N, Btyp, Suppress => All_Checks);
4457       end Mod_Case;
4458
4459       -----------
4460       -- Model --
4461       -----------
4462
4463       --  Transforms 'Model into a call to the floating-point attribute
4464       --  function Model in Fat_xxx (where xxx is the root type).
4465       --  Expansion is avoided for cases the back end can handle directly.
4466
4467       when Attribute_Model =>
4468          if not Is_Inline_Floating_Point_Attribute (N) then
4469             Expand_Fpt_Attribute_R (N);
4470          end if;
4471
4472       -----------------
4473       -- Object_Size --
4474       -----------------
4475
4476       --  The processing for Object_Size shares the processing for Size
4477
4478       ---------
4479       -- Old --
4480       ---------
4481
4482       when Attribute_Old => Old : declare
4483          Typ     : constant Entity_Id := Etype (N);
4484          CW_Temp : Entity_Id;
4485          CW_Typ  : Entity_Id;
4486          Ins_Nod : Node_Id;
4487          Subp    : Node_Id;
4488          Temp    : Entity_Id;
4489
4490       begin
4491          --  Generating C code we don't need to expand this attribute when
4492          --  we are analyzing the internally built nested postconditions
4493          --  procedure since it will be expanded inline (and later it will
4494          --  be removed by Expand_N_Subprogram_Body). It this expansion is
4495          --  performed in such case then the compiler generates unreferenced
4496          --  extra temporaries.
4497
4498          if Modify_Tree_For_C
4499            and then Chars (Current_Scope) = Name_uPostconditions
4500          then
4501             return;
4502          end if;
4503
4504          --  Climb the parent chain looking for subprogram _Postconditions
4505
4506          Subp := N;
4507          while Present (Subp) loop
4508             exit when Nkind (Subp) = N_Subprogram_Body
4509               and then Chars (Defining_Entity (Subp)) = Name_uPostconditions;
4510
4511             --  If assertions are disabled, no need to create the declaration
4512             --  that preserves the value. The postcondition pragma in which
4513             --  'Old appears will be checked or disabled according to the
4514             --  current policy in effect.
4515
4516             if Nkind (Subp) = N_Pragma and then not Is_Checked (Subp) then
4517                return;
4518             end if;
4519
4520             Subp := Parent (Subp);
4521          end loop;
4522
4523          --  'Old can only appear in a postcondition, the generated body of
4524          --  _Postconditions must be in the tree (or inlined if we are
4525          --  generating C code).
4526
4527          pragma Assert
4528            (Present (Subp)
4529              or else (Modify_Tree_For_C and then In_Inlined_Body));
4530
4531          Temp := Make_Temporary (Loc, 'T', Pref);
4532
4533          --  Set the entity kind now in order to mark the temporary as a
4534          --  handler of attribute 'Old's prefix.
4535
4536          Set_Ekind (Temp, E_Constant);
4537          Set_Stores_Attribute_Old_Prefix (Temp);
4538
4539          --  Push the scope of the related subprogram where _Postcondition
4540          --  resides as this ensures that the object will be analyzed in the
4541          --  proper context.
4542
4543          if Present (Subp) then
4544             Push_Scope (Scope (Defining_Entity (Subp)));
4545
4546          --  No need to push the scope when generating C code since the
4547          --  _Postcondition procedure has been inlined.
4548
4549          else pragma Assert (Modify_Tree_For_C);
4550             pragma Assert (In_Inlined_Body);
4551             null;
4552          end if;
4553
4554          --  Locate the insertion place of the internal temporary that saves
4555          --  the 'Old value.
4556
4557          if Present (Subp) then
4558             Ins_Nod := Subp;
4559
4560          --  Generating C, the postcondition procedure has been inlined and the
4561          --  temporary is added before the first declaration of the enclosing
4562          --  subprogram.
4563
4564          else pragma Assert (Modify_Tree_For_C);
4565             Ins_Nod := N;
4566             while Nkind (Ins_Nod) /= N_Subprogram_Body loop
4567                Ins_Nod := Parent (Ins_Nod);
4568             end loop;
4569
4570             Ins_Nod := First (Declarations (Ins_Nod));
4571          end if;
4572
4573          --  Preserve the tag of the prefix by offering a specific view of the
4574          --  class-wide version of the prefix.
4575
4576          if Is_Tagged_Type (Typ) then
4577
4578             --  Generate:
4579             --    CW_Temp : constant Typ'Class := Typ'Class (Pref);
4580
4581             CW_Temp := Make_Temporary (Loc, 'T');
4582             CW_Typ  := Class_Wide_Type (Typ);
4583
4584             Insert_Before_And_Analyze (Ins_Nod,
4585               Make_Object_Declaration (Loc,
4586                 Defining_Identifier => CW_Temp,
4587                 Constant_Present    => True,
4588                 Object_Definition   => New_Occurrence_Of (CW_Typ, Loc),
4589                 Expression          =>
4590                   Convert_To (CW_Typ, Relocate_Node (Pref))));
4591
4592             --  Generate:
4593             --    Temp : Typ renames Typ (CW_Temp);
4594
4595             Insert_Before_And_Analyze (Ins_Nod,
4596               Make_Object_Renaming_Declaration (Loc,
4597                 Defining_Identifier => Temp,
4598                 Subtype_Mark        => New_Occurrence_Of (Typ, Loc),
4599                 Name                =>
4600                   Convert_To (Typ, New_Occurrence_Of (CW_Temp, Loc))));
4601
4602          --  Non-tagged case
4603
4604          else
4605             --  Generate:
4606             --    Temp : constant Typ := Pref;
4607
4608             Insert_Before_And_Analyze (Ins_Nod,
4609               Make_Object_Declaration (Loc,
4610                 Defining_Identifier => Temp,
4611                 Constant_Present    => True,
4612                 Object_Definition   => New_Occurrence_Of (Typ, Loc),
4613                 Expression          => Relocate_Node (Pref)));
4614          end if;
4615
4616          if Present (Subp) then
4617             Pop_Scope;
4618          end if;
4619
4620          --  Ensure that the prefix of attribute 'Old is valid. The check must
4621          --  be inserted after the expansion of the attribute has taken place
4622          --  to reflect the new placement of the prefix.
4623
4624          if Validity_Checks_On and then Validity_Check_Operands then
4625             Ensure_Valid (Pref);
4626          end if;
4627
4628          Rewrite (N, New_Occurrence_Of (Temp, Loc));
4629       end Old;
4630
4631       ----------------------
4632       -- Overlaps_Storage --
4633       ----------------------
4634
4635       when Attribute_Overlaps_Storage => Overlaps_Storage : declare
4636          Loc : constant Source_Ptr := Sloc (N);
4637
4638          X   : constant Node_Id := Prefix (N);
4639          Y   : constant Node_Id := First (Expressions (N));
4640          --  The arguments
4641
4642          X_Addr, Y_Addr : Node_Id;
4643          --  the expressions for their integer addresses
4644
4645          X_Size, Y_Size : Node_Id;
4646          --  the expressions for their sizes
4647
4648          Cond : Node_Id;
4649
4650       begin
4651          --  Attribute expands into:
4652
4653          --    if X'Address < Y'address then
4654          --      (X'address + X'Size - 1) >= Y'address
4655          --    else
4656          --      (Y'address + Y'size - 1) >= X'Address
4657          --    end if;
4658
4659          --  with the proper address operations. We convert addresses to
4660          --  integer addresses to use predefined arithmetic. The size is
4661          --  expressed in storage units. We add copies of X_Addr and Y_Addr
4662          --  to prevent the appearance of the same node in two places in
4663          --  the tree.
4664
4665          X_Addr :=
4666            Unchecked_Convert_To (RTE (RE_Integer_Address),
4667              Make_Attribute_Reference (Loc,
4668                Attribute_Name => Name_Address,
4669                Prefix         => New_Copy_Tree (X)));
4670
4671          Y_Addr :=
4672            Unchecked_Convert_To (RTE (RE_Integer_Address),
4673              Make_Attribute_Reference (Loc,
4674                Attribute_Name => Name_Address,
4675                Prefix         => New_Copy_Tree (Y)));
4676
4677          X_Size :=
4678            Make_Op_Divide (Loc,
4679              Left_Opnd  =>
4680                Make_Attribute_Reference (Loc,
4681                  Attribute_Name => Name_Size,
4682                  Prefix         => New_Copy_Tree (X)),
4683              Right_Opnd =>
4684                Make_Integer_Literal (Loc, System_Storage_Unit));
4685
4686          Y_Size :=
4687            Make_Op_Divide (Loc,
4688              Left_Opnd  =>
4689                Make_Attribute_Reference (Loc,
4690                  Attribute_Name => Name_Size,
4691                  Prefix         => New_Copy_Tree (Y)),
4692              Right_Opnd =>
4693                Make_Integer_Literal (Loc, System_Storage_Unit));
4694
4695          Cond :=
4696             Make_Op_Le (Loc,
4697               Left_Opnd  => X_Addr,
4698               Right_Opnd => Y_Addr);
4699
4700          Rewrite (N,
4701            Make_If_Expression (Loc, New_List (
4702              Cond,
4703
4704              Make_Op_Ge (Loc,
4705                Left_Opnd   =>
4706                  Make_Op_Add (Loc,
4707                    Left_Opnd  => New_Copy_Tree (X_Addr),
4708                    Right_Opnd =>
4709                      Make_Op_Subtract (Loc,
4710                        Left_Opnd  => X_Size,
4711                        Right_Opnd => Make_Integer_Literal (Loc, 1))),
4712                Right_Opnd => Y_Addr),
4713
4714              Make_Op_Ge (Loc,
4715                Left_Opnd  =>
4716                  Make_Op_Add (Loc,
4717                    Left_Opnd  => New_Copy_Tree (Y_Addr),
4718                    Right_Opnd =>
4719                      Make_Op_Subtract (Loc,
4720                        Left_Opnd  => Y_Size,
4721                        Right_Opnd => Make_Integer_Literal (Loc, 1))),
4722                Right_Opnd => X_Addr))));
4723
4724          Analyze_And_Resolve (N, Standard_Boolean);
4725       end Overlaps_Storage;
4726
4727       ------------
4728       -- Output --
4729       ------------
4730
4731       when Attribute_Output => Output : declare
4732          P_Type : constant Entity_Id := Entity (Pref);
4733          U_Type : constant Entity_Id := Underlying_Type (P_Type);
4734          Pname  : Entity_Id;
4735          Decl   : Node_Id;
4736          Prag   : Node_Id;
4737          Arg3   : Node_Id;
4738          Wfunc  : Node_Id;
4739
4740       begin
4741          --  If no underlying type, we have an error that will be diagnosed
4742          --  elsewhere, so here we just completely ignore the expansion.
4743
4744          if No (U_Type) then
4745             return;
4746          end if;
4747
4748          --  Stream operations can appear in user code even if the restriction
4749          --  No_Streams is active (for example, when instantiating a predefined
4750          --  container). In that case rewrite the attribute as a Raise to
4751          --  prevent any run-time use.
4752
4753          if Restriction_Active (No_Streams) then
4754             Rewrite (N,
4755               Make_Raise_Program_Error (Sloc (N),
4756                 Reason => PE_Stream_Operation_Not_Allowed));
4757             Set_Etype (N, Standard_Void_Type);
4758             return;
4759          end if;
4760
4761          --  If TSS for Output is present, just call it
4762
4763          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Output);
4764
4765          if Present (Pname) then
4766             null;
4767
4768          else
4769             --  If there is a Stream_Convert pragma, use it, we rewrite
4770
4771             --     sourcetyp'Output (stream, Item)
4772
4773             --  as
4774
4775             --     strmtyp'Output (Stream, strmwrite (acttyp (Item)));
4776
4777             --  where strmwrite is the given Write function that converts an
4778             --  argument of type sourcetyp or a type acctyp, from which it is
4779             --  derived to type strmtyp. The conversion to acttyp is required
4780             --  for the derived case.
4781
4782             Prag := Get_Stream_Convert_Pragma (P_Type);
4783
4784             if Present (Prag) then
4785                Arg3 :=
4786                  Next (Next (First (Pragma_Argument_Associations (Prag))));
4787                Wfunc := Entity (Expression (Arg3));
4788
4789                Rewrite (N,
4790                  Make_Attribute_Reference (Loc,
4791                    Prefix => New_Occurrence_Of (Etype (Wfunc), Loc),
4792                    Attribute_Name => Name_Output,
4793                    Expressions => New_List (
4794                    Relocate_Node (First (Exprs)),
4795                      Make_Function_Call (Loc,
4796                        Name => New_Occurrence_Of (Wfunc, Loc),
4797                        Parameter_Associations => New_List (
4798                          OK_Convert_To (Etype (First_Formal (Wfunc)),
4799                            Relocate_Node (Next (First (Exprs)))))))));
4800
4801                Analyze (N);
4802                return;
4803
4804             --  For elementary types, we call the W_xxx routine directly. Note
4805             --  that the effect of Write and Output is identical for the case
4806             --  of an elementary type (there are no discriminants or bounds).
4807
4808             elsif Is_Elementary_Type (U_Type) then
4809
4810                --  A special case arises if we have a defined _Write routine,
4811                --  since in this case we are required to call this routine.
4812
4813                if Present (TSS (Base_Type (U_Type), TSS_Stream_Write)) then
4814                   Build_Record_Or_Elementary_Output_Procedure
4815                     (Loc, U_Type, Decl, Pname);
4816                   Insert_Action (N, Decl);
4817
4818                --  For normal cases, we call the W_xxx routine directly
4819
4820                else
4821                   Rewrite (N, Build_Elementary_Write_Call (N));
4822                   Analyze (N);
4823                   return;
4824                end if;
4825
4826             --  Array type case
4827
4828             elsif Is_Array_Type (U_Type) then
4829                Build_Array_Output_Procedure (Loc, U_Type, Decl, Pname);
4830                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
4831
4832             --  Class-wide case, first output external tag, then dispatch
4833             --  to the appropriate primitive Output function (RM 13.13.2(31)).
4834
4835             elsif Is_Class_Wide_Type (P_Type) then
4836
4837                --  No need to do anything else compiling under restriction
4838                --  No_Dispatching_Calls. During the semantic analysis we
4839                --  already notified such violation.
4840
4841                if Restriction_Active (No_Dispatching_Calls) then
4842                   return;
4843                end if;
4844
4845                Tag_Write : declare
4846                   Strm : constant Node_Id := First (Exprs);
4847                   Item : constant Node_Id := Next (Strm);
4848
4849                begin
4850                   --  Ada 2005 (AI-344): Check that the accessibility level
4851                   --  of the type of the output object is not deeper than
4852                   --  that of the attribute's prefix type.
4853
4854                   --  if Get_Access_Level (Item'Tag)
4855                   --       /= Get_Access_Level (P_Type'Tag)
4856                   --  then
4857                   --     raise Tag_Error;
4858                   --  end if;
4859
4860                   --  String'Output (Strm, External_Tag (Item'Tag));
4861
4862                   --  We cannot figure out a practical way to implement this
4863                   --  accessibility check on virtual machines, so we omit it.
4864
4865                   if Ada_Version >= Ada_2005
4866                     and then Tagged_Type_Expansion
4867                   then
4868                      Insert_Action (N,
4869                        Make_Implicit_If_Statement (N,
4870                          Condition =>
4871                            Make_Op_Ne (Loc,
4872                              Left_Opnd  =>
4873                                Build_Get_Access_Level (Loc,
4874                                  Make_Attribute_Reference (Loc,
4875                                    Prefix         =>
4876                                      Relocate_Node (
4877                                        Duplicate_Subexpr (Item,
4878                                          Name_Req => True)),
4879                                    Attribute_Name => Name_Tag)),
4880
4881                              Right_Opnd =>
4882                                Make_Integer_Literal (Loc,
4883                                  Type_Access_Level (P_Type))),
4884
4885                          Then_Statements =>
4886                            New_List (Make_Raise_Statement (Loc,
4887                                        New_Occurrence_Of (
4888                                          RTE (RE_Tag_Error), Loc)))));
4889                   end if;
4890
4891                   Insert_Action (N,
4892                     Make_Attribute_Reference (Loc,
4893                       Prefix => New_Occurrence_Of (Standard_String, Loc),
4894                       Attribute_Name => Name_Output,
4895                       Expressions => New_List (
4896                         Relocate_Node (Duplicate_Subexpr (Strm)),
4897                         Make_Function_Call (Loc,
4898                           Name =>
4899                             New_Occurrence_Of (RTE (RE_External_Tag), Loc),
4900                           Parameter_Associations => New_List (
4901                            Make_Attribute_Reference (Loc,
4902                              Prefix =>
4903                                Relocate_Node
4904                                  (Duplicate_Subexpr (Item, Name_Req => True)),
4905                              Attribute_Name => Name_Tag))))));
4906                end Tag_Write;
4907
4908                Pname := Find_Prim_Op (U_Type, TSS_Stream_Output);
4909
4910             --  Tagged type case, use the primitive Output function
4911
4912             elsif Is_Tagged_Type (U_Type) then
4913                Pname := Find_Prim_Op (U_Type, TSS_Stream_Output);
4914
4915             --  All other record type cases, including protected records.
4916             --  The latter only arise for expander generated code for
4917             --  handling shared passive partition access.
4918
4919             else
4920                pragma Assert
4921                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
4922
4923                --  Ada 2005 (AI-216): Program_Error is raised when executing
4924                --  the default implementation of the Output attribute of an
4925                --  unchecked union type if the type lacks default discriminant
4926                --  values.
4927
4928                if Is_Unchecked_Union (Base_Type (U_Type))
4929                  and then No (Discriminant_Constraint (U_Type))
4930                then
4931                   Insert_Action (N,
4932                     Make_Raise_Program_Error (Loc,
4933                       Reason => PE_Unchecked_Union_Restriction));
4934
4935                   return;
4936                end if;
4937
4938                Build_Record_Or_Elementary_Output_Procedure
4939                  (Loc, Base_Type (U_Type), Decl, Pname);
4940                Insert_Action (N, Decl);
4941             end if;
4942          end if;
4943
4944          --  If we fall through, Pname is the name of the procedure to call
4945
4946          Rewrite_Stream_Proc_Call (Pname);
4947       end Output;
4948
4949       ---------
4950       -- Pos --
4951       ---------
4952
4953       --  For enumeration types with a standard representation, Pos is
4954       --  handled by the back end.
4955
4956       --  For enumeration types, with a non-standard representation we generate
4957       --  a call to the _Rep_To_Pos function created when the type was frozen.
4958       --  The call has the form
4959
4960       --    _rep_to_pos (expr, flag)
4961
4962       --  The parameter flag is True if range checks are enabled, causing
4963       --  Program_Error to be raised if the expression has an invalid
4964       --  representation, and False if range checks are suppressed.
4965
4966       --  For integer types, Pos is equivalent to a simple integer
4967       --  conversion and we rewrite it as such
4968
4969       when Attribute_Pos => Pos :
4970       declare
4971          Etyp : Entity_Id := Base_Type (Entity (Pref));
4972
4973       begin
4974          --  Deal with zero/non-zero boolean values
4975
4976          if Is_Boolean_Type (Etyp) then
4977             Adjust_Condition (First (Exprs));
4978             Etyp := Standard_Boolean;
4979             Set_Prefix (N, New_Occurrence_Of (Standard_Boolean, Loc));
4980          end if;
4981
4982          --  Case of enumeration type
4983
4984          if Is_Enumeration_Type (Etyp) then
4985
4986             --  Non-standard enumeration type (generate call)
4987
4988             if Present (Enum_Pos_To_Rep (Etyp)) then
4989                Append_To (Exprs, Rep_To_Pos_Flag (Etyp, Loc));
4990                Rewrite (N,
4991                  Convert_To (Typ,
4992                    Make_Function_Call (Loc,
4993                      Name =>
4994                        New_Occurrence_Of (TSS (Etyp, TSS_Rep_To_Pos), Loc),
4995                      Parameter_Associations => Exprs)));
4996
4997                Analyze_And_Resolve (N, Typ);
4998
4999             --  Standard enumeration type (do universal integer check)
5000
5001             else
5002                Apply_Universal_Integer_Attribute_Checks (N);
5003             end if;
5004
5005          --  Deal with integer types (replace by conversion)
5006
5007          elsif Is_Integer_Type (Etyp) then
5008             Rewrite (N, Convert_To (Typ, First (Exprs)));
5009             Analyze_And_Resolve (N, Typ);
5010          end if;
5011
5012       end Pos;
5013
5014       --------------
5015       -- Position --
5016       --------------
5017
5018       --  We compute this if a component clause was present, otherwise we leave
5019       --  the computation up to the back end, since we don't know what layout
5020       --  will be chosen.
5021
5022       when Attribute_Position => Position_Attr :
5023       declare
5024          CE : constant Entity_Id := Entity (Selector_Name (Pref));
5025
5026       begin
5027          if Present (Component_Clause (CE)) then
5028
5029             --  In Ada 2005 (or later) if we have the non-default bit order,
5030             --  then we return the original value as given in the component
5031             --  clause (RM 2005 13.5.2(2/2)).
5032
5033             if Ada_Version >= Ada_2005
5034               and then Reverse_Bit_Order (Scope (CE))
5035             then
5036                Rewrite (N,
5037                   Make_Integer_Literal (Loc,
5038                     Intval => Expr_Value (Position (Component_Clause (CE)))));
5039
5040             --  Otherwise (Ada 83 or 95, or default bit order specified in
5041             --  later Ada version), return the normalized value.
5042
5043             else
5044                Rewrite (N,
5045                  Make_Integer_Literal (Loc,
5046                    Intval => Component_Bit_Offset (CE) / System_Storage_Unit));
5047             end if;
5048
5049             Analyze_And_Resolve (N, Typ);
5050
5051          --  If back end is doing things, just apply universal integer checks
5052
5053          else
5054             Apply_Universal_Integer_Attribute_Checks (N);
5055          end if;
5056       end Position_Attr;
5057
5058       ----------
5059       -- Pred --
5060       ----------
5061
5062       --  1. Deal with enumeration types with holes.
5063       --  2. For floating-point, generate call to attribute function.
5064       --  3. For other cases, deal with constraint checking.
5065
5066       when Attribute_Pred => Pred :
5067       declare
5068          Etyp : constant Entity_Id := Base_Type (Ptyp);
5069
5070       begin
5071
5072          --  For enumeration types with non-standard representations, we
5073          --  expand typ'Pred (x) into
5074
5075          --    Pos_To_Rep (Rep_To_Pos (x) - 1)
5076
5077          --    If the representation is contiguous, we compute instead
5078          --    Lit1 + Rep_to_Pos (x -1), to catch invalid representations.
5079          --    The conversion function Enum_Pos_To_Rep is defined on the
5080          --    base type, not the subtype, so we have to use the base type
5081          --    explicitly for this and other enumeration attributes.
5082
5083          if Is_Enumeration_Type (Ptyp)
5084            and then Present (Enum_Pos_To_Rep (Etyp))
5085          then
5086             if Has_Contiguous_Rep (Etyp) then
5087                Rewrite (N,
5088                   Unchecked_Convert_To (Ptyp,
5089                      Make_Op_Add (Loc,
5090                         Left_Opnd  =>
5091                          Make_Integer_Literal (Loc,
5092                            Enumeration_Rep (First_Literal (Ptyp))),
5093                         Right_Opnd =>
5094                           Make_Function_Call (Loc,
5095                             Name =>
5096                               New_Occurrence_Of
5097                                (TSS (Etyp, TSS_Rep_To_Pos), Loc),
5098
5099                             Parameter_Associations =>
5100                               New_List (
5101                                 Unchecked_Convert_To (Ptyp,
5102                                   Make_Op_Subtract (Loc,
5103                                     Left_Opnd =>
5104                                      Unchecked_Convert_To (Standard_Integer,
5105                                        Relocate_Node (First (Exprs))),
5106                                     Right_Opnd =>
5107                                       Make_Integer_Literal (Loc, 1))),
5108                                 Rep_To_Pos_Flag (Ptyp, Loc))))));
5109
5110             else
5111                --  Add Boolean parameter True, to request program errror if
5112                --  we have a bad representation on our hands. If checks are
5113                --  suppressed, then add False instead
5114
5115                Append_To (Exprs, Rep_To_Pos_Flag (Ptyp, Loc));
5116                Rewrite (N,
5117                  Make_Indexed_Component (Loc,
5118                    Prefix =>
5119                      New_Occurrence_Of
5120                        (Enum_Pos_To_Rep (Etyp), Loc),
5121                    Expressions => New_List (
5122                      Make_Op_Subtract (Loc,
5123                     Left_Opnd =>
5124                       Make_Function_Call (Loc,
5125                         Name =>
5126                           New_Occurrence_Of
5127                             (TSS (Etyp, TSS_Rep_To_Pos), Loc),
5128                           Parameter_Associations => Exprs),
5129                     Right_Opnd => Make_Integer_Literal (Loc, 1)))));
5130             end if;
5131
5132             Analyze_And_Resolve (N, Typ);
5133
5134          --  For floating-point, we transform 'Pred into a call to the Pred
5135          --  floating-point attribute function in Fat_xxx (xxx is root type).
5136          --  Note that this function takes care of the overflow case.
5137
5138          elsif Is_Floating_Point_Type (Ptyp) then
5139             Expand_Fpt_Attribute_R (N);
5140             Analyze_And_Resolve (N, Typ);
5141
5142          --  For modular types, nothing to do (no overflow, since wraps)
5143
5144          elsif Is_Modular_Integer_Type (Ptyp) then
5145             null;
5146
5147          --  For other types, if argument is marked as needing a range check or
5148          --  overflow checking is enabled, we must generate a check.
5149
5150          elsif not Overflow_Checks_Suppressed (Ptyp)
5151            or else Do_Range_Check (First (Exprs))
5152          then
5153             Set_Do_Range_Check (First (Exprs), False);
5154             Expand_Pred_Succ_Attribute (N);
5155          end if;
5156       end Pred;
5157
5158       --------------
5159       -- Priority --
5160       --------------
5161
5162       --  Ada 2005 (AI-327): Dynamic ceiling priorities
5163
5164       --  We rewrite X'Priority as the following run-time call:
5165
5166       --     Get_Ceiling (X._Object)
5167
5168       --  Note that although X'Priority is notionally an object, it is quite
5169       --  deliberately not defined as an aliased object in the RM. This means
5170       --  that it works fine to rewrite it as a call, without having to worry
5171       --  about complications that would other arise from X'Priority'Access,
5172       --  which is illegal, because of the lack of aliasing.
5173
5174       when Attribute_Priority =>
5175          declare
5176             Call           : Node_Id;
5177             Conctyp        : Entity_Id;
5178             Object_Parm    : Node_Id;
5179             Subprg         : Entity_Id;
5180             RT_Subprg_Name : Node_Id;
5181
5182          begin
5183             --  Look for the enclosing concurrent type
5184
5185             Conctyp := Current_Scope;
5186             while not Is_Concurrent_Type (Conctyp) loop
5187                Conctyp := Scope (Conctyp);
5188             end loop;
5189
5190             pragma Assert (Is_Protected_Type (Conctyp));
5191
5192             --  Generate the actual of the call
5193
5194             Subprg := Current_Scope;
5195             while not Present (Protected_Body_Subprogram (Subprg)) loop
5196                Subprg := Scope (Subprg);
5197             end loop;
5198
5199             --  Use of 'Priority inside protected entries and barriers (in
5200             --  both cases the type of the first formal of their expanded
5201             --  subprogram is Address)
5202
5203             if Etype (First_Entity (Protected_Body_Subprogram (Subprg))) =
5204                  RTE (RE_Address)
5205             then
5206                declare
5207                   New_Itype : Entity_Id;
5208
5209                begin
5210                   --  In the expansion of protected entries the type of the
5211                   --  first formal of the Protected_Body_Subprogram is an
5212                   --  Address. In order to reference the _object component
5213                   --  we generate:
5214
5215                   --    type T is access p__ptTV;
5216                   --    freeze T []
5217
5218                   New_Itype := Create_Itype (E_Access_Type, N);
5219                   Set_Etype (New_Itype, New_Itype);
5220                   Set_Directly_Designated_Type (New_Itype,
5221                     Corresponding_Record_Type (Conctyp));
5222                   Freeze_Itype (New_Itype, N);
5223
5224                   --  Generate:
5225                   --    T!(O)._object'unchecked_access
5226
5227                   Object_Parm :=
5228                     Make_Attribute_Reference (Loc,
5229                       Prefix =>
5230                         Make_Selected_Component (Loc,
5231                           Prefix =>
5232                             Unchecked_Convert_To (New_Itype,
5233                               New_Occurrence_Of
5234                                 (First_Entity
5235                                   (Protected_Body_Subprogram (Subprg)),
5236                                  Loc)),
5237                           Selector_Name =>
5238                             Make_Identifier (Loc, Name_uObject)),
5239                        Attribute_Name => Name_Unchecked_Access);
5240                end;
5241
5242             --  Use of 'Priority inside a protected subprogram
5243
5244             else
5245                Object_Parm :=
5246                  Make_Attribute_Reference (Loc,
5247                     Prefix =>
5248                       Make_Selected_Component (Loc,
5249                         Prefix => New_Occurrence_Of
5250                                     (First_Entity
5251                                       (Protected_Body_Subprogram (Subprg)),
5252                                        Loc),
5253                         Selector_Name => Make_Identifier (Loc, Name_uObject)),
5254                     Attribute_Name => Name_Unchecked_Access);
5255             end if;
5256
5257             --  Select the appropriate run-time subprogram
5258
5259             if Number_Entries (Conctyp) = 0 then
5260                RT_Subprg_Name :=
5261                  New_Occurrence_Of (RTE (RE_Get_Ceiling), Loc);
5262             else
5263                RT_Subprg_Name :=
5264                  New_Occurrence_Of (RTE (RO_PE_Get_Ceiling), Loc);
5265             end if;
5266
5267             Call :=
5268               Make_Function_Call (Loc,
5269                 Name => RT_Subprg_Name,
5270                 Parameter_Associations => New_List (Object_Parm));
5271
5272             Rewrite (N, Call);
5273
5274             --  Avoid the generation of extra checks on the pointer to the
5275             --  protected object.
5276
5277             Analyze_And_Resolve (N, Typ, Suppress => Access_Check);
5278          end;
5279
5280       ------------------
5281       -- Range_Length --
5282       ------------------
5283
5284       when Attribute_Range_Length => Range_Length : begin
5285
5286          --  The only special processing required is for the case where
5287          --  Range_Length is applied to an enumeration type with holes.
5288          --  In this case we transform
5289
5290          --     X'Range_Length
5291
5292          --  to
5293
5294          --     X'Pos (X'Last) - X'Pos (X'First) + 1
5295
5296          --  So that the result reflects the proper Pos values instead
5297          --  of the underlying representations.
5298
5299          if Is_Enumeration_Type (Ptyp)
5300            and then Has_Non_Standard_Rep (Ptyp)
5301          then
5302             Rewrite (N,
5303               Make_Op_Add (Loc,
5304                 Left_Opnd =>
5305                   Make_Op_Subtract (Loc,
5306                     Left_Opnd =>
5307                       Make_Attribute_Reference (Loc,
5308                         Attribute_Name => Name_Pos,
5309                         Prefix => New_Occurrence_Of (Ptyp, Loc),
5310                         Expressions => New_List (
5311                           Make_Attribute_Reference (Loc,
5312                             Attribute_Name => Name_Last,
5313                             Prefix => New_Occurrence_Of (Ptyp, Loc)))),
5314
5315                     Right_Opnd =>
5316                       Make_Attribute_Reference (Loc,
5317                         Attribute_Name => Name_Pos,
5318                         Prefix => New_Occurrence_Of (Ptyp, Loc),
5319                         Expressions => New_List (
5320                           Make_Attribute_Reference (Loc,
5321                             Attribute_Name => Name_First,
5322                             Prefix => New_Occurrence_Of (Ptyp, Loc))))),
5323
5324                 Right_Opnd => Make_Integer_Literal (Loc, 1)));
5325
5326             Analyze_And_Resolve (N, Typ);
5327
5328          --  For all other cases, the attribute is handled by the back end, but
5329          --  we need to deal with the case of the range check on a universal
5330          --  integer.
5331
5332          else
5333             Apply_Universal_Integer_Attribute_Checks (N);
5334          end if;
5335       end Range_Length;
5336
5337       ----------
5338       -- Read --
5339       ----------
5340
5341       when Attribute_Read => Read : declare
5342          P_Type : constant Entity_Id := Entity (Pref);
5343          B_Type : constant Entity_Id := Base_Type (P_Type);
5344          U_Type : constant Entity_Id := Underlying_Type (P_Type);
5345          Pname  : Entity_Id;
5346          Decl   : Node_Id;
5347          Prag   : Node_Id;
5348          Arg2   : Node_Id;
5349          Rfunc  : Node_Id;
5350          Lhs    : Node_Id;
5351          Rhs    : Node_Id;
5352
5353       begin
5354          --  If no underlying type, we have an error that will be diagnosed
5355          --  elsewhere, so here we just completely ignore the expansion.
5356
5357          if No (U_Type) then
5358             return;
5359          end if;
5360
5361          --  Stream operations can appear in user code even if the restriction
5362          --  No_Streams is active (for example, when instantiating a predefined
5363          --  container). In that case rewrite the attribute as a Raise to
5364          --  prevent any run-time use.
5365
5366          if Restriction_Active (No_Streams) then
5367             Rewrite (N,
5368               Make_Raise_Program_Error (Sloc (N),
5369                 Reason => PE_Stream_Operation_Not_Allowed));
5370             Set_Etype (N, B_Type);
5371             return;
5372          end if;
5373
5374          --  The simple case, if there is a TSS for Read, just call it
5375
5376          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Read);
5377
5378          if Present (Pname) then
5379             null;
5380
5381          else
5382             --  If there is a Stream_Convert pragma, use it, we rewrite
5383
5384             --     sourcetyp'Read (stream, Item)
5385
5386             --  as
5387
5388             --     Item := sourcetyp (strmread (strmtyp'Input (Stream)));
5389
5390             --  where strmread is the given Read function that converts an
5391             --  argument of type strmtyp to type sourcetyp or a type from which
5392             --  it is derived. The conversion to sourcetyp is required in the
5393             --  latter case.
5394
5395             --  A special case arises if Item is a type conversion in which
5396             --  case, we have to expand to:
5397
5398             --     Itemx := typex (strmread (strmtyp'Input (Stream)));
5399
5400             --  where Itemx is the expression of the type conversion (i.e.
5401             --  the actual object), and typex is the type of Itemx.
5402
5403             Prag := Get_Stream_Convert_Pragma (P_Type);
5404
5405             if Present (Prag) then
5406                Arg2  := Next (First (Pragma_Argument_Associations (Prag)));
5407                Rfunc := Entity (Expression (Arg2));
5408                Lhs := Relocate_Node (Next (First (Exprs)));
5409                Rhs :=
5410                  OK_Convert_To (B_Type,
5411                    Make_Function_Call (Loc,
5412                      Name => New_Occurrence_Of (Rfunc, Loc),
5413                      Parameter_Associations => New_List (
5414                        Make_Attribute_Reference (Loc,
5415                          Prefix =>
5416                            New_Occurrence_Of
5417                              (Etype (First_Formal (Rfunc)), Loc),
5418                          Attribute_Name => Name_Input,
5419                          Expressions => New_List (
5420                            Relocate_Node (First (Exprs)))))));
5421
5422                if Nkind (Lhs) = N_Type_Conversion then
5423                   Lhs := Expression (Lhs);
5424                   Rhs := Convert_To (Etype (Lhs), Rhs);
5425                end if;
5426
5427                Rewrite (N,
5428                  Make_Assignment_Statement (Loc,
5429                    Name       => Lhs,
5430                    Expression => Rhs));
5431                Set_Assignment_OK (Lhs);
5432                Analyze (N);
5433                return;
5434
5435             --  For elementary types, we call the I_xxx routine using the first
5436             --  parameter and then assign the result into the second parameter.
5437             --  We set Assignment_OK to deal with the conversion case.
5438
5439             elsif Is_Elementary_Type (U_Type) then
5440                declare
5441                   Lhs : Node_Id;
5442                   Rhs : Node_Id;
5443
5444                begin
5445                   Lhs := Relocate_Node (Next (First (Exprs)));
5446                   Rhs := Build_Elementary_Input_Call (N);
5447
5448                   if Nkind (Lhs) = N_Type_Conversion then
5449                      Lhs := Expression (Lhs);
5450                      Rhs := Convert_To (Etype (Lhs), Rhs);
5451                   end if;
5452
5453                   Set_Assignment_OK (Lhs);
5454
5455                   Rewrite (N,
5456                     Make_Assignment_Statement (Loc,
5457                       Name       => Lhs,
5458                       Expression => Rhs));
5459
5460                   Analyze (N);
5461                   return;
5462                end;
5463
5464             --  Array type case
5465
5466             elsif Is_Array_Type (U_Type) then
5467                Build_Array_Read_Procedure (N, U_Type, Decl, Pname);
5468                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
5469
5470             --  Tagged type case, use the primitive Read function. Note that
5471             --  this will dispatch in the class-wide case which is what we want
5472
5473             elsif Is_Tagged_Type (U_Type) then
5474                Pname := Find_Prim_Op (U_Type, TSS_Stream_Read);
5475
5476             --  All other record type cases, including protected records. The
5477             --  latter only arise for expander generated code for handling
5478             --  shared passive partition access.
5479
5480             else
5481                pragma Assert
5482                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
5483
5484                --  Ada 2005 (AI-216): Program_Error is raised when executing
5485                --  the default implementation of the Read attribute of an
5486                --  Unchecked_Union type.
5487
5488                if Is_Unchecked_Union (Base_Type (U_Type)) then
5489                   Insert_Action (N,
5490                     Make_Raise_Program_Error (Loc,
5491                       Reason => PE_Unchecked_Union_Restriction));
5492                end if;
5493
5494                if Has_Discriminants (U_Type)
5495                  and then Present
5496                    (Discriminant_Default_Value (First_Discriminant (U_Type)))
5497                then
5498                   Build_Mutable_Record_Read_Procedure
5499                     (Loc, Full_Base (U_Type), Decl, Pname);
5500                else
5501                   Build_Record_Read_Procedure
5502                     (Loc, Full_Base (U_Type), Decl, Pname);
5503                end if;
5504
5505                --  Suppress checks, uninitialized or otherwise invalid
5506                --  data does not cause constraint errors to be raised for
5507                --  a complete record read.
5508
5509                Insert_Action (N, Decl, All_Checks);
5510             end if;
5511          end if;
5512
5513          Rewrite_Stream_Proc_Call (Pname);
5514       end Read;
5515
5516       ---------
5517       -- Ref --
5518       ---------
5519
5520       --  Ref is identical to To_Address, see To_Address for processing
5521
5522       ---------------
5523       -- Remainder --
5524       ---------------
5525
5526       --  Transforms 'Remainder into a call to the floating-point attribute
5527       --  function Remainder in Fat_xxx (where xxx is the root type)
5528
5529       when Attribute_Remainder =>
5530          Expand_Fpt_Attribute_RR (N);
5531
5532       ------------
5533       -- Result --
5534       ------------
5535
5536       --  Transform 'Result into reference to _Result formal. At the point
5537       --  where a legal 'Result attribute is expanded, we know that we are in
5538       --  the context of a _Postcondition function with a _Result parameter.
5539
5540       when Attribute_Result =>
5541          Rewrite (N, Make_Identifier (Loc, Chars => Name_uResult));
5542          Analyze_And_Resolve (N, Typ);
5543
5544       -----------
5545       -- Round --
5546       -----------
5547
5548       --  The handling of the Round attribute is quite delicate. The processing
5549       --  in Sem_Attr introduced a conversion to universal real, reflecting the
5550       --  semantics of Round, but we do not want anything to do with universal
5551       --  real at runtime, since this corresponds to using floating-point
5552       --  arithmetic.
5553
5554       --  What we have now is that the Etype of the Round attribute correctly
5555       --  indicates the final result type. The operand of the Round is the
5556       --  conversion to universal real, described above, and the operand of
5557       --  this conversion is the actual operand of Round, which may be the
5558       --  special case of a fixed point multiplication or division (Etype =
5559       --  universal fixed)
5560
5561       --  The exapander will expand first the operand of the conversion, then
5562       --  the conversion, and finally the round attribute itself, since we
5563       --  always work inside out. But we cannot simply process naively in this
5564       --  order. In the semantic world where universal fixed and real really
5565       --  exist and have infinite precision, there is no problem, but in the
5566       --  implementation world, where universal real is a floating-point type,
5567       --  we would get the wrong result.
5568
5569       --  So the approach is as follows. First, when expanding a multiply or
5570       --  divide whose type is universal fixed, we do nothing at all, instead
5571       --  deferring the operation till later.
5572
5573       --  The actual processing is done in Expand_N_Type_Conversion which
5574       --  handles the special case of Round by looking at its parent to see if
5575       --  it is a Round attribute, and if it is, handling the conversion (or
5576       --  its fixed multiply/divide child) in an appropriate manner.
5577
5578       --  This means that by the time we get to expanding the Round attribute
5579       --  itself, the Round is nothing more than a type conversion (and will
5580       --  often be a null type conversion), so we just replace it with the
5581       --  appropriate conversion operation.
5582
5583       when Attribute_Round =>
5584          Rewrite (N,
5585            Convert_To (Etype (N), Relocate_Node (First (Exprs))));
5586          Analyze_And_Resolve (N);
5587
5588       --------------
5589       -- Rounding --
5590       --------------
5591
5592       --  Transforms 'Rounding into a call to the floating-point attribute
5593       --  function Rounding in Fat_xxx (where xxx is the root type)
5594       --  Expansion is avoided for cases the back end can handle directly.
5595
5596       when Attribute_Rounding =>
5597          if not Is_Inline_Floating_Point_Attribute (N) then
5598             Expand_Fpt_Attribute_R (N);
5599          end if;
5600
5601       -------------
5602       -- Scaling --
5603       -------------
5604
5605       --  Transforms 'Scaling into a call to the floating-point attribute
5606       --  function Scaling in Fat_xxx (where xxx is the root type)
5607
5608       when Attribute_Scaling =>
5609          Expand_Fpt_Attribute_RI (N);
5610
5611       -------------------------
5612       -- Simple_Storage_Pool --
5613       -------------------------
5614
5615       when Attribute_Simple_Storage_Pool =>
5616          Rewrite (N,
5617            Make_Type_Conversion (Loc,
5618              Subtype_Mark => New_Occurrence_Of (Etype (N), Loc),
5619              Expression   => New_Occurrence_Of (Entity (N), Loc)));
5620          Analyze_And_Resolve (N, Typ);
5621
5622       ----------
5623       -- Size --
5624       ----------
5625
5626       when Attribute_Size        |
5627            Attribute_Object_Size |
5628            Attribute_Value_Size  |
5629            Attribute_VADS_Size   => Size :
5630
5631       declare
5632          Siz      : Uint;
5633          New_Node : Node_Id;
5634
5635       begin
5636          --  Processing for VADS_Size case. Note that this processing removes
5637          --  all traces of VADS_Size from the tree, and completes all required
5638          --  processing for VADS_Size by translating the attribute reference
5639          --  to an appropriate Size or Object_Size reference.
5640
5641          if Id = Attribute_VADS_Size
5642            or else (Use_VADS_Size and then Id = Attribute_Size)
5643          then
5644             --  If the size is specified, then we simply use the specified
5645             --  size. This applies to both types and objects. The size of an
5646             --  object can be specified in the following ways:
5647
5648             --    An explicit size object is given for an object
5649             --    A component size is specified for an indexed component
5650             --    A component clause is specified for a selected component
5651             --    The object is a component of a packed composite object
5652
5653             --  If the size is specified, then VADS_Size of an object
5654
5655             if (Is_Entity_Name (Pref)
5656                  and then Present (Size_Clause (Entity (Pref))))
5657               or else
5658                 (Nkind (Pref) = N_Component_Clause
5659                   and then (Present (Component_Clause
5660                                      (Entity (Selector_Name (Pref))))
5661                              or else Is_Packed (Etype (Prefix (Pref)))))
5662               or else
5663                 (Nkind (Pref) = N_Indexed_Component
5664                   and then (Component_Size (Etype (Prefix (Pref))) /= 0
5665                              or else Is_Packed (Etype (Prefix (Pref)))))
5666             then
5667                Set_Attribute_Name (N, Name_Size);
5668
5669             --  Otherwise if we have an object rather than a type, then the
5670             --  VADS_Size attribute applies to the type of the object, rather
5671             --  than the object itself. This is one of the respects in which
5672             --  VADS_Size differs from Size.
5673
5674             else
5675                if (not Is_Entity_Name (Pref)
5676                     or else not Is_Type (Entity (Pref)))
5677                  and then (Is_Scalar_Type (Ptyp) or else Is_Constrained (Ptyp))
5678                then
5679                   Rewrite (Pref, New_Occurrence_Of (Ptyp, Loc));
5680                end if;
5681
5682                --  For a scalar type for which no size was explicitly given,
5683                --  VADS_Size means Object_Size. This is the other respect in
5684                --  which VADS_Size differs from Size.
5685
5686                if Is_Scalar_Type (Ptyp) and then No (Size_Clause (Ptyp)) then
5687                   Set_Attribute_Name (N, Name_Object_Size);
5688
5689                --  In all other cases, Size and VADS_Size are the sane
5690
5691                else
5692                   Set_Attribute_Name (N, Name_Size);
5693                end if;
5694             end if;
5695          end if;
5696
5697          --  If the prefix is X'Class, we transform it into a direct reference
5698          --  to the class-wide type, because the back end must not see a 'Class
5699          --  reference.
5700
5701          if Is_Entity_Name (Pref)
5702            and then Is_Class_Wide_Type (Entity (Pref))
5703          then
5704             Rewrite (Prefix (N), New_Occurrence_Of (Entity (Pref), Loc));
5705             return;
5706
5707          --  For X'Size applied to an object of a class-wide type, transform
5708          --  X'Size into a call to the primitive operation _Size applied to X.
5709
5710          elsif Is_Class_Wide_Type (Ptyp) then
5711
5712             --  No need to do anything else compiling under restriction
5713             --  No_Dispatching_Calls. During the semantic analysis we
5714             --  already noted this restriction violation.
5715
5716             if Restriction_Active (No_Dispatching_Calls) then
5717                return;
5718             end if;
5719
5720             New_Node :=
5721               Make_Function_Call (Loc,
5722                 Name => New_Occurrence_Of
5723                   (Find_Prim_Op (Ptyp, Name_uSize), Loc),
5724                 Parameter_Associations => New_List (Pref));
5725
5726             if Typ /= Standard_Long_Long_Integer then
5727
5728                --  The context is a specific integer type with which the
5729                --  original attribute was compatible. The function has a
5730                --  specific type as well, so to preserve the compatibility
5731                --  we must convert explicitly.
5732
5733                New_Node := Convert_To (Typ, New_Node);
5734             end if;
5735
5736             Rewrite (N, New_Node);
5737             Analyze_And_Resolve (N, Typ);
5738             return;
5739
5740          --  Case of known RM_Size of a type
5741
5742          elsif (Id = Attribute_Size or else Id = Attribute_Value_Size)
5743            and then Is_Entity_Name (Pref)
5744            and then Is_Type (Entity (Pref))
5745            and then Known_Static_RM_Size (Entity (Pref))
5746          then
5747             Siz := RM_Size (Entity (Pref));
5748
5749          --  Case of known Esize of a type
5750
5751          elsif Id = Attribute_Object_Size
5752            and then Is_Entity_Name (Pref)
5753            and then Is_Type (Entity (Pref))
5754            and then Known_Static_Esize (Entity (Pref))
5755          then
5756             Siz := Esize (Entity (Pref));
5757
5758          --  Case of known size of object
5759
5760          elsif Id = Attribute_Size
5761            and then Is_Entity_Name (Pref)
5762            and then Is_Object (Entity (Pref))
5763            and then Known_Esize (Entity (Pref))
5764            and then Known_Static_Esize (Entity (Pref))
5765          then
5766             Siz := Esize (Entity (Pref));
5767
5768          --  For an array component, we can do Size in the front end
5769          --  if the component_size of the array is set.
5770
5771          elsif Nkind (Pref) = N_Indexed_Component then
5772             Siz := Component_Size (Etype (Prefix (Pref)));
5773
5774          --  For a record component, we can do Size in the front end if there
5775          --  is a component clause, or if the record is packed and the
5776          --  component's size is known at compile time.
5777
5778          elsif Nkind (Pref) = N_Selected_Component then
5779             declare
5780                Rec  : constant Entity_Id := Etype (Prefix (Pref));
5781                Comp : constant Entity_Id := Entity (Selector_Name (Pref));
5782
5783             begin
5784                if Present (Component_Clause (Comp)) then
5785                   Siz := Esize (Comp);
5786
5787                elsif Is_Packed (Rec) then
5788                   Siz := RM_Size (Ptyp);
5789
5790                else
5791                   Apply_Universal_Integer_Attribute_Checks (N);
5792                   return;
5793                end if;
5794             end;
5795
5796          --  All other cases are handled by the back end
5797
5798          else
5799             Apply_Universal_Integer_Attribute_Checks (N);
5800
5801             --  If Size is applied to a formal parameter that is of a packed
5802             --  array subtype, then apply Size to the actual subtype.
5803
5804             if Is_Entity_Name (Pref)
5805               and then Is_Formal (Entity (Pref))
5806               and then Is_Array_Type (Ptyp)
5807               and then Is_Packed (Ptyp)
5808             then
5809                Rewrite (N,
5810                  Make_Attribute_Reference (Loc,
5811                    Prefix =>
5812                      New_Occurrence_Of (Get_Actual_Subtype (Pref), Loc),
5813                    Attribute_Name => Name_Size));
5814                Analyze_And_Resolve (N, Typ);
5815             end if;
5816
5817             --  If Size applies to a dereference of an access to unconstrained
5818             --  packed array, the back end needs to see its unconstrained
5819             --  nominal type, but also a hint to the actual constrained type.
5820
5821             if Nkind (Pref) = N_Explicit_Dereference
5822               and then Is_Array_Type (Ptyp)
5823               and then not Is_Constrained (Ptyp)
5824               and then Is_Packed (Ptyp)
5825             then
5826                Set_Actual_Designated_Subtype (Pref,
5827                  Get_Actual_Subtype (Pref));
5828             end if;
5829
5830             return;
5831          end if;
5832
5833          --  Common processing for record and array component case
5834
5835          if Siz /= No_Uint and then Siz /= 0 then
5836             declare
5837                CS : constant Boolean := Comes_From_Source (N);
5838
5839             begin
5840                Rewrite (N, Make_Integer_Literal (Loc, Siz));
5841
5842                --  This integer literal is not a static expression. We do not
5843                --  call Analyze_And_Resolve here, because this would activate
5844                --  the circuit for deciding that a static value was out of
5845                --  range, and we don't want that.
5846
5847                --  So just manually set the type, mark the expression as non-
5848                --  static, and then ensure that the result is checked properly
5849                --  if the attribute comes from source (if it was internally
5850                --  generated, we never need a constraint check).
5851
5852                Set_Etype (N, Typ);
5853                Set_Is_Static_Expression (N, False);
5854
5855                if CS then
5856                   Apply_Constraint_Check (N, Typ);
5857                end if;
5858             end;
5859          end if;
5860       end Size;
5861
5862       ------------------
5863       -- Storage_Pool --
5864       ------------------
5865
5866       when Attribute_Storage_Pool =>
5867          Rewrite (N,
5868            Make_Type_Conversion (Loc,
5869              Subtype_Mark => New_Occurrence_Of (Etype (N), Loc),
5870              Expression   => New_Occurrence_Of (Entity (N), Loc)));
5871          Analyze_And_Resolve (N, Typ);
5872
5873       ------------------
5874       -- Storage_Size --
5875       ------------------
5876
5877       when Attribute_Storage_Size => Storage_Size : declare
5878          Alloc_Op  : Entity_Id := Empty;
5879
5880       begin
5881
5882          --  Access type case, always go to the root type
5883
5884          --  The case of access types results in a value of zero for the case
5885          --  where no storage size attribute clause has been given. If a
5886          --  storage size has been given, then the attribute is converted
5887          --  to a reference to the variable used to hold this value.
5888
5889          if Is_Access_Type (Ptyp) then
5890             if Present (Storage_Size_Variable (Root_Type (Ptyp))) then
5891                Rewrite (N,
5892                  Make_Attribute_Reference (Loc,
5893                    Prefix => New_Occurrence_Of (Typ, Loc),
5894                    Attribute_Name => Name_Max,
5895                    Expressions => New_List (
5896                      Make_Integer_Literal (Loc, 0),
5897                      Convert_To (Typ,
5898                        New_Occurrence_Of
5899                          (Storage_Size_Variable (Root_Type (Ptyp)), Loc)))));
5900
5901             elsif Present (Associated_Storage_Pool (Root_Type (Ptyp))) then
5902
5903                --  If the access type is associated with a simple storage pool
5904                --  object, then attempt to locate the optional Storage_Size
5905                --  function of the simple storage pool type. If not found,
5906                --  then the result will default to zero.
5907
5908                if Present (Get_Rep_Pragma (Root_Type (Ptyp),
5909                                            Name_Simple_Storage_Pool_Type))
5910                then
5911                   declare
5912                      Pool_Type : constant Entity_Id :=
5913                                    Base_Type (Etype (Entity (N)));
5914
5915                   begin
5916                      Alloc_Op := Get_Name_Entity_Id (Name_Storage_Size);
5917                      while Present (Alloc_Op) loop
5918                         if Scope (Alloc_Op) = Scope (Pool_Type)
5919                           and then Present (First_Formal (Alloc_Op))
5920                           and then Etype (First_Formal (Alloc_Op)) = Pool_Type
5921                         then
5922                            exit;
5923                         end if;
5924
5925                         Alloc_Op := Homonym (Alloc_Op);
5926                      end loop;
5927                   end;
5928
5929                --  In the normal Storage_Pool case, retrieve the primitive
5930                --  function associated with the pool type.
5931
5932                else
5933                   Alloc_Op :=
5934                     Find_Prim_Op
5935                       (Etype (Associated_Storage_Pool (Root_Type (Ptyp))),
5936                        Attribute_Name (N));
5937                end if;
5938
5939                --  If Storage_Size wasn't found (can only occur in the simple
5940                --  storage pool case), then simply use zero for the result.
5941
5942                if not Present (Alloc_Op) then
5943                   Rewrite (N, Make_Integer_Literal (Loc, 0));
5944
5945                --  Otherwise, rewrite the allocator as a call to pool type's
5946                --  Storage_Size function.
5947
5948                else
5949                   Rewrite (N,
5950                     OK_Convert_To (Typ,
5951                       Make_Function_Call (Loc,
5952                         Name =>
5953                           New_Occurrence_Of (Alloc_Op, Loc),
5954
5955                         Parameter_Associations => New_List (
5956                           New_Occurrence_Of
5957                             (Associated_Storage_Pool
5958                                (Root_Type (Ptyp)), Loc)))));
5959                end if;
5960
5961             else
5962                Rewrite (N, Make_Integer_Literal (Loc, 0));
5963             end if;
5964
5965             Analyze_And_Resolve (N, Typ);
5966
5967          --  For tasks, we retrieve the size directly from the TCB. The
5968          --  size may depend on a discriminant of the type, and therefore
5969          --  can be a per-object expression, so type-level information is
5970          --  not sufficient in general. There are four cases to consider:
5971
5972          --  a) If the attribute appears within a task body, the designated
5973          --    TCB is obtained by a call to Self.
5974
5975          --  b) If the prefix of the attribute is the name of a task object,
5976          --  the designated TCB is the one stored in the corresponding record.
5977
5978          --  c) If the prefix is a task type, the size is obtained from the
5979          --  size variable created for each task type
5980
5981          --  d) If no Storage_Size was specified for the type, there is no
5982          --  size variable, and the value is a system-specific default.
5983
5984          else
5985             if In_Open_Scopes (Ptyp) then
5986
5987                --  Storage_Size (Self)
5988
5989                Rewrite (N,
5990                  Convert_To (Typ,
5991                    Make_Function_Call (Loc,
5992                      Name =>
5993                        New_Occurrence_Of (RTE (RE_Storage_Size), Loc),
5994                      Parameter_Associations =>
5995                        New_List (
5996                          Make_Function_Call (Loc,
5997                            Name =>
5998                              New_Occurrence_Of (RTE (RE_Self), Loc))))));
5999
6000             elsif not Is_Entity_Name (Pref)
6001               or else not Is_Type (Entity (Pref))
6002             then
6003                --  Storage_Size (Rec (Obj).Size)
6004
6005                Rewrite (N,
6006                  Convert_To (Typ,
6007                    Make_Function_Call (Loc,
6008                      Name =>
6009                        New_Occurrence_Of (RTE (RE_Storage_Size), Loc),
6010                        Parameter_Associations =>
6011                           New_List (
6012                             Make_Selected_Component (Loc,
6013                               Prefix =>
6014                                 Unchecked_Convert_To (
6015                                   Corresponding_Record_Type (Ptyp),
6016                                     New_Copy_Tree (Pref)),
6017                               Selector_Name =>
6018                                  Make_Identifier (Loc, Name_uTask_Id))))));
6019
6020             elsif Present (Storage_Size_Variable (Ptyp)) then
6021
6022                --  Static Storage_Size pragma given for type: retrieve value
6023                --  from its allocated storage variable.
6024
6025                Rewrite (N,
6026                  Convert_To (Typ,
6027                    Make_Function_Call (Loc,
6028                      Name => New_Occurrence_Of (
6029                        RTE (RE_Adjust_Storage_Size), Loc),
6030                      Parameter_Associations =>
6031                        New_List (
6032                          New_Occurrence_Of (
6033                            Storage_Size_Variable (Ptyp), Loc)))));
6034             else
6035                --  Get system default
6036
6037                Rewrite (N,
6038                  Convert_To (Typ,
6039                    Make_Function_Call (Loc,
6040                      Name =>
6041                        New_Occurrence_Of (
6042                         RTE (RE_Default_Stack_Size), Loc))));
6043             end if;
6044
6045             Analyze_And_Resolve (N, Typ);
6046          end if;
6047       end Storage_Size;
6048
6049       -----------------
6050       -- Stream_Size --
6051       -----------------
6052
6053       when Attribute_Stream_Size =>
6054          Rewrite (N,
6055            Make_Integer_Literal (Loc, Intval => Get_Stream_Size (Ptyp)));
6056          Analyze_And_Resolve (N, Typ);
6057
6058       ----------
6059       -- Succ --
6060       ----------
6061
6062       --  1. Deal with enumeration types with holes.
6063       --  2. For floating-point, generate call to attribute function.
6064       --  3. For other cases, deal with constraint checking.
6065
6066       when Attribute_Succ => Succ : declare
6067          Etyp : constant Entity_Id := Base_Type (Ptyp);
6068
6069       begin
6070
6071          --  For enumeration types with non-standard representations, we
6072          --  expand typ'Succ (x) into
6073
6074          --    Pos_To_Rep (Rep_To_Pos (x) + 1)
6075
6076          --    If the representation is contiguous, we compute instead
6077          --    Lit1 + Rep_to_Pos (x+1), to catch invalid representations.
6078
6079          if Is_Enumeration_Type (Ptyp)
6080            and then Present (Enum_Pos_To_Rep (Etyp))
6081          then
6082             if Has_Contiguous_Rep (Etyp) then
6083                Rewrite (N,
6084                   Unchecked_Convert_To (Ptyp,
6085                      Make_Op_Add (Loc,
6086                         Left_Opnd  =>
6087                          Make_Integer_Literal (Loc,
6088                            Enumeration_Rep (First_Literal (Ptyp))),
6089                         Right_Opnd =>
6090                           Make_Function_Call (Loc,
6091                             Name =>
6092                               New_Occurrence_Of
6093                                (TSS (Etyp, TSS_Rep_To_Pos), Loc),
6094
6095                             Parameter_Associations =>
6096                               New_List (
6097                                 Unchecked_Convert_To (Ptyp,
6098                                   Make_Op_Add (Loc,
6099                                   Left_Opnd =>
6100                                     Unchecked_Convert_To (Standard_Integer,
6101                                       Relocate_Node (First (Exprs))),
6102                                   Right_Opnd =>
6103                                     Make_Integer_Literal (Loc, 1))),
6104                                 Rep_To_Pos_Flag (Ptyp, Loc))))));
6105             else
6106                --  Add Boolean parameter True, to request program errror if
6107                --  we have a bad representation on our hands. Add False if
6108                --  checks are suppressed.
6109
6110                Append_To (Exprs, Rep_To_Pos_Flag (Ptyp, Loc));
6111                Rewrite (N,
6112                  Make_Indexed_Component (Loc,
6113                    Prefix =>
6114                      New_Occurrence_Of
6115                        (Enum_Pos_To_Rep (Etyp), Loc),
6116                    Expressions => New_List (
6117                      Make_Op_Add (Loc,
6118                        Left_Opnd =>
6119                          Make_Function_Call (Loc,
6120                            Name =>
6121                              New_Occurrence_Of
6122                                (TSS (Etyp, TSS_Rep_To_Pos), Loc),
6123                            Parameter_Associations => Exprs),
6124                        Right_Opnd => Make_Integer_Literal (Loc, 1)))));
6125             end if;
6126
6127             Analyze_And_Resolve (N, Typ);
6128
6129          --  For floating-point, we transform 'Succ into a call to the Succ
6130          --  floating-point attribute function in Fat_xxx (xxx is root type)
6131
6132          elsif Is_Floating_Point_Type (Ptyp) then
6133             Expand_Fpt_Attribute_R (N);
6134             Analyze_And_Resolve (N, Typ);
6135
6136          --  For modular types, nothing to do (no overflow, since wraps)
6137
6138          elsif Is_Modular_Integer_Type (Ptyp) then
6139             null;
6140
6141          --  For other types, if argument is marked as needing a range check or
6142          --  overflow checking is enabled, we must generate a check.
6143
6144          elsif not Overflow_Checks_Suppressed (Ptyp)
6145            or else Do_Range_Check (First (Exprs))
6146          then
6147             Set_Do_Range_Check (First (Exprs), False);
6148             Expand_Pred_Succ_Attribute (N);
6149          end if;
6150       end Succ;
6151
6152       ---------
6153       -- Tag --
6154       ---------
6155
6156       --  Transforms X'Tag into a direct reference to the tag of X
6157
6158       when Attribute_Tag => Tag : declare
6159          Ttyp           : Entity_Id;
6160          Prefix_Is_Type : Boolean;
6161
6162       begin
6163          if Is_Entity_Name (Pref) and then Is_Type (Entity (Pref)) then
6164             Ttyp := Entity (Pref);
6165             Prefix_Is_Type := True;
6166          else
6167             Ttyp := Ptyp;
6168             Prefix_Is_Type := False;
6169          end if;
6170
6171          if Is_Class_Wide_Type (Ttyp) then
6172             Ttyp := Root_Type (Ttyp);
6173          end if;
6174
6175          Ttyp := Underlying_Type (Ttyp);
6176
6177          --  Ada 2005: The type may be a synchronized tagged type, in which
6178          --  case the tag information is stored in the corresponding record.
6179
6180          if Is_Concurrent_Type (Ttyp) then
6181             Ttyp := Corresponding_Record_Type (Ttyp);
6182          end if;
6183
6184          if Prefix_Is_Type then
6185
6186             --  For VMs we leave the type attribute unexpanded because
6187             --  there's not a dispatching table to reference.
6188
6189             if Tagged_Type_Expansion then
6190                Rewrite (N,
6191                  Unchecked_Convert_To (RTE (RE_Tag),
6192                    New_Occurrence_Of
6193                      (Node (First_Elmt (Access_Disp_Table (Ttyp))), Loc)));
6194                Analyze_And_Resolve (N, RTE (RE_Tag));
6195             end if;
6196
6197          --  Ada 2005 (AI-251): The use of 'Tag in the sources always
6198          --  references the primary tag of the actual object. If 'Tag is
6199          --  applied to class-wide interface objects we generate code that
6200          --  displaces "this" to reference the base of the object.
6201
6202          elsif Comes_From_Source (N)
6203             and then Is_Class_Wide_Type (Etype (Prefix (N)))
6204             and then Is_Interface (Etype (Prefix (N)))
6205          then
6206             --  Generate:
6207             --    (To_Tag_Ptr (Prefix'Address)).all
6208
6209             --  Note that Prefix'Address is recursively expanded into a call
6210             --  to Base_Address (Obj.Tag)
6211
6212             --  Not needed for VM targets, since all handled by the VM
6213
6214             if Tagged_Type_Expansion then
6215                Rewrite (N,
6216                  Make_Explicit_Dereference (Loc,
6217                    Unchecked_Convert_To (RTE (RE_Tag_Ptr),
6218                      Make_Attribute_Reference (Loc,
6219                        Prefix => Relocate_Node (Pref),
6220                        Attribute_Name => Name_Address))));
6221                Analyze_And_Resolve (N, RTE (RE_Tag));
6222             end if;
6223
6224          else
6225             Rewrite (N,
6226               Make_Selected_Component (Loc,
6227                 Prefix => Relocate_Node (Pref),
6228                 Selector_Name =>
6229                   New_Occurrence_Of (First_Tag_Component (Ttyp), Loc)));
6230             Analyze_And_Resolve (N, RTE (RE_Tag));
6231          end if;
6232       end Tag;
6233
6234       ----------------
6235       -- Terminated --
6236       ----------------
6237
6238       --  Transforms 'Terminated attribute into a call to Terminated function
6239
6240       when Attribute_Terminated => Terminated :
6241       begin
6242          --  The prefix of Terminated is of a task interface class-wide type.
6243          --  Generate:
6244          --    terminated (Task_Id (Pref._disp_get_task_id));
6245
6246          if Ada_Version >= Ada_2005
6247            and then Ekind (Ptyp) = E_Class_Wide_Type
6248            and then Is_Interface (Ptyp)
6249            and then Is_Task_Interface (Ptyp)
6250          then
6251             Rewrite (N,
6252               Make_Function_Call (Loc,
6253                 Name =>
6254                   New_Occurrence_Of (RTE (RE_Terminated), Loc),
6255                 Parameter_Associations => New_List (
6256                   Make_Unchecked_Type_Conversion (Loc,
6257                     Subtype_Mark =>
6258                       New_Occurrence_Of (RTE (RO_ST_Task_Id), Loc),
6259                     Expression =>
6260                       Make_Selected_Component (Loc,
6261                         Prefix =>
6262                           New_Copy_Tree (Pref),
6263                         Selector_Name =>
6264                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id))))));
6265
6266          elsif Restricted_Profile then
6267             Rewrite (N,
6268               Build_Call_With_Task (Pref, RTE (RE_Restricted_Terminated)));
6269
6270          else
6271             Rewrite (N,
6272               Build_Call_With_Task (Pref, RTE (RE_Terminated)));
6273          end if;
6274
6275          Analyze_And_Resolve (N, Standard_Boolean);
6276       end Terminated;
6277
6278       ----------------
6279       -- To_Address --
6280       ----------------
6281
6282       --  Transforms System'To_Address (X) and System.Address'Ref (X) into
6283       --  unchecked conversion from (integral) type of X to type address.
6284
6285       when Attribute_To_Address | Attribute_Ref =>
6286          Rewrite (N,
6287            Unchecked_Convert_To (RTE (RE_Address),
6288              Relocate_Node (First (Exprs))));
6289          Analyze_And_Resolve (N, RTE (RE_Address));
6290
6291       ------------
6292       -- To_Any --
6293       ------------
6294
6295       when Attribute_To_Any => To_Any : declare
6296          P_Type : constant Entity_Id := Etype (Pref);
6297          Decls  : constant List_Id   := New_List;
6298       begin
6299          Rewrite (N,
6300            Build_To_Any_Call
6301              (Loc,
6302               Convert_To (P_Type,
6303               Relocate_Node (First (Exprs))), Decls));
6304          Insert_Actions (N, Decls);
6305          Analyze_And_Resolve (N, RTE (RE_Any));
6306       end To_Any;
6307
6308       ----------------
6309       -- Truncation --
6310       ----------------
6311
6312       --  Transforms 'Truncation into a call to the floating-point attribute
6313       --  function Truncation in Fat_xxx (where xxx is the root type).
6314       --  Expansion is avoided for cases the back end can handle directly.
6315
6316       when Attribute_Truncation =>
6317          if not Is_Inline_Floating_Point_Attribute (N) then
6318             Expand_Fpt_Attribute_R (N);
6319          end if;
6320
6321       --------------
6322       -- TypeCode --
6323       --------------
6324
6325       when Attribute_TypeCode => TypeCode : declare
6326          P_Type : constant Entity_Id := Etype (Pref);
6327          Decls  : constant List_Id   := New_List;
6328       begin
6329          Rewrite (N, Build_TypeCode_Call (Loc, P_Type, Decls));
6330          Insert_Actions (N, Decls);
6331          Analyze_And_Resolve (N, RTE (RE_TypeCode));
6332       end TypeCode;
6333
6334       -----------------------
6335       -- Unbiased_Rounding --
6336       -----------------------
6337
6338       --  Transforms 'Unbiased_Rounding into a call to the floating-point
6339       --  attribute function Unbiased_Rounding in Fat_xxx (where xxx is the
6340       --  root type). Expansion is avoided for cases the back end can handle
6341       --  directly.
6342
6343       when Attribute_Unbiased_Rounding =>
6344          if not Is_Inline_Floating_Point_Attribute (N) then
6345             Expand_Fpt_Attribute_R (N);
6346          end if;
6347
6348       ------------
6349       -- Update --
6350       ------------
6351
6352       when Attribute_Update =>
6353          Expand_Update_Attribute (N);
6354
6355       ---------------
6356       -- VADS_Size --
6357       ---------------
6358
6359       --  The processing for VADS_Size is shared with Size
6360
6361       ---------
6362       -- Val --
6363       ---------
6364
6365       --  For enumeration types with a standard representation, and for all
6366       --  other types, Val is handled by the back end. For enumeration types
6367       --  with a non-standard representation we use the _Pos_To_Rep array that
6368       --  was created when the type was frozen.
6369
6370       when Attribute_Val => Val : declare
6371          Etyp : constant Entity_Id := Base_Type (Entity (Pref));
6372
6373       begin
6374          if Is_Enumeration_Type (Etyp)
6375            and then Present (Enum_Pos_To_Rep (Etyp))
6376          then
6377             if Has_Contiguous_Rep (Etyp) then
6378                declare
6379                   Rep_Node : constant Node_Id :=
6380                     Unchecked_Convert_To (Etyp,
6381                        Make_Op_Add (Loc,
6382                          Left_Opnd =>
6383                             Make_Integer_Literal (Loc,
6384                               Enumeration_Rep (First_Literal (Etyp))),
6385                          Right_Opnd =>
6386                           (Convert_To (Standard_Integer,
6387                              Relocate_Node (First (Exprs))))));
6388
6389                begin
6390                   Rewrite (N,
6391                      Unchecked_Convert_To (Etyp,
6392                          Make_Op_Add (Loc,
6393                            Left_Opnd =>
6394                              Make_Integer_Literal (Loc,
6395                                Enumeration_Rep (First_Literal (Etyp))),
6396                            Right_Opnd =>
6397                              Make_Function_Call (Loc,
6398                                Name =>
6399                                  New_Occurrence_Of
6400                                    (TSS (Etyp, TSS_Rep_To_Pos), Loc),
6401                                Parameter_Associations => New_List (
6402                                  Rep_Node,
6403                                  Rep_To_Pos_Flag (Etyp, Loc))))));
6404                end;
6405
6406             else
6407                Rewrite (N,
6408                  Make_Indexed_Component (Loc,
6409                    Prefix => New_Occurrence_Of (Enum_Pos_To_Rep (Etyp), Loc),
6410                    Expressions => New_List (
6411                      Convert_To (Standard_Integer,
6412                        Relocate_Node (First (Exprs))))));
6413             end if;
6414
6415             Analyze_And_Resolve (N, Typ);
6416
6417          --  If the argument is marked as requiring a range check then generate
6418          --  it here.
6419
6420          elsif Do_Range_Check (First (Exprs)) then
6421             Generate_Range_Check (First (Exprs), Etyp, CE_Range_Check_Failed);
6422          end if;
6423       end Val;
6424
6425       -----------
6426       -- Valid --
6427       -----------
6428
6429       --  The code for valid is dependent on the particular types involved.
6430       --  See separate sections below for the generated code in each case.
6431
6432       when Attribute_Valid => Valid : declare
6433          Btyp : Entity_Id := Base_Type (Ptyp);
6434          Tst  : Node_Id;
6435
6436          Save_Validity_Checks_On : constant Boolean := Validity_Checks_On;
6437          --  Save the validity checking mode. We always turn off validity
6438          --  checking during process of 'Valid since this is one place
6439          --  where we do not want the implicit validity checks to intefere
6440          --  with the explicit validity check that the programmer is doing.
6441
6442          function Make_Range_Test return Node_Id;
6443          --  Build the code for a range test of the form
6444          --    Btyp!(Pref) in Btyp!(Ptyp'First) .. Btyp!(Ptyp'Last)
6445
6446          ---------------------
6447          -- Make_Range_Test --
6448          ---------------------
6449
6450          function Make_Range_Test return Node_Id is
6451             Temp : constant Node_Id := Duplicate_Subexpr (Pref);
6452
6453          begin
6454             --  The value whose validity is being checked has been captured in
6455             --  an object declaration. We certainly don't want this object to
6456             --  appear valid because the declaration initializes it.
6457
6458             if Is_Entity_Name (Temp) then
6459                Set_Is_Known_Valid (Entity (Temp), False);
6460             end if;
6461
6462             return
6463               Make_In (Loc,
6464                 Left_Opnd  =>
6465                   Unchecked_Convert_To (Btyp, Temp),
6466                 Right_Opnd =>
6467                   Make_Range (Loc,
6468                     Low_Bound =>
6469                       Unchecked_Convert_To (Btyp,
6470                         Make_Attribute_Reference (Loc,
6471                           Prefix => New_Occurrence_Of (Ptyp, Loc),
6472                           Attribute_Name => Name_First)),
6473                     High_Bound =>
6474                       Unchecked_Convert_To (Btyp,
6475                         Make_Attribute_Reference (Loc,
6476                           Prefix => New_Occurrence_Of (Ptyp, Loc),
6477                           Attribute_Name => Name_Last))));
6478          end Make_Range_Test;
6479
6480       --  Start of processing for Attribute_Valid
6481
6482       begin
6483          --  Do not expand sourced code 'Valid reference in CodePeer mode,
6484          --  will be handled by the back-end directly.
6485
6486          if CodePeer_Mode and then Comes_From_Source (N) then
6487             return;
6488          end if;
6489
6490          --  Turn off validity checks. We do not want any implicit validity
6491          --  checks to intefere with the explicit check from the attribute
6492
6493          Validity_Checks_On := False;
6494
6495          --  Retrieve the base type. Handle the case where the base type is a
6496          --  private enumeration type.
6497
6498          if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
6499             Btyp := Full_View (Btyp);
6500          end if;
6501
6502          --  Floating-point case. This case is handled by the Valid attribute
6503          --  code in the floating-point attribute run-time library.
6504
6505          if Is_Floating_Point_Type (Ptyp) then
6506             Float_Valid : declare
6507                Pkg : RE_Id;
6508                Ftp : Entity_Id;
6509
6510                function Get_Fat_Entity (Nam : Name_Id) return Entity_Id;
6511                --  Return entity for Pkg.Nam
6512
6513                --------------------
6514                -- Get_Fat_Entity --
6515                --------------------
6516
6517                function Get_Fat_Entity (Nam : Name_Id) return Entity_Id is
6518                   Exp_Name : constant Node_Id :=
6519                     Make_Selected_Component (Loc,
6520                       Prefix        => New_Occurrence_Of (RTE (Pkg), Loc),
6521                       Selector_Name => Make_Identifier (Loc, Nam));
6522                begin
6523                   Find_Selected_Component (Exp_Name);
6524                   return Entity (Exp_Name);
6525                end Get_Fat_Entity;
6526
6527             --  Start of processing for Float_Valid
6528
6529             begin
6530                --  The C and AAMP back-ends handle Valid for fpt types
6531
6532                if Generate_C_Code or else Float_Rep (Btyp) = AAMP then
6533                   Analyze_And_Resolve (Pref, Ptyp);
6534                   Set_Etype (N, Standard_Boolean);
6535                   Set_Analyzed (N);
6536
6537                else
6538                   Find_Fat_Info (Ptyp, Ftp, Pkg);
6539
6540                   --  If the prefix is a reverse SSO component, or is possibly
6541                   --  unaligned, first create a temporary copy that is in
6542                   --  native SSO, and properly aligned. Make it Volatile to
6543                   --  prevent folding in the back-end. Note that we use an
6544                   --  intermediate constrained string type to initialize the
6545                   --  temporary, as the value at hand might be invalid, and in
6546                   --  that case it cannot be copied using a floating point
6547                   --  register.
6548
6549                   if In_Reverse_Storage_Order_Object (Pref)
6550                     or else Is_Possibly_Unaligned_Object (Pref)
6551                   then
6552                      declare
6553                         Temp : constant Entity_Id :=
6554                                  Make_Temporary (Loc, 'F');
6555
6556                         Fat_S : constant Entity_Id :=
6557                                   Get_Fat_Entity (Name_S);
6558                         --  Constrained string subtype of appropriate size
6559
6560                         Fat_P : constant Entity_Id :=
6561                                   Get_Fat_Entity (Name_P);
6562                         --  Access to Fat_S
6563
6564                         Decl : constant Node_Id :=
6565                                  Make_Object_Declaration (Loc,
6566                                    Defining_Identifier => Temp,
6567                                    Aliased_Present     => True,
6568                                    Object_Definition   =>
6569                                      New_Occurrence_Of (Ptyp, Loc));
6570
6571                      begin
6572                         Set_Aspect_Specifications (Decl, New_List (
6573                           Make_Aspect_Specification (Loc,
6574                             Identifier =>
6575                               Make_Identifier (Loc, Name_Volatile))));
6576
6577                         Insert_Actions (N,
6578                           New_List (
6579                             Decl,
6580
6581                             Make_Assignment_Statement (Loc,
6582                               Name =>
6583                                 Make_Explicit_Dereference (Loc,
6584                                   Prefix =>
6585                                     Unchecked_Convert_To (Fat_P,
6586                                       Make_Attribute_Reference (Loc,
6587                                         Prefix =>
6588                                           New_Occurrence_Of (Temp, Loc),
6589                                         Attribute_Name =>
6590                                           Name_Unrestricted_Access))),
6591                               Expression =>
6592                                 Unchecked_Convert_To (Fat_S,
6593                                   Relocate_Node (Pref)))),
6594
6595                           Suppress => All_Checks);
6596
6597                         Rewrite (Pref, New_Occurrence_Of (Temp, Loc));
6598                      end;
6599                   end if;
6600
6601                   --  We now have an object of the proper endianness and
6602                   --  alignment, and can construct a Valid attribute.
6603
6604                   --  We make sure the prefix of this valid attribute is
6605                   --  marked as not coming from source, to avoid losing
6606                   --  warnings from 'Valid looking like a possible update.
6607
6608                   Set_Comes_From_Source (Pref, False);
6609
6610                   Expand_Fpt_Attribute
6611                     (N, Pkg, Name_Valid,
6612                      New_List (
6613                        Make_Attribute_Reference (Loc,
6614                          Prefix         => Unchecked_Convert_To (Ftp, Pref),
6615                          Attribute_Name => Name_Unrestricted_Access)));
6616                end if;
6617
6618                --  One more task, we still need a range check. Required
6619                --  only if we have a constraint, since the Valid routine
6620                --  catches infinities properly (infinities are never valid).
6621
6622                --  The way we do the range check is simply to create the
6623                --  expression: Valid (N) and then Base_Type(Pref) in Typ.
6624
6625                if not Subtypes_Statically_Match (Ptyp, Btyp) then
6626                   Rewrite (N,
6627                     Make_And_Then (Loc,
6628                       Left_Opnd  => Relocate_Node (N),
6629                       Right_Opnd =>
6630                         Make_In (Loc,
6631                           Left_Opnd  => Convert_To (Btyp, Pref),
6632                           Right_Opnd => New_Occurrence_Of (Ptyp, Loc))));
6633                end if;
6634             end Float_Valid;
6635
6636          --  Enumeration type with holes
6637
6638          --  For enumeration types with holes, the Pos value constructed by
6639          --  the Enum_Rep_To_Pos function built in Exp_Ch3 called with a
6640          --  second argument of False returns minus one for an invalid value,
6641          --  and the non-negative pos value for a valid value, so the
6642          --  expansion of X'Valid is simply:
6643
6644          --     type(X)'Pos (X) >= 0
6645
6646          --  We can't quite generate it that way because of the requirement
6647          --  for the non-standard second argument of False in the resulting
6648          --  rep_to_pos call, so we have to explicitly create:
6649
6650          --     _rep_to_pos (X, False) >= 0
6651
6652          --  If we have an enumeration subtype, we also check that the
6653          --  value is in range:
6654
6655          --    _rep_to_pos (X, False) >= 0
6656          --      and then
6657          --       (X >= type(X)'First and then type(X)'Last <= X)
6658
6659          elsif Is_Enumeration_Type (Ptyp)
6660            and then Present (Enum_Pos_To_Rep (Btyp))
6661          then
6662             Tst :=
6663               Make_Op_Ge (Loc,
6664                 Left_Opnd =>
6665                   Make_Function_Call (Loc,
6666                     Name =>
6667                       New_Occurrence_Of (TSS (Btyp, TSS_Rep_To_Pos), Loc),
6668                     Parameter_Associations => New_List (
6669                       Pref,
6670                       New_Occurrence_Of (Standard_False, Loc))),
6671                 Right_Opnd => Make_Integer_Literal (Loc, 0));
6672
6673             if Ptyp /= Btyp
6674               and then
6675                 (Type_Low_Bound (Ptyp) /= Type_Low_Bound (Btyp)
6676                   or else
6677                  Type_High_Bound (Ptyp) /= Type_High_Bound (Btyp))
6678             then
6679                --  The call to Make_Range_Test will create declarations
6680                --  that need a proper insertion point, but Pref is now
6681                --  attached to a node with no ancestor. Attach to tree
6682                --  even if it is to be rewritten below.
6683
6684                Set_Parent (Tst, Parent (N));
6685
6686                Tst :=
6687                  Make_And_Then (Loc,
6688                    Left_Opnd  => Make_Range_Test,
6689                    Right_Opnd => Tst);
6690             end if;
6691
6692             Rewrite (N, Tst);
6693
6694          --  Fortran convention booleans
6695
6696          --  For the very special case of Fortran convention booleans, the
6697          --  value is always valid, since it is an integer with the semantics
6698          --  that non-zero is true, and any value is permissible.
6699
6700          elsif Is_Boolean_Type (Ptyp)
6701            and then Convention (Ptyp) = Convention_Fortran
6702          then
6703             Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
6704
6705          --  For biased representations, we will be doing an unchecked
6706          --  conversion without unbiasing the result. That means that the range
6707          --  test has to take this into account, and the proper form of the
6708          --  test is:
6709
6710          --    Btyp!(Pref) < Btyp!(Ptyp'Range_Length)
6711
6712          elsif Has_Biased_Representation (Ptyp) then
6713             Btyp := RTE (RE_Unsigned_32);
6714             Rewrite (N,
6715               Make_Op_Lt (Loc,
6716                 Left_Opnd =>
6717                   Unchecked_Convert_To (Btyp, Duplicate_Subexpr (Pref)),
6718                 Right_Opnd =>
6719                   Unchecked_Convert_To (Btyp,
6720                     Make_Attribute_Reference (Loc,
6721                       Prefix => New_Occurrence_Of (Ptyp, Loc),
6722                       Attribute_Name => Name_Range_Length))));
6723
6724          --  For all other scalar types, what we want logically is a
6725          --  range test:
6726
6727          --     X in type(X)'First .. type(X)'Last
6728
6729          --  But that's precisely what won't work because of possible
6730          --  unwanted optimization (and indeed the basic motivation for
6731          --  the Valid attribute is exactly that this test does not work).
6732          --  What will work is:
6733
6734          --     Btyp!(X) >= Btyp!(type(X)'First)
6735          --       and then
6736          --     Btyp!(X) <= Btyp!(type(X)'Last)
6737
6738          --  where Btyp is an integer type large enough to cover the full
6739          --  range of possible stored values (i.e. it is chosen on the basis
6740          --  of the size of the type, not the range of the values). We write
6741          --  this as two tests, rather than a range check, so that static
6742          --  evaluation will easily remove either or both of the checks if
6743          --  they can be -statically determined to be true (this happens
6744          --  when the type of X is static and the range extends to the full
6745          --  range of stored values).
6746
6747          --  Unsigned types. Note: it is safe to consider only whether the
6748          --  subtype is unsigned, since we will in that case be doing all
6749          --  unsigned comparisons based on the subtype range. Since we use the
6750          --  actual subtype object size, this is appropriate.
6751
6752          --  For example, if we have
6753
6754          --    subtype x is integer range 1 .. 200;
6755          --    for x'Object_Size use 8;
6756
6757          --  Now the base type is signed, but objects of this type are bits
6758          --  unsigned, and doing an unsigned test of the range 1 to 200 is
6759          --  correct, even though a value greater than 127 looks signed to a
6760          --  signed comparison.
6761
6762          elsif Is_Unsigned_Type (Ptyp) then
6763             if Esize (Ptyp) <= 32 then
6764                Btyp := RTE (RE_Unsigned_32);
6765             else
6766                Btyp := RTE (RE_Unsigned_64);
6767             end if;
6768
6769             Rewrite (N, Make_Range_Test);
6770
6771          --  Signed types
6772
6773          else
6774             if Esize (Ptyp) <= Esize (Standard_Integer) then
6775                Btyp := Standard_Integer;
6776             else
6777                Btyp := Universal_Integer;
6778             end if;
6779
6780             Rewrite (N, Make_Range_Test);
6781          end if;
6782
6783          --  If a predicate is present, then we do the predicate test, even if
6784          --  within the predicate function (infinite recursion is warned about
6785          --  in Sem_Attr in that case).
6786
6787          declare
6788             Pred_Func : constant Entity_Id := Predicate_Function (Ptyp);
6789
6790          begin
6791             if Present (Pred_Func) then
6792                Rewrite (N,
6793                  Make_And_Then (Loc,
6794                    Left_Opnd  => Relocate_Node (N),
6795                    Right_Opnd => Make_Predicate_Call (Ptyp, Pref)));
6796             end if;
6797          end;
6798
6799          Analyze_And_Resolve (N, Standard_Boolean);
6800          Validity_Checks_On := Save_Validity_Checks_On;
6801       end Valid;
6802
6803       -------------------
6804       -- Valid_Scalars --
6805       -------------------
6806
6807       when Attribute_Valid_Scalars => Valid_Scalars : declare
6808          Ftyp : Entity_Id;
6809
6810       begin
6811          if Present (Underlying_Type (Ptyp)) then
6812             Ftyp := Underlying_Type (Ptyp);
6813          else
6814             Ftyp := Ptyp;
6815          end if;
6816
6817          --  Replace by True if no scalar parts
6818
6819          if not Scalar_Part_Present (Ftyp) then
6820             Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
6821
6822          --  For scalar types, Valid_Scalars is the same as Valid
6823
6824          elsif Is_Scalar_Type (Ftyp) then
6825             Rewrite (N,
6826               Make_Attribute_Reference (Loc,
6827                 Attribute_Name => Name_Valid,
6828                 Prefix         => Pref));
6829
6830          --  For array types, we construct a function that determines if there
6831          --  are any non-valid scalar subcomponents, and call the function.
6832          --  We only do this for arrays whose component type needs checking
6833
6834          elsif Is_Array_Type (Ftyp)
6835            and then Scalar_Part_Present (Component_Type (Ftyp))
6836          then
6837             Rewrite (N,
6838               Make_Function_Call (Loc,
6839                 Name                   =>
6840                   New_Occurrence_Of (Build_Array_VS_Func (Ftyp, N), Loc),
6841                 Parameter_Associations => New_List (Pref)));
6842
6843          --  For record types, we construct a function that determines if there
6844          --  are any non-valid scalar subcomponents, and call the function.
6845
6846          elsif Is_Record_Type (Ftyp)
6847             and then Nkind (Type_Definition (Declaration_Node (Ftyp))) =
6848                                                         N_Record_Definition
6849          then
6850             Rewrite (N,
6851               Make_Function_Call (Loc,
6852                 Name                   =>
6853                   New_Occurrence_Of (Build_Record_VS_Func (Ftyp, N), Loc),
6854               Parameter_Associations => New_List (Pref)));
6855
6856          --  Other record types or types with discriminants
6857
6858          elsif Is_Record_Type (Ftyp) or else Has_Discriminants (Ptyp) then
6859
6860             --  Build expression with list of equality tests
6861
6862             declare
6863                C : Entity_Id;
6864                X : Node_Id;
6865                A : Name_Id;
6866
6867             begin
6868                X := New_Occurrence_Of (Standard_True, Loc);
6869                C := First_Component_Or_Discriminant (Ptyp);
6870                while Present (C) loop
6871                   if not Scalar_Part_Present (Etype (C)) then
6872                      goto Continue;
6873                   elsif Is_Scalar_Type (Etype (C)) then
6874                      A := Name_Valid;
6875                   else
6876                      A := Name_Valid_Scalars;
6877                   end if;
6878
6879                   X :=
6880                     Make_And_Then (Loc,
6881                       Left_Opnd   => X,
6882                       Right_Opnd  =>
6883                         Make_Attribute_Reference (Loc,
6884                           Attribute_Name => A,
6885                           Prefix         =>
6886                             Make_Selected_Component (Loc,
6887                               Prefix        =>
6888                                 Duplicate_Subexpr (Pref, Name_Req => True),
6889                               Selector_Name =>
6890                                 New_Occurrence_Of (C, Loc))));
6891                <<Continue>>
6892                   Next_Component_Or_Discriminant (C);
6893                end loop;
6894
6895                Rewrite (N, X);
6896             end;
6897
6898          --  For all other types, result is True
6899
6900          else
6901             Rewrite (N, New_Occurrence_Of (Standard_Boolean, Loc));
6902          end if;
6903
6904          --  Result is always boolean, but never static
6905
6906          Analyze_And_Resolve (N, Standard_Boolean);
6907          Set_Is_Static_Expression (N, False);
6908       end Valid_Scalars;
6909
6910       -----------
6911       -- Value --
6912       -----------
6913
6914       --  Value attribute is handled in separate unit Exp_Imgv
6915
6916       when Attribute_Value =>
6917          Exp_Imgv.Expand_Value_Attribute (N);
6918
6919       -----------------
6920       -- Value_Size --
6921       -----------------
6922
6923       --  The processing for Value_Size shares the processing for Size
6924
6925       -------------
6926       -- Version --
6927       -------------
6928
6929       --  The processing for Version shares the processing for Body_Version
6930
6931       ----------------
6932       -- Wide_Image --
6933       ----------------
6934
6935       --  Wide_Image attribute is handled in separate unit Exp_Imgv
6936
6937       when Attribute_Wide_Image =>
6938          Exp_Imgv.Expand_Wide_Image_Attribute (N);
6939
6940       ---------------------
6941       -- Wide_Wide_Image --
6942       ---------------------
6943
6944       --  Wide_Wide_Image attribute is handled in separate unit Exp_Imgv
6945
6946       when Attribute_Wide_Wide_Image =>
6947          Exp_Imgv.Expand_Wide_Wide_Image_Attribute (N);
6948
6949       ----------------
6950       -- Wide_Value --
6951       ----------------
6952
6953       --  We expand typ'Wide_Value (X) into
6954
6955       --    typ'Value
6956       --      (Wide_String_To_String (X, Wide_Character_Encoding_Method))
6957
6958       --  Wide_String_To_String is a runtime function that converts its wide
6959       --  string argument to String, converting any non-translatable characters
6960       --  into appropriate escape sequences. This preserves the required
6961       --  semantics of Wide_Value in all cases, and results in a very simple
6962       --  implementation approach.
6963
6964       --  Note: for this approach to be fully standard compliant for the cases
6965       --  where typ is Wide_Character and Wide_Wide_Character, the encoding
6966       --  method must cover the entire character range (e.g. UTF-8). But that
6967       --  is a reasonable requirement when dealing with encoded character
6968       --  sequences. Presumably if one of the restrictive encoding mechanisms
6969       --  is in use such as Shift-JIS, then characters that cannot be
6970       --  represented using this encoding will not appear in any case.
6971
6972       when Attribute_Wide_Value => Wide_Value :
6973       begin
6974          Rewrite (N,
6975            Make_Attribute_Reference (Loc,
6976              Prefix         => Pref,
6977              Attribute_Name => Name_Value,
6978
6979              Expressions    => New_List (
6980                Make_Function_Call (Loc,
6981                  Name =>
6982                    New_Occurrence_Of (RTE (RE_Wide_String_To_String), Loc),
6983
6984                  Parameter_Associations => New_List (
6985                    Relocate_Node (First (Exprs)),
6986                    Make_Integer_Literal (Loc,
6987                      Intval => Int (Wide_Character_Encoding_Method)))))));
6988
6989          Analyze_And_Resolve (N, Typ);
6990       end Wide_Value;
6991
6992       ---------------------
6993       -- Wide_Wide_Value --
6994       ---------------------
6995
6996       --  We expand typ'Wide_Value_Value (X) into
6997
6998       --    typ'Value
6999       --      (Wide_Wide_String_To_String (X, Wide_Character_Encoding_Method))
7000
7001       --  Wide_Wide_String_To_String is a runtime function that converts its
7002       --  wide string argument to String, converting any non-translatable
7003       --  characters into appropriate escape sequences. This preserves the
7004       --  required semantics of Wide_Wide_Value in all cases, and results in a
7005       --  very simple implementation approach.
7006
7007       --  It's not quite right where typ = Wide_Wide_Character, because the
7008       --  encoding method may not cover the whole character type ???
7009
7010       when Attribute_Wide_Wide_Value => Wide_Wide_Value :
7011       begin
7012          Rewrite (N,
7013            Make_Attribute_Reference (Loc,
7014              Prefix         => Pref,
7015              Attribute_Name => Name_Value,
7016
7017              Expressions    => New_List (
7018                Make_Function_Call (Loc,
7019                  Name =>
7020                    New_Occurrence_Of
7021                      (RTE (RE_Wide_Wide_String_To_String), Loc),
7022
7023                  Parameter_Associations => New_List (
7024                    Relocate_Node (First (Exprs)),
7025                    Make_Integer_Literal (Loc,
7026                      Intval => Int (Wide_Character_Encoding_Method)))))));
7027
7028          Analyze_And_Resolve (N, Typ);
7029       end Wide_Wide_Value;
7030
7031       ---------------------
7032       -- Wide_Wide_Width --
7033       ---------------------
7034
7035       --  Wide_Wide_Width attribute is handled in separate unit Exp_Imgv
7036
7037       when Attribute_Wide_Wide_Width =>
7038          Exp_Imgv.Expand_Width_Attribute (N, Wide_Wide);
7039
7040       ----------------
7041       -- Wide_Width --
7042       ----------------
7043
7044       --  Wide_Width attribute is handled in separate unit Exp_Imgv
7045
7046       when Attribute_Wide_Width =>
7047          Exp_Imgv.Expand_Width_Attribute (N, Wide);
7048
7049       -----------
7050       -- Width --
7051       -----------
7052
7053       --  Width attribute is handled in separate unit Exp_Imgv
7054
7055       when Attribute_Width =>
7056          Exp_Imgv.Expand_Width_Attribute (N, Normal);
7057
7058       -----------
7059       -- Write --
7060       -----------
7061
7062       when Attribute_Write => Write : declare
7063          P_Type : constant Entity_Id := Entity (Pref);
7064          U_Type : constant Entity_Id := Underlying_Type (P_Type);
7065          Pname  : Entity_Id;
7066          Decl   : Node_Id;
7067          Prag   : Node_Id;
7068          Arg3   : Node_Id;
7069          Wfunc  : Node_Id;
7070
7071       begin
7072          --  If no underlying type, we have an error that will be diagnosed
7073          --  elsewhere, so here we just completely ignore the expansion.
7074
7075          if No (U_Type) then
7076             return;
7077          end if;
7078
7079          --  Stream operations can appear in user code even if the restriction
7080          --  No_Streams is active (for example, when instantiating a predefined
7081          --  container). In that case rewrite the attribute as a Raise to
7082          --  prevent any run-time use.
7083
7084          if Restriction_Active (No_Streams) then
7085             Rewrite (N,
7086               Make_Raise_Program_Error (Sloc (N),
7087                 Reason => PE_Stream_Operation_Not_Allowed));
7088             Set_Etype (N, U_Type);
7089             return;
7090          end if;
7091
7092          --  The simple case, if there is a TSS for Write, just call it
7093
7094          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Write);
7095
7096          if Present (Pname) then
7097             null;
7098
7099          else
7100             --  If there is a Stream_Convert pragma, use it, we rewrite
7101
7102             --     sourcetyp'Output (stream, Item)
7103
7104             --  as
7105
7106             --     strmtyp'Output (Stream, strmwrite (acttyp (Item)));
7107
7108             --  where strmwrite is the given Write function that converts an
7109             --  argument of type sourcetyp or a type acctyp, from which it is
7110             --  derived to type strmtyp. The conversion to acttyp is required
7111             --  for the derived case.
7112
7113             Prag := Get_Stream_Convert_Pragma (P_Type);
7114
7115             if Present (Prag) then
7116                Arg3 :=
7117                  Next (Next (First (Pragma_Argument_Associations (Prag))));
7118                Wfunc := Entity (Expression (Arg3));
7119
7120                Rewrite (N,
7121                  Make_Attribute_Reference (Loc,
7122                    Prefix => New_Occurrence_Of (Etype (Wfunc), Loc),
7123                    Attribute_Name => Name_Output,
7124                    Expressions => New_List (
7125                      Relocate_Node (First (Exprs)),
7126                      Make_Function_Call (Loc,
7127                        Name => New_Occurrence_Of (Wfunc, Loc),
7128                        Parameter_Associations => New_List (
7129                          OK_Convert_To (Etype (First_Formal (Wfunc)),
7130                            Relocate_Node (Next (First (Exprs)))))))));
7131
7132                Analyze (N);
7133                return;
7134
7135             --  For elementary types, we call the W_xxx routine directly
7136
7137             elsif Is_Elementary_Type (U_Type) then
7138                Rewrite (N, Build_Elementary_Write_Call (N));
7139                Analyze (N);
7140                return;
7141
7142             --  Array type case
7143
7144             elsif Is_Array_Type (U_Type) then
7145                Build_Array_Write_Procedure (N, U_Type, Decl, Pname);
7146                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
7147
7148             --  Tagged type case, use the primitive Write function. Note that
7149             --  this will dispatch in the class-wide case which is what we want
7150
7151             elsif Is_Tagged_Type (U_Type) then
7152                Pname := Find_Prim_Op (U_Type, TSS_Stream_Write);
7153
7154             --  All other record type cases, including protected records.
7155             --  The latter only arise for expander generated code for
7156             --  handling shared passive partition access.
7157
7158             else
7159                pragma Assert
7160                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
7161
7162                --  Ada 2005 (AI-216): Program_Error is raised when executing
7163                --  the default implementation of the Write attribute of an
7164                --  Unchecked_Union type. However, if the 'Write reference is
7165                --  within the generated Output stream procedure, Write outputs
7166                --  the components, and the default values of the discriminant
7167                --  are streamed by the Output procedure itself.
7168
7169                if Is_Unchecked_Union (Base_Type (U_Type))
7170                  and not Is_TSS (Current_Scope, TSS_Stream_Output)
7171                then
7172                   Insert_Action (N,
7173                     Make_Raise_Program_Error (Loc,
7174                       Reason => PE_Unchecked_Union_Restriction));
7175                end if;
7176
7177                if Has_Discriminants (U_Type)
7178                  and then Present
7179                    (Discriminant_Default_Value (First_Discriminant (U_Type)))
7180                then
7181                   Build_Mutable_Record_Write_Procedure
7182                     (Loc, Full_Base (U_Type), Decl, Pname);
7183                else
7184                   Build_Record_Write_Procedure
7185                     (Loc, Full_Base (U_Type), Decl, Pname);
7186                end if;
7187
7188                Insert_Action (N, Decl);
7189             end if;
7190          end if;
7191
7192          --  If we fall through, Pname is the procedure to be called
7193
7194          Rewrite_Stream_Proc_Call (Pname);
7195       end Write;
7196
7197       --  Component_Size is handled by the back end, unless the component size
7198       --  is known at compile time, which is always true in the packed array
7199       --  case. It is important that the packed array case is handled in the
7200       --  front end (see Eval_Attribute) since the back end would otherwise get
7201       --  confused by the equivalent packed array type.
7202
7203       when Attribute_Component_Size =>
7204          null;
7205
7206       --  The following attributes are handled by the back end (except that
7207       --  static cases have already been evaluated during semantic processing,
7208       --  but in any case the back end should not count on this).
7209
7210       --  The back end also handles the non-class-wide cases of Size
7211
7212       when Attribute_Bit_Order                    |
7213            Attribute_Code_Address                 |
7214            Attribute_Definite                     |
7215            Attribute_Deref                        |
7216            Attribute_Null_Parameter               |
7217            Attribute_Passed_By_Reference          |
7218            Attribute_Pool_Address                 |
7219            Attribute_Scalar_Storage_Order         =>
7220          null;
7221
7222       --  The following attributes are also handled by the back end, but return
7223       --  a universal integer result, so may need a conversion for checking
7224       --  that the result is in range.
7225
7226       when Attribute_Aft                          |
7227            Attribute_Max_Alignment_For_Allocation =>
7228          Apply_Universal_Integer_Attribute_Checks (N);
7229
7230       --  The following attributes should not appear at this stage, since they
7231       --  have already been handled by the analyzer (and properly rewritten
7232       --  with corresponding values or entities to represent the right values)
7233
7234       when Attribute_Abort_Signal                 |
7235            Attribute_Address_Size                 |
7236            Attribute_Atomic_Always_Lock_Free      |
7237            Attribute_Base                         |
7238            Attribute_Class                        |
7239            Attribute_Compiler_Version             |
7240            Attribute_Default_Bit_Order            |
7241            Attribute_Default_Scalar_Storage_Order |
7242            Attribute_Delta                        |
7243            Attribute_Denorm                       |
7244            Attribute_Digits                       |
7245            Attribute_Emax                         |
7246            Attribute_Enabled                      |
7247            Attribute_Epsilon                      |
7248            Attribute_Fast_Math                    |
7249            Attribute_First_Valid                  |
7250            Attribute_Has_Access_Values            |
7251            Attribute_Has_Discriminants            |
7252            Attribute_Has_Tagged_Values            |
7253            Attribute_Large                        |
7254            Attribute_Last_Valid                   |
7255            Attribute_Library_Level                |
7256            Attribute_Lock_Free                    |
7257            Attribute_Machine_Emax                 |
7258            Attribute_Machine_Emin                 |
7259            Attribute_Machine_Mantissa             |
7260            Attribute_Machine_Overflows            |
7261            Attribute_Machine_Radix                |
7262            Attribute_Machine_Rounds               |
7263            Attribute_Maximum_Alignment            |
7264            Attribute_Model_Emin                   |
7265            Attribute_Model_Epsilon                |
7266            Attribute_Model_Mantissa               |
7267            Attribute_Model_Small                  |
7268            Attribute_Modulus                      |
7269            Attribute_Partition_ID                 |
7270            Attribute_Range                        |
7271            Attribute_Restriction_Set              |
7272            Attribute_Safe_Emax                    |
7273            Attribute_Safe_First                   |
7274            Attribute_Safe_Large                   |
7275            Attribute_Safe_Last                    |
7276            Attribute_Safe_Small                   |
7277            Attribute_Scale                        |
7278            Attribute_Signed_Zeros                 |
7279            Attribute_Small                        |
7280            Attribute_Storage_Unit                 |
7281            Attribute_Stub_Type                    |
7282            Attribute_System_Allocator_Alignment   |
7283            Attribute_Target_Name                  |
7284            Attribute_Type_Class                   |
7285            Attribute_Type_Key                     |
7286            Attribute_Unconstrained_Array          |
7287            Attribute_Universal_Literal_String     |
7288            Attribute_Wchar_T_Size                 |
7289            Attribute_Word_Size                    =>
7290          raise Program_Error;
7291
7292       --  The Asm_Input and Asm_Output attributes are not expanded at this
7293       --  stage, but will be eliminated in the expansion of the Asm call, see
7294       --  Exp_Intr for details. So the back end will never see these either.
7295
7296       when Attribute_Asm_Input                    |
7297            Attribute_Asm_Output                   =>
7298          null;
7299       end case;
7300
7301    --  Note: as mentioned earlier, individual sections of the above case
7302    --  statement assume there is no code after the case statement, and are
7303    --  legitimately allowed to execute return statements if they have nothing
7304    --  more to do, so DO NOT add code at this point.
7305
7306    exception
7307       when RE_Not_Available =>
7308          return;
7309    end Expand_N_Attribute_Reference;
7310
7311    --------------------------------
7312    -- Expand_Pred_Succ_Attribute --
7313    --------------------------------
7314
7315    --  For typ'Pred (exp), we generate the check
7316
7317    --    [constraint_error when exp = typ'Base'First]
7318
7319    --  Similarly, for typ'Succ (exp), we generate the check
7320
7321    --    [constraint_error when exp = typ'Base'Last]
7322
7323    --  These checks are not generated for modular types, since the proper
7324    --  semantics for Succ and Pred on modular types is to wrap, not raise CE.
7325    --  We also suppress these checks if we are the right side of an assignment
7326    --  statement or the expression of an object declaration, where the flag
7327    --  Suppress_Assignment_Checks is set for the assignment/declaration.
7328
7329    procedure Expand_Pred_Succ_Attribute (N : Node_Id) is
7330       Loc  : constant Source_Ptr := Sloc (N);
7331       P    : constant Node_Id    := Parent (N);
7332       Cnam : Name_Id;
7333
7334    begin
7335       if Attribute_Name (N) = Name_Pred then
7336          Cnam := Name_First;
7337       else
7338          Cnam := Name_Last;
7339       end if;
7340
7341       if not Nkind_In (P, N_Assignment_Statement, N_Object_Declaration)
7342         or else not Suppress_Assignment_Checks (P)
7343       then
7344          Insert_Action (N,
7345            Make_Raise_Constraint_Error (Loc,
7346              Condition =>
7347                Make_Op_Eq (Loc,
7348                  Left_Opnd =>
7349                    Duplicate_Subexpr_Move_Checks (First (Expressions (N))),
7350                  Right_Opnd =>
7351                    Make_Attribute_Reference (Loc,
7352                      Prefix =>
7353                        New_Occurrence_Of (Base_Type (Etype (Prefix (N))), Loc),
7354                      Attribute_Name => Cnam)),
7355              Reason => CE_Overflow_Check_Failed));
7356       end if;
7357    end Expand_Pred_Succ_Attribute;
7358
7359    -----------------------------
7360    -- Expand_Update_Attribute --
7361    -----------------------------
7362
7363    procedure Expand_Update_Attribute (N : Node_Id) is
7364       procedure Process_Component_Or_Element_Update
7365         (Temp : Entity_Id;
7366          Comp : Node_Id;
7367          Expr : Node_Id;
7368          Typ  : Entity_Id);
7369       --  Generate the statements necessary to update a single component or an
7370       --  element of the prefix. The code is inserted before the attribute N.
7371       --  Temp denotes the entity of the anonymous object created to reflect
7372       --  the changes in values. Comp is the component/index expression to be
7373       --  updated. Expr is an expression yielding the new value of Comp. Typ
7374       --  is the type of the prefix of attribute Update.
7375
7376       procedure Process_Range_Update
7377         (Temp : Entity_Id;
7378          Comp : Node_Id;
7379          Expr : Node_Id;
7380          Typ  : Entity_Id);
7381       --  Generate the statements necessary to update a slice of the prefix.
7382       --  The code is inserted before the attribute N. Temp denotes the entity
7383       --  of the anonymous object created to reflect the changes in values.
7384       --  Comp is range of the slice to be updated. Expr is an expression
7385       --  yielding the new value of Comp. Typ is the type of the prefix of
7386       --  attribute Update.
7387
7388       -----------------------------------------
7389       -- Process_Component_Or_Element_Update --
7390       -----------------------------------------
7391
7392       procedure Process_Component_Or_Element_Update
7393         (Temp : Entity_Id;
7394          Comp : Node_Id;
7395          Expr : Node_Id;
7396          Typ  : Entity_Id)
7397       is
7398          Loc   : constant Source_Ptr := Sloc (Comp);
7399          Exprs : List_Id;
7400          LHS   : Node_Id;
7401
7402       begin
7403          --  An array element may be modified by the following relations
7404          --  depending on the number of dimensions:
7405
7406          --     1 => Expr           --  one dimensional update
7407          --    (1, ..., N) => Expr  --  multi dimensional update
7408
7409          --  The above forms are converted in assignment statements where the
7410          --  left hand side is an indexed component:
7411
7412          --    Temp (1) := Expr;          --  one dimensional update
7413          --    Temp (1, ..., N) := Expr;  --  multi dimensional update
7414
7415          if Is_Array_Type (Typ) then
7416
7417             --  The index expressions of a multi dimensional array update
7418             --  appear as an aggregate.
7419
7420             if Nkind (Comp) = N_Aggregate then
7421                Exprs := New_Copy_List_Tree (Expressions (Comp));
7422             else
7423                Exprs := New_List (Relocate_Node (Comp));
7424             end if;
7425
7426             LHS :=
7427               Make_Indexed_Component (Loc,
7428                 Prefix      => New_Occurrence_Of (Temp, Loc),
7429                 Expressions => Exprs);
7430
7431          --  A record component update appears in the following form:
7432
7433          --    Comp => Expr
7434
7435          --  The above relation is transformed into an assignment statement
7436          --  where the left hand side is a selected component:
7437
7438          --    Temp.Comp := Expr;
7439
7440          else pragma Assert (Is_Record_Type (Typ));
7441             LHS :=
7442               Make_Selected_Component (Loc,
7443                 Prefix        => New_Occurrence_Of (Temp, Loc),
7444                 Selector_Name => Relocate_Node (Comp));
7445          end if;
7446
7447          Insert_Action (N,
7448            Make_Assignment_Statement (Loc,
7449              Name       => LHS,
7450              Expression => Relocate_Node (Expr)));
7451       end Process_Component_Or_Element_Update;
7452
7453       --------------------------
7454       -- Process_Range_Update --
7455       --------------------------
7456
7457       procedure Process_Range_Update
7458         (Temp : Entity_Id;
7459          Comp : Node_Id;
7460          Expr : Node_Id;
7461          Typ  : Entity_Id)
7462       is
7463          Index_Typ : constant Entity_Id  := Etype (First_Index (Typ));
7464          Loc       : constant Source_Ptr := Sloc (Comp);
7465          Index     : Entity_Id;
7466
7467       begin
7468          --  A range update appears as
7469
7470          --    (Low .. High => Expr)
7471
7472          --  The above construct is transformed into a loop that iterates over
7473          --  the given range and modifies the corresponding array values to the
7474          --  value of Expr:
7475
7476          --    for Index in Low .. High loop
7477          --       Temp (<Index_Typ> (Index)) := Expr;
7478          --    end loop;
7479
7480          Index := Make_Temporary (Loc, 'I');
7481
7482          Insert_Action (N,
7483            Make_Loop_Statement (Loc,
7484              Iteration_Scheme =>
7485                Make_Iteration_Scheme (Loc,
7486                  Loop_Parameter_Specification =>
7487                    Make_Loop_Parameter_Specification (Loc,
7488                      Defining_Identifier         => Index,
7489                      Discrete_Subtype_Definition => Relocate_Node (Comp))),
7490
7491              Statements       => New_List (
7492                Make_Assignment_Statement (Loc,
7493                  Name       =>
7494                    Make_Indexed_Component (Loc,
7495                      Prefix      => New_Occurrence_Of (Temp, Loc),
7496                      Expressions => New_List (
7497                        Convert_To (Index_Typ,
7498                          New_Occurrence_Of (Index, Loc)))),
7499                  Expression => Relocate_Node (Expr))),
7500
7501              End_Label        => Empty));
7502       end Process_Range_Update;
7503
7504       --  Local variables
7505
7506       Aggr    : constant Node_Id    := First (Expressions (N));
7507       Loc     : constant Source_Ptr := Sloc (N);
7508       Pref    : constant Node_Id    := Prefix (N);
7509       Typ     : constant Entity_Id  := Etype (Pref);
7510       Assoc   : Node_Id;
7511       Comp    : Node_Id;
7512       CW_Temp : Entity_Id;
7513       CW_Typ  : Entity_Id;
7514       Expr    : Node_Id;
7515       Temp    : Entity_Id;
7516
7517    --  Start of processing for Expand_Update_Attribute
7518
7519    begin
7520       --  Create the anonymous object to store the value of the prefix and
7521       --  capture subsequent changes in value.
7522
7523       Temp := Make_Temporary (Loc, 'T', Pref);
7524
7525       --  Preserve the tag of the prefix by offering a specific view of the
7526       --  class-wide version of the prefix.
7527
7528       if Is_Tagged_Type (Typ) then
7529
7530          --  Generate:
7531          --    CW_Temp : Typ'Class := Typ'Class (Pref);
7532
7533          CW_Temp := Make_Temporary (Loc, 'T');
7534          CW_Typ  := Class_Wide_Type (Typ);
7535
7536          Insert_Action (N,
7537            Make_Object_Declaration (Loc,
7538              Defining_Identifier => CW_Temp,
7539              Object_Definition   => New_Occurrence_Of (CW_Typ, Loc),
7540              Expression          =>
7541                Convert_To (CW_Typ, Relocate_Node (Pref))));
7542
7543          --  Generate:
7544          --    Temp : Typ renames Typ (CW_Temp);
7545
7546          Insert_Action (N,
7547            Make_Object_Renaming_Declaration (Loc,
7548              Defining_Identifier => Temp,
7549              Subtype_Mark        => New_Occurrence_Of (Typ, Loc),
7550              Name                =>
7551                Convert_To (Typ, New_Occurrence_Of (CW_Temp, Loc))));
7552
7553       --  Non-tagged case
7554
7555       else
7556          --  Generate:
7557          --    Temp : Typ := Pref;
7558
7559          Insert_Action (N,
7560            Make_Object_Declaration (Loc,
7561              Defining_Identifier => Temp,
7562              Object_Definition   => New_Occurrence_Of (Typ, Loc),
7563              Expression          => Relocate_Node (Pref)));
7564       end if;
7565
7566       --  Process the update aggregate
7567
7568       Assoc := First (Component_Associations (Aggr));
7569       while Present (Assoc) loop
7570          Comp := First (Choices (Assoc));
7571          Expr := Expression (Assoc);
7572          while Present (Comp) loop
7573             if Nkind (Comp) = N_Range then
7574                Process_Range_Update (Temp, Comp, Expr, Typ);
7575             else
7576                Process_Component_Or_Element_Update (Temp, Comp, Expr, Typ);
7577             end if;
7578
7579             Next (Comp);
7580          end loop;
7581
7582          Next (Assoc);
7583       end loop;
7584
7585       --  The attribute is replaced by a reference to the anonymous object
7586
7587       Rewrite (N, New_Occurrence_Of (Temp, Loc));
7588       Analyze (N);
7589    end Expand_Update_Attribute;
7590
7591    -------------------
7592    -- Find_Fat_Info --
7593    -------------------
7594
7595    procedure Find_Fat_Info
7596      (T        : Entity_Id;
7597       Fat_Type : out Entity_Id;
7598       Fat_Pkg  : out RE_Id)
7599    is
7600       Rtyp : constant Entity_Id := Root_Type (T);
7601
7602    begin
7603       --  All we do is use the root type (historically this dealt with
7604       --  VAX-float .. to be cleaned up further later ???)
7605
7606       Fat_Type := Rtyp;
7607
7608       if Fat_Type = Standard_Short_Float then
7609          Fat_Pkg := RE_Attr_Short_Float;
7610
7611       elsif Fat_Type = Standard_Float then
7612          Fat_Pkg := RE_Attr_Float;
7613
7614       elsif Fat_Type = Standard_Long_Float then
7615          Fat_Pkg := RE_Attr_Long_Float;
7616
7617       elsif Fat_Type = Standard_Long_Long_Float then
7618          Fat_Pkg := RE_Attr_Long_Long_Float;
7619
7620          --  Universal real (which is its own root type) is treated as being
7621          --  equivalent to Standard.Long_Long_Float, since it is defined to
7622          --  have the same precision as the longest Float type.
7623
7624       elsif Fat_Type = Universal_Real then
7625          Fat_Type := Standard_Long_Long_Float;
7626          Fat_Pkg := RE_Attr_Long_Long_Float;
7627
7628       else
7629          raise Program_Error;
7630       end if;
7631    end Find_Fat_Info;
7632
7633    ----------------------------
7634    -- Find_Stream_Subprogram --
7635    ----------------------------
7636
7637    function Find_Stream_Subprogram
7638      (Typ : Entity_Id;
7639       Nam : TSS_Name_Type) return Entity_Id
7640    is
7641       Base_Typ : constant Entity_Id := Base_Type (Typ);
7642       Ent      : constant Entity_Id := TSS (Typ, Nam);
7643
7644       function Is_Available (Entity : RE_Id) return Boolean;
7645       pragma Inline (Is_Available);
7646       --  Function to check whether the specified run-time call is available
7647       --  in the run time used. In the case of a configurable run time, it
7648       --  is normal that some subprograms are not there.
7649       --
7650       --  I don't understand this routine at all, why is this not just a
7651       --  call to RTE_Available? And if for some reason we need a different
7652       --  routine with different semantics, why is not in Rtsfind ???
7653
7654       ------------------
7655       -- Is_Available --
7656       ------------------
7657
7658       function Is_Available (Entity : RE_Id) return Boolean is
7659       begin
7660          --  Assume that the unit will always be available when using a
7661          --  "normal" (not configurable) run time.
7662
7663          return not Configurable_Run_Time_Mode or else RTE_Available (Entity);
7664       end Is_Available;
7665
7666    --  Start of processing for Find_Stream_Subprogram
7667
7668    begin
7669       if Present (Ent) then
7670          return Ent;
7671       end if;
7672
7673       --  Stream attributes for strings are expanded into library calls. The
7674       --  following checks are disabled when the run-time is not available or
7675       --  when compiling predefined types due to bootstrap issues. As a result,
7676       --  the compiler will generate in-place stream routines for string types
7677       --  that appear in GNAT's library, but will generate calls via rtsfind
7678       --  to library routines for user code.
7679
7680       --  Note: In the case of using a configurable run time, it is very likely
7681       --  that stream routines for string types are not present (they require
7682       --  file system support). In this case, the specific stream routines for
7683       --  strings are not used, relying on the regular stream mechanism
7684       --  instead. That is why we include the test Is_Available when dealing
7685       --  with these cases.
7686
7687       if not Is_Predefined_File_Name (Unit_File_Name (Current_Sem_Unit)) then
7688          --  Storage_Array as defined in package System.Storage_Elements
7689
7690          if Is_RTE (Base_Typ, RE_Storage_Array) then
7691
7692             --  Case of No_Stream_Optimizations restriction active
7693
7694             if Restriction_Active (No_Stream_Optimizations) then
7695                if Nam = TSS_Stream_Input
7696                  and then Is_Available (RE_Storage_Array_Input)
7697                then
7698                   return RTE (RE_Storage_Array_Input);
7699
7700                elsif Nam = TSS_Stream_Output
7701                  and then Is_Available (RE_Storage_Array_Output)
7702                then
7703                   return RTE (RE_Storage_Array_Output);
7704
7705                elsif Nam = TSS_Stream_Read
7706                  and then Is_Available (RE_Storage_Array_Read)
7707                then
7708                   return RTE (RE_Storage_Array_Read);
7709
7710                elsif Nam = TSS_Stream_Write
7711                  and then Is_Available (RE_Storage_Array_Write)
7712                then
7713                   return RTE (RE_Storage_Array_Write);
7714
7715                elsif Nam /= TSS_Stream_Input  and then
7716                      Nam /= TSS_Stream_Output and then
7717                      Nam /= TSS_Stream_Read   and then
7718                      Nam /= TSS_Stream_Write
7719                then
7720                   raise Program_Error;
7721                end if;
7722
7723             --  Restriction No_Stream_Optimizations is not set, so we can go
7724             --  ahead and optimize using the block IO forms of the routines.
7725
7726             else
7727                if Nam = TSS_Stream_Input
7728                  and then Is_Available (RE_Storage_Array_Input_Blk_IO)
7729                then
7730                   return RTE (RE_Storage_Array_Input_Blk_IO);
7731
7732                elsif Nam = TSS_Stream_Output
7733                  and then Is_Available (RE_Storage_Array_Output_Blk_IO)
7734                then
7735                   return RTE (RE_Storage_Array_Output_Blk_IO);
7736
7737                elsif Nam = TSS_Stream_Read
7738                  and then Is_Available (RE_Storage_Array_Read_Blk_IO)
7739                then
7740                   return RTE (RE_Storage_Array_Read_Blk_IO);
7741
7742                elsif Nam = TSS_Stream_Write
7743                  and then Is_Available (RE_Storage_Array_Write_Blk_IO)
7744                then
7745                   return RTE (RE_Storage_Array_Write_Blk_IO);
7746
7747                elsif Nam /= TSS_Stream_Input  and then
7748                      Nam /= TSS_Stream_Output and then
7749                      Nam /= TSS_Stream_Read   and then
7750                      Nam /= TSS_Stream_Write
7751                then
7752                   raise Program_Error;
7753                end if;
7754             end if;
7755
7756          --  Stream_Element_Array as defined in package Ada.Streams
7757
7758          elsif Is_RTE (Base_Typ, RE_Stream_Element_Array) then
7759
7760             --  Case of No_Stream_Optimizations restriction active
7761
7762             if Restriction_Active (No_Stream_Optimizations) then
7763                if Nam = TSS_Stream_Input
7764                  and then Is_Available (RE_Stream_Element_Array_Input)
7765                then
7766                   return RTE (RE_Stream_Element_Array_Input);
7767
7768                elsif Nam = TSS_Stream_Output
7769                  and then Is_Available (RE_Stream_Element_Array_Output)
7770                then
7771                   return RTE (RE_Stream_Element_Array_Output);
7772
7773                elsif Nam = TSS_Stream_Read
7774                  and then Is_Available (RE_Stream_Element_Array_Read)
7775                then
7776                   return RTE (RE_Stream_Element_Array_Read);
7777
7778                elsif Nam = TSS_Stream_Write
7779                  and then Is_Available (RE_Stream_Element_Array_Write)
7780                then
7781                   return RTE (RE_Stream_Element_Array_Write);
7782
7783                elsif Nam /= TSS_Stream_Input  and then
7784                      Nam /= TSS_Stream_Output and then
7785                      Nam /= TSS_Stream_Read   and then
7786                      Nam /= TSS_Stream_Write
7787                then
7788                   raise Program_Error;
7789                end if;
7790
7791             --  Restriction No_Stream_Optimizations is not set, so we can go
7792             --  ahead and optimize using the block IO forms of the routines.
7793
7794             else
7795                if Nam = TSS_Stream_Input
7796                  and then Is_Available (RE_Stream_Element_Array_Input_Blk_IO)
7797                then
7798                   return RTE (RE_Stream_Element_Array_Input_Blk_IO);
7799
7800                elsif Nam = TSS_Stream_Output
7801                  and then Is_Available (RE_Stream_Element_Array_Output_Blk_IO)
7802                then
7803                   return RTE (RE_Stream_Element_Array_Output_Blk_IO);
7804
7805                elsif Nam = TSS_Stream_Read
7806                  and then Is_Available (RE_Stream_Element_Array_Read_Blk_IO)
7807                then
7808                   return RTE (RE_Stream_Element_Array_Read_Blk_IO);
7809
7810                elsif Nam = TSS_Stream_Write
7811                  and then Is_Available (RE_Stream_Element_Array_Write_Blk_IO)
7812                then
7813                   return RTE (RE_Stream_Element_Array_Write_Blk_IO);
7814
7815                elsif Nam /= TSS_Stream_Input  and then
7816                      Nam /= TSS_Stream_Output and then
7817                      Nam /= TSS_Stream_Read   and then
7818                      Nam /= TSS_Stream_Write
7819                then
7820                   raise Program_Error;
7821                end if;
7822             end if;
7823
7824          --  String as defined in package Ada
7825
7826          elsif Base_Typ = Standard_String then
7827
7828             --  Case of No_Stream_Optimizations restriction active
7829
7830             if Restriction_Active (No_Stream_Optimizations) then
7831                if Nam = TSS_Stream_Input
7832                  and then Is_Available (RE_String_Input)
7833                then
7834                   return RTE (RE_String_Input);
7835
7836                elsif Nam = TSS_Stream_Output
7837                  and then Is_Available (RE_String_Output)
7838                then
7839                   return RTE (RE_String_Output);
7840
7841                elsif Nam = TSS_Stream_Read
7842                  and then Is_Available (RE_String_Read)
7843                then
7844                   return RTE (RE_String_Read);
7845
7846                elsif Nam = TSS_Stream_Write
7847                  and then Is_Available (RE_String_Write)
7848                then
7849                   return RTE (RE_String_Write);
7850
7851                elsif Nam /= TSS_Stream_Input and then
7852                      Nam /= TSS_Stream_Output and then
7853                      Nam /= TSS_Stream_Read and then
7854                      Nam /= TSS_Stream_Write
7855                then
7856                   raise Program_Error;
7857                end if;
7858
7859             --  Restriction No_Stream_Optimizations is not set, so we can go
7860             --  ahead and optimize using the block IO forms of the routines.
7861
7862             else
7863                if Nam = TSS_Stream_Input
7864                  and then Is_Available (RE_String_Input_Blk_IO)
7865                then
7866                   return RTE (RE_String_Input_Blk_IO);
7867
7868                elsif Nam = TSS_Stream_Output
7869                  and then Is_Available (RE_String_Output_Blk_IO)
7870                then
7871                   return RTE (RE_String_Output_Blk_IO);
7872
7873                elsif Nam = TSS_Stream_Read
7874                  and then Is_Available (RE_String_Read_Blk_IO)
7875                then
7876                   return RTE (RE_String_Read_Blk_IO);
7877
7878                elsif Nam = TSS_Stream_Write
7879                  and then Is_Available (RE_String_Write_Blk_IO)
7880                then
7881                   return RTE (RE_String_Write_Blk_IO);
7882
7883                elsif Nam /= TSS_Stream_Input  and then
7884                      Nam /= TSS_Stream_Output and then
7885                      Nam /= TSS_Stream_Read   and then
7886                      Nam /= TSS_Stream_Write
7887                then
7888                   raise Program_Error;
7889                end if;
7890             end if;
7891
7892          --  Wide_String as defined in package Ada
7893
7894          elsif Base_Typ = Standard_Wide_String then
7895
7896             --  Case of No_Stream_Optimizations restriction active
7897
7898             if Restriction_Active (No_Stream_Optimizations) then
7899                if Nam = TSS_Stream_Input
7900                  and then Is_Available (RE_Wide_String_Input)
7901                then
7902                   return RTE (RE_Wide_String_Input);
7903
7904                elsif Nam = TSS_Stream_Output
7905                  and then Is_Available (RE_Wide_String_Output)
7906                then
7907                   return RTE (RE_Wide_String_Output);
7908
7909                elsif Nam = TSS_Stream_Read
7910                  and then Is_Available (RE_Wide_String_Read)
7911                then
7912                   return RTE (RE_Wide_String_Read);
7913
7914                elsif Nam = TSS_Stream_Write
7915                  and then Is_Available (RE_Wide_String_Write)
7916                then
7917                   return RTE (RE_Wide_String_Write);
7918
7919                elsif Nam /= TSS_Stream_Input  and then
7920                      Nam /= TSS_Stream_Output and then
7921                      Nam /= TSS_Stream_Read   and then
7922                      Nam /= TSS_Stream_Write
7923                then
7924                   raise Program_Error;
7925                end if;
7926
7927             --  Restriction No_Stream_Optimizations is not set, so we can go
7928             --  ahead and optimize using the block IO forms of the routines.
7929
7930             else
7931                if Nam = TSS_Stream_Input
7932                  and then Is_Available (RE_Wide_String_Input_Blk_IO)
7933                then
7934                   return RTE (RE_Wide_String_Input_Blk_IO);
7935
7936                elsif Nam = TSS_Stream_Output
7937                  and then Is_Available (RE_Wide_String_Output_Blk_IO)
7938                then
7939                   return RTE (RE_Wide_String_Output_Blk_IO);
7940
7941                elsif Nam = TSS_Stream_Read
7942                  and then Is_Available (RE_Wide_String_Read_Blk_IO)
7943                then
7944                   return RTE (RE_Wide_String_Read_Blk_IO);
7945
7946                elsif Nam = TSS_Stream_Write
7947                  and then Is_Available (RE_Wide_String_Write_Blk_IO)
7948                then
7949                   return RTE (RE_Wide_String_Write_Blk_IO);
7950
7951                elsif Nam /= TSS_Stream_Input  and then
7952                      Nam /= TSS_Stream_Output and then
7953                      Nam /= TSS_Stream_Read   and then
7954                      Nam /= TSS_Stream_Write
7955                then
7956                   raise Program_Error;
7957                end if;
7958             end if;
7959
7960          --  Wide_Wide_String as defined in package Ada
7961
7962          elsif Base_Typ = Standard_Wide_Wide_String then
7963
7964             --  Case of No_Stream_Optimizations restriction active
7965
7966             if Restriction_Active (No_Stream_Optimizations) then
7967                if Nam = TSS_Stream_Input
7968                  and then Is_Available (RE_Wide_Wide_String_Input)
7969                then
7970                   return RTE (RE_Wide_Wide_String_Input);
7971
7972                elsif Nam = TSS_Stream_Output
7973                  and then Is_Available (RE_Wide_Wide_String_Output)
7974                then
7975                   return RTE (RE_Wide_Wide_String_Output);
7976
7977                elsif Nam = TSS_Stream_Read
7978                  and then Is_Available (RE_Wide_Wide_String_Read)
7979                then
7980                   return RTE (RE_Wide_Wide_String_Read);
7981
7982                elsif Nam = TSS_Stream_Write
7983                  and then Is_Available (RE_Wide_Wide_String_Write)
7984                then
7985                   return RTE (RE_Wide_Wide_String_Write);
7986
7987                elsif Nam /= TSS_Stream_Input  and then
7988                      Nam /= TSS_Stream_Output and then
7989                      Nam /= TSS_Stream_Read   and then
7990                      Nam /= TSS_Stream_Write
7991                then
7992                   raise Program_Error;
7993                end if;
7994
7995             --  Restriction No_Stream_Optimizations is not set, so we can go
7996             --  ahead and optimize using the block IO forms of the routines.
7997
7998             else
7999                if Nam = TSS_Stream_Input
8000                  and then Is_Available (RE_Wide_Wide_String_Input_Blk_IO)
8001                then
8002                   return RTE (RE_Wide_Wide_String_Input_Blk_IO);
8003
8004                elsif Nam = TSS_Stream_Output
8005                  and then Is_Available (RE_Wide_Wide_String_Output_Blk_IO)
8006                then
8007                   return RTE (RE_Wide_Wide_String_Output_Blk_IO);
8008
8009                elsif Nam = TSS_Stream_Read
8010                  and then Is_Available (RE_Wide_Wide_String_Read_Blk_IO)
8011                then
8012                   return RTE (RE_Wide_Wide_String_Read_Blk_IO);
8013
8014                elsif Nam = TSS_Stream_Write
8015                  and then Is_Available (RE_Wide_Wide_String_Write_Blk_IO)
8016                then
8017                   return RTE (RE_Wide_Wide_String_Write_Blk_IO);
8018
8019                elsif Nam /= TSS_Stream_Input  and then
8020                      Nam /= TSS_Stream_Output and then
8021                      Nam /= TSS_Stream_Read   and then
8022                      Nam /= TSS_Stream_Write
8023                then
8024                   raise Program_Error;
8025                end if;
8026             end if;
8027          end if;
8028       end if;
8029
8030       if Is_Tagged_Type (Typ) and then Is_Derived_Type (Typ) then
8031          return Find_Prim_Op (Typ, Nam);
8032       else
8033          return Find_Inherited_TSS (Typ, Nam);
8034       end if;
8035    end Find_Stream_Subprogram;
8036
8037    ---------------
8038    -- Full_Base --
8039    ---------------
8040
8041    function Full_Base (T : Entity_Id) return Entity_Id is
8042       BT : Entity_Id;
8043
8044    begin
8045       BT := Base_Type (T);
8046
8047       if Is_Private_Type (BT)
8048         and then Present (Full_View (BT))
8049       then
8050          BT := Full_View (BT);
8051       end if;
8052
8053       return BT;
8054    end Full_Base;
8055
8056    -----------------------
8057    -- Get_Index_Subtype --
8058    -----------------------
8059
8060    function Get_Index_Subtype (N : Node_Id) return Node_Id is
8061       P_Type : Entity_Id := Etype (Prefix (N));
8062       Indx   : Node_Id;
8063       J      : Int;
8064
8065    begin
8066       if Is_Access_Type (P_Type) then
8067          P_Type := Designated_Type (P_Type);
8068       end if;
8069
8070       if No (Expressions (N)) then
8071          J := 1;
8072       else
8073          J := UI_To_Int (Expr_Value (First (Expressions (N))));
8074       end if;
8075
8076       Indx := First_Index (P_Type);
8077       while J > 1 loop
8078          Next_Index (Indx);
8079          J := J - 1;
8080       end loop;
8081
8082       return Etype (Indx);
8083    end Get_Index_Subtype;
8084
8085    -------------------------------
8086    -- Get_Stream_Convert_Pragma --
8087    -------------------------------
8088
8089    function Get_Stream_Convert_Pragma (T : Entity_Id) return Node_Id is
8090       Typ : Entity_Id;
8091       N   : Node_Id;
8092
8093    begin
8094       --  Note: we cannot use Get_Rep_Pragma here because of the peculiarity
8095       --  that a stream convert pragma for a tagged type is not inherited from
8096       --  its parent. Probably what is wrong here is that it is basically
8097       --  incorrect to consider a stream convert pragma to be a representation
8098       --  pragma at all ???
8099
8100       N := First_Rep_Item (Implementation_Base_Type (T));
8101       while Present (N) loop
8102          if Nkind (N) = N_Pragma
8103            and then Pragma_Name_Mapped (N) = Name_Stream_Convert
8104          then
8105             --  For tagged types this pragma is not inherited, so we
8106             --  must verify that it is defined for the given type and
8107             --  not an ancestor.
8108
8109             Typ :=
8110               Entity (Expression (First (Pragma_Argument_Associations (N))));
8111
8112             if not Is_Tagged_Type (T)
8113               or else T = Typ
8114               or else (Is_Private_Type (Typ) and then T = Full_View (Typ))
8115             then
8116                return N;
8117             end if;
8118          end if;
8119
8120          Next_Rep_Item (N);
8121       end loop;
8122
8123       return Empty;
8124    end Get_Stream_Convert_Pragma;
8125
8126    ---------------------------------
8127    -- Is_Constrained_Packed_Array --
8128    ---------------------------------
8129
8130    function Is_Constrained_Packed_Array (Typ : Entity_Id) return Boolean is
8131       Arr : Entity_Id := Typ;
8132
8133    begin
8134       if Is_Access_Type (Arr) then
8135          Arr := Designated_Type (Arr);
8136       end if;
8137
8138       return Is_Array_Type (Arr)
8139         and then Is_Constrained (Arr)
8140         and then Present (Packed_Array_Impl_Type (Arr));
8141    end Is_Constrained_Packed_Array;
8142
8143    ----------------------------------------
8144    -- Is_Inline_Floating_Point_Attribute --
8145    ----------------------------------------
8146
8147    function Is_Inline_Floating_Point_Attribute (N : Node_Id) return Boolean is
8148       Id : constant Attribute_Id := Get_Attribute_Id (Attribute_Name (N));
8149
8150       function Is_GCC_Target return Boolean;
8151       --  Return True if we are using a GCC target/back-end
8152       --  ??? Note: the implementation is kludgy/fragile
8153
8154       -------------------
8155       -- Is_GCC_Target --
8156       -------------------
8157
8158       function Is_GCC_Target return Boolean is
8159       begin
8160          return not CodePeer_Mode
8161            and then not AAMP_On_Target
8162            and then not Generate_C_Code;
8163       end Is_GCC_Target;
8164
8165    --  Start of processing for Is_Inline_Floating_Point_Attribute
8166
8167    begin
8168       --  Machine and Model can be expanded by the GCC and AAMP back ends only
8169
8170       if Id = Attribute_Machine or else Id = Attribute_Model then
8171          return Is_GCC_Target or else AAMP_On_Target;
8172
8173       --  Remaining cases handled by all back ends are Rounding and Truncation
8174       --  when appearing as the operand of a conversion to some integer type.
8175
8176       elsif Nkind (Parent (N)) /= N_Type_Conversion
8177         or else not Is_Integer_Type (Etype (Parent (N)))
8178       then
8179          return False;
8180       end if;
8181
8182       --  Here we are in the integer conversion context
8183
8184       --  Very probably we should also recognize the cases of Machine_Rounding
8185       --  and unbiased rounding in this conversion context, but the back end is
8186       --  not yet prepared to handle these cases ???
8187
8188       return Id = Attribute_Rounding or else Id = Attribute_Truncation;
8189    end Is_Inline_Floating_Point_Attribute;
8190
8191 end Exp_Attr;